]> sigrok.org Git - libsigrok.git/blob - hardware/common/serial.c
serial: Fix two segfaults.
[libsigrok.git] / hardware / common / serial.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <string.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <fcntl.h>
25 #include <unistd.h>
26 #ifdef _WIN32
27 #include <windows.h>
28 #else
29 #include <glob.h>
30 #include <termios.h>
31 #endif
32 #include <stdlib.h>
33 #include <errno.h>
34 #include <glib.h>
35 #include "libsigrok.h"
36 #include "libsigrok-internal.h"
37
38 /* Message logging helpers with driver-specific prefix string. */
39 #define DRIVER_LOG_DOMAIN "serial: "
40 #define sr_log(l, s, args...) sr_log(l, DRIVER_LOG_DOMAIN s, ## args)
41 #define sr_spew(s, args...) sr_spew(DRIVER_LOG_DOMAIN s, ## args)
42 #define sr_dbg(s, args...) sr_dbg(DRIVER_LOG_DOMAIN s, ## args)
43 #define sr_info(s, args...) sr_info(DRIVER_LOG_DOMAIN s, ## args)
44 #define sr_warn(s, args...) sr_warn(DRIVER_LOG_DOMAIN s, ## args)
45 #define sr_err(s, args...) sr_err(DRIVER_LOG_DOMAIN s, ## args)
46
47 // FIXME: Must be moved, or rather passed as function argument.
48 #ifdef _WIN32
49 static HANDLE hdl;
50 #endif
51
52 static const char *serial_port_glob[] = {
53         /* Linux */
54         "/dev/ttyS*",
55         "/dev/ttyUSB*",
56         "/dev/ttyACM*",
57         /* MacOS X */
58         "/dev/ttys*",
59         "/dev/tty.USB-*",
60         "/dev/tty.Modem-*",
61         NULL,
62 };
63
64 SR_PRIV GSList *list_serial_ports(void)
65 {
66         GSList *ports;
67
68         sr_dbg("Getting list of serial ports on the system.");
69
70 #ifdef _WIN32
71         /* TODO */
72         ports = NULL;
73         ports = g_slist_append(ports, g_strdup("COM1"));
74 #else
75         glob_t g;
76         unsigned int i, j;
77
78         ports = NULL;
79         for (i = 0; serial_port_glob[i]; i++) {
80                 if (glob(serial_port_glob[i], 0, NULL, &g))
81                         continue;
82                 for (j = 0; j < g.gl_pathc; j++) {
83                         ports = g_slist_append(ports, g_strdup(g.gl_pathv[j]));
84                         sr_dbg("Found serial port '%s'.", g.gl_pathv[j]);
85                 }
86                 globfree(&g);
87         }
88 #endif
89
90         return ports;
91 }
92
93 /**
94  * Open the specified serial port.
95  *
96  * @param pathname OS-specific serial port specification. Examples:
97  *                 "/dev/ttyUSB0", "/dev/ttyACM1", "/dev/tty.Modem-0", "COM1".
98  * @param flags Flags to use when opening the serial port.
99  *
100  * @return 0 upon success, -1 upon failure.
101  */
102 SR_PRIV int serial_open(const char *pathname, int flags)
103 {
104         /* TODO: Abstract 'flags', currently they're OS-specific! */
105
106         sr_dbg("Opening serial port '%s' (flags = %d).", pathname, flags);
107
108 #ifdef _WIN32
109         pathname = "COM1"; /* FIXME: Don't hardcode COM1. */
110
111         hdl = CreateFile(pathname, GENERIC_READ | GENERIC_WRITE, 0, 0,
112                          OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
113         if (hdl == INVALID_HANDLE_VALUE) {
114                 sr_err("Error opening serial port '%s'.", pathname);
115                 return -1;
116         }
117         return 0;
118 #else
119         int fd;
120
121         if ((fd = open(pathname, flags)) < 0) {
122                 /*
123                  * Should be sr_err(), but since some drivers try to open all
124                  * ports on a system and see if they succeed, this would
125                  * yield ugly output for e.g. "sigrok-cli -D".
126                  */
127                 sr_dbg("Error opening serial port '%s': %s.", pathname,
128                        strerror(errno));
129         }
130
131         return fd;
132 #endif
133 }
134
135 /**
136  * Close the specified serial port.
137  *
138  * @param fd File descriptor of the serial port.
139  *
140  * @return 0 upon success, -1 upon failure.
141  */
142 SR_PRIV int serial_close(int fd)
143 {
144         sr_dbg("FD %d: Closing serial port.", fd);
145
146 #ifdef _WIN32
147         /* Returns non-zero upon success, 0 upon failure. */
148         return (CloseHandle(hdl) == 0) ? -1 : 0;
149 #else
150         int ret;
151
152         /* Returns 0 upon success, -1 upon failure. */
153         if ((ret = close(fd)) < 0) {
154                 sr_dbg("FD %d: Error closing serial port: %s.",
155                        fd, strerror(errno));
156         }
157
158         return ret;
159 #endif
160 }
161
162 /**
163  * Flush serial port buffers (if any).
164  *
165  * @param fd File descriptor of the serial port.
166  *
167  * @return 0 upon success, -1 upon failure.
168  */
169 SR_PRIV int serial_flush(int fd)
170 {
171         sr_dbg("FD %d: Flushing serial port.", fd);
172
173 #ifdef _WIN32
174         /* Returns non-zero upon success, 0 upon failure. */
175         return (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) ? -1 : 0;
176 #else
177         int ret;
178
179         /* Returns 0 upon success, -1 upon failure. */
180         if ((ret = tcflush(fd, TCIOFLUSH)) < 0)
181                 sr_err("Error flushing serial port: %s.", strerror(errno));
182
183         return ret;
184 #endif
185 }
186
187 /**
188  * Write a number of bytes to the specified serial port.
189  *
190  * @param fd File descriptor of the serial port.
191  * @param buf Buffer containing the bytes to write.
192  * @param count Number of bytes to write.
193  *
194  * @return The number of bytes written, or -1 upon failure.
195  */
196 SR_PRIV int serial_write(int fd, const void *buf, size_t count)
197 {
198         sr_spew("FD %d: Writing %d bytes.", fd, count);
199
200 #ifdef _WIN32
201         DWORD tmp = 0;
202
203         /* FIXME */
204         /* Returns non-zero upon success, 0 upon failure. */
205         WriteFile(hdl, buf, count, &tmp, NULL);
206 #else
207         ssize_t ret;
208
209         /* Returns the number of bytes written, or -1 upon failure. */
210         ret = write(fd, buf, count);
211         if (ret < 0)
212                 sr_err("FD %d: Write error: %s.", fd, strerror(errno));
213         else if ((size_t)ret != count)
214                 sr_spew("FD %d: Only wrote %d/%d bytes.", fd, ret, count);
215
216         return ret;
217 #endif
218 }
219
220 /**
221  * Read a number of bytes from the specified serial port.
222  *
223  * @param fd File descriptor of the serial port.
224  * @param buf Buffer where to store the bytes that are read.
225  * @param count The number of bytes to read.
226  *
227  * @return The number of bytes read, or -1 upon failure.
228  */
229 SR_PRIV int serial_read(int fd, void *buf, size_t count)
230 {
231         sr_spew("FD %d: Reading %d bytes.", fd, count);
232
233 #ifdef _WIN32
234         DWORD tmp = 0;
235
236         /* FIXME */
237         /* Returns non-zero upon success, 0 upon failure. */
238         return ReadFile(hdl, buf, count, &tmp, NULL);
239 #else
240         ssize_t ret;
241
242         /* Returns the number of bytes read, or -1 upon failure. */
243         ret = read(fd, buf, count);
244         if (ret < 0) {
245                 /*
246                  * Should be sr_err(), but that would yield lots of
247                  * "Resource temporarily unavailable" messages.
248                  */
249                 sr_spew("FD %d: Read error: %s.", fd, strerror(errno));
250         } else if ((size_t)ret != count) {
251                 sr_spew("FD %d: Only read %d/%d bytes.", fd, ret, count);
252         }
253
254         return ret;
255 #endif
256 }
257
258 /**
259  * Create a backup of the current parameters of the specified serial port.
260  *
261  * @param fd File descriptor of the serial port.
262  *
263  * @return Pointer to a struct termios upon success, NULL upon errors.
264  *         It is the caller's responsibility to g_free() the pointer if no
265  *         longer needed.
266  */
267 SR_PRIV void *serial_backup_params(int fd)
268 {
269         sr_dbg("FD %d: Creating serial parameters backup.", fd);
270
271 #ifdef _WIN32
272         /* TODO */
273 #else
274         struct termios *term;
275
276         if (!(term = g_try_malloc(sizeof(struct termios)))) {
277                 sr_err("termios struct malloc failed.");
278                 return NULL;
279         }
280
281         /* Returns 0 upon success, -1 upon failure. */
282         if (tcgetattr(fd, term) < 0) {
283                 sr_err("FD %d: Error getting serial parameters: %s.",
284                        fd, strerror(errno));
285                 g_free(term);
286                 return NULL;
287         }
288
289         return term;
290 #endif
291 }
292
293 /**
294  * Restore serial port settings from a previously created backup.
295  *
296  * @param fd File descriptor of the serial port.
297  * @param backup Pointer to a struct termios which contains the settings
298  *               to restore.
299  *
300  * @return 0 upon success, -1 upon failure.
301  */
302 SR_PRIV int serial_restore_params(int fd, void *backup)
303 {
304         sr_dbg("FD %d: Restoring serial parameters from backup.", fd);
305
306         if (!backup) {
307                 sr_err("FD %d: Cannot restore serial params (NULL).", fd);
308                 return -1;
309         }
310
311 #ifdef _WIN32
312         /* TODO */
313 #else
314         int ret;
315
316         /* Returns 0 upon success, -1 upon failure. */
317         if ((ret = tcsetattr(fd, TCSADRAIN, (struct termios *)backup)) < 0) {
318                 sr_err("FD %d: Error restoring serial parameters: %s.",
319                        fd, strerror(errno));
320         }
321
322         return ret;
323 #endif
324 }
325
326 /**
327  * Set serial parameters for the specified serial port.
328  *
329  * @param baudrate The baudrate to set.
330  * @param bits The number of data bits to use.
331  * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
332  * @param stopbits The number of stop bits to use (1 or 2).
333  * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
334  *                    2 = XON/XOFF).
335  *
336  * @return SR_OK upon success, SR_ERR upon failure.
337  */
338 SR_PRIV int serial_set_params(int fd, int baudrate, int bits, int parity,
339                               int stopbits, int flowcontrol)
340 {
341         sr_dbg("FD %d: Setting serial parameters.", fd);
342
343 #ifdef _WIN32
344         DCB dcb;
345
346         if (!GetCommState(hdl, &dcb)) {
347                 /* TODO: Error handling. */
348                 return SR_ERR;
349         }
350
351         switch (baudrate) {
352         /* TODO: Support for higher baud rates. */
353         case 115200:
354                 dcb.BaudRate = CBR_115200;
355                 break;
356         case 57600:
357                 dcb.BaudRate = CBR_57600;
358                 break;
359         case 38400:
360                 dcb.BaudRate = CBR_38400;
361                 break;
362         case 19200:
363                 dcb.BaudRate = CBR_19200;
364                 break;
365         case 9600:
366                 dcb.BaudRate = CBR_9600;
367                 break;
368         case 4800:
369                 dcb.BaudRate = CBR_4800;
370                 break;
371         case 2400:
372                 dcb.BaudRate = CBR_2400;
373                 break;
374         default:
375                 sr_err("Unsupported baudrate: %d.", baudrate);
376                 return SR_ERR;
377         }
378         dcb.ByteSize = bits;
379         dcb.Parity = NOPARITY; /* TODO: Don't hardcode. */
380         dcb.StopBits = ONESTOPBIT; /* TODO: Don't hardcode. */
381
382         if (!SetCommState(hdl, &dcb)) {
383                 /* TODO: Error handling. */
384                 return SR_ERR;
385         }
386 #else
387         struct termios term;
388         speed_t baud;
389
390         sr_dbg("FD %d: Getting terminal settings.", fd);
391         if (tcgetattr(fd, &term) < 0) {
392                 sr_err("tcgetattr() error: %s.", strerror(errno));
393                 return SR_ERR;
394         }
395
396         switch (baudrate) {
397         case 50:
398                 baud = B50;
399                 break;
400         case 75:
401                 baud = B75;
402                 break;
403         case 110:
404                 baud = B110;
405                 break;
406         case 134:
407                 baud = B134;
408                 break;
409         case 150:
410                 baud = B150;
411                 break;
412         case 200:
413                 baud = B200;
414                 break;
415         case 300:
416                 baud = B300;
417                 break;
418         case 600:
419                 baud = B600;
420                 break;
421         case 1200:
422                 baud = B1200;
423                 break;
424         case 1800:
425                 baud = B1800;
426                 break;
427         case 2400:
428                 baud = B2400;
429                 break;
430         case 4800:
431                 baud = B4800;
432                 break;
433         case 9600:
434                 baud = B9600;
435                 break;
436         case 19200:
437                 baud = B19200;
438                 break;
439         case 38400:
440                 baud = B38400;
441                 break;
442         case 57600:
443                 baud = B57600;
444                 break;
445         case 115200:
446                 baud = B115200;
447                 break;
448         case 230400:
449                 baud = B230400;
450                 break;
451 #ifndef __APPLE__
452         case 460800:
453                 baud = B460800;
454                 break;
455 #endif
456         default:
457                 sr_err("Unsupported baudrate: %d.", baudrate);
458                 return SR_ERR;
459         }
460
461         sr_dbg("FD %d: Configuring output baudrate to %d (%d).",
462                 fd, baudrate, baud);
463         if (cfsetospeed(&term, baud) < 0) {
464                 sr_err("cfsetospeed() error: %ѕ.", strerror(errno));
465                 return SR_ERR;
466         }
467
468         sr_dbg("FD %d: Configuring input baudrate to %d (%d).",
469                 fd, baudrate, baud);
470         if (cfsetispeed(&term, baud) < 0) {
471                 sr_err("cfsetispeed() error: %ѕ.", strerror(errno));
472                 return SR_ERR;
473         }
474
475         sr_dbg("FD %d: Configuring %d data bits.", fd, bits);
476         term.c_cflag &= ~CSIZE;
477         switch (bits) {
478         case 8:
479                 term.c_cflag |= CS8;
480                 break;
481         case 7:
482                 term.c_cflag |= CS7;
483                 break;
484         default:
485                 sr_err("Unsupported data bits number: %d.", bits);
486                 return SR_ERR;
487         }
488
489         sr_dbg("FD %d: Configuring %d stop bits.", fd, stopbits);
490         term.c_cflag &= ~CSTOPB;
491         switch (stopbits) {
492         case 1:
493                 /* Do nothing, a cleared CSTOPB entry means "1 stop bit". */
494                 break;
495         case 2:
496                 term.c_cflag |= CSTOPB;
497                 break;
498         default:
499                 sr_err("Unsupported stopbits number: %d.", stopbits);
500                 return SR_ERR;
501         }
502
503         term.c_iflag &= ~(IXON | IXOFF);
504         term.c_cflag &= ~CRTSCTS;
505         switch (flowcontrol) {
506         case 0:
507                 /* No flow control. */
508                 sr_dbg("FD %d: Configuring no flow control.", fd);
509                 break;
510         case 1:
511                 sr_dbg("FD %d: Configuring RTS/CTS flow control.", fd);
512                 term.c_cflag |= CRTSCTS;
513                 break;
514         case 2:
515                 sr_dbg("FD %d: Configuring XON/XOFF flow control.", fd);
516                 term.c_iflag |= IXON | IXOFF;
517                 break;
518         default:
519                 sr_err("Unsupported flow control setting: %d.", flowcontrol);
520                 return SR_ERR;
521         }
522
523         term.c_iflag &= ~IGNPAR;
524         term.c_cflag &= ~(PARODD | PARENB);
525         switch (parity) {
526         case SERIAL_PARITY_NONE:
527                 sr_dbg("FD %d: Configuring no parity.", fd);
528                 term.c_iflag |= IGNPAR;
529                 break;
530         case SERIAL_PARITY_EVEN:
531                 sr_dbg("FD %d: Configuring even parity.", fd);
532                 term.c_cflag |= PARENB;
533                 break;
534         case SERIAL_PARITY_ODD:
535                 sr_dbg("FD %d: Configuring odd parity.", fd);
536                 term.c_cflag |= PARENB | PARODD;
537                 break;
538         default:
539                 sr_err("Unsupported parity setting: %d.", parity);
540                 return SR_ERR;
541         }
542
543         /* Do NOT translate carriage return to newline on input. */
544         term.c_iflag &= ~(ICRNL);
545
546         /* Disable canonical mode, and don't echo input characters. */
547         term.c_lflag &= ~(ICANON | ECHO);
548
549         /* Write the configured settings. */
550         if (tcsetattr(fd, TCSADRAIN, &term) < 0) {
551                 sr_err("tcsetattr() error: %ѕ.", strerror(errno));
552                 return SR_ERR;
553         }
554 #endif
555
556         return SR_OK;
557 }
558
559 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])$"
560 SR_PRIV int serial_set_paramstr(int fd, const char *paramstr)
561 {
562         GRegex *reg;
563         GMatchInfo *match;
564         int speed, databits, parity, stopbits;
565         char *mstr;
566
567         speed = databits = parity = stopbits = 0;
568         reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
569         if (g_regex_match(reg, paramstr, 0, &match)) {
570                 if ((mstr = g_match_info_fetch(match, 1)))
571                         speed = strtoul(mstr, NULL, 10);
572                 g_free(mstr);
573                 if ((mstr = g_match_info_fetch(match, 2)))
574                         databits = strtoul(mstr, NULL, 10);
575                 g_free(mstr);
576                 if ((mstr = g_match_info_fetch(match, 3))) {
577                         switch (mstr[0]) {
578                         case 'n':
579                                 parity = SERIAL_PARITY_NONE;
580                                 break;
581                         case 'e':
582                                 parity = SERIAL_PARITY_EVEN;
583                                 break;
584                         case 'o':
585                                 parity = SERIAL_PARITY_ODD;
586                                 break;
587                         }
588                 }
589                 g_free(mstr);
590                 if ((mstr = g_match_info_fetch(match, 4)))
591                         stopbits = strtoul(mstr, NULL, 10);
592                 g_free(mstr);
593         }
594         g_match_info_unref(match);
595         g_regex_unref(reg);
596
597         if (speed)
598                 return serial_set_params(fd, speed, databits, parity, stopbits, 0);
599         else
600                 return SR_ERR_ARG;
601 }
602
603 SR_PRIV int serial_readline(int fd, char **buf, int *buflen,
604                             uint64_t timeout_ms)
605 {
606         uint64_t start;
607         int maxlen, len;
608
609         timeout_ms *= 1000;
610         start = g_get_monotonic_time();
611
612         maxlen = *buflen;
613         *buflen = len = 0;
614         while(1) {
615                 len = maxlen - *buflen - 1;
616                 if (len < 1)
617                         break;
618                 len = serial_read(fd, *buf + *buflen, 1);
619                 if (len > 0) {
620                         *buflen += len;
621                         *(*buf + *buflen) = '\0';
622                         if (*buflen > 0 && *(*buf + *buflen - 1) == '\r') {
623                                 /* Strip LF and terminate. */
624                                 *(*buf + --*buflen) = '\0';
625                                 break;
626                         }
627                 }
628                 if (g_get_monotonic_time() - start > timeout_ms)
629                         /* Timeout */
630                         break;
631                 g_usleep(2000);
632         }
633         sr_dbg("Received %d: '%s'.", *buflen, *buf);
634
635         return SR_OK;
636 }