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 * @return SR_OK on success, SR_ERR on failure.
44 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
51 sr_dbg("Invalid serial port.");
55 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
57 sp_get_port_by_name(serial->port, &serial->data);
59 if (flags & SERIAL_RDWR)
60 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
61 else if (flags & SERIAL_RDONLY)
62 sp_flags = SP_MODE_READ;
64 serial->nonblocking = (flags & SERIAL_NONBLOCK) ? 1 : 0;
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 * @return SR_OK on success, SR_ERR on failure.
93 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
99 sr_dbg("Invalid serial port.");
104 sr_dbg("Cannot close unopened serial port %s.", serial->port);
108 sr_spew("Closing serial port %s.", serial->port);
110 ret = sp_close(serial->data);
114 sr_err("Attempt to close an invalid serial port.");
117 error = sp_last_error_message();
118 sr_err("Error closing port (%d): %s.",
119 sp_last_error_code(), error);
120 sp_free_error_message(error);
124 sp_free_port(serial->data);
131 * Flush serial port buffers.
133 * @param serial Previously initialized serial port structure.
135 * @return SR_OK on success, SR_ERR on failure.
137 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
143 sr_dbg("Invalid serial port.");
148 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
152 sr_spew("Flushing serial port %s.", serial->port);
154 ret = sp_flush(serial->data, SP_BUF_BOTH);
158 sr_err("Attempt to flush an invalid serial port.");
161 error = sp_last_error_message();
162 sr_err("Error flushing port (%d): %s.",
163 sp_last_error_code(), error);
164 sp_free_error_message(error);
171 static int _serial_write(struct sr_serial_dev_inst *serial,
172 const void *buf, size_t count, int nonblocking)
178 sr_dbg("Invalid serial port.");
183 sr_dbg("Cannot use unopened serial port %s.", serial->port);
188 ret = sp_nonblocking_write(serial->data, buf, count);
190 ret = sp_blocking_write(serial->data, buf, count, 0);
194 sr_err("Attempted serial port write with invalid arguments.");
197 error = sp_last_error_message();
198 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
199 sp_free_error_message(error);
203 sr_spew("Wrote %d/%d bytes.", ret, count);
209 * Write a number of bytes to the specified serial port.
211 * @param serial Previously initialized serial port structure.
212 * @param buf Buffer containing the bytes to write.
213 * @param count Number of bytes to write.
215 * @return The number of bytes written, or a negative error code upon failure.
217 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
218 const void *buf, size_t count)
220 return _serial_write(serial, buf, count, serial->nonblocking);
223 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
224 const void *buf, size_t count)
226 return _serial_write(serial, buf, count, 0);
229 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
230 const void *buf, size_t count)
232 return _serial_write(serial, buf, count, 1);
235 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
236 size_t count, int nonblocking)
242 sr_dbg("Invalid serial port.");
247 sr_dbg("Cannot use unopened serial port %s.", serial->port);
252 ret = sp_nonblocking_read(serial->data, buf, count);
254 ret = sp_blocking_read(serial->data, buf, count, 0);
258 sr_err("Attempted serial port read with invalid arguments.");
261 error = sp_last_error_message();
262 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
263 sp_free_error_message(error);
268 sr_spew("Read %d/%d bytes.", ret, count);
274 * Read a number of bytes from the specified serial port.
276 * @param serial Previously initialized serial port structure.
277 * @param buf Buffer where to store the bytes that are read.
278 * @param count The number of bytes to read.
280 * @return The number of bytes read, or a negative error code upon failure.
282 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
285 return _serial_read(serial, buf, count, serial->nonblocking);
288 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
291 return _serial_read(serial, buf, count, 0);
294 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
297 return _serial_read(serial, buf, count, 1);
301 * Set serial parameters for the specified serial port.
303 * @param serial Previously initialized serial port structure.
304 * @param[in] baudrate The baudrate to set.
305 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
306 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
307 * @param[in] stopbits The number of stop bits to use (1 or 2).
308 * @param[in] flowcontrol The flow control settings to use (0 = none,
309 * 1 = RTS/CTS, 2 = XON/XOFF).
310 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
311 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
313 * @retval SR_OK Success
314 * @retval SR_ERR Failure.
316 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
317 int bits, int parity, int stopbits,
318 int flowcontrol, int rts, int dtr)
322 struct sp_port_config *config;
325 sr_dbg("Invalid serial port.");
330 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
334 sr_spew("Setting serial parameters on port %s.", serial->port);
336 sp_new_config(&config);
337 sp_set_config_baudrate(config, baudrate);
338 sp_set_config_bits(config, bits);
341 sp_set_config_parity(config, SP_PARITY_NONE);
344 sp_set_config_parity(config, SP_PARITY_EVEN);
347 sp_set_config_parity(config, SP_PARITY_ODD);
352 sp_set_config_stopbits(config, stopbits);
353 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
354 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
355 sp_set_config_dtr(config, dtr);
356 sp_set_config_dsr(config, SP_DSR_IGNORE);
357 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
359 ret = sp_set_config(serial->data, config);
360 sp_free_config(config);
364 sr_err("Invalid arguments for setting serial port parameters.");
367 error = sp_last_error_message();
368 sr_err("Error setting serial port parameters (%d): %s.",
369 sp_last_error_code(), error);
370 sp_free_error_message(error);
378 * Set serial parameters for the specified serial port from parameter string.
380 * @param serial Previously initialized serial port structure.
381 * @param[in] paramstr A serial communication parameters string of the form
382 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
383 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
384 * \<baudrate\>=integer Baud rate.\n
385 * \<bits\>=5|6|7|8 Number of data bits.\n
386 * \<parity\>=n|e|o None, even, odd.\n
387 * \<stopbits\>=1|2 One or two stop bits.\n
389 * dtr=0|1 Set DTR off resp. on.\n
390 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
391 * rts=0|1 Set RTS off resp. on.\n
392 * Please note that values and combinations of these parameters must be
393 * supported by the concrete serial interface hardware and the drivers for it.
394 * @retval SR_OK Success.
395 * @retval SR_ERR Failure.
397 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
398 const char *paramstr)
400 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
404 int speed, databits, parity, stopbits, flow, rts, dtr, i;
405 char *mstr, **opts, **kv;
407 speed = databits = parity = stopbits = flow = 0;
409 sr_spew("Parsing parameters from \"%s\".", paramstr);
410 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
411 if (g_regex_match(reg, paramstr, 0, &match)) {
412 if ((mstr = g_match_info_fetch(match, 1)))
413 speed = strtoul(mstr, NULL, 10);
415 if ((mstr = g_match_info_fetch(match, 2)))
416 databits = strtoul(mstr, NULL, 10);
418 if ((mstr = g_match_info_fetch(match, 3))) {
421 parity = SERIAL_PARITY_NONE;
424 parity = SERIAL_PARITY_EVEN;
427 parity = SERIAL_PARITY_ODD;
432 if ((mstr = g_match_info_fetch(match, 4)))
433 stopbits = strtoul(mstr, NULL, 10);
435 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
436 if (mstr[0] != '/') {
437 sr_dbg("missing separator before extra options");
440 /* A set of "key=value" options separated by / */
441 opts = g_strsplit(mstr + 1, "/", 0);
442 for (i = 0; opts[i]; i++) {
443 kv = g_strsplit(opts[i], "=", 2);
444 if (!strncmp(kv[0], "rts", 3)) {
447 else if (kv[1][0] == '0')
450 sr_dbg("invalid value for rts: %c", kv[1][0]);
453 } else if (!strncmp(kv[0], "dtr", 3)) {
456 else if (kv[1][0] == '0')
459 sr_dbg("invalid value for dtr: %c", kv[1][0]);
462 } else if (!strncmp(kv[0], "flow", 4)) {
465 else if (kv[1][0] == '1')
467 else if (kv[1][0] == '2')
470 sr_dbg("invalid value for flow: %c", kv[1][0]);
481 g_match_info_unref(match);
485 return serial_set_params(serial, speed, databits, parity,
486 stopbits, flow, rts, dtr);
488 sr_dbg("Could not infer speed from parameter string.");
494 * Read a line from the specified serial port.
496 * @param serial Previously initialized serial port structure.
497 * @param buf Buffer where to store the bytes that are read.
498 * @param buflen Size of the buffer.
499 * @param[in] timeout_ms How long to wait for a line to come in.
501 * Reading stops when CR of LR is found, which is stripped from the buffer.
503 * @retval SR_OK Success.
504 * @retval SR_ERR Failure.
506 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
507 int *buflen, gint64 timeout_ms)
513 sr_dbg("Invalid serial port.");
518 sr_dbg("Cannot use unopened serial port %s.", serial->port);
523 start = g_get_monotonic_time();
528 len = maxlen - *buflen - 1;
531 len = serial_read(serial, *buf + *buflen, 1);
534 *(*buf + *buflen) = '\0';
535 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
536 || *(*buf + *buflen - 1) == '\n')) {
537 /* Strip CR/LF and terminate. */
538 *(*buf + --*buflen) = '\0';
542 if (g_get_monotonic_time() - start > timeout_ms)
549 sr_dbg("Received %d: '%s'.", *buflen, *buf);
555 * Try to find a valid packet in a serial data stream.
557 * @param serial Previously initialized serial port structure.
558 * @param buf Buffer containing the bytes to write.
559 * @param buflen Size of the buffer.
560 * @param[in] packet_size Size, in bytes, of a valid packet.
561 * @param is_valid Callback that assesses whether the packet is valid or not.
562 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
564 * @param[in] baudrate The baudrate of the serial port. This parameter is not
565 * critical, but it helps fine tune the serial port polling
568 * @retval SR_OK Valid packet was found within the given timeout
569 * @retval SR_ERR Failure.
571 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
572 uint8_t *buf, size_t *buflen,
573 size_t packet_size, packet_valid_t is_valid,
574 uint64_t timeout_ms, int baudrate)
576 uint64_t start, time, byte_delay_us;
577 size_t ibuf, i, maxlen;
582 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
583 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
585 if (maxlen < (packet_size / 2) ) {
586 sr_err("Buffer size must be at least twice the packet size.");
590 /* Assume 8n1 transmission. That is 10 bits for every byte. */
591 byte_delay_us = 10 * (1000000 / baudrate);
592 start = g_get_monotonic_time();
595 while (ibuf < maxlen) {
596 len = serial_read(serial, &buf[ibuf], 1);
599 } else if (len == 0) {
600 /* No logging, already done in serial_read(). */
602 /* Error reading byte, but continuing anyway. */
605 time = g_get_monotonic_time() - start;
608 if ((ibuf - i) >= packet_size) {
609 /* We have at least a packet's worth of data. */
610 if (is_valid(&buf[i])) {
611 sr_spew("Found valid %d-byte packet after "
612 "%" PRIu64 "ms.", (ibuf - i), time);
616 sr_spew("Got %d bytes, but not a valid "
617 "packet.", (ibuf - i));
619 /* Not a valid packet. Continue searching. */
622 if (time >= timeout_ms) {
624 sr_dbg("Detection timed out after %dms.", time);
628 g_usleep(byte_delay_us);
633 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
639 * Extract the serial device and options from the options linked list.
641 * @param options List of options passed from the command line.
642 * @param serial_device Pointer where to store the exctracted serial device.
643 * @param serial_options Pointer where to store the optional extracted serial
646 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
647 * returned string should not be freed by the caller.
649 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
650 const char **serial_options)
653 struct sr_config *src;
655 *serial_device = NULL;
657 for (l = options; l; l = l->next) {
661 *serial_device = g_variant_get_string(src->data, NULL);
662 sr_dbg("Parsed serial device: %s", *serial_device);
665 case SR_CONF_SERIALCOMM:
666 *serial_options = g_variant_get_string(src->data, NULL);
667 sr_dbg("Parsed serial options: %s", *serial_options);
672 if (!*serial_device) {
673 sr_dbg("No serial device specified");
681 typedef HANDLE event_handle;
683 typedef int event_handle;
686 SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
687 int timeout, sr_receive_data_callback_t cb, void *cb_data)
689 enum sp_event mask = 0;
692 if (sp_new_event_set(&serial->event_set) != SP_OK)
695 if (events & G_IO_IN)
696 mask |= SP_EVENT_RX_READY;
697 if (events & G_IO_OUT)
698 mask |= SP_EVENT_TX_READY;
699 if (events & G_IO_ERR)
700 mask |= SP_EVENT_ERROR;
702 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
703 sp_free_event_set(serial->event_set);
707 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
709 for (i = 0; i < serial->event_set->count; i++) {
711 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
713 mask = serial->event_set->masks[i];
715 if (mask & SP_EVENT_RX_READY)
716 serial->pollfds[i].events |= G_IO_IN;
717 if (mask & SP_EVENT_TX_READY)
718 serial->pollfds[i].events |= G_IO_OUT;
719 if (mask & SP_EVENT_ERROR)
720 serial->pollfds[i].events |= G_IO_ERR;
722 if (sr_session_source_add_pollfd(&serial->pollfds[i],
723 timeout, cb, cb_data) != SR_OK)
730 SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
734 for (i = 0; i < serial->event_set->count; i++)
735 if (sr_session_source_remove_pollfd(&serial->pollfds[i]) != SR_OK)
738 g_free(serial->pollfds);
739 sp_free_event_set(serial->event_set);
741 serial->pollfds = NULL;
742 serial->event_set = NULL;
748 * Find USB serial devices via the USB vendor ID and product ID.
750 * @param vendor_id Vendor ID of the USB device.
751 * @param product_id Product ID of the USB device.
753 * @return A GSList of strings containing the path of the serial device or
754 * NULL if no serial device is found. The returned list must be freed
757 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
760 const gchar *usb_dev;
761 const char device_tree[] = "/sys/bus/usb/devices/";
762 GDir *devices_dir, *device_dir;
765 GSList *matched_paths;
768 gchar *vendor_path, *product_path, *path_copy;
769 gchar *prefix, *subdir_path, *device_path, *tty_path;
770 unsigned long read_vendor_id, read_product_id;
775 matched_paths = NULL;
777 if (!(devices_dir = g_dir_open(device_tree, 0, NULL)))
781 * Find potential candidates using the vendor ID and product ID
782 * and store them in matched_paths.
784 while ((usb_dev = g_dir_read_name(devices_dir))) {
785 vendor_path = g_strconcat(device_tree,
786 usb_dev, "/idVendor", NULL);
787 product_path = g_strconcat(device_tree,
788 usb_dev, "/idProduct", NULL);
790 if (!g_file_test(vendor_path, G_FILE_TEST_EXISTS) ||
791 !g_file_test(product_path, G_FILE_TEST_EXISTS))
794 if ((fd = g_fopen(vendor_path, "r")) == NULL)
797 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
801 read_vendor_id = strtoul(tmp, NULL, 16);
805 if ((fd = g_fopen(product_path, "r")) == NULL)
808 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
812 read_product_id = strtoul(tmp, NULL, 16);
816 if (vendor_id == read_vendor_id &&
817 product_id == read_product_id) {
818 path_copy = g_strdup(usb_dev);
819 matched_paths = g_slist_prepend(matched_paths,
825 g_free(product_path);
827 g_dir_close(devices_dir);
829 /* For every matched device try to find a ttyUSBX subfolder. */
830 for (l = matched_paths; l; l = l->next) {
833 device_path = g_strconcat(device_tree, l->data, NULL);
835 if (!(device_dir = g_dir_open(device_path, 0, NULL))) {
840 prefix = g_strconcat(l->data, ":", NULL);
842 while ((file = g_dir_read_name(device_dir))) {
843 if (g_str_has_prefix(file, prefix)) {
844 subdir_path = g_strconcat(device_path,
849 g_dir_close(device_dir);
855 if (!(device_dir = g_dir_open(subdir_path, 0, NULL))) {
861 while ((file = g_dir_read_name(device_dir))) {
862 if (g_str_has_prefix(file, "ttyUSB")) {
863 tty_path = g_strconcat("/dev/",
865 sr_dbg("Found USB device %04x:%04x attached to %s.",
866 vendor_id, product_id, tty_path);
867 tty_devs = g_slist_prepend(tty_devs,
872 g_dir_close(device_dir);
875 g_slist_free_full(matched_paths, g_free);