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>
32 #include <sys/ioctl.h>
37 #include "libsigrok.h"
38 #include "libsigrok-internal.h"
40 /* Message logging helpers with subsystem-specific prefix string. */
41 #define LOG_PREFIX "serial: "
42 #define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
43 #define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
44 #define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
45 #define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
46 #define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
47 #define sr_err(s, args...) sr_err(LOG_PREFIX 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. Possible flags
59 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
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 DWORD desired_access = 0, flags_and_attributes = 0;
74 sr_dbg("Invalid serial port.");
78 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
81 /* Map 'flags' to the OS-specific settings. */
82 desired_access |= GENERIC_READ;
83 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
84 if (flags & SERIAL_RDWR)
85 desired_access |= GENERIC_WRITE;
86 if (flags & SERIAL_NONBLOCK)
87 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
89 hdl = CreateFile(serial->port, desired_access, 0, 0,
90 OPEN_EXISTING, flags_and_attributes, 0);
91 if (hdl == INVALID_HANDLE_VALUE) {
92 sr_err("Error opening serial port '%s'.", serial->port);
96 /* Map 'flags' to the OS-specific settings. */
97 if (flags & SERIAL_RDWR)
98 flags_local |= O_RDWR;
99 if (flags & SERIAL_RDONLY)
100 flags_local |= O_RDONLY;
101 if (flags & SERIAL_NONBLOCK)
102 flags_local |= O_NONBLOCK;
104 if ((serial->fd = open(serial->port, flags_local)) < 0) {
105 sr_err("Error opening serial port '%s': %s.", serial->port,
110 sr_spew("Opened serial port '%s' (fd %d).", serial->port, serial->fd);
113 if (serial->serialcomm)
114 return serial_set_paramstr(serial, serial->serialcomm);
120 * Close the specified serial port.
122 * @param serial Previously initialized serial port structure.
124 * @return SR_OK on success, SR_ERR on failure.
126 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
131 sr_dbg("Invalid serial port.");
135 if (serial->fd == -1) {
136 sr_dbg("Cannot close unopened serial port %s (fd %d).",
137 serial->port, serial->fd);
141 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
145 /* Returns non-zero upon success, 0 upon failure. */
146 if (CloseHandle(hdl) == 0)
149 /* Returns 0 upon success, -1 upon failure. */
150 if (close(serial->fd) < 0) {
151 sr_err("Error closing serial port: %s (fd %d).", strerror(errno),
163 * Flush serial port buffers.
165 * @param serial Previously initialized serial port structure.
167 * @return SR_OK on success, SR_ERR on failure.
169 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
174 sr_dbg("Invalid serial port.");
178 if (serial->fd == -1) {
179 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
180 serial->port, serial->fd);
184 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
188 /* Returns non-zero upon success, 0 upon failure. */
189 if (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) {
190 sr_err("Error flushing serial port: %s.", strerror(errno));
194 /* Returns 0 upon success, -1 upon failure. */
195 if (tcflush(serial->fd, TCIOFLUSH) < 0) {
196 sr_err("Error flushing serial port: %s.", strerror(errno));
205 * Write a number of bytes to the specified serial port.
207 * @param serial Previously initialized serial port structure.
208 * @param buf Buffer containing the bytes to write.
209 * @param count Number of bytes to write.
211 * @return The number of bytes written, or -1 upon failure.
213 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
214 const void *buf, size_t count)
219 sr_dbg("Invalid serial port.");
223 if (serial->fd == -1) {
224 sr_dbg("Cannot use unopened serial port %s (fd %d).",
225 serial->port, serial->fd);
233 /* Returns non-zero upon success, 0 upon failure. */
234 WriteFile(hdl, buf, count, &tmp, NULL);
236 /* Returns the number of bytes written, or -1 upon failure. */
237 ret = write(serial->fd, buf, count);
239 sr_err("Write error: %s.", strerror(errno));
241 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
248 * Read a number of bytes from the specified serial port.
250 * @param serial Previously initialized serial port structure.
251 * @param buf Buffer where to store the bytes that are read.
252 * @param count The number of bytes to read.
254 * @return The number of bytes read, or -1 upon failure.
256 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
262 sr_dbg("Invalid serial port.");
266 if (serial->fd == -1) {
267 sr_dbg("Cannot use unopened serial port %s (fd %d).",
268 serial->port, serial->fd);
276 /* Returns non-zero upon success, 0 upon failure. */
277 return ReadFile(hdl, buf, count, &tmp, NULL);
279 /* Returns the number of bytes read, or -1 upon failure. */
280 ret = read(serial->fd, buf, count);
287 * Set serial parameters for the specified serial port.
289 * @param serial Previously initialized serial port structure.
290 * @param baudrate The baudrate to set.
291 * @param bits The number of data bits to use.
292 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
293 * @param stopbits The number of stop bits to use (1 or 2).
294 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
297 * @return SR_OK upon success, SR_ERR upon failure.
299 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
300 int bits, int parity, int stopbits,
301 int flowcontrol, int rts, int dtr)
304 sr_dbg("Invalid serial port.");
308 if (serial->fd == -1) {
309 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
310 serial->port, serial->fd);
314 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
320 if (!GetCommState(hdl, &dcb)) {
321 sr_err("Failed to get comm state on port %s (fd %d): %d.",
322 serial->port, serial->fd, GetLastError());
328 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
329 * have documented CBR_* macros.
332 dcb.BaudRate = CBR_110;
335 dcb.BaudRate = CBR_300;
338 dcb.BaudRate = CBR_600;
341 dcb.BaudRate = CBR_1200;
344 dcb.BaudRate = CBR_2400;
347 dcb.BaudRate = CBR_4800;
350 dcb.BaudRate = CBR_9600;
353 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
356 dcb.BaudRate = CBR_19200;
359 dcb.BaudRate = CBR_38400;
362 dcb.BaudRate = CBR_57600;
365 dcb.BaudRate = CBR_115200;
368 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
371 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
374 sr_err("Unsupported baudrate: %d.", baudrate);
377 sr_spew("Configuring baudrate to %d (%d).", baudrate, dcb.BaudRate);
379 sr_spew("Configuring %d data bits.", bits);
382 sr_spew("Configuring %d stop bits.", stopbits);
384 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
386 dcb.StopBits = ONESTOPBIT;
389 dcb.StopBits = TWOSTOPBITS;
392 sr_err("Unsupported stopbits number: %d.", stopbits);
397 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
398 case SERIAL_PARITY_NONE:
399 sr_spew("Configuring no parity.");
400 dcb.Parity = NOPARITY;
402 case SERIAL_PARITY_EVEN:
403 sr_spew("Configuring even parity.");
404 dcb.Parity = EVENPARITY;
406 case SERIAL_PARITY_ODD:
407 sr_spew("Configuring odd parity.");
408 dcb.Parity = ODDPARITY;
411 sr_err("Unsupported parity setting: %d.", parity);
416 sr_spew("Setting RTS %s.", rts ? "high" : "low");
418 dcb.fRtsControl = RTS_CONTROL_ENABLE;
420 dcb.fRtsControl = RTS_CONTROL_DISABLE;
424 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
426 dcb.fDtrControl = DTR_CONTROL_ENABLE;
428 dcb.fDtrControl = DTR_CONTROL_DISABLE;
431 if (!SetCommState(hdl, &dcb)) {
432 sr_err("Failed to set comm state on port %s (fd %d): %d.",
433 serial->port, serial->fd, GetLastError());
439 int ret, controlbits;
441 if (tcgetattr(serial->fd, &term) < 0) {
442 sr_err("tcgetattr() error on port %s (fd %d): %s.",
443 serial->port, serial->fd, strerror(errno));
502 #if !defined(__APPLE__) && !defined(__OpenBSD__)
508 sr_err("Unsupported baudrate: %d.", baudrate);
512 sr_spew("Configuring output baudrate to %d (%d).", baudrate, baud);
513 if (cfsetospeed(&term, baud) < 0) {
514 sr_err("cfsetospeed() error: %s.", strerror(errno));
518 sr_spew("Configuring input baudrate to %d (%d).", baudrate, baud);
519 if (cfsetispeed(&term, baud) < 0) {
520 sr_err("cfsetispeed() error: %s.", strerror(errno));
524 sr_spew("Configuring %d data bits.", bits);
525 term.c_cflag &= ~CSIZE;
534 sr_err("Unsupported data bits number %d.", bits);
538 sr_spew("Configuring %d stop bits.", stopbits);
539 term.c_cflag &= ~CSTOPB;
542 term.c_cflag &= ~CSTOPB;
545 term.c_cflag |= CSTOPB;
548 sr_err("Unsupported stopbits number %d.", stopbits);
552 term.c_iflag &= ~(IXON | IXOFF);
553 term.c_cflag &= ~CRTSCTS;
554 switch (flowcontrol) {
556 /* No flow control. */
557 sr_spew("Configuring no flow control.");
560 sr_spew("Configuring RTS/CTS flow control.");
561 term.c_cflag |= CRTSCTS;
564 sr_spew("Configuring XON/XOFF flow control.");
565 term.c_iflag |= IXON | IXOFF;
568 sr_err("Unsupported flow control setting %d.", flowcontrol);
572 term.c_iflag &= ~IGNPAR;
573 term.c_cflag &= ~(PARODD | PARENB);
575 case SERIAL_PARITY_NONE:
576 sr_spew("Configuring no parity.");
577 term.c_iflag |= IGNPAR;
579 case SERIAL_PARITY_EVEN:
580 sr_spew("Configuring even parity.");
581 term.c_cflag |= PARENB;
583 case SERIAL_PARITY_ODD:
584 sr_spew("Configuring odd parity.");
585 term.c_cflag |= PARENB | PARODD;
588 sr_err("Unsupported parity setting %d.", parity);
592 /* Turn off all serial port cooking. */
593 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
594 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
595 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
596 term.c_oflag &= ~OFILL;
599 /* Disable canonical mode, and don't echo input characters. */
600 term.c_lflag &= ~(ICANON | ECHO);
602 /* Write the configured settings. */
603 if (tcsetattr(serial->fd, TCSADRAIN, &term) < 0) {
604 sr_err("tcsetattr() error: %s.", strerror(errno));
609 sr_spew("Setting RTS %s.", rts ? "high" : "low");
610 controlbits = TIOCM_RTS;
611 if ((ret = ioctl(serial->fd, rts ? TIOCMBIS : TIOCMBIC,
612 &controlbits)) < 0) {
613 sr_err("Error setting RTS: %s.", strerror(errno));
619 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
620 controlbits = TIOCM_DTR;
621 if ((ret = ioctl(serial->fd, dtr ? TIOCMBIS : TIOCMBIC,
622 &controlbits)) < 0) {
623 sr_err("Error setting DTR: %s.", strerror(errno));
634 * Set serial parameters for the specified serial port.
636 * @param serial Previously initialized serial port structure.
637 * @param paramstr A serial communication parameters string, in the form
638 * of <speed>/<data bits><parity><stopbits><flow>, for example "9600/8n1" or
639 * "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none, 1 for rts/cts and 2 for xon/xoff.
641 * @return SR_OK upon success, SR_ERR upon failure.
643 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
644 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
645 const char *paramstr)
649 int speed, databits, parity, stopbits, flow, rts, dtr, i;
650 char *mstr, **opts, **kv;
652 speed = databits = parity = stopbits = flow = 0;
654 sr_spew("Parsing parameters from \"%s\".", paramstr);
655 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
656 if (g_regex_match(reg, paramstr, 0, &match)) {
657 if ((mstr = g_match_info_fetch(match, 1)))
658 speed = strtoul(mstr, NULL, 10);
660 if ((mstr = g_match_info_fetch(match, 2)))
661 databits = strtoul(mstr, NULL, 10);
663 if ((mstr = g_match_info_fetch(match, 3))) {
666 parity = SERIAL_PARITY_NONE;
669 parity = SERIAL_PARITY_EVEN;
672 parity = SERIAL_PARITY_ODD;
677 if ((mstr = g_match_info_fetch(match, 4)))
678 stopbits = strtoul(mstr, NULL, 10);
680 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
681 if (mstr[0] != '/') {
682 sr_dbg("missing separator before extra options");
685 /* A set of "key=value" options separated by / */
686 opts = g_strsplit(mstr + 1, "/", 0);
687 for (i = 0; opts[i]; i++) {
688 kv = g_strsplit(opts[i], "=", 2);
689 if (!strncmp(kv[0], "rts", 3)) {
692 else if (kv[1][0] == '0')
695 sr_dbg("invalid value for rts: %c", kv[1][0]);
698 } else if (!strncmp(kv[0], "dtr", 3)) {
701 else if (kv[1][0] == '0')
704 sr_dbg("invalid value for dtr: %c", kv[1][0]);
707 } else if (!strncmp(kv[0], "flow", 4)) {
710 else if (kv[1][0] == '1')
712 else if (kv[1][0] == '2')
715 sr_dbg("invalid value for flow: %c", kv[1][0]);
726 g_match_info_unref(match);
730 return serial_set_params(serial, speed, databits, parity,
731 stopbits, flow, rts, dtr);
733 sr_dbg("Could not infer speed from parameter string.");
739 * Read a line from the specified serial port.
741 * @param serial Previously initialized serial port structure.
742 * @param buf Buffer where to store the bytes that are read.
743 * @param buflen Size of the buffer.
744 * @param timeout_ms How long to wait for a line to come in.
746 * Reading stops when CR of LR is found, which is stripped from the buffer.
748 * @return SR_OK on success, SR_ERR on failure.
750 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
751 int *buflen, gint64 timeout_ms)
756 if (!serial || serial->fd == -1) {
757 sr_dbg("Invalid serial port.");
761 if (serial->fd == -1) {
762 sr_dbg("Cannot use unopened serial port %s (fd %d).",
763 serial->port, serial->fd);
768 start = g_get_monotonic_time();
773 len = maxlen - *buflen - 1;
776 len = serial_read(serial, *buf + *buflen, 1);
779 *(*buf + *buflen) = '\0';
780 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
781 || *(*buf + *buflen - 1) == '\n')) {
782 /* Strip CR/LF and terminate. */
783 *(*buf + --*buflen) = '\0';
787 if (g_get_monotonic_time() - start > timeout_ms)
793 sr_dbg("Received %d: '%s'.", *buflen, *buf);
799 * Try to find a valid packet in a serial data stream.
801 * @param serial Previously initialized serial port structure.
802 * @param buf Buffer containing the bytes to write.
803 * @param count Size of the buffer.
804 * @param packet_size Size, in bytes, of a valid packet.
805 * @param is_valid Callback that assesses whether the packet is valid or not.
806 * @param timeout_ms The timeout after which, if no packet is detected, to
808 * @param baudrate The baudrate of the serial port. This parameter is not
809 * critical, but it helps fine tune the serial port polling
812 * @return SR_OK if a valid packet is found within the given timeout,
813 * SR_ERR upon failure.
815 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
816 uint8_t *buf, size_t *buflen,
817 size_t packet_size, packet_valid_t is_valid,
818 uint64_t timeout_ms, int baudrate)
820 uint64_t start, time, byte_delay_us;
821 size_t ibuf, i, maxlen;
826 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
827 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
829 if (maxlen < (packet_size / 2) ) {
830 sr_err("Buffer size must be at least twice the packet size.");
834 /* Assume 8n1 transmission. That is 10 bits for every byte. */
835 byte_delay_us = 10 * (1000000 / baudrate);
836 start = g_get_monotonic_time();
839 while (ibuf < maxlen) {
840 len = serial_read(serial, &buf[ibuf], 1);
843 } else if (len == 0) {
844 /* No logging, already done in serial_read(). */
846 /* Error reading byte, but continuing anyway. */
849 time = g_get_monotonic_time() - start;
852 if ((ibuf - i) >= packet_size) {
853 /* We have at least a packet's worth of data. */
854 if (is_valid(&buf[i])) {
855 sr_spew("Found valid %d-byte packet after "
856 "%" PRIu64 "ms.", (ibuf - i), time);
860 sr_spew("Got %d bytes, but not a valid "
861 "packet.", (ibuf - i));
863 /* Not a valid packet. Continue searching. */
866 if (time >= timeout_ms) {
868 sr_dbg("Detection timed out after %dms.", time);
871 g_usleep(byte_delay_us);
876 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);