2 * This file is part of the sigrok project.
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
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.
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.
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/>.
22 #include <sys/types.h>
35 #include "libsigrok.h"
36 #include "libsigrok-internal.h"
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)
47 // FIXME: Must be moved, or rather passed as function argument.
52 static const char *serial_port_glob[] = {
64 SR_PRIV GSList *list_serial_ports(void)
68 sr_dbg("Getting list of serial ports on the system.");
73 ports = g_slist_append(ports, g_strdup("COM1"));
79 for (i = 0; serial_port_glob[i]; i++) {
80 if (glob(serial_port_glob[i], 0, NULL, &g))
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]);
94 * Open the specified serial port.
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.
100 * @return 0 upon success, -1 upon failure.
102 SR_PRIV int serial_open(const char *pathname, int flags)
104 /* TODO: Abstract 'flags', currently they're OS-specific! */
106 sr_dbg("Opening serial port '%s' (flags = %d).", pathname, flags);
109 pathname = "COM1"; /* FIXME: Don't hardcode COM1. */
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);
121 if ((fd = open(pathname, flags)) < 0) {
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".
127 sr_dbg("Error opening serial port '%s': %s.", pathname,
130 sr_dbg("Opened serial port '%s' as FD %d.", pathname, fd);
138 * Close the specified serial port.
140 * @param fd File descriptor of the serial port.
142 * @return 0 upon success, -1 upon failure.
144 SR_PRIV int serial_close(int fd)
146 sr_dbg("FD %d: Closing serial port.", fd);
149 /* Returns non-zero upon success, 0 upon failure. */
150 return (CloseHandle(hdl) == 0) ? -1 : 0;
154 /* Returns 0 upon success, -1 upon failure. */
155 if ((ret = close(fd)) < 0) {
156 sr_dbg("FD %d: Error closing serial port: %s.",
157 fd, strerror(errno));
165 * Flush serial port buffers (if any).
167 * @param fd File descriptor of the serial port.
169 * @return 0 upon success, -1 upon failure.
171 SR_PRIV int serial_flush(int fd)
173 sr_dbg("FD %d: Flushing serial port.", fd);
176 /* Returns non-zero upon success, 0 upon failure. */
177 return (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) ? -1 : 0;
181 /* Returns 0 upon success, -1 upon failure. */
182 if ((ret = tcflush(fd, TCIOFLUSH)) < 0)
183 sr_err("Error flushing serial port: %s.", strerror(errno));
190 * Write a number of bytes to the specified serial port.
192 * @param fd File descriptor of the serial port.
193 * @param buf Buffer containing the bytes to write.
194 * @param count Number of bytes to write.
196 * @return The number of bytes written, or -1 upon failure.
198 SR_PRIV int serial_write(int fd, const void *buf, size_t count)
200 sr_spew("FD %d: Writing %d bytes.", fd, count);
206 /* Returns non-zero upon success, 0 upon failure. */
207 WriteFile(hdl, buf, count, &tmp, NULL);
211 /* Returns the number of bytes written, or -1 upon failure. */
212 ret = write(fd, buf, count);
214 sr_err("FD %d: Write error: %s.", fd, strerror(errno));
215 else if ((size_t)ret != count)
216 sr_spew("FD %d: Only wrote %d/%d bytes.", fd, ret, count);
223 * Read a number of bytes from the specified serial port.
225 * @param fd File descriptor of the serial port.
226 * @param buf Buffer where to store the bytes that are read.
227 * @param count The number of bytes to read.
229 * @return The number of bytes read, or -1 upon failure.
231 SR_PRIV int serial_read(int fd, void *buf, size_t count)
233 sr_spew("FD %d: Reading %d bytes.", fd, count);
239 /* Returns non-zero upon success, 0 upon failure. */
240 return ReadFile(hdl, buf, count, &tmp, NULL);
244 /* Returns the number of bytes read, or -1 upon failure. */
245 ret = read(fd, buf, count);
248 * Should be sr_err(), but that would yield lots of
249 * "Resource temporarily unavailable" messages.
251 sr_spew("FD %d: Read error: %s.", fd, strerror(errno));
252 } else if ((size_t)ret != count) {
253 sr_spew("FD %d: Only read %d/%d bytes.", fd, ret, count);
261 * Create a backup of the current parameters of the specified serial port.
263 * @param fd File descriptor of the serial port.
265 * @return Pointer to a struct termios upon success, NULL upon errors.
266 * It is the caller's responsibility to g_free() the pointer if no
269 SR_PRIV void *serial_backup_params(int fd)
271 sr_dbg("FD %d: Creating serial parameters backup.", fd);
276 struct termios *term;
278 if (!(term = g_try_malloc(sizeof(struct termios)))) {
279 sr_err("termios struct malloc failed.");
283 /* Returns 0 upon success, -1 upon failure. */
284 if (tcgetattr(fd, term) < 0) {
285 sr_err("FD %d: Error getting serial parameters: %s.",
286 fd, strerror(errno));
296 * Restore serial port settings from a previously created backup.
298 * @param fd File descriptor of the serial port.
299 * @param backup Pointer to a struct termios which contains the settings
302 * @return 0 upon success, -1 upon failure.
304 SR_PRIV int serial_restore_params(int fd, void *backup)
306 sr_dbg("FD %d: Restoring serial parameters from backup.", fd);
309 sr_err("FD %d: Cannot restore serial params (NULL).", fd);
318 /* Returns 0 upon success, -1 upon failure. */
319 if ((ret = tcsetattr(fd, TCSADRAIN, (struct termios *)backup)) < 0) {
320 sr_err("FD %d: Error restoring serial parameters: %s.",
321 fd, strerror(errno));
329 * Set serial parameters for the specified serial port.
331 * @param baudrate The baudrate to set.
332 * @param bits The number of data bits to use.
333 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
334 * @param stopbits The number of stop bits to use (1 or 2).
335 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
338 * @return SR_OK upon success, SR_ERR upon failure.
340 SR_PRIV int serial_set_params(int fd, int baudrate, int bits, int parity,
341 int stopbits, int flowcontrol)
343 sr_dbg("FD %d: Setting serial parameters.", fd);
348 if (!GetCommState(hdl, &dcb)) {
349 /* TODO: Error handling. */
354 /* TODO: Support for higher baud rates. */
356 dcb.BaudRate = CBR_115200;
359 dcb.BaudRate = CBR_57600;
362 dcb.BaudRate = CBR_38400;
365 dcb.BaudRate = CBR_19200;
368 dcb.BaudRate = CBR_9600;
371 dcb.BaudRate = CBR_4800;
374 dcb.BaudRate = CBR_2400;
377 sr_err("Unsupported baudrate: %d.", baudrate);
381 dcb.Parity = NOPARITY; /* TODO: Don't hardcode. */
382 dcb.StopBits = ONESTOPBIT; /* TODO: Don't hardcode. */
384 if (!SetCommState(hdl, &dcb)) {
385 /* TODO: Error handling. */
392 sr_dbg("FD %d: Getting terminal settings.", fd);
393 if (tcgetattr(fd, &term) < 0) {
394 sr_err("tcgetattr() error: %s.", strerror(errno));
459 sr_err("Unsupported baudrate: %d.", baudrate);
463 sr_dbg("FD %d: Configuring output baudrate to %d (%d).",
465 if (cfsetospeed(&term, baud) < 0) {
466 sr_err("cfsetospeed() error: %ѕ.", strerror(errno));
470 sr_dbg("FD %d: Configuring input baudrate to %d (%d).",
472 if (cfsetispeed(&term, baud) < 0) {
473 sr_err("cfsetispeed() error: %ѕ.", strerror(errno));
477 sr_dbg("FD %d: Configuring %d data bits.", fd, bits);
478 term.c_cflag &= ~CSIZE;
487 sr_err("Unsupported data bits number: %d.", bits);
491 sr_dbg("FD %d: Configuring %d stop bits.", fd, stopbits);
492 term.c_cflag &= ~CSTOPB;
495 /* Do nothing, a cleared CSTOPB entry means "1 stop bit". */
498 term.c_cflag |= CSTOPB;
501 sr_err("Unsupported stopbits number: %d.", stopbits);
505 term.c_iflag &= ~(IXON | IXOFF);
506 term.c_cflag &= ~CRTSCTS;
507 switch (flowcontrol) {
509 /* No flow control. */
510 sr_dbg("FD %d: Configuring no flow control.", fd);
513 sr_dbg("FD %d: Configuring RTS/CTS flow control.", fd);
514 term.c_cflag |= CRTSCTS;
517 sr_dbg("FD %d: Configuring XON/XOFF flow control.", fd);
518 term.c_iflag |= IXON | IXOFF;
521 sr_err("Unsupported flow control setting: %d.", flowcontrol);
525 term.c_iflag &= ~IGNPAR;
526 term.c_cflag &= ~(PARODD | PARENB);
528 case SERIAL_PARITY_NONE:
529 sr_dbg("FD %d: Configuring no parity.", fd);
530 term.c_iflag |= IGNPAR;
532 case SERIAL_PARITY_EVEN:
533 sr_dbg("FD %d: Configuring even parity.", fd);
534 term.c_cflag |= PARENB;
536 case SERIAL_PARITY_ODD:
537 sr_dbg("FD %d: Configuring odd parity.", fd);
538 term.c_cflag |= PARENB | PARODD;
541 sr_err("Unsupported parity setting: %d.", parity);
545 /* Do NOT translate carriage return to newline on input. */
546 term.c_iflag &= ~(ICRNL);
548 /* Disable canonical mode, and don't echo input characters. */
549 term.c_lflag &= ~(ICANON | ECHO);
551 /* Write the configured settings. */
552 if (tcsetattr(fd, TCSADRAIN, &term) < 0) {
553 sr_err("tcsetattr() error: %ѕ.", strerror(errno));
561 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])$"
562 SR_PRIV int serial_set_paramstr(int fd, const char *paramstr)
566 int speed, databits, parity, stopbits;
569 speed = databits = parity = stopbits = 0;
570 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
571 if (g_regex_match(reg, paramstr, 0, &match)) {
572 if ((mstr = g_match_info_fetch(match, 1)))
573 speed = strtoul(mstr, NULL, 10);
575 if ((mstr = g_match_info_fetch(match, 2)))
576 databits = strtoul(mstr, NULL, 10);
578 if ((mstr = g_match_info_fetch(match, 3))) {
581 parity = SERIAL_PARITY_NONE;
584 parity = SERIAL_PARITY_EVEN;
587 parity = SERIAL_PARITY_ODD;
592 if ((mstr = g_match_info_fetch(match, 4)))
593 stopbits = strtoul(mstr, NULL, 10);
596 g_match_info_unref(match);
600 return serial_set_params(fd, speed, databits, parity, stopbits, 0);
605 SR_PRIV int serial_readline(int fd, char **buf, int *buflen,
612 start = g_get_monotonic_time();
617 len = maxlen - *buflen - 1;
620 len = serial_read(fd, *buf + *buflen, 1);
623 *(*buf + *buflen) = '\0';
624 if (*buflen > 0 && *(*buf + *buflen - 1) == '\r') {
625 /* Strip LF and terminate. */
626 *(*buf + --*buflen) = '\0';
630 if (g_get_monotonic_time() - start > timeout_ms)
635 sr_dbg("Received %d: '%s'.", *buflen, *buf);