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.
53 * Open the specified serial port.
55 * @param serial Previously initialized serial port structure.
56 * @param flags Flags to use when opening the serial port.
57 * TODO: Abstract 'flags', currently they're OS-specific!
59 * If the serial structure contains a serialcomm string, it will be
60 * passed to serial_set_paramstr() after the port is opened.
62 * @return SR_OK on success, SR_ERR on failure.
64 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
68 sr_dbg("Invalid serial port.");
72 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
75 hdl = CreateFile(serial->port, GENERIC_READ | GENERIC_WRITE, 0, 0,
76 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
77 if (hdl == INVALID_HANDLE_VALUE) {
78 sr_err("Error opening serial port '%s'.", serial->port);
82 if ((serial->fd = open(serial->port, flags)) < 0) {
83 sr_err("Error opening serial port '%s': %s.", serial->port,
87 sr_spew("Opened serial port '%s' (fd %d).", serial->port, serial->fd);
90 if (serial->serialcomm)
91 return serial_set_paramstr(serial, serial->serialcomm);
97 * Close the specified serial port.
99 * @param serial Previously initialized serial port structure.
101 * @return SR_OK on success, SR_ERR on failure.
103 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
108 sr_dbg("Invalid serial port.");
112 if (serial->fd == -1) {
113 sr_dbg("Cannot close unopened serial port %s (fd %d).",
114 serial->port, serial->fd);
118 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
122 /* Returns non-zero upon success, 0 upon failure. */
123 if (CloseHandle(hdl) == 0)
126 /* Returns 0 upon success, -1 upon failure. */
127 if (close(serial->fd) < 0) {
128 sr_err("Error closing serial port: %s (fd %d).", strerror(errno),
140 * Flush serial port buffers.
142 * @param serial Previously initialized serial port structure.
144 * @return SR_OK on success, SR_ERR on failure.
146 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
151 sr_dbg("Invalid serial port.");
155 if (serial->fd == -1) {
156 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
157 serial->port, serial->fd);
161 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
165 /* Returns non-zero upon success, 0 upon failure. */
166 if (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) {
167 sr_err("Error flushing serial port: %s.", strerror(errno));
171 /* Returns 0 upon success, -1 upon failure. */
172 if (tcflush(serial->fd, TCIOFLUSH) < 0) {
173 sr_err("Error flushing serial port: %s.", strerror(errno));
182 * Write a number of bytes to the specified serial port.
184 * @param serial Previously initialized serial port structure.
185 * @param buf Buffer containing the bytes to write.
186 * @param count Number of bytes to write.
188 * @return The number of bytes written, or -1 upon failure.
190 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
191 const void *buf, size_t count)
196 sr_dbg("Invalid serial port.");
200 if (serial->fd == -1) {
201 sr_dbg("Cannot use unopened serial port %s (fd %d).",
202 serial->port, serial->fd);
210 /* Returns non-zero upon success, 0 upon failure. */
211 WriteFile(hdl, buf, count, &tmp, NULL);
213 /* Returns the number of bytes written, or -1 upon failure. */
214 ret = write(serial->fd, buf, count);
216 sr_err("Write error: %s.", strerror(errno));
218 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
225 * Read a number of bytes from the specified serial port.
227 * @param serial Previously initialized serial port structure.
228 * @param buf Buffer where to store the bytes that are read.
229 * @param count The number of bytes to read.
231 * @return The number of bytes read, or -1 upon failure.
233 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
239 sr_dbg("Invalid serial port.");
243 if (serial->fd == -1) {
244 sr_dbg("Cannot use unopened serial port %s (fd %d).",
245 serial->port, serial->fd);
253 /* Returns non-zero upon success, 0 upon failure. */
254 return ReadFile(hdl, buf, count, &tmp, NULL);
256 /* Returns the number of bytes read, or -1 upon failure. */
257 ret = read(serial->fd, buf, count);
260 * Should be sr_err(), but that would yield lots of
261 * "Resource temporarily unavailable" messages.
263 sr_spew("Read error: %s (fd %d).", strerror(errno), serial->fd);
265 sr_spew("Read %d/%d bytes (fd %d).", ret, count, serial->fd);
272 * Set serial parameters for the specified serial port.
274 * @param serial Previously initialized serial port structure.
275 * @param baudrate The baudrate to set.
276 * @param bits The number of data bits to use.
277 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
278 * @param stopbits The number of stop bits to use (1 or 2).
279 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
282 * @return SR_OK upon success, SR_ERR upon failure.
284 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
285 int bits, int parity, int stopbits, int flowcontrol)
289 sr_dbg("Invalid serial port.");
293 if (serial->fd == -1) {
294 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
295 serial->port, serial->fd);
299 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
305 if (!GetCommState(hdl, &dcb))
310 dcb.BaudRate = CBR_115200;
313 dcb.BaudRate = CBR_57600;
316 dcb.BaudRate = CBR_38400;
319 dcb.BaudRate = CBR_19200;
322 dcb.BaudRate = CBR_9600;
325 dcb.BaudRate = CBR_4800;
328 dcb.BaudRate = CBR_2400;
331 sr_err("Unsupported baudrate %d.", baudrate);
335 dcb.Parity = NOPARITY; /* TODO: Don't hardcode. */
336 dcb.StopBits = ONESTOPBIT; /* TODO: Don't hardcode. */
338 if (!SetCommState(hdl, &dcb))
344 if (tcgetattr(serial->fd, &term) < 0) {
345 sr_err("tcgetattr() error on port %s (fd %d): %s.",
346 serial->port, serial->fd, strerror(errno));
411 sr_err("Unsupported baudrate %d.", baudrate);
415 sr_spew("Configuring output baudrate to %d (%d).", baudrate, baud);
416 if (cfsetospeed(&term, baud) < 0) {
417 sr_err("cfsetospeed() error: %s.", strerror(errno));
421 sr_spew("Configuring input baudrate to %d (%d).", baudrate, baud);
422 if (cfsetispeed(&term, baud) < 0) {
423 sr_err("cfsetispeed() error: %s.", strerror(errno));
427 sr_spew("Configuring %d data bits.", bits);
428 term.c_cflag &= ~CSIZE;
437 sr_err("Unsupported data bits number %d.", bits);
441 sr_spew("Configuring %d stop bits.", stopbits);
442 term.c_cflag &= ~CSTOPB;
445 term.c_cflag &= ~CSTOPB;
448 term.c_cflag |= CSTOPB;
451 sr_err("Unsupported stopbits number %d.", stopbits);
455 term.c_iflag &= ~(IXON | IXOFF);
456 term.c_cflag &= ~CRTSCTS;
457 switch (flowcontrol) {
459 /* No flow control. */
460 sr_spew("Configuring no flow control.");
463 sr_spew("Configuring RTS/CTS flow control.");
464 term.c_cflag |= CRTSCTS;
467 sr_spew("Configuring XON/XOFF flow control.");
468 term.c_iflag |= IXON | IXOFF;
471 sr_err("Unsupported flow control setting %d.", flowcontrol);
475 term.c_iflag &= ~IGNPAR;
476 term.c_cflag &= ~(PARODD | PARENB);
478 case SERIAL_PARITY_NONE:
479 sr_spew("Configuring no parity.");
480 term.c_iflag |= IGNPAR;
482 case SERIAL_PARITY_EVEN:
483 sr_spew("Configuring even parity.");
484 term.c_cflag |= PARENB;
486 case SERIAL_PARITY_ODD:
487 sr_spew("Configuring odd parity.");
488 term.c_cflag |= PARENB | PARODD;
491 sr_err("Unsupported parity setting %d.", parity);
495 /* Do not translate carriage return to newline on input. */
496 term.c_iflag &= ~(ICRNL);
498 /* Disable canonical mode, and don't echo input characters. */
499 term.c_lflag &= ~(ICANON | ECHO);
501 /* Write the configured settings. */
502 if (tcsetattr(serial->fd, TCSADRAIN, &term) < 0) {
503 sr_err("tcsetattr() error: %s.", strerror(errno));
512 * Set serial parameters for the specified serial port.
514 * @param serial Previously initialized serial port structure.
515 * @param paramstr A serial communication parameters string, in the form
516 * of <speed>/<data bits><parity><stopbits>, for example "9600/8n1" or
519 * @return SR_OK upon success, SR_ERR upon failure.
521 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])$"
522 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
523 const char *paramstr)
527 int speed, databits, parity, stopbits;
530 speed = databits = parity = stopbits = 0;
531 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
532 if (g_regex_match(reg, paramstr, 0, &match)) {
533 if ((mstr = g_match_info_fetch(match, 1)))
534 speed = strtoul(mstr, NULL, 10);
536 if ((mstr = g_match_info_fetch(match, 2)))
537 databits = strtoul(mstr, NULL, 10);
539 if ((mstr = g_match_info_fetch(match, 3))) {
542 parity = SERIAL_PARITY_NONE;
545 parity = SERIAL_PARITY_EVEN;
548 parity = SERIAL_PARITY_ODD;
553 if ((mstr = g_match_info_fetch(match, 4)))
554 stopbits = strtoul(mstr, NULL, 10);
557 g_match_info_unref(match);
561 return serial_set_params(serial, speed, databits, parity, stopbits, 0);
567 * Read a line from the specified serial port.
569 * @param serial Previously initialized serial port structure.
570 * @param buf Buffer where to store the bytes that are read.
571 * @param buflen Size of the buffer.
572 * @param timeout_ms How long to wait for a line to come in.
574 * Reading stops when CR of LR is found, which is stripped from the buffer.
576 * @return SR_OK on success, SR_ERR on failure.
578 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
579 int *buflen, gint64 timeout_ms)
584 if (!serial || serial->fd == -1) {
585 sr_dbg("Invalid serial port.");
589 if (serial->fd == -1) {
590 sr_dbg("Cannot use unopened serial port %s (fd %d).",
591 serial->port, serial->fd);
596 start = g_get_monotonic_time();
601 len = maxlen - *buflen - 1;
604 len = serial_read(serial, *buf + *buflen, 1);
607 *(*buf + *buflen) = '\0';
608 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
609 || *(*buf + *buflen - 1) == '\n')) {
610 /* Strip CR/LF and terminate. */
611 *(*buf + --*buflen) = '\0';
615 if (g_get_monotonic_time() - start > timeout_ms)
621 sr_dbg("Received %d: '%s'.", *buflen, *buf);