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/>.
26 #include <glib/gstdio.h>
27 #include <libserialport.h>
28 #include "libsigrok.h"
29 #include "libsigrok-internal.h"
31 #define LOG_PREFIX "serial"
34 * Open the specified serial port.
36 * @param serial Previously initialized serial port structure.
37 * @param[in] flags Flags to use when opening the serial port. Possible flags
38 * include SERIAL_RDWR, SERIAL_RDONLY.
40 * If the serial structure contains a serialcomm string, it will be
41 * passed to serial_set_paramstr() after the port is opened.
43 * @retval SR_OK Success.
44 * @retval SR_ERR Failure.
46 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
53 sr_dbg("Invalid serial port.");
57 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
59 sp_get_port_by_name(serial->port, &serial->data);
61 if (flags & SERIAL_RDWR)
62 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
63 else if (flags & SERIAL_RDONLY)
64 sp_flags = SP_MODE_READ;
66 ret = sp_open(serial->data, sp_flags);
70 sr_err("Attempt to open serial port with invalid parameters.");
73 error = sp_last_error_message();
74 sr_err("Error opening port (%d): %s.",
75 sp_last_error_code(), error);
76 sp_free_error_message(error);
80 if (serial->serialcomm)
81 return serial_set_paramstr(serial, serial->serialcomm);
87 * Close the specified serial port.
89 * @param serial Previously initialized serial port structure.
91 * @retval SR_OK Success.
92 * @retval SR_ERR Failure.
94 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
100 sr_dbg("Invalid serial port.");
105 sr_dbg("Cannot close unopened serial port %s.", serial->port);
109 sr_spew("Closing serial port %s.", serial->port);
111 ret = sp_close(serial->data);
115 sr_err("Attempt to close an invalid serial port.");
118 error = sp_last_error_message();
119 sr_err("Error closing port (%d): %s.",
120 sp_last_error_code(), error);
121 sp_free_error_message(error);
125 sp_free_port(serial->data);
132 * Flush serial port buffers.
134 * @param serial Previously initialized serial port structure.
136 * @retval SR_OK Success.
137 * @retval SR_ERR Failure.
139 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
145 sr_dbg("Invalid serial port.");
150 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
154 sr_spew("Flushing serial port %s.", serial->port);
156 ret = sp_flush(serial->data, SP_BUF_BOTH);
160 sr_err("Attempt to flush an invalid serial port.");
163 error = sp_last_error_message();
164 sr_err("Error flushing port (%d): %s.",
165 sp_last_error_code(), error);
166 sp_free_error_message(error);
174 * Drain serial port buffers.
176 * @param serial Previously initialized serial port structure.
178 * @retval SR_OK Success.
179 * @retval SR_ERR Failure.
181 SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
187 sr_dbg("Invalid serial port.");
192 sr_dbg("Cannot drain unopened serial port %s.", serial->port);
196 sr_spew("Draining serial port %s.", serial->port);
198 ret = sp_drain(serial->data);
200 if (ret == SP_ERR_FAIL) {
201 error = sp_last_error_message();
202 sr_err("Error draining port (%d): %s.",
203 sp_last_error_code(), error);
204 sp_free_error_message(error);
211 static int _serial_write(struct sr_serial_dev_inst *serial,
212 const void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
218 sr_dbg("Invalid serial port.");
223 sr_dbg("Cannot use unopened serial port %s.", serial->port);
228 ret = sp_nonblocking_write(serial->data, buf, count);
230 ret = sp_blocking_write(serial->data, buf, count, timeout_ms);
234 sr_err("Attempted serial port write with invalid arguments.");
237 error = sp_last_error_message();
238 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
239 sp_free_error_message(error);
243 sr_spew("Wrote %d/%d bytes.", ret, count);
249 * Write a number of bytes to the specified serial port, blocking until finished.
251 * @param serial Previously initialized serial port structure.
252 * @param[in] buf Buffer containing the bytes to write.
253 * @param[in] count Number of bytes to write.
254 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
256 * @retval SR_ERR_ARG Invalid argument.
257 * @retval SR_ERR Other error.
258 * @retval other The number of bytes written. If this is less than the number
259 * specified in the call, the timeout was reached.
261 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
262 const void *buf, size_t count, unsigned int timeout_ms)
264 return _serial_write(serial, buf, count, 0, timeout_ms);
268 * Write a number of bytes to the specified serial port, return immediately.
270 * @param serial Previously initialized serial port structure.
271 * @param[in] buf Buffer containing the bytes to write.
272 * @param[in] count Number of bytes to write.
274 * @retval SR_ERR_ARG Invalid argument.
275 * @retval SR_ERR Other error.
276 * @retval other The number of bytes written.
278 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
279 const void *buf, size_t count)
281 return _serial_write(serial, buf, count, 1, 0);
284 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
285 size_t count, int nonblocking, unsigned int timeout_ms)
291 sr_dbg("Invalid serial port.");
296 sr_dbg("Cannot use unopened serial port %s.", serial->port);
301 ret = sp_nonblocking_read(serial->data, buf, count);
303 ret = sp_blocking_read(serial->data, buf, count, timeout_ms);
307 sr_err("Attempted serial port read with invalid arguments.");
310 error = sp_last_error_message();
311 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
312 sp_free_error_message(error);
317 sr_spew("Read %d/%d bytes.", ret, count);
323 * Read a number of bytes from the specified serial port, block until finished.
325 * @param serial Previously initialized serial port structure.
326 * @param buf Buffer where to store the bytes that are read.
327 * @param[in] count The number of bytes to read.
328 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
330 * @retval SR_ERR_ARG Invalid argument.
331 * @retval SR_ERR Other error.
332 * @retval other The number of bytes read. If this is less than the number
333 * requested, the timeout was reached.
335 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
336 size_t count, unsigned int timeout_ms)
338 return _serial_read(serial, buf, count, 0, timeout_ms);
342 * Try to read up to @a count bytes from the specified serial port, return
343 * immediately with what's available.
345 * @param serial Previously initialized serial port structure.
346 * @param buf Buffer where to store the bytes that are read.
347 * @param[in] count The number of bytes to read.
349 * @retval SR_ERR_ARG Invalid argument.
350 * @retval SR_ERR Other error.
351 * @retval other The number of bytes read.
353 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
356 return _serial_read(serial, buf, count, 1, 0);
360 * Set serial parameters for the specified serial port.
362 * @param serial Previously initialized serial port structure.
363 * @param[in] baudrate The baudrate to set.
364 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
365 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
366 * @param[in] stopbits The number of stop bits to use (1 or 2).
367 * @param[in] flowcontrol The flow control settings to use (0 = none,
368 * 1 = RTS/CTS, 2 = XON/XOFF).
369 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
370 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
372 * @retval SR_OK Success.
373 * @retval SR_ERR Failure.
375 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
376 int bits, int parity, int stopbits,
377 int flowcontrol, int rts, int dtr)
381 struct sp_port_config *config;
384 sr_dbg("Invalid serial port.");
389 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
393 sr_spew("Setting serial parameters on port %s.", serial->port);
395 sp_new_config(&config);
396 sp_set_config_baudrate(config, baudrate);
397 sp_set_config_bits(config, bits);
400 sp_set_config_parity(config, SP_PARITY_NONE);
403 sp_set_config_parity(config, SP_PARITY_EVEN);
406 sp_set_config_parity(config, SP_PARITY_ODD);
411 sp_set_config_stopbits(config, stopbits);
412 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
413 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
414 sp_set_config_dtr(config, dtr);
415 sp_set_config_dsr(config, SP_DSR_IGNORE);
416 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
418 ret = sp_set_config(serial->data, config);
419 sp_free_config(config);
423 sr_err("Invalid arguments for setting serial port parameters.");
426 error = sp_last_error_message();
427 sr_err("Error setting serial port parameters (%d): %s.",
428 sp_last_error_code(), error);
429 sp_free_error_message(error);
437 * Set serial parameters for the specified serial port from parameter string.
439 * @param serial Previously initialized serial port structure.
440 * @param[in] paramstr A serial communication parameters string of the form
441 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
442 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
443 * \<baudrate\>=integer Baud rate.\n
444 * \<bits\>=5|6|7|8 Number of data bits.\n
445 * \<parity\>=n|e|o None, even, odd.\n
446 * \<stopbits\>=1|2 One or two stop bits.\n
448 * dtr=0|1 Set DTR off resp. on.\n
449 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
450 * rts=0|1 Set RTS off resp. on.\n
451 * Please note that values and combinations of these parameters must be
452 * supported by the concrete serial interface hardware and the drivers for it.
453 * @retval SR_OK Success.
454 * @retval SR_ERR Failure.
456 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
457 const char *paramstr)
459 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
463 int speed, databits, parity, stopbits, flow, rts, dtr, i;
464 char *mstr, **opts, **kv;
466 speed = databits = parity = stopbits = flow = 0;
468 sr_spew("Parsing parameters from \"%s\".", paramstr);
469 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
470 if (g_regex_match(reg, paramstr, 0, &match)) {
471 if ((mstr = g_match_info_fetch(match, 1)))
472 speed = strtoul(mstr, NULL, 10);
474 if ((mstr = g_match_info_fetch(match, 2)))
475 databits = strtoul(mstr, NULL, 10);
477 if ((mstr = g_match_info_fetch(match, 3))) {
480 parity = SERIAL_PARITY_NONE;
483 parity = SERIAL_PARITY_EVEN;
486 parity = SERIAL_PARITY_ODD;
491 if ((mstr = g_match_info_fetch(match, 4)))
492 stopbits = strtoul(mstr, NULL, 10);
494 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
495 if (mstr[0] != '/') {
496 sr_dbg("missing separator before extra options");
499 /* A set of "key=value" options separated by / */
500 opts = g_strsplit(mstr + 1, "/", 0);
501 for (i = 0; opts[i]; i++) {
502 kv = g_strsplit(opts[i], "=", 2);
503 if (!strncmp(kv[0], "rts", 3)) {
506 else if (kv[1][0] == '0')
509 sr_dbg("invalid value for rts: %c", kv[1][0]);
512 } else if (!strncmp(kv[0], "dtr", 3)) {
515 else if (kv[1][0] == '0')
518 sr_dbg("invalid value for dtr: %c", kv[1][0]);
521 } else if (!strncmp(kv[0], "flow", 4)) {
524 else if (kv[1][0] == '1')
526 else if (kv[1][0] == '2')
529 sr_dbg("invalid value for flow: %c", kv[1][0]);
540 g_match_info_unref(match);
544 return serial_set_params(serial, speed, databits, parity,
545 stopbits, flow, rts, dtr);
547 sr_dbg("Could not infer speed from parameter string.");
553 * Read a line from the specified serial port.
555 * @param serial Previously initialized serial port structure.
556 * @param buf Buffer where to store the bytes that are read.
557 * @param buflen Size of the buffer.
558 * @param[in] timeout_ms How long to wait for a line to come in.
560 * Reading stops when CR of LR is found, which is stripped from the buffer.
562 * @retval SR_OK Success.
563 * @retval SR_ERR Failure.
565 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
566 int *buflen, gint64 timeout_ms)
568 gint64 start, remaining;
572 sr_dbg("Invalid serial port.");
577 sr_dbg("Cannot use unopened serial port %s.", serial->port);
581 start = g_get_monotonic_time();
582 remaining = timeout_ms;
587 len = maxlen - *buflen - 1;
590 len = sp_blocking_read(serial->data, *buf + *buflen, 1, remaining);
593 *(*buf + *buflen) = '\0';
594 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
595 || *(*buf + *buflen - 1) == '\n')) {
596 /* Strip CR/LF and terminate. */
597 *(*buf + --*buflen) = '\0';
601 /* Reduce timeout by time elapsed. */
602 remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
610 sr_dbg("Received %d: '%s'.", *buflen, *buf);
616 * Try to find a valid packet in a serial data stream.
618 * @param serial Previously initialized serial port structure.
619 * @param buf Buffer containing the bytes to write.
620 * @param buflen Size of the buffer.
621 * @param[in] packet_size Size, in bytes, of a valid packet.
622 * @param is_valid Callback that assesses whether the packet is valid or not.
623 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
625 * @param[in] baudrate The baudrate of the serial port. This parameter is not
626 * critical, but it helps fine tune the serial port polling
629 * @retval SR_OK Valid packet was found within the given timeout.
630 * @retval SR_ERR Failure.
632 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
633 uint8_t *buf, size_t *buflen,
635 packet_valid_callback is_valid,
636 uint64_t timeout_ms, int baudrate)
638 uint64_t start, time, byte_delay_us;
639 size_t ibuf, i, maxlen;
644 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
645 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
647 if (maxlen < (packet_size / 2) ) {
648 sr_err("Buffer size must be at least twice the packet size.");
652 /* Assume 8n1 transmission. That is 10 bits for every byte. */
653 byte_delay_us = 10 * (1000000 / baudrate);
654 start = g_get_monotonic_time();
657 while (ibuf < maxlen) {
658 len = serial_read_nonblocking(serial, &buf[ibuf], 1);
661 } else if (len == 0) {
662 /* No logging, already done in serial_read(). */
664 /* Error reading byte, but continuing anyway. */
667 time = g_get_monotonic_time() - start;
670 if ((ibuf - i) >= packet_size) {
671 /* We have at least a packet's worth of data. */
672 if (is_valid(&buf[i])) {
673 sr_spew("Found valid %d-byte packet after "
674 "%" PRIu64 "ms.", (ibuf - i), time);
678 sr_spew("Got %d bytes, but not a valid "
679 "packet.", (ibuf - i));
681 /* Not a valid packet. Continue searching. */
684 if (time >= timeout_ms) {
686 sr_dbg("Detection timed out after %dms.", time);
690 g_usleep(byte_delay_us);
695 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
701 * Extract the serial device and options from the options linked list.
703 * @param options List of options passed from the command line.
704 * @param serial_device Pointer where to store the exctracted serial device.
705 * @param serial_options Pointer where to store the optional extracted serial
708 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
709 * returned string should not be freed by the caller.
711 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
712 const char **serial_options)
715 struct sr_config *src;
717 *serial_device = NULL;
719 for (l = options; l; l = l->next) {
723 *serial_device = g_variant_get_string(src->data, NULL);
724 sr_dbg("Parsed serial device: %s", *serial_device);
727 case SR_CONF_SERIALCOMM:
728 *serial_options = g_variant_get_string(src->data, NULL);
729 sr_dbg("Parsed serial options: %s", *serial_options);
734 if (!*serial_device) {
735 sr_dbg("No serial device specified");
743 typedef HANDLE event_handle;
745 typedef int event_handle;
748 SR_PRIV int serial_source_add(struct sr_session *session,
749 struct sr_serial_dev_inst *serial, int events, int timeout,
750 sr_receive_data_callback cb, void *cb_data)
752 enum sp_event mask = 0;
755 if (sp_new_event_set(&serial->event_set) != SP_OK)
758 if (events & G_IO_IN)
759 mask |= SP_EVENT_RX_READY;
760 if (events & G_IO_OUT)
761 mask |= SP_EVENT_TX_READY;
762 if (events & G_IO_ERR)
763 mask |= SP_EVENT_ERROR;
765 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
766 sp_free_event_set(serial->event_set);
770 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
772 for (i = 0; i < serial->event_set->count; i++) {
774 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
776 mask = serial->event_set->masks[i];
778 if (mask & SP_EVENT_RX_READY)
779 serial->pollfds[i].events |= G_IO_IN;
780 if (mask & SP_EVENT_TX_READY)
781 serial->pollfds[i].events |= G_IO_OUT;
782 if (mask & SP_EVENT_ERROR)
783 serial->pollfds[i].events |= G_IO_ERR;
785 if (sr_session_source_add_pollfd(session, &serial->pollfds[i],
786 timeout, cb, cb_data) != SR_OK)
793 SR_PRIV int serial_source_remove(struct sr_session *session,
794 struct sr_serial_dev_inst *serial)
798 for (i = 0; i < serial->event_set->count; i++)
799 if (sr_session_source_remove_pollfd(session, &serial->pollfds[i]) != SR_OK)
802 g_free(serial->pollfds);
803 sp_free_event_set(serial->event_set);
805 serial->pollfds = NULL;
806 serial->event_set = NULL;
812 * Find USB serial devices via the USB vendor ID and product ID.
814 * @param[in] vendor_id Vendor ID of the USB device.
815 * @param[in] product_id Product ID of the USB device.
817 * @return A GSList of strings containing the path of the serial device or
818 * NULL if no serial device is found. The returned list must be freed
821 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
823 GSList *tty_devs = NULL;
824 struct sp_port **ports;
827 if (sp_list_ports(&ports) != SP_OK)
830 for (i=0; ports[i]; i++)
831 if (sp_get_port_transport(ports[i]) == SP_TRANSPORT_USB &&
832 sp_get_port_usb_vid_pid(ports[i], &vid, &pid) == SP_OK &&
833 vid == vendor_id && pid == product_id)
834 tty_devs = g_slist_prepend(tty_devs,
835 g_strdup(sp_get_port_name(ports[i])));
837 sp_free_port_list(ports);
841 SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
843 struct sp_port_config *config;
844 int timeout_ms, bits, baud, tmp;
849 if (sp_new_config(&config) < 0)
854 if (sp_get_config(port->data, config) < 0)
859 if (sp_get_config_bits(config, &tmp) < 0)
862 if (sp_get_config_stopbits(config, &tmp) < 0)
865 if (sp_get_config_baudrate(config, &tmp) < 0)
871 /* Throw in 10ms for misc OS overhead. */
873 timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
876 sp_free_config(config);