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>
6 * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include <sys/types.h>
32 #include <sys/ioctl.h>
37 #include "libsigrok.h"
38 #include "libsigrok-internal.h"
40 /* Message logging helpers with driver-specific prefix string. */
41 #define DRIVER_LOG_DOMAIN "serial: "
42 #define sr_log(l, s, args...) sr_log(l, DRIVER_LOG_DOMAIN s, ## args)
43 #define sr_spew(s, args...) sr_spew(DRIVER_LOG_DOMAIN s, ## args)
44 #define sr_dbg(s, args...) sr_dbg(DRIVER_LOG_DOMAIN s, ## args)
45 #define sr_info(s, args...) sr_info(DRIVER_LOG_DOMAIN s, ## args)
46 #define sr_warn(s, args...) sr_warn(DRIVER_LOG_DOMAIN s, ## args)
47 #define sr_err(s, args...) sr_err(DRIVER_LOG_DOMAIN s, ## args)
49 // FIXME: Must be moved, or rather passed as function argument.
55 * Open the specified serial port.
57 * @param serial Previously initialized serial port structure.
58 * @param flags Flags to use when opening the serial port.
59 * TODO: Abstract 'flags', currently they're OS-specific!
61 * If the serial structure contains a serialcomm string, it will be
62 * passed to serial_set_paramstr() after the port is opened.
64 * @return SR_OK on success, SR_ERR on failure.
66 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
70 sr_dbg("Invalid serial port.");
74 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
77 hdl = CreateFile(serial->port, GENERIC_READ | GENERIC_WRITE, 0, 0,
78 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
79 if (hdl == INVALID_HANDLE_VALUE) {
80 sr_err("Error opening serial port '%s'.", serial->port);
84 if ((serial->fd = open(serial->port, flags)) < 0) {
85 sr_err("Error opening serial port '%s': %s.", serial->port,
89 sr_spew("Opened serial port '%s' (fd %d).", serial->port, serial->fd);
92 if (serial->serialcomm)
93 return serial_set_paramstr(serial, serial->serialcomm);
99 * Close the specified serial port.
101 * @param serial Previously initialized serial port structure.
103 * @return SR_OK on success, SR_ERR on failure.
105 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
110 sr_dbg("Invalid serial port.");
114 if (serial->fd == -1) {
115 sr_dbg("Cannot close unopened serial port %s (fd %d).",
116 serial->port, serial->fd);
120 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
124 /* Returns non-zero upon success, 0 upon failure. */
125 if (CloseHandle(hdl) == 0)
128 /* Returns 0 upon success, -1 upon failure. */
129 if (close(serial->fd) < 0) {
130 sr_err("Error closing serial port: %s (fd %d).", strerror(errno),
142 * Flush serial port buffers.
144 * @param serial Previously initialized serial port structure.
146 * @return SR_OK on success, SR_ERR on failure.
148 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
153 sr_dbg("Invalid serial port.");
157 if (serial->fd == -1) {
158 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
159 serial->port, serial->fd);
163 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
167 /* Returns non-zero upon success, 0 upon failure. */
168 if (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) {
169 sr_err("Error flushing serial port: %s.", strerror(errno));
173 /* Returns 0 upon success, -1 upon failure. */
174 if (tcflush(serial->fd, TCIOFLUSH) < 0) {
175 sr_err("Error flushing serial port: %s.", strerror(errno));
184 * Write a number of bytes to the specified serial port.
186 * @param serial Previously initialized serial port structure.
187 * @param buf Buffer containing the bytes to write.
188 * @param count Number of bytes to write.
190 * @return The number of bytes written, or -1 upon failure.
192 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
193 const void *buf, size_t count)
198 sr_dbg("Invalid serial port.");
202 if (serial->fd == -1) {
203 sr_dbg("Cannot use unopened serial port %s (fd %d).",
204 serial->port, serial->fd);
212 /* Returns non-zero upon success, 0 upon failure. */
213 WriteFile(hdl, buf, count, &tmp, NULL);
215 /* Returns the number of bytes written, or -1 upon failure. */
216 ret = write(serial->fd, buf, count);
218 sr_err("Write error: %s.", strerror(errno));
220 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
227 * Read a number of bytes from the specified serial port.
229 * @param serial Previously initialized serial port structure.
230 * @param buf Buffer where to store the bytes that are read.
231 * @param count The number of bytes to read.
233 * @return The number of bytes read, or -1 upon failure.
235 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
241 sr_dbg("Invalid serial port.");
245 if (serial->fd == -1) {
246 sr_dbg("Cannot use unopened serial port %s (fd %d).",
247 serial->port, serial->fd);
255 /* Returns non-zero upon success, 0 upon failure. */
256 return ReadFile(hdl, buf, count, &tmp, NULL);
258 /* Returns the number of bytes read, or -1 upon failure. */
259 ret = read(serial->fd, buf, count);
262 * Should be sr_err(), but that would yield lots of
263 * "Resource temporarily unavailable" messages.
265 sr_spew("Read error: %s (fd %d).", strerror(errno), serial->fd);
267 sr_spew("Read %d/%d bytes (fd %d).", ret, count, serial->fd);
274 * Set serial parameters for the specified serial port.
276 * @param serial Previously initialized serial port structure.
277 * @param baudrate The baudrate to set.
278 * @param bits The number of data bits to use.
279 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
280 * @param stopbits The number of stop bits to use (1 or 2).
281 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
284 * @return SR_OK upon success, SR_ERR upon failure.
286 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
287 int bits, int parity, int stopbits, int flowcontrol, int rts, int dtr)
290 sr_dbg("Invalid serial port.");
294 if (serial->fd == -1) {
295 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
296 serial->port, serial->fd);
300 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
306 if (!GetCommState(hdl, &dcb))
311 dcb.BaudRate = CBR_115200;
314 dcb.BaudRate = CBR_57600;
317 dcb.BaudRate = CBR_38400;
320 dcb.BaudRate = CBR_19200;
323 dcb.BaudRate = CBR_9600;
326 dcb.BaudRate = CBR_4800;
329 dcb.BaudRate = CBR_2400;
332 sr_err("Unsupported baudrate %d.", baudrate);
336 dcb.Parity = NOPARITY; /* TODO: Don't hardcode. */
337 dcb.StopBits = ONESTOPBIT; /* TODO: Don't hardcode. */
339 if (!SetCommState(hdl, &dcb))
344 int ret, controlbits;
346 if (tcgetattr(serial->fd, &term) < 0) {
347 sr_err("tcgetattr() error on port %s (fd %d): %s.",
348 serial->port, serial->fd, strerror(errno));
413 sr_err("Unsupported baudrate %d.", baudrate);
417 sr_spew("Configuring output baudrate to %d (%d).", baudrate, baud);
418 if (cfsetospeed(&term, baud) < 0) {
419 sr_err("cfsetospeed() error: %s.", strerror(errno));
423 sr_spew("Configuring input baudrate to %d (%d).", baudrate, baud);
424 if (cfsetispeed(&term, baud) < 0) {
425 sr_err("cfsetispeed() error: %s.", strerror(errno));
429 sr_spew("Configuring %d data bits.", bits);
430 term.c_cflag &= ~CSIZE;
439 sr_err("Unsupported data bits number %d.", bits);
443 sr_spew("Configuring %d stop bits.", stopbits);
444 term.c_cflag &= ~CSTOPB;
447 term.c_cflag &= ~CSTOPB;
450 term.c_cflag |= CSTOPB;
453 sr_err("Unsupported stopbits number %d.", stopbits);
457 term.c_iflag &= ~(IXON | IXOFF);
458 term.c_cflag &= ~CRTSCTS;
459 switch (flowcontrol) {
461 /* No flow control. */
462 sr_spew("Configuring no flow control.");
465 sr_spew("Configuring RTS/CTS flow control.");
466 term.c_cflag |= CRTSCTS;
469 sr_spew("Configuring XON/XOFF flow control.");
470 term.c_iflag |= IXON | IXOFF;
473 sr_err("Unsupported flow control setting %d.", flowcontrol);
477 term.c_iflag &= ~IGNPAR;
478 term.c_cflag &= ~(PARODD | PARENB);
480 case SERIAL_PARITY_NONE:
481 sr_spew("Configuring no parity.");
482 term.c_iflag |= IGNPAR;
484 case SERIAL_PARITY_EVEN:
485 sr_spew("Configuring even parity.");
486 term.c_cflag |= PARENB;
488 case SERIAL_PARITY_ODD:
489 sr_spew("Configuring odd parity.");
490 term.c_cflag |= PARENB | PARODD;
493 sr_err("Unsupported parity setting %d.", parity);
497 /* Do not translate carriage return to newline on input. */
498 term.c_iflag &= ~(ICRNL);
500 /* Disable canonical mode, and don't echo input characters. */
501 term.c_lflag &= ~(ICANON | ECHO);
503 /* Write the configured settings. */
504 if (tcsetattr(serial->fd, TCSADRAIN, &term) < 0) {
505 sr_err("tcsetattr() error: %s.", strerror(errno));
510 sr_spew("Setting RTS %s.", rts ? "high" : "low");
511 controlbits = TIOCM_RTS;
512 if ((ret = ioctl(serial->fd, rts ? TIOCMBIS : TIOCMBIC,
513 &controlbits)) < 0) {
514 sr_err("Error setting RTS: %s.", strerror(errno));
520 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
521 controlbits = TIOCM_DTR;
522 if ((ret = ioctl(serial->fd, dtr ? TIOCMBIS : TIOCMBIC,
523 &controlbits)) < 0) {
524 sr_err("Error setting DTR: %s.", strerror(errno));
535 * Set serial parameters for the specified serial port.
537 * @param serial Previously initialized serial port structure.
538 * @param paramstr A serial communication parameters string, in the form
539 * of <speed>/<data bits><parity><stopbits>, for example "9600/8n1" or
542 * @return SR_OK upon success, SR_ERR upon failure.
544 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
545 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
546 const char *paramstr)
550 int speed, databits, parity, stopbits, rts, dtr, i;
551 char *mstr, **opts, **kv;
553 speed = databits = parity = stopbits = 0;
555 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
556 if (g_regex_match(reg, paramstr, 0, &match)) {
557 if ((mstr = g_match_info_fetch(match, 1)))
558 speed = strtoul(mstr, NULL, 10);
560 if ((mstr = g_match_info_fetch(match, 2)))
561 databits = strtoul(mstr, NULL, 10);
563 if ((mstr = g_match_info_fetch(match, 3))) {
566 parity = SERIAL_PARITY_NONE;
569 parity = SERIAL_PARITY_EVEN;
572 parity = SERIAL_PARITY_ODD;
577 if ((mstr = g_match_info_fetch(match, 4)))
578 stopbits = strtoul(mstr, NULL, 10);
580 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
581 if (mstr[0] != '/') {
582 sr_dbg("missing separator before extra options");
585 /* A set of "key=value" options separated by / */
586 opts = g_strsplit(mstr + 1, "/", 0);
587 for (i = 0; opts[i]; i++) {
588 kv = g_strsplit(opts[i], "=", 2);
589 if (!strncmp(kv[0], "rts", 3)) {
592 else if (kv[1][0] == '0')
595 sr_dbg("invalid value for rts: %c", kv[1][0]);
598 } else if (!strncmp(kv[0], "dtr", 3)) {
601 else if (kv[1][0] == '0')
604 sr_dbg("invalid value for dtr: %c", kv[1][0]);
615 g_match_info_unref(match);
619 return serial_set_params(serial, speed, databits, parity, stopbits,
626 * Read a line from the specified serial port.
628 * @param serial Previously initialized serial port structure.
629 * @param buf Buffer where to store the bytes that are read.
630 * @param buflen Size of the buffer.
631 * @param timeout_ms How long to wait for a line to come in.
633 * Reading stops when CR of LR is found, which is stripped from the buffer.
635 * @return SR_OK on success, SR_ERR on failure.
637 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
638 int *buflen, gint64 timeout_ms)
643 if (!serial || serial->fd == -1) {
644 sr_dbg("Invalid serial port.");
648 if (serial->fd == -1) {
649 sr_dbg("Cannot use unopened serial port %s (fd %d).",
650 serial->port, serial->fd);
655 start = g_get_monotonic_time();
660 len = maxlen - *buflen - 1;
663 len = serial_read(serial, *buf + *buflen, 1);
666 *(*buf + *buflen) = '\0';
667 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
668 || *(*buf + *buflen - 1) == '\n')) {
669 /* Strip CR/LF and terminate. */
670 *(*buf + --*buflen) = '\0';
674 if (g_get_monotonic_time() - start > timeout_ms)
680 sr_dbg("Received %d: '%s'.", *buflen, *buf);
686 * Try to find a valid packet in a serial data stream.
688 * @param serial Previously initialized serial port structure.
689 * @param buf Buffer containing the bytes to write.
690 * @param count Size of the buffer.
691 * @param packet_size Size, in bytes, of a valid packet.
692 * @param is_valid Callback that assesses whether the packet is valid or not.
693 * @param timeout_ms The timeout after which, if no packet is detected, to
695 * @param baudrate The baudrate of the serial port. This parameter is not
696 * critical, but it helps fine tune the serial port polling
699 * @return SR_OK if a valid packet is found within the given timeout,
700 * SR_ERR upon failure.
702 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
703 uint8_t *buf, size_t *buflen,
704 size_t packet_size, packet_valid_t is_valid,
705 uint64_t timeout_ms, int baudrate)
707 uint64_t start, time, byte_delay_us;
708 size_t ibuf, i, maxlen;
713 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
714 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
716 if (maxlen < (packet_size / 2) ) {
717 sr_err("Buffer size must be at least twice the packet size.");
721 /* Assume 8n1 transmission. That is 10 bits for every byte. */
722 byte_delay_us = 10 * (1000000 / baudrate);
723 start = g_get_monotonic_time();
726 while (ibuf < maxlen) {
727 len = serial_read(serial, &buf[ibuf], 1);
730 } else if (len == 0) {
731 sr_spew("Error: Only read 0 bytes.");
733 /* Error reading byte, but continuing anyway. */
736 time = g_get_monotonic_time() - start;
739 if ((ibuf - i) >= packet_size) {
740 /* We have at least a packet's worth of data. */
741 if (is_valid(&buf[i])) {
742 sr_spew("Found valid %d-byte packet after "
743 "%" PRIu64 "ms.", (ibuf - i), time);
747 sr_spew("Got %d bytes, but not a valid "
748 "packet.", (ibuf - i));
750 /* Not a valid packet. Continue searching. */
753 if (time >= timeout_ms) {
755 sr_dbg("Detection timed out after %dms.", time);
758 g_usleep(byte_delay_us);
763 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);