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"
32 #define LOG_PREFIX "serial"
38 * Serial port handling.
42 * @defgroup grp_serial Serial port handling
44 * Serial port handling functions.
50 * Open the specified serial port.
52 * @param serial Previously initialized serial port structure.
53 * @param[in] flags Flags to use when opening the serial port. Possible flags
54 * include SERIAL_RDWR, SERIAL_RDONLY.
56 * If the serial structure contains a serialcomm string, it will be
57 * passed to serial_set_paramstr() after the port is opened.
59 * @retval SR_OK Success.
60 * @retval SR_ERR Failure.
64 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
71 sr_dbg("Invalid serial port.");
75 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
77 sp_get_port_by_name(serial->port, &serial->data);
79 if (flags & SERIAL_RDWR)
80 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
81 else if (flags & SERIAL_RDONLY)
82 sp_flags = SP_MODE_READ;
84 ret = sp_open(serial->data, sp_flags);
88 sr_err("Attempt to open serial port with invalid parameters.");
91 error = sp_last_error_message();
92 sr_err("Error opening port (%d): %s.",
93 sp_last_error_code(), error);
94 sp_free_error_message(error);
98 if (serial->serialcomm)
99 return serial_set_paramstr(serial, serial->serialcomm);
105 * Close the specified serial port.
107 * @param serial Previously initialized serial port structure.
109 * @retval SR_OK Success.
110 * @retval SR_ERR Failure.
114 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
120 sr_dbg("Invalid serial port.");
125 sr_dbg("Cannot close unopened serial port %s.", serial->port);
129 sr_spew("Closing serial port %s.", serial->port);
131 ret = sp_close(serial->data);
135 sr_err("Attempt to close an invalid serial port.");
138 error = sp_last_error_message();
139 sr_err("Error closing port (%d): %s.",
140 sp_last_error_code(), error);
141 sp_free_error_message(error);
145 sp_free_port(serial->data);
152 * Flush serial port buffers.
154 * @param serial Previously initialized serial port structure.
156 * @retval SR_OK Success.
157 * @retval SR_ERR Failure.
161 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
167 sr_dbg("Invalid serial port.");
172 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
176 sr_spew("Flushing serial port %s.", serial->port);
178 ret = sp_flush(serial->data, SP_BUF_BOTH);
182 sr_err("Attempt to flush an invalid serial port.");
185 error = sp_last_error_message();
186 sr_err("Error flushing port (%d): %s.",
187 sp_last_error_code(), error);
188 sp_free_error_message(error);
196 * Drain serial port buffers.
198 * @param serial Previously initialized serial port structure.
200 * @retval SR_OK Success.
201 * @retval SR_ERR Failure.
205 SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
211 sr_dbg("Invalid serial port.");
216 sr_dbg("Cannot drain unopened serial port %s.", serial->port);
220 sr_spew("Draining serial port %s.", serial->port);
222 ret = sp_drain(serial->data);
224 if (ret == SP_ERR_FAIL) {
225 error = sp_last_error_message();
226 sr_err("Error draining port (%d): %s.",
227 sp_last_error_code(), error);
228 sp_free_error_message(error);
235 static int _serial_write(struct sr_serial_dev_inst *serial,
236 const void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
242 sr_dbg("Invalid serial port.");
247 sr_dbg("Cannot use unopened serial port %s.", serial->port);
252 ret = sp_nonblocking_write(serial->data, buf, count);
254 ret = sp_blocking_write(serial->data, buf, count, timeout_ms);
258 sr_err("Attempted serial port write with invalid arguments.");
261 error = sp_last_error_message();
262 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
263 sp_free_error_message(error);
267 sr_spew("Wrote %d/%d bytes.", ret, count);
273 * Write a number of bytes to the specified serial port, blocking until finished.
275 * @param serial Previously initialized serial port structure.
276 * @param[in] buf Buffer containing the bytes to write.
277 * @param[in] count Number of bytes to write.
278 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
280 * @retval SR_ERR_ARG Invalid argument.
281 * @retval SR_ERR Other error.
282 * @retval other The number of bytes written. If this is less than the number
283 * specified in the call, the timeout was reached.
287 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
288 const void *buf, size_t count, unsigned int timeout_ms)
290 return _serial_write(serial, buf, count, 0, timeout_ms);
294 * Write a number of bytes to the specified serial port, return immediately.
296 * @param serial Previously initialized serial port structure.
297 * @param[in] buf Buffer containing the bytes to write.
298 * @param[in] count Number of bytes to write.
300 * @retval SR_ERR_ARG Invalid argument.
301 * @retval SR_ERR Other error.
302 * @retval other The number of bytes written.
306 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
307 const void *buf, size_t count)
309 return _serial_write(serial, buf, count, 1, 0);
312 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
313 size_t count, int nonblocking, unsigned int timeout_ms)
319 sr_dbg("Invalid serial port.");
324 sr_dbg("Cannot use unopened serial port %s.", serial->port);
329 ret = sp_nonblocking_read(serial->data, buf, count);
331 ret = sp_blocking_read(serial->data, buf, count, timeout_ms);
335 sr_err("Attempted serial port read with invalid arguments.");
338 error = sp_last_error_message();
339 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
340 sp_free_error_message(error);
345 sr_spew("Read %d/%d bytes.", ret, count);
351 * Read a number of bytes from the specified serial port, block until finished.
353 * @param serial Previously initialized serial port structure.
354 * @param buf Buffer where to store the bytes that are read.
355 * @param[in] count The number of bytes to read.
356 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
358 * @retval SR_ERR_ARG Invalid argument.
359 * @retval SR_ERR Other error.
360 * @retval other The number of bytes read. If this is less than the number
361 * requested, the timeout was reached.
365 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
366 size_t count, unsigned int timeout_ms)
368 return _serial_read(serial, buf, count, 0, timeout_ms);
372 * Try to read up to @a count bytes from the specified serial port, return
373 * immediately with what's available.
375 * @param serial Previously initialized serial port structure.
376 * @param buf Buffer where to store the bytes that are read.
377 * @param[in] count The number of bytes to read.
379 * @retval SR_ERR_ARG Invalid argument.
380 * @retval SR_ERR Other error.
381 * @retval other The number of bytes read.
385 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
388 return _serial_read(serial, buf, count, 1, 0);
392 * Set serial parameters for the specified serial port.
394 * @param serial Previously initialized serial port structure.
395 * @param[in] baudrate The baudrate to set.
396 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
397 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
398 * @param[in] stopbits The number of stop bits to use (1 or 2).
399 * @param[in] flowcontrol The flow control settings to use (0 = none,
400 * 1 = RTS/CTS, 2 = XON/XOFF).
401 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
402 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
404 * @retval SR_OK Success.
405 * @retval SR_ERR Failure.
409 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
410 int bits, int parity, int stopbits,
411 int flowcontrol, int rts, int dtr)
415 struct sp_port_config *config;
418 sr_dbg("Invalid serial port.");
423 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
427 sr_spew("Setting serial parameters on port %s.", serial->port);
429 sp_new_config(&config);
430 sp_set_config_baudrate(config, baudrate);
431 sp_set_config_bits(config, bits);
434 sp_set_config_parity(config, SP_PARITY_NONE);
437 sp_set_config_parity(config, SP_PARITY_EVEN);
440 sp_set_config_parity(config, SP_PARITY_ODD);
445 sp_set_config_stopbits(config, stopbits);
446 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
447 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
448 sp_set_config_dtr(config, dtr);
449 sp_set_config_dsr(config, SP_DSR_IGNORE);
450 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
452 ret = sp_set_config(serial->data, config);
453 sp_free_config(config);
457 sr_err("Invalid arguments for setting serial port parameters.");
460 error = sp_last_error_message();
461 sr_err("Error setting serial port parameters (%d): %s.",
462 sp_last_error_code(), error);
463 sp_free_error_message(error);
471 * Set serial parameters for the specified serial port from parameter string.
473 * @param serial Previously initialized serial port structure.
474 * @param[in] paramstr A serial communication parameters string of the form
475 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
476 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
477 * \<baudrate\>=integer Baud rate.\n
478 * \<bits\>=5|6|7|8 Number of data bits.\n
479 * \<parity\>=n|e|o None, even, odd.\n
480 * \<stopbits\>=1|2 One or two stop bits.\n
482 * dtr=0|1 Set DTR off resp. on.\n
483 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
484 * rts=0|1 Set RTS off resp. on.\n
485 * Please note that values and combinations of these parameters must be
486 * supported by the concrete serial interface hardware and the drivers for it.
488 * @retval SR_OK Success.
489 * @retval SR_ERR Failure.
493 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
494 const char *paramstr)
497 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
502 int speed, databits, parity, stopbits, flow, rts, dtr, i;
503 char *mstr, **opts, **kv;
505 speed = databits = parity = stopbits = flow = 0;
507 sr_spew("Parsing parameters from \"%s\".", paramstr);
508 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
509 if (g_regex_match(reg, paramstr, 0, &match)) {
510 if ((mstr = g_match_info_fetch(match, 1)))
511 speed = strtoul(mstr, NULL, 10);
513 if ((mstr = g_match_info_fetch(match, 2)))
514 databits = strtoul(mstr, NULL, 10);
516 if ((mstr = g_match_info_fetch(match, 3))) {
519 parity = SERIAL_PARITY_NONE;
522 parity = SERIAL_PARITY_EVEN;
525 parity = SERIAL_PARITY_ODD;
530 if ((mstr = g_match_info_fetch(match, 4)))
531 stopbits = strtoul(mstr, NULL, 10);
533 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
534 if (mstr[0] != '/') {
535 sr_dbg("missing separator before extra options");
538 /* A set of "key=value" options separated by / */
539 opts = g_strsplit(mstr + 1, "/", 0);
540 for (i = 0; opts[i]; i++) {
541 kv = g_strsplit(opts[i], "=", 2);
542 if (!strncmp(kv[0], "rts", 3)) {
545 else if (kv[1][0] == '0')
548 sr_dbg("invalid value for rts: %c", kv[1][0]);
551 } else if (!strncmp(kv[0], "dtr", 3)) {
554 else if (kv[1][0] == '0')
557 sr_dbg("invalid value for dtr: %c", kv[1][0]);
560 } else if (!strncmp(kv[0], "flow", 4)) {
563 else if (kv[1][0] == '1')
565 else if (kv[1][0] == '2')
568 sr_dbg("invalid value for flow: %c", kv[1][0]);
579 g_match_info_unref(match);
583 return serial_set_params(serial, speed, databits, parity,
584 stopbits, flow, rts, dtr);
586 sr_dbg("Could not infer speed from parameter string.");
592 * Read a line from the specified serial port.
594 * @param serial Previously initialized serial port structure.
595 * @param buf Buffer where to store the bytes that are read.
596 * @param buflen Size of the buffer.
597 * @param[in] timeout_ms How long to wait for a line to come in.
599 * Reading stops when CR of LR is found, which is stripped from the buffer.
601 * @retval SR_OK Success.
602 * @retval SR_ERR Failure.
606 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
607 int *buflen, gint64 timeout_ms)
609 gint64 start, remaining;
613 sr_dbg("Invalid serial port.");
618 sr_dbg("Cannot use unopened serial port %s.", serial->port);
622 start = g_get_monotonic_time();
623 remaining = timeout_ms;
628 len = maxlen - *buflen - 1;
631 len = sp_blocking_read(serial->data, *buf + *buflen, 1, remaining);
634 *(*buf + *buflen) = '\0';
635 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
636 || *(*buf + *buflen - 1) == '\n')) {
637 /* Strip CR/LF and terminate. */
638 *(*buf + --*buflen) = '\0';
642 /* Reduce timeout by time elapsed. */
643 remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
651 sr_dbg("Received %d: '%s'.", *buflen, *buf);
657 * Try to find a valid packet in a serial data stream.
659 * @param serial Previously initialized serial port structure.
660 * @param buf Buffer containing the bytes to write.
661 * @param buflen Size of the buffer.
662 * @param[in] packet_size Size, in bytes, of a valid packet.
663 * @param is_valid Callback that assesses whether the packet is valid or not.
664 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
666 * @param[in] baudrate The baudrate of the serial port. This parameter is not
667 * critical, but it helps fine tune the serial port polling
670 * @retval SR_OK Valid packet was found within the given timeout.
671 * @retval SR_ERR Failure.
675 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
676 uint8_t *buf, size_t *buflen,
678 packet_valid_callback is_valid,
679 uint64_t timeout_ms, int baudrate)
681 uint64_t start, time, byte_delay_us;
682 size_t ibuf, i, maxlen;
687 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
688 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
690 if (maxlen < (packet_size / 2) ) {
691 sr_err("Buffer size must be at least twice the packet size.");
695 /* Assume 8n1 transmission. That is 10 bits for every byte. */
696 byte_delay_us = 10 * (1000000 / baudrate);
697 start = g_get_monotonic_time();
700 while (ibuf < maxlen) {
701 len = serial_read_nonblocking(serial, &buf[ibuf], 1);
704 } else if (len == 0) {
705 /* No logging, already done in serial_read(). */
707 /* Error reading byte, but continuing anyway. */
710 time = g_get_monotonic_time() - start;
713 if ((ibuf - i) >= packet_size) {
714 /* We have at least a packet's worth of data. */
715 if (is_valid(&buf[i])) {
716 sr_spew("Found valid %d-byte packet after "
717 "%" PRIu64 "ms.", (ibuf - i), time);
721 sr_spew("Got %d bytes, but not a valid "
722 "packet.", (ibuf - i));
724 /* Not a valid packet. Continue searching. */
727 if (time >= timeout_ms) {
729 sr_dbg("Detection timed out after %dms.", time);
733 g_usleep(byte_delay_us);
738 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
744 * Extract the serial device and options from the options linked list.
746 * @param options List of options passed from the command line.
747 * @param serial_device Pointer where to store the exctracted serial device.
748 * @param serial_options Pointer where to store the optional extracted serial
751 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
752 * returned string should not be freed by the caller.
756 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
757 const char **serial_options)
760 struct sr_config *src;
762 *serial_device = NULL;
764 for (l = options; l; l = l->next) {
768 *serial_device = g_variant_get_string(src->data, NULL);
769 sr_dbg("Parsed serial device: %s.", *serial_device);
771 case SR_CONF_SERIALCOMM:
772 *serial_options = g_variant_get_string(src->data, NULL);
773 sr_dbg("Parsed serial options: %s.", *serial_options);
778 if (!*serial_device) {
779 sr_dbg("No serial device specified.");
788 typedef HANDLE event_handle;
790 typedef int event_handle;
795 SR_PRIV int serial_source_add(struct sr_session *session,
796 struct sr_serial_dev_inst *serial, int events, int timeout,
797 sr_receive_data_callback cb, void *cb_data)
799 enum sp_event mask = 0;
802 if (sp_new_event_set(&serial->event_set) != SP_OK)
805 if (events & G_IO_IN)
806 mask |= SP_EVENT_RX_READY;
807 if (events & G_IO_OUT)
808 mask |= SP_EVENT_TX_READY;
809 if (events & G_IO_ERR)
810 mask |= SP_EVENT_ERROR;
812 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
813 sp_free_event_set(serial->event_set);
817 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
819 for (i = 0; i < serial->event_set->count; i++) {
821 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
823 mask = serial->event_set->masks[i];
825 if (mask & SP_EVENT_RX_READY)
826 serial->pollfds[i].events |= G_IO_IN;
827 if (mask & SP_EVENT_TX_READY)
828 serial->pollfds[i].events |= G_IO_OUT;
829 if (mask & SP_EVENT_ERROR)
830 serial->pollfds[i].events |= G_IO_ERR;
832 if (sr_session_source_add_pollfd(session, &serial->pollfds[i],
833 timeout, cb, cb_data) != SR_OK)
841 SR_PRIV int serial_source_remove(struct sr_session *session,
842 struct sr_serial_dev_inst *serial)
846 for (i = 0; i < serial->event_set->count; i++)
847 if (sr_session_source_remove_pollfd(session, &serial->pollfds[i]) != SR_OK)
850 g_free(serial->pollfds);
851 sp_free_event_set(serial->event_set);
853 serial->pollfds = NULL;
854 serial->event_set = NULL;
860 * Create/allocate a new sr_serial_port structure.
862 * @param name The OS dependent name of the serial port. Must not be NULL.
863 * @param description An end user friendly description for the serial port.
864 * Can be NULL (in that case the empty string is used
867 * @return The newly allocated sr_serial_port struct.
869 static struct sr_serial_port *sr_serial_new(const char *name,
870 const char *description)
872 struct sr_serial_port *serial;
877 serial = g_malloc(sizeof(struct sr_serial_port));
878 serial->name = g_strdup(name);
879 serial->description = g_strdup(description ? description : "");
885 * Free a previously allocated sr_serial_port structure.
887 * @param serial The sr_serial_port struct to free. Must not be NULL.
889 SR_API void sr_serial_free(struct sr_serial_port *serial)
893 g_free(serial->name);
894 g_free(serial->description);
899 * List available serial devices.
901 * @return A GSList of strings containing the path of the serial devices or
902 * NULL if no serial device is found. The returned list must be freed
905 SR_API GSList *sr_serial_list(const struct sr_dev_driver *driver)
907 GSList *tty_devs = NULL;
908 struct sp_port **ports;
909 struct sr_serial_port *port;
912 /* Currently unused, but will be used by some drivers later on. */
915 if (sp_list_ports(&ports) != SP_OK)
918 for (i = 0; ports[i]; i++) {
919 port = sr_serial_new(sp_get_port_name(ports[i]),
920 sp_get_port_description(ports[i]));
921 tty_devs = g_slist_append(tty_devs, port);
924 sp_free_port_list(ports);
930 * Find USB serial devices via the USB vendor ID and product ID.
932 * @param[in] vendor_id Vendor ID of the USB device.
933 * @param[in] product_id Product ID of the USB device.
935 * @return A GSList of strings containing the path of the serial device or
936 * NULL if no serial device is found. The returned list must be freed
941 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
943 GSList *tty_devs = NULL;
944 struct sp_port **ports;
947 if (sp_list_ports(&ports) != SP_OK)
950 for (i = 0; ports[i]; i++)
951 if (sp_get_port_transport(ports[i]) == SP_TRANSPORT_USB &&
952 sp_get_port_usb_vid_pid(ports[i], &vid, &pid) == SP_OK &&
953 vid == vendor_id && pid == product_id) {
954 tty_devs = g_slist_prepend(tty_devs,
955 g_strdup(sp_get_port_name(ports[i])));
958 sp_free_port_list(ports);
964 SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
966 struct sp_port_config *config;
967 int timeout_ms, bits, baud, tmp;
972 if (sp_new_config(&config) < 0)
977 if (sp_get_config(port->data, config) < 0)
982 if (sp_get_config_bits(config, &tmp) < 0)
985 if (sp_get_config_stopbits(config, &tmp) < 0)
988 if (sp_get_config_baudrate(config, &tmp) < 0)
994 /* Throw in 10ms for misc OS overhead. */
996 timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
999 sp_free_config(config);