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 pathname OS-specific serial port specification. Examples:
56 * "/dev/ttyUSB0", "/dev/ttyACM1", "/dev/tty.Modem-0", "COM1".
57 * @param flags Flags to use when opening the serial port.
59 * @return 0 upon success, -1 upon failure.
61 SR_PRIV int serial_open(const char *pathname, int flags)
63 /* TODO: Abstract 'flags', currently they're OS-specific! */
65 sr_dbg("Opening serial port '%s' (flags = %d).", pathname, flags);
68 pathname = "COM1"; /* FIXME: Don't hardcode COM1. */
70 hdl = CreateFile(pathname, GENERIC_READ | GENERIC_WRITE, 0, 0,
71 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
72 if (hdl == INVALID_HANDLE_VALUE) {
73 sr_err("Error opening serial port '%s'.", pathname);
80 if ((fd = open(pathname, flags)) < 0) {
82 * Should be sr_err(), but since some drivers try to open all
83 * ports on a system and see if they succeed, this would
84 * yield ugly output for e.g. "sigrok-cli -D".
86 sr_dbg("Error opening serial port '%s': %s.", pathname,
89 sr_dbg("Opened serial port '%s' as FD %d.", pathname, fd);
97 * Close the specified serial port.
99 * @param fd File descriptor of the serial port.
101 * @return 0 upon success, -1 upon failure.
103 SR_PRIV int serial_close(int fd)
105 sr_dbg("FD %d: Closing serial port.", fd);
108 /* Returns non-zero upon success, 0 upon failure. */
109 return (CloseHandle(hdl) == 0) ? -1 : 0;
113 /* Returns 0 upon success, -1 upon failure. */
114 if ((ret = close(fd)) < 0) {
115 sr_dbg("FD %d: Error closing serial port: %s.",
116 fd, strerror(errno));
124 * Flush serial port buffers (if any).
126 * @param fd File descriptor of the serial port.
128 * @return 0 upon success, -1 upon failure.
130 SR_PRIV int serial_flush(int fd)
132 sr_dbg("FD %d: Flushing serial port.", fd);
135 /* Returns non-zero upon success, 0 upon failure. */
136 return (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) ? -1 : 0;
140 /* Returns 0 upon success, -1 upon failure. */
141 if ((ret = tcflush(fd, TCIOFLUSH)) < 0)
142 sr_err("Error flushing serial port: %s.", strerror(errno));
149 * Write a number of bytes to the specified serial port.
151 * @param fd File descriptor of the serial port.
152 * @param buf Buffer containing the bytes to write.
153 * @param count Number of bytes to write.
155 * @return The number of bytes written, or -1 upon failure.
157 SR_PRIV int serial_write(int fd, const void *buf, size_t count)
163 /* Returns non-zero upon success, 0 upon failure. */
164 WriteFile(hdl, buf, count, &tmp, NULL);
168 /* Returns the number of bytes written, or -1 upon failure. */
169 ret = write(fd, buf, count);
171 sr_err("FD %d: Write error: %s.", fd, strerror(errno));
173 sr_spew("FD %d: Wrote %d/%d bytes.", fd, ret, count);
180 * Read a number of bytes from the specified serial port.
182 * @param fd File descriptor of the serial port.
183 * @param buf Buffer where to store the bytes that are read.
184 * @param count The number of bytes to read.
186 * @return The number of bytes read, or -1 upon failure.
188 SR_PRIV int serial_read(int fd, void *buf, size_t count)
194 /* Returns non-zero upon success, 0 upon failure. */
195 return ReadFile(hdl, buf, count, &tmp, NULL);
199 /* Returns the number of bytes read, or -1 upon failure. */
200 ret = read(fd, buf, count);
203 * Should be sr_err(), but that would yield lots of
204 * "Resource temporarily unavailable" messages.
206 sr_spew("FD %d: Read error: %s.", fd, strerror(errno));
208 sr_spew("FD %d: Read %d/%d bytes.", fd, ret, count);
216 * Set serial parameters for the specified serial port.
218 * @param baudrate The baudrate to set.
219 * @param bits The number of data bits to use.
220 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
221 * @param stopbits The number of stop bits to use (1 or 2).
222 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
225 * @return SR_OK upon success, SR_ERR upon failure.
227 SR_PRIV int serial_set_params(int fd, int baudrate, int bits, int parity,
228 int stopbits, int flowcontrol)
230 sr_dbg("FD %d: Setting serial parameters.", fd);
235 if (!GetCommState(hdl, &dcb)) {
236 /* TODO: Error handling. */
241 /* TODO: Support for higher baud rates. */
243 dcb.BaudRate = CBR_115200;
246 dcb.BaudRate = CBR_57600;
249 dcb.BaudRate = CBR_38400;
252 dcb.BaudRate = CBR_19200;
255 dcb.BaudRate = CBR_9600;
258 dcb.BaudRate = CBR_4800;
261 dcb.BaudRate = CBR_2400;
264 sr_err("Unsupported baudrate: %d.", baudrate);
268 dcb.Parity = NOPARITY; /* TODO: Don't hardcode. */
269 dcb.StopBits = ONESTOPBIT; /* TODO: Don't hardcode. */
271 if (!SetCommState(hdl, &dcb)) {
272 /* TODO: Error handling. */
279 sr_dbg("FD %d: Getting terminal settings.", fd);
280 if (tcgetattr(fd, &term) < 0) {
281 sr_err("tcgetattr() error: %s.", strerror(errno));
346 sr_err("Unsupported baudrate: %d.", baudrate);
350 sr_dbg("FD %d: Configuring output baudrate to %d (%d).",
352 if (cfsetospeed(&term, baud) < 0) {
353 sr_err("cfsetospeed() error: %s.", strerror(errno));
357 sr_dbg("FD %d: Configuring input baudrate to %d (%d).",
359 if (cfsetispeed(&term, baud) < 0) {
360 sr_err("cfsetispeed() error: %s.", strerror(errno));
364 sr_dbg("FD %d: Configuring %d data bits.", fd, bits);
365 term.c_cflag &= ~CSIZE;
374 sr_err("Unsupported data bits number: %d.", bits);
378 sr_dbg("FD %d: Configuring %d stop bits.", fd, stopbits);
379 term.c_cflag &= ~CSTOPB;
382 /* Do nothing, a cleared CSTOPB entry means "1 stop bit". */
385 term.c_cflag |= CSTOPB;
388 sr_err("Unsupported stopbits number: %d.", stopbits);
392 term.c_iflag &= ~(IXON | IXOFF);
393 term.c_cflag &= ~CRTSCTS;
394 switch (flowcontrol) {
396 /* No flow control. */
397 sr_dbg("FD %d: Configuring no flow control.", fd);
400 sr_dbg("FD %d: Configuring RTS/CTS flow control.", fd);
401 term.c_cflag |= CRTSCTS;
404 sr_dbg("FD %d: Configuring XON/XOFF flow control.", fd);
405 term.c_iflag |= IXON | IXOFF;
408 sr_err("Unsupported flow control setting: %d.", flowcontrol);
412 term.c_iflag &= ~IGNPAR;
413 term.c_cflag &= ~(PARODD | PARENB);
415 case SERIAL_PARITY_NONE:
416 sr_dbg("FD %d: Configuring no parity.", fd);
417 term.c_iflag |= IGNPAR;
419 case SERIAL_PARITY_EVEN:
420 sr_dbg("FD %d: Configuring even parity.", fd);
421 term.c_cflag |= PARENB;
423 case SERIAL_PARITY_ODD:
424 sr_dbg("FD %d: Configuring odd parity.", fd);
425 term.c_cflag |= PARENB | PARODD;
428 sr_err("Unsupported parity setting: %d.", parity);
432 /* Do NOT translate carriage return to newline on input. */
433 term.c_iflag &= ~(ICRNL);
435 /* Disable canonical mode, and don't echo input characters. */
436 term.c_lflag &= ~(ICANON | ECHO);
438 /* Write the configured settings. */
439 if (tcsetattr(fd, TCSADRAIN, &term) < 0) {
440 sr_err("tcsetattr() error: %ѕ.", strerror(errno));
448 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])$"
449 SR_PRIV int serial_set_paramstr(int fd, const char *paramstr)
453 int speed, databits, parity, stopbits;
456 speed = databits = parity = stopbits = 0;
457 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
458 if (g_regex_match(reg, paramstr, 0, &match)) {
459 if ((mstr = g_match_info_fetch(match, 1)))
460 speed = strtoul(mstr, NULL, 10);
462 if ((mstr = g_match_info_fetch(match, 2)))
463 databits = strtoul(mstr, NULL, 10);
465 if ((mstr = g_match_info_fetch(match, 3))) {
468 parity = SERIAL_PARITY_NONE;
471 parity = SERIAL_PARITY_EVEN;
474 parity = SERIAL_PARITY_ODD;
479 if ((mstr = g_match_info_fetch(match, 4)))
480 stopbits = strtoul(mstr, NULL, 10);
483 g_match_info_unref(match);
487 return serial_set_params(fd, speed, databits, parity, stopbits, 0);
492 SR_PRIV int serial_readline(int fd, char **buf, int *buflen,
499 start = g_get_monotonic_time();
504 len = maxlen - *buflen - 1;
507 len = serial_read(fd, *buf + *buflen, 1);
510 *(*buf + *buflen) = '\0';
511 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
512 || *(*buf + *buflen - 1) == '\n')) {
513 /* Strip CR/LF and terminate. */
514 *(*buf + --*buflen) = '\0';
518 if (g_get_monotonic_time() - start > timeout_ms)
524 sr_dbg("Received %d: '%s'.", *buflen, *buf);