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>
7 * Copyright (C) 2014 Uffe Jakobsen <uffe@uffe.org>
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include <glib/gstdio.h>
28 #include <libserialport.h>
29 #include <libsigrok/libsigrok.h>
30 #include "libsigrok-internal.h"
32 #include <windows.h> /* for HANDLE */
36 #define LOG_PREFIX "serial"
42 * Serial port handling.
46 * @defgroup grp_serial Serial port handling
48 * Serial port handling functions.
54 * Open the specified serial port.
56 * @param serial Previously initialized serial port structure.
57 * @param[in] flags Flags to use when opening the serial port. Possible flags
58 * include SERIAL_RDWR, SERIAL_RDONLY.
60 * If the serial structure contains a serialcomm string, it will be
61 * passed to serial_set_paramstr() after the port is opened.
63 * @retval SR_OK Success.
64 * @retval SR_ERR Failure.
68 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
73 sr_dbg("Invalid serial port.");
77 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
79 ret = sr_ser_libsp_open(serial, flags);
83 if (serial->serialcomm)
84 return serial_set_paramstr(serial, serial->serialcomm);
90 * Close the specified serial port.
92 * @param serial Previously initialized serial port structure.
94 * @retval SR_OK Success.
95 * @retval SR_ERR Failure.
99 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
102 sr_dbg("Invalid serial port.");
106 sr_spew("Closing serial port %s.", serial->port);
108 return sr_ser_libsp_close(serial);
112 * Flush serial port buffers. Empty buffers, discard pending RX and TX data.
114 * @param serial Previously initialized serial port structure.
116 * @retval SR_OK Success.
117 * @retval SR_ERR Failure.
121 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
124 sr_dbg("Invalid serial port.");
128 sr_spew("Flushing serial port %s.", serial->port);
130 return sr_ser_libsp_flush(serial);
134 * Drain serial port buffers. Wait for pending TX data to be sent.
136 * @param serial Previously initialized serial port structure.
138 * @retval SR_OK Success.
139 * @retval SR_ERR Failure.
143 SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
146 sr_dbg("Invalid serial port.");
150 sr_spew("Draining serial port %s.", serial->port);
152 return sr_ser_libsp_drain(serial);
155 static int _serial_write(struct sr_serial_dev_inst *serial,
156 const void *buf, size_t count,
157 int nonblocking, unsigned int timeout_ms)
162 sr_dbg("Invalid serial port.");
166 ret = sr_ser_libsp_write(serial, buf, count, nonblocking, timeout_ms);
167 sr_spew("Wrote %zd/%zu bytes.", ret, count);
173 * Write a number of bytes to the specified serial port, blocking until finished.
175 * @param serial Previously initialized serial port structure.
176 * @param[in] buf Buffer containing the bytes to write.
177 * @param[in] count Number of bytes to write.
178 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
180 * @retval SR_ERR_ARG Invalid argument.
181 * @retval SR_ERR Other error.
182 * @retval other The number of bytes written. If this is less than the number
183 * specified in the call, the timeout was reached.
187 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
188 const void *buf, size_t count, unsigned int timeout_ms)
190 return _serial_write(serial, buf, count, 0, timeout_ms);
194 * Write a number of bytes to the specified serial port, return immediately.
196 * @param serial Previously initialized serial port structure.
197 * @param[in] buf Buffer containing the bytes to write.
198 * @param[in] count Number of bytes to write.
200 * @retval SR_ERR_ARG Invalid argument.
201 * @retval SR_ERR Other error.
202 * @retval other The number of bytes written.
206 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
207 const void *buf, size_t count)
209 return _serial_write(serial, buf, count, 1, 0);
212 static int _serial_read(struct sr_serial_dev_inst *serial,
213 void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
218 sr_dbg("Invalid serial port.");
222 ret = sr_ser_libsp_read(serial, buf, count, nonblocking, timeout_ms);
224 sr_spew("Read %zd/%zu bytes.", ret, count);
230 * Read a number of bytes from the specified serial port, block until finished.
232 * @param serial Previously initialized serial port structure.
233 * @param buf Buffer where to store the bytes that are read.
234 * @param[in] count The number of bytes to read.
235 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
237 * @retval SR_ERR_ARG Invalid argument.
238 * @retval SR_ERR Other error.
239 * @retval other The number of bytes read. If this is less than the number
240 * requested, the timeout was reached.
244 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial,
245 void *buf, size_t count, unsigned int timeout_ms)
247 return _serial_read(serial, buf, count, 0, timeout_ms);
251 * Try to read up to @a count bytes from the specified serial port, return
252 * immediately with what's available.
254 * @param serial Previously initialized serial port structure.
255 * @param buf Buffer where to store the bytes that are read.
256 * @param[in] count The number of bytes to read.
258 * @retval SR_ERR_ARG Invalid argument.
259 * @retval SR_ERR Other error.
260 * @retval other The number of bytes read.
264 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial,
265 void *buf, size_t count)
267 return _serial_read(serial, buf, count, 1, 0);
271 * Set serial parameters for the specified serial port.
273 * @param serial Previously initialized serial port structure.
274 * @param[in] baudrate The baudrate to set.
275 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
276 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
277 * @param[in] stopbits The number of stop bits to use (1 or 2).
278 * @param[in] flowcontrol The flow control settings to use (0 = none,
279 * 1 = RTS/CTS, 2 = XON/XOFF).
280 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
281 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
283 * @retval SR_OK Success.
284 * @retval SR_ERR Failure.
288 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial,
289 int baudrate, int bits, int parity, int stopbits,
290 int flowcontrol, int rts, int dtr)
295 sr_dbg("Invalid serial port.");
299 sr_spew("Setting serial parameters on port %s.", serial->port);
301 ret = sr_ser_libsp_set_params(serial,
302 baudrate, bits, parity, stopbits, flowcontrol, rts, dtr);
304 serial->comm_params.bit_rate = baudrate;
305 serial->comm_params.data_bits = bits;
306 serial->comm_params.parity_bits = parity ? 1 : 0;
307 serial->comm_params.stop_bits = stopbits;
308 sr_dbg("DBG: %s() rate %d, %d%s%d", __func__,
310 (parity == 0) ? "n" : "x",
318 * Set serial parameters for the specified serial port from parameter string.
320 * @param serial Previously initialized serial port structure.
321 * @param[in] paramstr A serial communication parameters string of the form
322 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
323 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
324 * \<baudrate\>=integer Baud rate.\n
325 * \<bits\>=5|6|7|8 Number of data bits.\n
326 * \<parity\>=n|e|o None, even, odd.\n
327 * \<stopbits\>=1|2 One or two stop bits.\n
329 * dtr=0|1 Set DTR off resp. on.\n
330 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
331 * rts=0|1 Set RTS off resp. on.\n
332 * Please note that values and combinations of these parameters must be
333 * supported by the concrete serial interface hardware and the drivers for it.
335 * @retval SR_OK Success.
336 * @retval SR_ERR Failure.
340 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
341 const char *paramstr)
344 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
349 int speed, databits, parity, stopbits, flow, rts, dtr, i;
350 char *mstr, **opts, **kv;
352 speed = databits = parity = stopbits = flow = 0;
354 sr_spew("Parsing parameters from \"%s\".", paramstr);
355 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
356 if (g_regex_match(reg, paramstr, 0, &match)) {
357 if ((mstr = g_match_info_fetch(match, 1)))
358 speed = strtoul(mstr, NULL, 10);
360 if ((mstr = g_match_info_fetch(match, 2)))
361 databits = strtoul(mstr, NULL, 10);
363 if ((mstr = g_match_info_fetch(match, 3))) {
366 parity = SP_PARITY_NONE;
369 parity = SP_PARITY_EVEN;
372 parity = SP_PARITY_ODD;
377 if ((mstr = g_match_info_fetch(match, 4)))
378 stopbits = strtoul(mstr, NULL, 10);
380 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
381 if (mstr[0] != '/') {
382 sr_dbg("missing separator before extra options");
385 /* A set of "key=value" options separated by / */
386 opts = g_strsplit(mstr + 1, "/", 0);
387 for (i = 0; opts[i]; i++) {
388 kv = g_strsplit(opts[i], "=", 2);
389 if (!strncmp(kv[0], "rts", 3)) {
392 else if (kv[1][0] == '0')
395 sr_dbg("invalid value for rts: %c", kv[1][0]);
398 } else if (!strncmp(kv[0], "dtr", 3)) {
401 else if (kv[1][0] == '0')
404 sr_dbg("invalid value for dtr: %c", kv[1][0]);
407 } else if (!strncmp(kv[0], "flow", 4)) {
410 else if (kv[1][0] == '1')
412 else if (kv[1][0] == '2')
415 sr_dbg("invalid value for flow: %c", kv[1][0]);
426 g_match_info_unref(match);
430 return serial_set_params(serial, speed, databits, parity,
431 stopbits, flow, rts, dtr);
433 sr_dbg("Could not infer speed from parameter string.");
439 * Read a line from the specified serial port.
441 * @param[in] serial Previously initialized serial port structure.
442 * @param[out] buf Buffer where to store the bytes that are read.
443 * @param[in] buflen Size of the buffer.
444 * @param[in] timeout_ms How long to wait for a line to come in.
446 * Reading stops when CR or LF is found, which is stripped from the buffer.
448 * @retval SR_OK Success.
449 * @retval SR_ERR Failure.
453 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial,
454 char **buf, int *buflen, gint64 timeout_ms)
456 gint64 start, remaining;
460 sr_dbg("Invalid serial port.");
464 if (!serial->sp_data) {
465 sr_dbg("Cannot use unopened serial port %s.", serial->port);
469 start = g_get_monotonic_time();
470 remaining = timeout_ms;
475 len = maxlen - *buflen - 1;
478 len = serial_read_blocking(serial, *buf + *buflen, 1, remaining);
481 *(*buf + *buflen) = '\0';
482 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
483 || *(*buf + *buflen - 1) == '\n')) {
484 /* Strip CR/LF and terminate. */
485 *(*buf + --*buflen) = '\0';
489 /* Reduce timeout by time elapsed. */
490 remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
498 sr_dbg("Received %d: '%s'.", *buflen, *buf);
504 * Try to find a valid packet in a serial data stream.
506 * @param serial Previously initialized serial port structure.
507 * @param buf Buffer containing the bytes to write.
508 * @param buflen Size of the buffer.
509 * @param[in] packet_size Size, in bytes, of a valid packet.
510 * @param is_valid Callback that assesses whether the packet is valid or not.
511 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
513 * @param[in] baudrate The baudrate of the serial port. This parameter is not
514 * critical, but it helps fine tune the serial port polling
517 * @retval SR_OK Valid packet was found within the given timeout.
518 * @retval SR_ERR Failure.
522 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
523 uint8_t *buf, size_t *buflen,
525 packet_valid_callback is_valid,
526 uint64_t timeout_ms, int baudrate)
528 uint64_t start, time, byte_delay_us;
529 size_t ibuf, i, maxlen;
534 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
535 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
537 if (maxlen < (packet_size / 2) ) {
538 sr_err("Buffer size must be at least twice the packet size.");
542 /* Assume 8n1 transmission. That is 10 bits for every byte. */
543 byte_delay_us = 10 * ((1000 * 1000) / baudrate);
544 start = g_get_monotonic_time();
547 while (ibuf < maxlen) {
548 len = serial_read_nonblocking(serial, &buf[ibuf], 1);
551 } else if (len == 0) {
552 /* No logging, already done in serial_read(). */
554 /* Error reading byte, but continuing anyway. */
557 time = g_get_monotonic_time() - start;
560 if ((ibuf - i) >= packet_size) {
562 /* We have at least a packet's worth of data. */
563 text = sr_hexdump_new(&buf[i], packet_size);
564 sr_spew("Trying packet: %s", text->str);
565 sr_hexdump_free(text);
566 if (is_valid(&buf[i])) {
567 sr_spew("Found valid %zu-byte packet after "
568 "%" PRIu64 "ms.", (ibuf - i), time);
572 sr_spew("Got %zu bytes, but not a valid "
573 "packet.", (ibuf - i));
575 /* Not a valid packet. Continue searching. */
578 if (time >= timeout_ms) {
580 sr_dbg("Detection timed out after %" PRIu64 "ms.", time);
584 g_usleep(byte_delay_us);
589 sr_err("Didn't find a valid packet (read %zu bytes).", *buflen);
595 * Extract the serial device and options from the options linked list.
597 * @param options List of options passed from the command line.
598 * @param serial_device Pointer where to store the extracted serial device.
599 * @param serial_options Pointer where to store the optional extracted serial
602 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
603 * returned string should not be freed by the caller.
607 SR_PRIV int sr_serial_extract_options(GSList *options,
608 const char **serial_device, const char **serial_options)
611 struct sr_config *src;
613 *serial_device = NULL;
615 for (l = options; l; l = l->next) {
619 *serial_device = g_variant_get_string(src->data, NULL);
620 sr_dbg("Parsed serial device: %s.", *serial_device);
622 case SR_CONF_SERIALCOMM:
623 *serial_options = g_variant_get_string(src->data, NULL);
624 sr_dbg("Parsed serial options: %s.", *serial_options);
629 if (!*serial_device) {
630 sr_dbg("No serial device specified.");
638 SR_PRIV int serial_source_add(struct sr_session *session,
639 struct sr_serial_dev_inst *serial, int events, int timeout,
640 sr_receive_data_callback cb, void *cb_data)
642 if ((events & (G_IO_IN | G_IO_ERR)) && (events & G_IO_OUT)) {
643 sr_err("Cannot poll input/error and output simultaneously.");
647 if (!serial->sp_data) {
648 sr_err("Invalid serial port.");
652 return sr_ser_libsp_source_add(session, serial,
653 events, timeout, cb, cb_data);
657 SR_PRIV int serial_source_remove(struct sr_session *session,
658 struct sr_serial_dev_inst *serial)
660 if (!serial->sp_data) {
661 sr_err("Invalid serial port.");
665 return sr_ser_libsp_source_remove(session, serial);
669 * Create/allocate a new sr_serial_port structure.
671 * @param name The OS dependent name of the serial port. Must not be NULL.
672 * @param description An end user friendly description for the serial port.
673 * Can be NULL (in that case the empty string is used
676 * @return The newly allocated sr_serial_port struct.
678 static struct sr_serial_port *sr_serial_new(const char *name,
679 const char *description)
681 struct sr_serial_port *serial;
686 serial = g_malloc0(sizeof(*serial));
687 serial->name = g_strdup(name);
688 serial->description = g_strdup(description ? description : "");
694 * Free a previously allocated sr_serial_port structure.
696 * @param serial The sr_serial_port struct to free. Must not be NULL.
698 SR_API void sr_serial_free(struct sr_serial_port *serial)
702 g_free(serial->name);
703 g_free(serial->description);
707 static GSList *append_port_list(GSList *devs, const char *name, const char *desc)
709 return g_slist_append(devs, sr_serial_new(name, desc));
713 * List available serial devices.
715 * @return A GSList of strings containing the path of the serial devices or
716 * NULL if no serial device is found. The returned list must be freed
719 SR_API GSList *sr_serial_list(const struct sr_dev_driver *driver)
723 /* Currently unused, but will be used by some drivers later on. */
727 tty_devs = sr_ser_libsp_list(tty_devs, append_port_list);
732 static GSList *append_port_find(GSList *devs, const char *name)
737 return g_slist_append(devs, g_strdup(name));
741 * Find USB serial devices via the USB vendor ID and product ID.
743 * @param[in] vendor_id Vendor ID of the USB device.
744 * @param[in] product_id Product ID of the USB device.
746 * @return A GSList of strings containing the path of the serial device or
747 * NULL if no serial device is found. The returned list must be freed
752 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
757 tty_devs = sr_ser_libsp_find_usb(tty_devs, append_port_find,
758 vendor_id, product_id);
764 SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
770 /* Get the bitrate and frame length. */
772 ret = sr_ser_libsp_get_frame_format(port, &baud, &bits);
775 if (!bits || !baud) {
776 baud = port->comm_params.bit_rate;
777 bits = 1 + port->comm_params.data_bits +
778 port->comm_params.parity_bits +
779 port->comm_params.stop_bits;
782 /* Derive the timeout. Default to 1s. */
785 /* Throw in 10ms for misc OS overhead. */
787 timeout_ms += ((1000.0 / baud) * bits) * num_bytes;