2 * This file is part of the libsigrok 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>
31 #include <sys/ioctl.h>
36 #include "libsigrok.h"
37 #include "libsigrok-internal.h"
39 /* Message logging helpers with subsystem-specific prefix string. */
40 #define LOG_PREFIX "serial: "
41 #define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
42 #define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
43 #define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
44 #define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
45 #define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
46 #define sr_err(s, args...) sr_err(LOG_PREFIX s, ## args)
48 // FIXME: Must be moved, or rather passed as function argument.
54 * Open the specified serial port.
56 * @param serial Previously initialized serial port structure.
57 * @param flags Flags to use when opening the serial port. Possible flags
58 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
60 * If the serial structure contains a serialcomm string, it will be
61 * passed to serial_set_paramstr() after the port is opened.
63 * @return SR_OK on success, SR_ERR on failure.
65 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
69 DWORD desired_access = 0, flags_and_attributes = 0;
73 sr_dbg("Invalid serial port.");
77 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
80 /* Map 'flags' to the OS-specific settings. */
81 desired_access |= GENERIC_READ;
82 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
83 if (flags & SERIAL_RDWR)
84 desired_access |= GENERIC_WRITE;
85 if (flags & SERIAL_NONBLOCK)
86 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
88 hdl = CreateFile(serial->port, desired_access, 0, 0,
89 OPEN_EXISTING, flags_and_attributes, 0);
90 if (hdl == INVALID_HANDLE_VALUE) {
91 sr_err("Error opening serial port '%s'.", serial->port);
95 /* Map 'flags' to the OS-specific settings. */
96 if (flags & SERIAL_RDWR)
97 flags_local |= O_RDWR;
98 if (flags & SERIAL_RDONLY)
99 flags_local |= O_RDONLY;
100 if (flags & SERIAL_NONBLOCK)
101 flags_local |= O_NONBLOCK;
103 if ((serial->fd = open(serial->port, flags_local)) < 0) {
104 sr_err("Error opening serial port '%s': %s.", serial->port,
109 sr_spew("Opened serial port '%s' (fd %d).", serial->port, serial->fd);
112 if (serial->serialcomm)
113 return serial_set_paramstr(serial, serial->serialcomm);
119 * Close the specified serial port.
121 * @param serial Previously initialized serial port structure.
123 * @return SR_OK on success, SR_ERR on failure.
125 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
130 sr_dbg("Invalid serial port.");
134 if (serial->fd == -1) {
135 sr_dbg("Cannot close unopened serial port %s (fd %d).",
136 serial->port, serial->fd);
140 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
144 /* Returns non-zero upon success, 0 upon failure. */
145 if (CloseHandle(hdl) == 0)
148 /* Returns 0 upon success, -1 upon failure. */
149 if (close(serial->fd) < 0) {
150 sr_err("Error closing serial port: %s (fd %d).", strerror(errno),
162 * Flush serial port buffers.
164 * @param serial Previously initialized serial port structure.
166 * @return SR_OK on success, SR_ERR on failure.
168 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
173 sr_dbg("Invalid serial port.");
177 if (serial->fd == -1) {
178 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
179 serial->port, serial->fd);
183 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
187 /* Returns non-zero upon success, 0 upon failure. */
188 if (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) {
189 sr_err("Error flushing serial port: %s.", strerror(errno));
193 /* Returns 0 upon success, -1 upon failure. */
194 if (tcflush(serial->fd, TCIOFLUSH) < 0) {
195 sr_err("Error flushing serial port: %s.", strerror(errno));
204 * Write a number of bytes to the specified serial port.
206 * @param serial Previously initialized serial port structure.
207 * @param buf Buffer containing the bytes to write.
208 * @param count Number of bytes to write.
210 * @return The number of bytes written, or -1 upon failure.
212 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
213 const void *buf, size_t count)
218 sr_dbg("Invalid serial port.");
222 if (serial->fd == -1) {
223 sr_dbg("Cannot use unopened serial port %s (fd %d).",
224 serial->port, serial->fd);
232 /* Returns non-zero upon success, 0 upon failure. */
233 WriteFile(hdl, buf, count, &tmp, NULL);
235 /* Returns the number of bytes written, or -1 upon failure. */
236 ret = write(serial->fd, buf, count);
238 sr_err("Write error: %s.", strerror(errno));
240 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
247 * Read a number of bytes from the specified serial port.
249 * @param serial Previously initialized serial port structure.
250 * @param buf Buffer where to store the bytes that are read.
251 * @param count The number of bytes to read.
253 * @return The number of bytes read, or -1 upon failure.
255 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
261 sr_dbg("Invalid serial port.");
265 if (serial->fd == -1) {
266 sr_dbg("Cannot use unopened serial port %s (fd %d).",
267 serial->port, serial->fd);
275 /* Returns non-zero upon success, 0 upon failure. */
276 return ReadFile(hdl, buf, count, &tmp, NULL);
278 /* Returns the number of bytes read, or -1 upon failure. */
279 ret = read(serial->fd, buf, count);
286 * Set serial parameters for the specified serial port.
288 * @param serial Previously initialized serial port structure.
289 * @param baudrate The baudrate to set.
290 * @param bits The number of data bits to use.
291 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
292 * @param stopbits The number of stop bits to use (1 or 2).
293 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
296 * @return SR_OK upon success, SR_ERR upon failure.
298 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
299 int bits, int parity, int stopbits,
300 int flowcontrol, int rts, int dtr)
303 sr_dbg("Invalid serial port.");
307 if (serial->fd == -1) {
308 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
309 serial->port, serial->fd);
313 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
319 if (!GetCommState(hdl, &dcb)) {
320 sr_err("Failed to get comm state on port %s (fd %d): %d.",
321 serial->port, serial->fd, GetLastError());
327 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
328 * have documented CBR_* macros.
331 dcb.BaudRate = CBR_110;
334 dcb.BaudRate = CBR_300;
337 dcb.BaudRate = CBR_600;
340 dcb.BaudRate = CBR_1200;
343 dcb.BaudRate = CBR_2400;
346 dcb.BaudRate = CBR_4800;
349 dcb.BaudRate = CBR_9600;
352 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
355 dcb.BaudRate = CBR_19200;
358 dcb.BaudRate = CBR_38400;
361 dcb.BaudRate = CBR_57600;
364 dcb.BaudRate = CBR_115200;
367 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
370 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
373 sr_err("Unsupported baudrate: %d.", baudrate);
376 sr_spew("Configuring baudrate to %d (%d).", baudrate, dcb.BaudRate);
378 sr_spew("Configuring %d data bits.", bits);
381 sr_spew("Configuring %d stop bits.", stopbits);
383 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
385 dcb.StopBits = ONESTOPBIT;
388 dcb.StopBits = TWOSTOPBITS;
391 sr_err("Unsupported stopbits number: %d.", stopbits);
396 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
397 case SERIAL_PARITY_NONE:
398 sr_spew("Configuring no parity.");
399 dcb.Parity = NOPARITY;
401 case SERIAL_PARITY_EVEN:
402 sr_spew("Configuring even parity.");
403 dcb.Parity = EVENPARITY;
405 case SERIAL_PARITY_ODD:
406 sr_spew("Configuring odd parity.");
407 dcb.Parity = ODDPARITY;
410 sr_err("Unsupported parity setting: %d.", parity);
415 sr_spew("Setting RTS %s.", rts ? "high" : "low");
417 dcb.fRtsControl = RTS_CONTROL_ENABLE;
419 dcb.fRtsControl = RTS_CONTROL_DISABLE;
423 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
425 dcb.fDtrControl = DTR_CONTROL_ENABLE;
427 dcb.fDtrControl = DTR_CONTROL_DISABLE;
430 if (!SetCommState(hdl, &dcb)) {
431 sr_err("Failed to set comm state on port %s (fd %d): %d.",
432 serial->port, serial->fd, GetLastError());
438 int ret, controlbits;
440 if (tcgetattr(serial->fd, &term) < 0) {
441 sr_err("tcgetattr() error on port %s (fd %d): %s.",
442 serial->port, serial->fd, strerror(errno));
501 #if !defined(__APPLE__) && !defined(__OpenBSD__)
507 sr_err("Unsupported baudrate: %d.", baudrate);
511 sr_spew("Configuring output baudrate to %d (%d).", baudrate, baud);
512 if (cfsetospeed(&term, baud) < 0) {
513 sr_err("cfsetospeed() error: %s.", strerror(errno));
517 sr_spew("Configuring input baudrate to %d (%d).", baudrate, baud);
518 if (cfsetispeed(&term, baud) < 0) {
519 sr_err("cfsetispeed() error: %s.", strerror(errno));
523 sr_spew("Configuring %d data bits.", bits);
524 term.c_cflag &= ~CSIZE;
533 sr_err("Unsupported data bits number %d.", bits);
537 sr_spew("Configuring %d stop bits.", stopbits);
538 term.c_cflag &= ~CSTOPB;
541 term.c_cflag &= ~CSTOPB;
544 term.c_cflag |= CSTOPB;
547 sr_err("Unsupported stopbits number %d.", stopbits);
551 term.c_iflag &= ~(IXON | IXOFF);
552 term.c_cflag &= ~CRTSCTS;
553 switch (flowcontrol) {
555 /* No flow control. */
556 sr_spew("Configuring no flow control.");
559 sr_spew("Configuring RTS/CTS flow control.");
560 term.c_cflag |= CRTSCTS;
563 sr_spew("Configuring XON/XOFF flow control.");
564 term.c_iflag |= IXON | IXOFF;
567 sr_err("Unsupported flow control setting %d.", flowcontrol);
571 term.c_iflag &= ~IGNPAR;
572 term.c_cflag &= ~(PARODD | PARENB);
574 case SERIAL_PARITY_NONE:
575 sr_spew("Configuring no parity.");
576 term.c_iflag |= IGNPAR;
578 case SERIAL_PARITY_EVEN:
579 sr_spew("Configuring even parity.");
580 term.c_cflag |= PARENB;
582 case SERIAL_PARITY_ODD:
583 sr_spew("Configuring odd parity.");
584 term.c_cflag |= PARENB | PARODD;
587 sr_err("Unsupported parity setting %d.", parity);
591 /* Turn off all serial port cooking. */
592 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
593 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
594 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
595 term.c_oflag &= ~OFILL;
598 /* Disable canonical mode, and don't echo input characters. */
599 term.c_lflag &= ~(ICANON | ECHO);
601 /* Write the configured settings. */
602 if (tcsetattr(serial->fd, TCSADRAIN, &term) < 0) {
603 sr_err("tcsetattr() error: %s.", strerror(errno));
608 sr_spew("Setting RTS %s.", rts ? "high" : "low");
609 controlbits = TIOCM_RTS;
610 if ((ret = ioctl(serial->fd, rts ? TIOCMBIS : TIOCMBIC,
611 &controlbits)) < 0) {
612 sr_err("Error setting RTS: %s.", strerror(errno));
618 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
619 controlbits = TIOCM_DTR;
620 if ((ret = ioctl(serial->fd, dtr ? TIOCMBIS : TIOCMBIC,
621 &controlbits)) < 0) {
622 sr_err("Error setting DTR: %s.", strerror(errno));
633 * Set serial parameters for the specified serial port.
635 * @param serial Previously initialized serial port structure.
636 * @param paramstr A serial communication parameters string, in the form
637 * of <speed>/<data bits><parity><stopbits><flow>, for example "9600/8n1" or
638 * "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none, 1 for rts/cts and 2 for xon/xoff.
640 * @return SR_OK upon success, SR_ERR upon failure.
642 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
643 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
644 const char *paramstr)
648 int speed, databits, parity, stopbits, flow, rts, dtr, i;
649 char *mstr, **opts, **kv;
651 speed = databits = parity = stopbits = flow = 0;
653 sr_spew("Parsing parameters from \"%s\".", paramstr);
654 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
655 if (g_regex_match(reg, paramstr, 0, &match)) {
656 if ((mstr = g_match_info_fetch(match, 1)))
657 speed = strtoul(mstr, NULL, 10);
659 if ((mstr = g_match_info_fetch(match, 2)))
660 databits = strtoul(mstr, NULL, 10);
662 if ((mstr = g_match_info_fetch(match, 3))) {
665 parity = SERIAL_PARITY_NONE;
668 parity = SERIAL_PARITY_EVEN;
671 parity = SERIAL_PARITY_ODD;
676 if ((mstr = g_match_info_fetch(match, 4)))
677 stopbits = strtoul(mstr, NULL, 10);
679 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
680 if (mstr[0] != '/') {
681 sr_dbg("missing separator before extra options");
684 /* A set of "key=value" options separated by / */
685 opts = g_strsplit(mstr + 1, "/", 0);
686 for (i = 0; opts[i]; i++) {
687 kv = g_strsplit(opts[i], "=", 2);
688 if (!strncmp(kv[0], "rts", 3)) {
691 else if (kv[1][0] == '0')
694 sr_dbg("invalid value for rts: %c", kv[1][0]);
697 } else if (!strncmp(kv[0], "dtr", 3)) {
700 else if (kv[1][0] == '0')
703 sr_dbg("invalid value for dtr: %c", kv[1][0]);
706 } else if (!strncmp(kv[0], "flow", 4)) {
709 else if (kv[1][0] == '1')
711 else if (kv[1][0] == '2')
714 sr_dbg("invalid value for flow: %c", kv[1][0]);
725 g_match_info_unref(match);
729 return serial_set_params(serial, speed, databits, parity,
730 stopbits, flow, rts, dtr);
732 sr_dbg("Could not infer speed from parameter string.");
738 * Read a line from the specified serial port.
740 * @param serial Previously initialized serial port structure.
741 * @param buf Buffer where to store the bytes that are read.
742 * @param buflen Size of the buffer.
743 * @param timeout_ms How long to wait for a line to come in.
745 * Reading stops when CR of LR is found, which is stripped from the buffer.
747 * @return SR_OK on success, SR_ERR on failure.
749 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
750 int *buflen, gint64 timeout_ms)
755 if (!serial || serial->fd == -1) {
756 sr_dbg("Invalid serial port.");
760 if (serial->fd == -1) {
761 sr_dbg("Cannot use unopened serial port %s (fd %d).",
762 serial->port, serial->fd);
767 start = g_get_monotonic_time();
772 len = maxlen - *buflen - 1;
775 len = serial_read(serial, *buf + *buflen, 1);
778 *(*buf + *buflen) = '\0';
779 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
780 || *(*buf + *buflen - 1) == '\n')) {
781 /* Strip CR/LF and terminate. */
782 *(*buf + --*buflen) = '\0';
786 if (g_get_monotonic_time() - start > timeout_ms)
792 sr_dbg("Received %d: '%s'.", *buflen, *buf);
798 * Try to find a valid packet in a serial data stream.
800 * @param serial Previously initialized serial port structure.
801 * @param buf Buffer containing the bytes to write.
802 * @param count Size of the buffer.
803 * @param packet_size Size, in bytes, of a valid packet.
804 * @param is_valid Callback that assesses whether the packet is valid or not.
805 * @param timeout_ms The timeout after which, if no packet is detected, to
807 * @param baudrate The baudrate of the serial port. This parameter is not
808 * critical, but it helps fine tune the serial port polling
811 * @return SR_OK if a valid packet is found within the given timeout,
812 * SR_ERR upon failure.
814 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
815 uint8_t *buf, size_t *buflen,
816 size_t packet_size, packet_valid_t is_valid,
817 uint64_t timeout_ms, int baudrate)
819 uint64_t start, time, byte_delay_us;
820 size_t ibuf, i, maxlen;
825 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
826 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
828 if (maxlen < (packet_size / 2) ) {
829 sr_err("Buffer size must be at least twice the packet size.");
833 /* Assume 8n1 transmission. That is 10 bits for every byte. */
834 byte_delay_us = 10 * (1000000 / baudrate);
835 start = g_get_monotonic_time();
838 while (ibuf < maxlen) {
839 len = serial_read(serial, &buf[ibuf], 1);
842 } else if (len == 0) {
843 /* No logging, already done in serial_read(). */
845 /* Error reading byte, but continuing anyway. */
848 time = g_get_monotonic_time() - start;
851 if ((ibuf - i) >= packet_size) {
852 /* We have at least a packet's worth of data. */
853 if (is_valid(&buf[i])) {
854 sr_spew("Found valid %d-byte packet after "
855 "%" PRIu64 "ms.", (ibuf - i), time);
859 sr_spew("Got %d bytes, but not a valid "
860 "packet.", (ibuf - i));
862 /* Not a valid packet. Continue searching. */
865 if (time >= timeout_ms) {
867 sr_dbg("Detection timed out after %dms.", time);
870 g_usleep(byte_delay_us);
875 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);