7 #include <sys/select.h>
13 static int baud_id(int baud);
15 int ser_open(const char *port, int baud, unsigned int mode)
20 if((baud = baud_id(baud)) == -1) {
21 fprintf(stderr, "ser_open: invalid baud number: %d\n", baud);
25 if((fd = open(port, O_RDWR | O_NONBLOCK | O_NOCTTY)) == -1) {
29 /*memset(&term, 0, sizeof term);*/
37 term.c_cflag = CLOCAL | CREAD | CS8 | HUPCL | CRTSCTS;
39 term.c_cflag |= CSTOPB;
42 term.c_iflag = IGNBRK | IGNPAR;
44 cfsetispeed(&term, baud);
45 cfsetospeed(&term, baud);
47 if(tcsetattr(fd, TCSANOW, &term) < 0) {
48 fprintf(stderr, "ser_open: failed to set terminal attributes\n");
53 if(mode & SER_HWFLOW) {
55 if(ioctl(fd, TIOCMGET, &st) == -1) {
56 perror("ser_open: failed to get modem status");
60 st |= TIOCM_DTR | TIOCM_RTS;
61 if(ioctl(fd, TIOCMSET, &st) == -1) {
62 perror("ser_open: failed to set flow control");
71 void ser_close(int fd)
76 int ser_pending(int fd)
78 static struct timeval tv_zero;
84 while(select(fd + 1, &rd, 0, 0, &tv_zero) == -1 && errno == EINTR);
85 return FD_ISSET(fd, &rd);
88 int ser_wait(int fd, long msec)
90 struct timeval tv, tv0;
96 tv.tv_sec = msec / 1000;
97 tv.tv_usec = msec * 1000;
99 gettimeofday(&tv0, 0);
101 while(select(fd + 1, &rd, 0, 0, msec >= 0 ? &tv : 0) == -1 && errno == EINTR) {
102 /* interrupted, recalc timeout and go back to sleep */
104 gettimeofday(&tv, 0);
105 msec -= (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000;
106 if(msec < 0) msec = 0;
108 tv.tv_sec = msec / 1000;
109 tv.tv_usec = msec * 1000;
113 return FD_ISSET(fd, &rd);
116 int ser_write(int fd, const char *buf, int count)
118 return write(fd, buf, count);
121 int ser_read(int fd, char *buf, int count)
123 return read(fd, buf, count);
126 void ser_printf(int fd, const char *fmt, ...)
131 vdprintf(fd, fmt, ap);
135 char *ser_getline(int fd, char *buf, int bsz)
137 static char linebuf[512];
142 size = sizeof linebuf - widx;
143 while(size && (rd = read(fd, linebuf + widx, size)) > 0) {
149 for(i=0; i<widx; i++) {
150 if(*ptr == '\r' || *ptr == '\n') {
152 if(i < widx - 1 && ptr[1] == '\n') {
156 size = widx >= bsz ? bsz - 1 : widx;
157 memcpy(buf, linebuf, size);
160 memmove(linebuf, linebuf + widx, sizeof linebuf - widx);
169 static int baud_id(int baud)
174 case 110: return B110;
175 case 134: return B134;
176 case 150: return B150;
177 case 200: return B200;
178 case 300: return B300;
179 case 600: return B600;
180 case 1200: return B1200;
181 case 1800: return B1800;
182 case 2400: return B2400;
183 case 4800: return B4800;
184 case 9600: return B9600;
185 case 19200: return B19200;
186 case 38400: return B38400;
187 case 57600: return B57600;
188 case 115200: return B115200;