serial_device_lin.c
00001
00002
00003
00004
00005
00006
00007 #include "serial_device.h"
00008 #include "connect_device.h"
00009 #include <sys/types.h>
00010 #include <sys/stat.h>
00011 #include <fcntl.h>
00012 #include <stdio.h>
00013 #include <termios.h>
00014 #include <sys/poll.h>
00015 #include <unistd.h>
00016
00017 typedef struct {
00018 int fd;
00019 struct termios sio;
00020 struct pollfd nfds;
00021 } ids_info_t;
00022 static ids_info_t ids[ID_MAX];
00023 static int last_id;
00024
00025
00026 int serial_open(const char *devName, long baudrate) {
00027 int fd;
00028 ids[last_id].fd = -1;
00029
00030 fd = open(devName, O_RDWR | O_SYNC);
00031 if (fd < 0) {
00032 perror(devName);
00033 return DEVICE_OPEN_ERROR;
00034 }
00035
00036 tcgetattr(fd, &ids[last_id].sio);
00037 ids[last_id].sio.c_iflag = IGNPAR;
00038 ids[last_id].sio.c_oflag = 0;
00039 ids[last_id].sio.c_cflag = CS8 | CREAD | CLOCAL;
00040 ids[last_id].sio.c_lflag = 0;
00041
00042 ids[last_id].sio.c_cc[VMIN] = 0;
00043 ids[last_id].sio.c_cc[VTIME] = 0;
00044 tcsetattr(fd, TCSAFLUSH, &ids[last_id].sio);
00045
00046
00047 ids[last_id].nfds.fd = fd;
00048 ids[last_id].nfds.events = POLLIN | POLLPRI | POLLERR | POLLHUP | POLLNVAL;
00049 ids[last_id].nfds.revents = 0;
00050 ids[last_id].fd = fd;
00051
00052 return last_id++;
00053 }
00054
00055
00056 void serial_close(int id) {
00057 close(ids[id].fd);
00058 ids[id].fd = -1;
00059 }
00060
00061
00062 int serial_is_connected(int id) {
00063 return ids[id].fd;
00064 }
00065
00066
00067 int serial_recv(int id, char *data, int size, int timeout) {
00068 struct pollfd *nfds = &ids[id].nfds;
00069 int fd = ids[id].fd;
00070 int filled = 0;
00071 int n;
00072
00073 while (filled < size) {
00074 if (poll(nfds, 1, timeout) == 0) {
00075 break;
00076 }
00077 n = read(fd, &data[filled], size - filled);
00078 if (n <= 0) {
00079 break;
00080 }
00081 filled += n;
00082 }
00083 return filled;
00084 }
00085
00086
00087 int serial_send(int id, const char *data, int length) {
00088 return write(ids[id].fd, data, length);
00089 }
00090
00091
00092 void serial_flush(int id) {
00093 tcflush(ids[id].fd, TCIOFLUSH);
00094 }
00095
00096
00097 int serial_set_baudrate(int id, long baudrate) {
00098 struct termios *sio = &ids[id].sio;
00099 int fd = ids[id].fd;
00100 long baudrate_value;
00101
00102 switch (baudrate) {
00103 case 9600:
00104 baudrate_value = B9600;
00105 break;
00106
00107 case 19200:
00108 baudrate_value = B19200;
00109 break;
00110
00111 case 38400:
00112 baudrate_value = B38400;
00113 break;
00114
00115 case 57600:
00116 baudrate_value = B57600;
00117 break;
00118
00119 case 115200:
00120 baudrate_value = B115200;
00121 break;
00122
00123 case 230400:
00124 baudrate_value = B230400;
00125 break;
00126
00127 default:
00128 return BAUDRATE_ADJUST_ERROR;
00129 break;
00130 }
00131
00132 cfsetospeed(sio, baudrate_value);
00133 cfsetispeed(sio, baudrate_value);
00134 tcsetattr(fd, TCSAFLUSH, sio);
00135
00136 return 0;
00137 }
00138