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 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 buf Buffer containing the bytes to write.
216 * @param count Number of bytes to write.
218 * @return The number of bytes written, or a negative error code upon failure.
220 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
221 const void *buf, size_t count)
223 return _serial_write(serial, buf, count, serial->nonblocking);
226 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
227 const void *buf, size_t count)
229 return _serial_write(serial, buf, count, 0);
232 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
233 const void *buf, size_t count)
235 return _serial_write(serial, buf, count, 1);
238 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
239 size_t count, int nonblocking)
245 sr_dbg("Invalid serial port.");
250 sr_dbg("Cannot use unopened serial port %s.", serial->port);
255 ret = sp_nonblocking_read(serial->data, buf, count);
257 ret = sp_blocking_read(serial->data, buf, count, 0);
261 sr_err("Attempted serial port read with invalid arguments.");
264 error = sp_last_error_message();
265 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
266 sp_free_error_message(error);
271 sr_spew("Read %d/%d bytes.", ret, count);
277 * Read a number of bytes from the specified serial port.
279 * @param serial Previously initialized serial port structure.
280 * @param buf Buffer where to store the bytes that are read.
281 * @param count The number of bytes to read.
283 * @return The number of bytes read, or a negative error code upon failure.
285 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
288 return _serial_read(serial, buf, count, serial->nonblocking);
291 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
294 return _serial_read(serial, buf, count, 0);
297 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
300 return _serial_read(serial, buf, count, 1);
304 * Set serial parameters for the specified serial port.
306 * @param serial Previously initialized serial port structure.
307 * @param[in] baudrate The baudrate to set.
308 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
309 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
310 * @param[in] stopbits The number of stop bits to use (1 or 2).
311 * @param[in] flowcontrol The flow control settings to use (0 = none,
312 * 1 = RTS/CTS, 2 = XON/XOFF).
313 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
314 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
316 * @retval SR_OK Success.
317 * @retval SR_ERR Failure.
319 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
320 int bits, int parity, int stopbits,
321 int flowcontrol, int rts, int dtr)
325 struct sp_port_config *config;
328 sr_dbg("Invalid serial port.");
333 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
337 sr_spew("Setting serial parameters on port %s.", serial->port);
339 sp_new_config(&config);
340 sp_set_config_baudrate(config, baudrate);
341 sp_set_config_bits(config, bits);
344 sp_set_config_parity(config, SP_PARITY_NONE);
347 sp_set_config_parity(config, SP_PARITY_EVEN);
350 sp_set_config_parity(config, SP_PARITY_ODD);
355 sp_set_config_stopbits(config, stopbits);
356 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
357 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
358 sp_set_config_dtr(config, dtr);
359 sp_set_config_dsr(config, SP_DSR_IGNORE);
360 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
362 ret = sp_set_config(serial->data, config);
363 sp_free_config(config);
367 sr_err("Invalid arguments for setting serial port parameters.");
370 error = sp_last_error_message();
371 sr_err("Error setting serial port parameters (%d): %s.",
372 sp_last_error_code(), error);
373 sp_free_error_message(error);
381 * Set serial parameters for the specified serial port from parameter string.
383 * @param serial Previously initialized serial port structure.
384 * @param[in] paramstr A serial communication parameters string of the form
385 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
386 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
387 * \<baudrate\>=integer Baud rate.\n
388 * \<bits\>=5|6|7|8 Number of data bits.\n
389 * \<parity\>=n|e|o None, even, odd.\n
390 * \<stopbits\>=1|2 One or two stop bits.\n
392 * dtr=0|1 Set DTR off resp. on.\n
393 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
394 * rts=0|1 Set RTS off resp. on.\n
395 * Please note that values and combinations of these parameters must be
396 * supported by the concrete serial interface hardware and the drivers for it.
397 * @retval SR_OK Success.
398 * @retval SR_ERR Failure.
400 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
401 const char *paramstr)
403 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
407 int speed, databits, parity, stopbits, flow, rts, dtr, i;
408 char *mstr, **opts, **kv;
410 speed = databits = parity = stopbits = flow = 0;
412 sr_spew("Parsing parameters from \"%s\".", paramstr);
413 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
414 if (g_regex_match(reg, paramstr, 0, &match)) {
415 if ((mstr = g_match_info_fetch(match, 1)))
416 speed = strtoul(mstr, NULL, 10);
418 if ((mstr = g_match_info_fetch(match, 2)))
419 databits = strtoul(mstr, NULL, 10);
421 if ((mstr = g_match_info_fetch(match, 3))) {
424 parity = SERIAL_PARITY_NONE;
427 parity = SERIAL_PARITY_EVEN;
430 parity = SERIAL_PARITY_ODD;
435 if ((mstr = g_match_info_fetch(match, 4)))
436 stopbits = strtoul(mstr, NULL, 10);
438 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
439 if (mstr[0] != '/') {
440 sr_dbg("missing separator before extra options");
443 /* A set of "key=value" options separated by / */
444 opts = g_strsplit(mstr + 1, "/", 0);
445 for (i = 0; opts[i]; i++) {
446 kv = g_strsplit(opts[i], "=", 2);
447 if (!strncmp(kv[0], "rts", 3)) {
450 else if (kv[1][0] == '0')
453 sr_dbg("invalid value for rts: %c", kv[1][0]);
456 } else if (!strncmp(kv[0], "dtr", 3)) {
459 else if (kv[1][0] == '0')
462 sr_dbg("invalid value for dtr: %c", kv[1][0]);
465 } else if (!strncmp(kv[0], "flow", 4)) {
468 else if (kv[1][0] == '1')
470 else if (kv[1][0] == '2')
473 sr_dbg("invalid value for flow: %c", kv[1][0]);
484 g_match_info_unref(match);
488 return serial_set_params(serial, speed, databits, parity,
489 stopbits, flow, rts, dtr);
491 sr_dbg("Could not infer speed from parameter string.");
497 * Read a line from the specified serial port.
499 * @param serial Previously initialized serial port structure.
500 * @param buf Buffer where to store the bytes that are read.
501 * @param buflen Size of the buffer.
502 * @param[in] timeout_ms How long to wait for a line to come in.
504 * Reading stops when CR of LR is found, which is stripped from the buffer.
506 * @retval SR_OK Success.
507 * @retval SR_ERR Failure.
509 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
510 int *buflen, gint64 timeout_ms)
516 sr_dbg("Invalid serial port.");
521 sr_dbg("Cannot use unopened serial port %s.", serial->port);
526 start = g_get_monotonic_time();
531 len = maxlen - *buflen - 1;
534 len = serial_read(serial, *buf + *buflen, 1);
537 *(*buf + *buflen) = '\0';
538 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
539 || *(*buf + *buflen - 1) == '\n')) {
540 /* Strip CR/LF and terminate. */
541 *(*buf + --*buflen) = '\0';
545 if (g_get_monotonic_time() - start > timeout_ms)
552 sr_dbg("Received %d: '%s'.", *buflen, *buf);
558 * Try to find a valid packet in a serial data stream.
560 * @param serial Previously initialized serial port structure.
561 * @param buf Buffer containing the bytes to write.
562 * @param buflen Size of the buffer.
563 * @param[in] packet_size Size, in bytes, of a valid packet.
564 * @param is_valid Callback that assesses whether the packet is valid or not.
565 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
567 * @param[in] baudrate The baudrate of the serial port. This parameter is not
568 * critical, but it helps fine tune the serial port polling
571 * @retval SR_OK Valid packet was found within the given timeout.
572 * @retval SR_ERR Failure.
574 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
575 uint8_t *buf, size_t *buflen,
577 packet_valid_callback is_valid,
578 uint64_t timeout_ms, int baudrate)
580 uint64_t start, time, byte_delay_us;
581 size_t ibuf, i, maxlen;
586 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
587 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
589 if (maxlen < (packet_size / 2) ) {
590 sr_err("Buffer size must be at least twice the packet size.");
594 /* Assume 8n1 transmission. That is 10 bits for every byte. */
595 byte_delay_us = 10 * (1000000 / baudrate);
596 start = g_get_monotonic_time();
599 while (ibuf < maxlen) {
600 len = serial_read(serial, &buf[ibuf], 1);
603 } else if (len == 0) {
604 /* No logging, already done in serial_read(). */
606 /* Error reading byte, but continuing anyway. */
609 time = g_get_monotonic_time() - start;
612 if ((ibuf - i) >= packet_size) {
613 /* We have at least a packet's worth of data. */
614 if (is_valid(&buf[i])) {
615 sr_spew("Found valid %d-byte packet after "
616 "%" PRIu64 "ms.", (ibuf - i), time);
620 sr_spew("Got %d bytes, but not a valid "
621 "packet.", (ibuf - i));
623 /* Not a valid packet. Continue searching. */
626 if (time >= timeout_ms) {
628 sr_dbg("Detection timed out after %dms.", time);
632 g_usleep(byte_delay_us);
637 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
643 * Extract the serial device and options from the options linked list.
645 * @param options List of options passed from the command line.
646 * @param serial_device Pointer where to store the exctracted serial device.
647 * @param serial_options Pointer where to store the optional extracted serial
650 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
651 * returned string should not be freed by the caller.
653 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
654 const char **serial_options)
657 struct sr_config *src;
659 *serial_device = NULL;
661 for (l = options; l; l = l->next) {
665 *serial_device = g_variant_get_string(src->data, NULL);
666 sr_dbg("Parsed serial device: %s", *serial_device);
669 case SR_CONF_SERIALCOMM:
670 *serial_options = g_variant_get_string(src->data, NULL);
671 sr_dbg("Parsed serial options: %s", *serial_options);
676 if (!*serial_device) {
677 sr_dbg("No serial device specified");
685 typedef HANDLE event_handle;
687 typedef int event_handle;
690 SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
691 int timeout, sr_receive_data_callback cb, void *cb_data)
693 enum sp_event mask = 0;
696 if (sp_new_event_set(&serial->event_set) != SP_OK)
699 if (events & G_IO_IN)
700 mask |= SP_EVENT_RX_READY;
701 if (events & G_IO_OUT)
702 mask |= SP_EVENT_TX_READY;
703 if (events & G_IO_ERR)
704 mask |= SP_EVENT_ERROR;
706 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
707 sp_free_event_set(serial->event_set);
711 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
713 for (i = 0; i < serial->event_set->count; i++) {
715 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
717 mask = serial->event_set->masks[i];
719 if (mask & SP_EVENT_RX_READY)
720 serial->pollfds[i].events |= G_IO_IN;
721 if (mask & SP_EVENT_TX_READY)
722 serial->pollfds[i].events |= G_IO_OUT;
723 if (mask & SP_EVENT_ERROR)
724 serial->pollfds[i].events |= G_IO_ERR;
726 if (sr_session_source_add_pollfd(&serial->pollfds[i],
727 timeout, cb, cb_data) != SR_OK)
734 SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
738 for (i = 0; i < serial->event_set->count; i++)
739 if (sr_session_source_remove_pollfd(&serial->pollfds[i]) != SR_OK)
742 g_free(serial->pollfds);
743 sp_free_event_set(serial->event_set);
745 serial->pollfds = NULL;
746 serial->event_set = NULL;
752 * Find USB serial devices via the USB vendor ID and product ID.
754 * @param[in] vendor_id Vendor ID of the USB device.
755 * @param[in] product_id Product ID of the USB device.
757 * @return A GSList of strings containing the path of the serial device or
758 * NULL if no serial device is found. The returned list must be freed
761 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
764 const gchar *usb_dev;
765 const char device_tree[] = "/sys/bus/usb/devices/";
766 GDir *devices_dir, *device_dir;
769 GSList *matched_paths;
772 gchar *vendor_path, *product_path, *path_copy;
773 gchar *prefix, *subdir_path, *device_path, *tty_path;
774 unsigned long read_vendor_id, read_product_id;
779 matched_paths = NULL;
781 if (!(devices_dir = g_dir_open(device_tree, 0, NULL)))
785 * Find potential candidates using the vendor ID and product ID
786 * and store them in matched_paths.
788 while ((usb_dev = g_dir_read_name(devices_dir))) {
789 vendor_path = g_strconcat(device_tree,
790 usb_dev, "/idVendor", NULL);
791 product_path = g_strconcat(device_tree,
792 usb_dev, "/idProduct", NULL);
794 if (!g_file_test(vendor_path, G_FILE_TEST_EXISTS) ||
795 !g_file_test(product_path, G_FILE_TEST_EXISTS))
798 if ((fd = g_fopen(vendor_path, "r")) == NULL)
801 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
805 read_vendor_id = strtoul(tmp, NULL, 16);
809 if ((fd = g_fopen(product_path, "r")) == NULL)
812 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
816 read_product_id = strtoul(tmp, NULL, 16);
820 if (vendor_id == read_vendor_id &&
821 product_id == read_product_id) {
822 path_copy = g_strdup(usb_dev);
823 matched_paths = g_slist_prepend(matched_paths,
829 g_free(product_path);
831 g_dir_close(devices_dir);
833 /* For every matched device try to find a ttyUSBX subfolder. */
834 for (l = matched_paths; l; l = l->next) {
837 device_path = g_strconcat(device_tree, l->data, NULL);
839 if (!(device_dir = g_dir_open(device_path, 0, NULL))) {
844 prefix = g_strconcat(l->data, ":", NULL);
846 while ((file = g_dir_read_name(device_dir))) {
847 if (g_str_has_prefix(file, prefix)) {
848 subdir_path = g_strconcat(device_path,
853 g_dir_close(device_dir);
859 if (!(device_dir = g_dir_open(subdir_path, 0, NULL))) {
865 while ((file = g_dir_read_name(device_dir))) {
866 if (g_str_has_prefix(file, "ttyUSB")) {
867 tty_path = g_strconcat("/dev/",
869 sr_dbg("Found USB device %04x:%04x attached to %s.",
870 vendor_id, product_id, tty_path);
871 tty_devs = g_slist_prepend(tty_devs,
876 g_dir_close(device_dir);
879 g_slist_free_full(matched_paths, g_free);