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/>.
25 #include <glib/gstdio.h>
26 #include <libserialport.h>
27 #include "libsigrok.h"
28 #include "libsigrok-internal.h"
30 #define LOG_PREFIX "serial"
33 * Open the specified serial port.
35 * @param serial Previously initialized serial port structure.
36 * @param[in] flags Flags to use when opening the serial port. Possible flags
37 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
39 * If the serial structure contains a serialcomm string, it will be
40 * passed to serial_set_paramstr() after the port is opened.
42 * @retval SR_OK Success.
43 * @retval SR_ERR Failure.
45 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
52 sr_dbg("Invalid serial port.");
56 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
58 sp_get_port_by_name(serial->port, &serial->data);
60 if (flags & SERIAL_RDWR)
61 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
62 else if (flags & SERIAL_RDONLY)
63 sp_flags = SP_MODE_READ;
65 serial->nonblocking = (flags & SERIAL_NONBLOCK) ? 1 : 0;
67 ret = sp_open(serial->data, sp_flags);
71 sr_err("Attempt to open serial port with invalid parameters.");
74 error = sp_last_error_message();
75 sr_err("Error opening port (%d): %s.",
76 sp_last_error_code(), error);
77 sp_free_error_message(error);
81 if (serial->serialcomm)
82 return serial_set_paramstr(serial, serial->serialcomm);
88 * Close the specified serial port.
90 * @param serial Previously initialized serial port structure.
92 * @retval SR_OK Success.
93 * @retval SR_ERR Failure.
95 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
101 sr_dbg("Invalid serial port.");
106 sr_dbg("Cannot close unopened serial port %s.", serial->port);
110 sr_spew("Closing serial port %s.", serial->port);
112 ret = sp_close(serial->data);
116 sr_err("Attempt to close an invalid serial port.");
119 error = sp_last_error_message();
120 sr_err("Error closing port (%d): %s.",
121 sp_last_error_code(), error);
122 sp_free_error_message(error);
126 sp_free_port(serial->data);
133 * Flush serial port buffers.
135 * @param serial Previously initialized serial port structure.
137 * @retval SR_OK Success.
138 * @retval SR_ERR Failure.
140 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
146 sr_dbg("Invalid serial port.");
151 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
155 sr_spew("Flushing serial port %s.", serial->port);
157 ret = sp_flush(serial->data, SP_BUF_BOTH);
161 sr_err("Attempt to flush an invalid serial port.");
164 error = sp_last_error_message();
165 sr_err("Error flushing port (%d): %s.",
166 sp_last_error_code(), error);
167 sp_free_error_message(error);
174 static int _serial_write(struct sr_serial_dev_inst *serial,
175 const void *buf, size_t count, int nonblocking)
181 sr_dbg("Invalid serial port.");
186 sr_dbg("Cannot use unopened serial port %s.", serial->port);
191 ret = sp_nonblocking_write(serial->data, buf, count);
193 ret = sp_blocking_write(serial->data, buf, count, 0);
197 sr_err("Attempted serial port write with invalid arguments.");
200 error = sp_last_error_message();
201 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
202 sp_free_error_message(error);
206 sr_spew("Wrote %d/%d bytes.", ret, count);
212 * Write a number of bytes to the specified serial port.
214 * @param serial Previously initialized serial port structure.
215 * @param[in] buf Buffer containing the bytes to write.
216 * @param[in] count Number of bytes to write.
218 * @retval SR_ERR_ARG Invalid argument.
219 * @retval SR_ERR Other error.
220 * @retval other The number of bytes written.
222 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
223 const void *buf, size_t count)
225 return _serial_write(serial, buf, count, serial->nonblocking);
229 * Write a number of bytes to the specified serial port, blocking until finished.
230 * @copydetails serial_write()
232 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
233 const void *buf, size_t count)
235 return _serial_write(serial, buf, count, 0);
239 * Write a number of bytes to the specified serial port, return immediately.
240 * @copydetails serial_write()
242 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
243 const void *buf, size_t count)
245 return _serial_write(serial, buf, count, 1);
248 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
249 size_t count, int nonblocking)
255 sr_dbg("Invalid serial port.");
260 sr_dbg("Cannot use unopened serial port %s.", serial->port);
265 ret = sp_nonblocking_read(serial->data, buf, count);
267 ret = sp_blocking_read(serial->data, buf, count, 0);
271 sr_err("Attempted serial port read with invalid arguments.");
274 error = sp_last_error_message();
275 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
276 sp_free_error_message(error);
281 sr_spew("Read %d/%d bytes.", ret, count);
287 * Read a number of bytes from the specified serial port.
289 * @param serial Previously initialized serial port structure.
290 * @param buf Buffer where to store the bytes that are read.
291 * @param[in] count The number of bytes to read.
293 * @retval SR_ERR_ARG Invalid argument.
294 * @retval SR_ERR Other error.
295 * @retval other The number of bytes read.
297 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
300 return _serial_read(serial, buf, count, serial->nonblocking);
304 * Read a number of bytes from the specified serial port, block until finished.
305 * @copydetails serial_read()
307 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
310 return _serial_read(serial, buf, count, 0);
314 * Try to read up to @a count bytes from the specified serial port, return
315 * immediately with what's available.
316 * @copydetails serial_read()
318 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
321 return _serial_read(serial, buf, count, 1);
325 * Set serial parameters for the specified serial port.
327 * @param serial Previously initialized serial port structure.
328 * @param[in] baudrate The baudrate to set.
329 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
330 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
331 * @param[in] stopbits The number of stop bits to use (1 or 2).
332 * @param[in] flowcontrol The flow control settings to use (0 = none,
333 * 1 = RTS/CTS, 2 = XON/XOFF).
334 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
335 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
337 * @retval SR_OK Success.
338 * @retval SR_ERR Failure.
340 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
341 int bits, int parity, int stopbits,
342 int flowcontrol, int rts, int dtr)
346 struct sp_port_config *config;
349 sr_dbg("Invalid serial port.");
354 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
358 sr_spew("Setting serial parameters on port %s.", serial->port);
360 sp_new_config(&config);
361 sp_set_config_baudrate(config, baudrate);
362 sp_set_config_bits(config, bits);
365 sp_set_config_parity(config, SP_PARITY_NONE);
368 sp_set_config_parity(config, SP_PARITY_EVEN);
371 sp_set_config_parity(config, SP_PARITY_ODD);
376 sp_set_config_stopbits(config, stopbits);
377 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
378 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
379 sp_set_config_dtr(config, dtr);
380 sp_set_config_dsr(config, SP_DSR_IGNORE);
381 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
383 ret = sp_set_config(serial->data, config);
384 sp_free_config(config);
388 sr_err("Invalid arguments for setting serial port parameters.");
391 error = sp_last_error_message();
392 sr_err("Error setting serial port parameters (%d): %s.",
393 sp_last_error_code(), error);
394 sp_free_error_message(error);
402 * Set serial parameters for the specified serial port from parameter string.
404 * @param serial Previously initialized serial port structure.
405 * @param[in] paramstr A serial communication parameters string of the form
406 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
407 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
408 * \<baudrate\>=integer Baud rate.\n
409 * \<bits\>=5|6|7|8 Number of data bits.\n
410 * \<parity\>=n|e|o None, even, odd.\n
411 * \<stopbits\>=1|2 One or two stop bits.\n
413 * dtr=0|1 Set DTR off resp. on.\n
414 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
415 * rts=0|1 Set RTS off resp. on.\n
416 * Please note that values and combinations of these parameters must be
417 * supported by the concrete serial interface hardware and the drivers for it.
418 * @retval SR_OK Success.
419 * @retval SR_ERR Failure.
421 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
422 const char *paramstr)
424 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
428 int speed, databits, parity, stopbits, flow, rts, dtr, i;
429 char *mstr, **opts, **kv;
431 speed = databits = parity = stopbits = flow = 0;
433 sr_spew("Parsing parameters from \"%s\".", paramstr);
434 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
435 if (g_regex_match(reg, paramstr, 0, &match)) {
436 if ((mstr = g_match_info_fetch(match, 1)))
437 speed = strtoul(mstr, NULL, 10);
439 if ((mstr = g_match_info_fetch(match, 2)))
440 databits = strtoul(mstr, NULL, 10);
442 if ((mstr = g_match_info_fetch(match, 3))) {
445 parity = SERIAL_PARITY_NONE;
448 parity = SERIAL_PARITY_EVEN;
451 parity = SERIAL_PARITY_ODD;
456 if ((mstr = g_match_info_fetch(match, 4)))
457 stopbits = strtoul(mstr, NULL, 10);
459 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
460 if (mstr[0] != '/') {
461 sr_dbg("missing separator before extra options");
464 /* A set of "key=value" options separated by / */
465 opts = g_strsplit(mstr + 1, "/", 0);
466 for (i = 0; opts[i]; i++) {
467 kv = g_strsplit(opts[i], "=", 2);
468 if (!strncmp(kv[0], "rts", 3)) {
471 else if (kv[1][0] == '0')
474 sr_dbg("invalid value for rts: %c", kv[1][0]);
477 } else if (!strncmp(kv[0], "dtr", 3)) {
480 else if (kv[1][0] == '0')
483 sr_dbg("invalid value for dtr: %c", kv[1][0]);
486 } else if (!strncmp(kv[0], "flow", 4)) {
489 else if (kv[1][0] == '1')
491 else if (kv[1][0] == '2')
494 sr_dbg("invalid value for flow: %c", kv[1][0]);
505 g_match_info_unref(match);
509 return serial_set_params(serial, speed, databits, parity,
510 stopbits, flow, rts, dtr);
512 sr_dbg("Could not infer speed from parameter string.");
518 * Read a line from the specified serial port.
520 * @param serial Previously initialized serial port structure.
521 * @param buf Buffer where to store the bytes that are read.
522 * @param buflen Size of the buffer.
523 * @param[in] timeout_ms How long to wait for a line to come in.
525 * Reading stops when CR of LR is found, which is stripped from the buffer.
527 * @retval SR_OK Success.
528 * @retval SR_ERR Failure.
530 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
531 int *buflen, gint64 timeout_ms)
537 sr_dbg("Invalid serial port.");
542 sr_dbg("Cannot use unopened serial port %s.", serial->port);
547 start = g_get_monotonic_time();
552 len = maxlen - *buflen - 1;
555 len = serial_read(serial, *buf + *buflen, 1);
558 *(*buf + *buflen) = '\0';
559 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
560 || *(*buf + *buflen - 1) == '\n')) {
561 /* Strip CR/LF and terminate. */
562 *(*buf + --*buflen) = '\0';
566 if (g_get_monotonic_time() - start > timeout_ms)
573 sr_dbg("Received %d: '%s'.", *buflen, *buf);
579 * Try to find a valid packet in a serial data stream.
581 * @param serial Previously initialized serial port structure.
582 * @param buf Buffer containing the bytes to write.
583 * @param buflen Size of the buffer.
584 * @param[in] packet_size Size, in bytes, of a valid packet.
585 * @param is_valid Callback that assesses whether the packet is valid or not.
586 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
588 * @param[in] baudrate The baudrate of the serial port. This parameter is not
589 * critical, but it helps fine tune the serial port polling
592 * @retval SR_OK Valid packet was found within the given timeout.
593 * @retval SR_ERR Failure.
595 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
596 uint8_t *buf, size_t *buflen,
598 packet_valid_callback is_valid,
599 uint64_t timeout_ms, int baudrate)
601 uint64_t start, time, byte_delay_us;
602 size_t ibuf, i, maxlen;
607 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
608 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
610 if (maxlen < (packet_size / 2) ) {
611 sr_err("Buffer size must be at least twice the packet size.");
615 /* Assume 8n1 transmission. That is 10 bits for every byte. */
616 byte_delay_us = 10 * (1000000 / baudrate);
617 start = g_get_monotonic_time();
620 while (ibuf < maxlen) {
621 len = serial_read(serial, &buf[ibuf], 1);
624 } else if (len == 0) {
625 /* No logging, already done in serial_read(). */
627 /* Error reading byte, but continuing anyway. */
630 time = g_get_monotonic_time() - start;
633 if ((ibuf - i) >= packet_size) {
634 /* We have at least a packet's worth of data. */
635 if (is_valid(&buf[i])) {
636 sr_spew("Found valid %d-byte packet after "
637 "%" PRIu64 "ms.", (ibuf - i), time);
641 sr_spew("Got %d bytes, but not a valid "
642 "packet.", (ibuf - i));
644 /* Not a valid packet. Continue searching. */
647 if (time >= timeout_ms) {
649 sr_dbg("Detection timed out after %dms.", time);
653 g_usleep(byte_delay_us);
658 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
664 * Extract the serial device and options from the options linked list.
666 * @param options List of options passed from the command line.
667 * @param serial_device Pointer where to store the exctracted serial device.
668 * @param serial_options Pointer where to store the optional extracted serial
671 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
672 * returned string should not be freed by the caller.
674 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
675 const char **serial_options)
678 struct sr_config *src;
680 *serial_device = NULL;
682 for (l = options; l; l = l->next) {
686 *serial_device = g_variant_get_string(src->data, NULL);
687 sr_dbg("Parsed serial device: %s", *serial_device);
690 case SR_CONF_SERIALCOMM:
691 *serial_options = g_variant_get_string(src->data, NULL);
692 sr_dbg("Parsed serial options: %s", *serial_options);
697 if (!*serial_device) {
698 sr_dbg("No serial device specified");
706 typedef HANDLE event_handle;
708 typedef int event_handle;
711 SR_PRIV int serial_source_add(struct sr_session *session,
712 struct sr_serial_dev_inst *serial, int events, int timeout,
713 sr_receive_data_callback cb, void *cb_data)
715 enum sp_event mask = 0;
718 if (sp_new_event_set(&serial->event_set) != SP_OK)
721 if (events & G_IO_IN)
722 mask |= SP_EVENT_RX_READY;
723 if (events & G_IO_OUT)
724 mask |= SP_EVENT_TX_READY;
725 if (events & G_IO_ERR)
726 mask |= SP_EVENT_ERROR;
728 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
729 sp_free_event_set(serial->event_set);
733 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
735 for (i = 0; i < serial->event_set->count; i++) {
737 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
739 mask = serial->event_set->masks[i];
741 if (mask & SP_EVENT_RX_READY)
742 serial->pollfds[i].events |= G_IO_IN;
743 if (mask & SP_EVENT_TX_READY)
744 serial->pollfds[i].events |= G_IO_OUT;
745 if (mask & SP_EVENT_ERROR)
746 serial->pollfds[i].events |= G_IO_ERR;
748 if (sr_session_source_add_pollfd(session, &serial->pollfds[i],
749 timeout, cb, cb_data) != SR_OK)
756 SR_PRIV int serial_source_remove(struct sr_session *session,
757 struct sr_serial_dev_inst *serial)
761 for (i = 0; i < serial->event_set->count; i++)
762 if (sr_session_source_remove_pollfd(session, &serial->pollfds[i]) != SR_OK)
765 g_free(serial->pollfds);
766 sp_free_event_set(serial->event_set);
768 serial->pollfds = NULL;
769 serial->event_set = NULL;
775 * Find USB serial devices via the USB vendor ID and product ID.
777 * @param[in] vendor_id Vendor ID of the USB device.
778 * @param[in] product_id Product ID of the USB device.
780 * @return A GSList of strings containing the path of the serial device or
781 * NULL if no serial device is found. The returned list must be freed
784 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
787 const gchar *usb_dev;
788 const char device_tree[] = "/sys/bus/usb/devices/";
789 GDir *devices_dir, *device_dir;
792 GSList *matched_paths;
795 gchar *vendor_path, *product_path, *path_copy;
796 gchar *prefix, *subdir_path, *device_path, *tty_path;
797 unsigned long read_vendor_id, read_product_id;
802 matched_paths = NULL;
804 if (!(devices_dir = g_dir_open(device_tree, 0, NULL)))
808 * Find potential candidates using the vendor ID and product ID
809 * and store them in matched_paths.
811 while ((usb_dev = g_dir_read_name(devices_dir))) {
812 vendor_path = g_strconcat(device_tree,
813 usb_dev, "/idVendor", NULL);
814 product_path = g_strconcat(device_tree,
815 usb_dev, "/idProduct", NULL);
817 if (!g_file_test(vendor_path, G_FILE_TEST_EXISTS) ||
818 !g_file_test(product_path, G_FILE_TEST_EXISTS))
821 if ((fd = g_fopen(vendor_path, "r")) == NULL)
824 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
828 read_vendor_id = strtoul(tmp, NULL, 16);
832 if ((fd = g_fopen(product_path, "r")) == NULL)
835 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
839 read_product_id = strtoul(tmp, NULL, 16);
843 if (vendor_id == read_vendor_id &&
844 product_id == read_product_id) {
845 path_copy = g_strdup(usb_dev);
846 matched_paths = g_slist_prepend(matched_paths,
852 g_free(product_path);
854 g_dir_close(devices_dir);
856 /* For every matched device try to find a ttyUSBX subfolder. */
857 for (l = matched_paths; l; l = l->next) {
860 device_path = g_strconcat(device_tree, l->data, NULL);
862 if (!(device_dir = g_dir_open(device_path, 0, NULL))) {
867 prefix = g_strconcat(l->data, ":", NULL);
869 while ((file = g_dir_read_name(device_dir))) {
870 if (g_str_has_prefix(file, prefix)) {
871 subdir_path = g_strconcat(device_path,
876 g_dir_close(device_dir);
882 if (!(device_dir = g_dir_open(subdir_path, 0, NULL))) {
888 while ((file = g_dir_read_name(device_dir))) {
889 if (g_str_has_prefix(file, "ttyUSB")) {
890 tty_path = g_strconcat("/dev/",
892 sr_dbg("Found USB device %04x:%04x attached to %s.",
893 vendor_id, product_id, tty_path);
894 tty_devs = g_slist_prepend(tty_devs,
899 g_dir_close(device_dir);
902 g_slist_free_full(matched_paths, g_free);