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/libsigrok.h>
29 #include "libsigrok-internal.h"
31 #include <windows.h> /* for HANDLE */
35 #define LOG_PREFIX "serial"
41 * Serial port handling.
45 * @defgroup grp_serial Serial port handling
47 * Serial port handling functions.
53 * Open the specified serial port.
55 * @param serial Previously initialized serial port structure.
56 * @param[in] flags Flags to use when opening the serial port. Possible flags
57 * include SERIAL_RDWR, SERIAL_RDONLY.
59 * If the serial structure contains a serialcomm string, it will be
60 * passed to serial_set_paramstr() after the port is opened.
62 * @retval SR_OK Success.
63 * @retval SR_ERR Failure.
67 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
74 sr_dbg("Invalid serial port.");
78 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
80 sp_get_port_by_name(serial->port, &serial->data);
82 if (flags & SERIAL_RDWR)
83 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
84 else if (flags & SERIAL_RDONLY)
85 sp_flags = SP_MODE_READ;
87 ret = sp_open(serial->data, sp_flags);
91 sr_err("Attempt to open serial port with invalid parameters.");
94 error = sp_last_error_message();
95 sr_err("Error opening port (%d): %s.",
96 sp_last_error_code(), error);
97 sp_free_error_message(error);
101 if (serial->serialcomm)
102 return serial_set_paramstr(serial, serial->serialcomm);
108 * Close the specified serial port.
110 * @param serial Previously initialized serial port structure.
112 * @retval SR_OK Success.
113 * @retval SR_ERR Failure.
117 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
123 sr_dbg("Invalid serial port.");
128 sr_dbg("Cannot close unopened serial port %s.", serial->port);
132 sr_spew("Closing serial port %s.", serial->port);
134 ret = sp_close(serial->data);
138 sr_err("Attempt to close an invalid serial port.");
141 error = sp_last_error_message();
142 sr_err("Error closing port (%d): %s.",
143 sp_last_error_code(), error);
144 sp_free_error_message(error);
148 sp_free_port(serial->data);
155 * Flush serial port buffers.
157 * @param serial Previously initialized serial port structure.
159 * @retval SR_OK Success.
160 * @retval SR_ERR Failure.
164 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
170 sr_dbg("Invalid serial port.");
175 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
179 sr_spew("Flushing serial port %s.", serial->port);
181 ret = sp_flush(serial->data, SP_BUF_BOTH);
185 sr_err("Attempt to flush an invalid serial port.");
188 error = sp_last_error_message();
189 sr_err("Error flushing port (%d): %s.",
190 sp_last_error_code(), error);
191 sp_free_error_message(error);
199 * Drain serial port buffers.
201 * @param serial Previously initialized serial port structure.
203 * @retval SR_OK Success.
204 * @retval SR_ERR Failure.
208 SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
214 sr_dbg("Invalid serial port.");
219 sr_dbg("Cannot drain unopened serial port %s.", serial->port);
223 sr_spew("Draining serial port %s.", serial->port);
225 ret = sp_drain(serial->data);
227 if (ret == SP_ERR_FAIL) {
228 error = sp_last_error_message();
229 sr_err("Error draining port (%d): %s.",
230 sp_last_error_code(), error);
231 sp_free_error_message(error);
238 static int _serial_write(struct sr_serial_dev_inst *serial,
239 const void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
245 sr_dbg("Invalid serial port.");
250 sr_dbg("Cannot use unopened serial port %s.", serial->port);
255 ret = sp_nonblocking_write(serial->data, buf, count);
257 ret = sp_blocking_write(serial->data, buf, count, timeout_ms);
261 sr_err("Attempted serial port write with invalid arguments.");
264 error = sp_last_error_message();
265 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
266 sp_free_error_message(error);
270 sr_spew("Wrote %zd/%zu bytes.", ret, count);
276 * Write a number of bytes to the specified serial port, blocking until finished.
278 * @param serial Previously initialized serial port structure.
279 * @param[in] buf Buffer containing the bytes to write.
280 * @param[in] count Number of bytes to write.
281 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
283 * @retval SR_ERR_ARG Invalid argument.
284 * @retval SR_ERR Other error.
285 * @retval other The number of bytes written. If this is less than the number
286 * specified in the call, the timeout was reached.
290 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
291 const void *buf, size_t count, unsigned int timeout_ms)
293 return _serial_write(serial, buf, count, 0, timeout_ms);
297 * Write a number of bytes to the specified serial port, return immediately.
299 * @param serial Previously initialized serial port structure.
300 * @param[in] buf Buffer containing the bytes to write.
301 * @param[in] count Number of bytes to write.
303 * @retval SR_ERR_ARG Invalid argument.
304 * @retval SR_ERR Other error.
305 * @retval other The number of bytes written.
309 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
310 const void *buf, size_t count)
312 return _serial_write(serial, buf, count, 1, 0);
315 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
316 size_t count, int nonblocking, unsigned int timeout_ms)
322 sr_dbg("Invalid serial port.");
327 sr_dbg("Cannot use unopened serial port %s.", serial->port);
332 ret = sp_nonblocking_read(serial->data, buf, count);
334 ret = sp_blocking_read(serial->data, buf, count, timeout_ms);
338 sr_err("Attempted serial port read with invalid arguments.");
341 error = sp_last_error_message();
342 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
343 sp_free_error_message(error);
348 sr_spew("Read %zd/%zu bytes.", ret, count);
354 * Read a number of bytes from the specified serial port, block until finished.
356 * @param serial Previously initialized serial port structure.
357 * @param buf Buffer where to store the bytes that are read.
358 * @param[in] count The number of bytes to read.
359 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
361 * @retval SR_ERR_ARG Invalid argument.
362 * @retval SR_ERR Other error.
363 * @retval other The number of bytes read. If this is less than the number
364 * requested, the timeout was reached.
368 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
369 size_t count, unsigned int timeout_ms)
371 return _serial_read(serial, buf, count, 0, timeout_ms);
375 * Try to read up to @a count bytes from the specified serial port, return
376 * immediately with what's available.
378 * @param serial Previously initialized serial port structure.
379 * @param buf Buffer where to store the bytes that are read.
380 * @param[in] count The number of bytes to read.
382 * @retval SR_ERR_ARG Invalid argument.
383 * @retval SR_ERR Other error.
384 * @retval other The number of bytes read.
388 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
391 return _serial_read(serial, buf, count, 1, 0);
395 * Set serial parameters for the specified serial port.
397 * @param serial Previously initialized serial port structure.
398 * @param[in] baudrate The baudrate to set.
399 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
400 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
401 * @param[in] stopbits The number of stop bits to use (1 or 2).
402 * @param[in] flowcontrol The flow control settings to use (0 = none,
403 * 1 = RTS/CTS, 2 = XON/XOFF).
404 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
405 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
407 * @retval SR_OK Success.
408 * @retval SR_ERR Failure.
412 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
413 int bits, int parity, int stopbits,
414 int flowcontrol, int rts, int dtr)
418 struct sp_port_config *config;
421 sr_dbg("Invalid serial port.");
426 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
430 sr_spew("Setting serial parameters on port %s.", serial->port);
432 sp_new_config(&config);
433 sp_set_config_baudrate(config, baudrate);
434 sp_set_config_bits(config, bits);
437 sp_set_config_parity(config, SP_PARITY_NONE);
440 sp_set_config_parity(config, SP_PARITY_EVEN);
443 sp_set_config_parity(config, SP_PARITY_ODD);
448 sp_set_config_stopbits(config, stopbits);
449 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
450 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
451 sp_set_config_dtr(config, dtr);
452 sp_set_config_dsr(config, SP_DSR_IGNORE);
453 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
455 ret = sp_set_config(serial->data, config);
456 sp_free_config(config);
460 sr_err("Invalid arguments for setting serial port parameters.");
463 error = sp_last_error_message();
464 sr_err("Error setting serial port parameters (%d): %s.",
465 sp_last_error_code(), error);
466 sp_free_error_message(error);
474 * Set serial parameters for the specified serial port from parameter string.
476 * @param serial Previously initialized serial port structure.
477 * @param[in] paramstr A serial communication parameters string of the form
478 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
479 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
480 * \<baudrate\>=integer Baud rate.\n
481 * \<bits\>=5|6|7|8 Number of data bits.\n
482 * \<parity\>=n|e|o None, even, odd.\n
483 * \<stopbits\>=1|2 One or two stop bits.\n
485 * dtr=0|1 Set DTR off resp. on.\n
486 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
487 * rts=0|1 Set RTS off resp. on.\n
488 * Please note that values and combinations of these parameters must be
489 * supported by the concrete serial interface hardware and the drivers for it.
491 * @retval SR_OK Success.
492 * @retval SR_ERR Failure.
496 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
497 const char *paramstr)
500 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
505 int speed, databits, parity, stopbits, flow, rts, dtr, i;
506 char *mstr, **opts, **kv;
508 speed = databits = parity = stopbits = flow = 0;
510 sr_spew("Parsing parameters from \"%s\".", paramstr);
511 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
512 if (g_regex_match(reg, paramstr, 0, &match)) {
513 if ((mstr = g_match_info_fetch(match, 1)))
514 speed = strtoul(mstr, NULL, 10);
516 if ((mstr = g_match_info_fetch(match, 2)))
517 databits = strtoul(mstr, NULL, 10);
519 if ((mstr = g_match_info_fetch(match, 3))) {
522 parity = SP_PARITY_NONE;
525 parity = SP_PARITY_EVEN;
528 parity = SP_PARITY_ODD;
533 if ((mstr = g_match_info_fetch(match, 4)))
534 stopbits = strtoul(mstr, NULL, 10);
536 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
537 if (mstr[0] != '/') {
538 sr_dbg("missing separator before extra options");
541 /* A set of "key=value" options separated by / */
542 opts = g_strsplit(mstr + 1, "/", 0);
543 for (i = 0; opts[i]; i++) {
544 kv = g_strsplit(opts[i], "=", 2);
545 if (!strncmp(kv[0], "rts", 3)) {
548 else if (kv[1][0] == '0')
551 sr_dbg("invalid value for rts: %c", kv[1][0]);
554 } else if (!strncmp(kv[0], "dtr", 3)) {
557 else if (kv[1][0] == '0')
560 sr_dbg("invalid value for dtr: %c", kv[1][0]);
563 } else if (!strncmp(kv[0], "flow", 4)) {
566 else if (kv[1][0] == '1')
568 else if (kv[1][0] == '2')
571 sr_dbg("invalid value for flow: %c", kv[1][0]);
582 g_match_info_unref(match);
586 return serial_set_params(serial, speed, databits, parity,
587 stopbits, flow, rts, dtr);
589 sr_dbg("Could not infer speed from parameter string.");
595 * Read a line from the specified serial port.
597 * @param serial Previously initialized serial port structure.
598 * @param buf Buffer where to store the bytes that are read.
599 * @param buflen Size of the buffer.
600 * @param[in] timeout_ms How long to wait for a line to come in.
602 * Reading stops when CR of LR is found, which is stripped from the buffer.
604 * @retval SR_OK Success.
605 * @retval SR_ERR Failure.
609 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
610 int *buflen, gint64 timeout_ms)
612 gint64 start, remaining;
616 sr_dbg("Invalid serial port.");
621 sr_dbg("Cannot use unopened serial port %s.", serial->port);
625 start = g_get_monotonic_time();
626 remaining = timeout_ms;
631 len = maxlen - *buflen - 1;
634 len = sp_blocking_read(serial->data, *buf + *buflen, 1, remaining);
637 *(*buf + *buflen) = '\0';
638 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
639 || *(*buf + *buflen - 1) == '\n')) {
640 /* Strip CR/LF and terminate. */
641 *(*buf + --*buflen) = '\0';
645 /* Reduce timeout by time elapsed. */
646 remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
654 sr_dbg("Received %d: '%s'.", *buflen, *buf);
660 * Try to find a valid packet in a serial data stream.
662 * @param serial Previously initialized serial port structure.
663 * @param buf Buffer containing the bytes to write.
664 * @param buflen Size of the buffer.
665 * @param[in] packet_size Size, in bytes, of a valid packet.
666 * @param is_valid Callback that assesses whether the packet is valid or not.
667 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
669 * @param[in] baudrate The baudrate of the serial port. This parameter is not
670 * critical, but it helps fine tune the serial port polling
673 * @retval SR_OK Valid packet was found within the given timeout.
674 * @retval SR_ERR Failure.
678 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
679 uint8_t *buf, size_t *buflen,
681 packet_valid_callback is_valid,
682 uint64_t timeout_ms, int baudrate)
684 uint64_t start, time, byte_delay_us;
685 size_t ibuf, i, maxlen;
690 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
691 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
693 if (maxlen < (packet_size / 2) ) {
694 sr_err("Buffer size must be at least twice the packet size.");
698 /* Assume 8n1 transmission. That is 10 bits for every byte. */
699 byte_delay_us = 10 * ((1000 * 1000) / baudrate);
700 start = g_get_monotonic_time();
703 while (ibuf < maxlen) {
704 len = serial_read_nonblocking(serial, &buf[ibuf], 1);
707 } else if (len == 0) {
708 /* No logging, already done in serial_read(). */
710 /* Error reading byte, but continuing anyway. */
713 time = g_get_monotonic_time() - start;
716 if ((ibuf - i) >= packet_size) {
717 /* We have at least a packet's worth of data. */
718 if (is_valid(&buf[i])) {
719 sr_spew("Found valid %zu-byte packet after "
720 "%" PRIu64 "ms.", (ibuf - i), time);
724 sr_spew("Got %zu bytes, but not a valid "
725 "packet.", (ibuf - i));
727 /* Not a valid packet. Continue searching. */
730 if (time >= timeout_ms) {
732 sr_dbg("Detection timed out after %" PRIu64 "ms.", time);
736 g_usleep(byte_delay_us);
741 sr_err("Didn't find a valid packet (read %zu bytes).", *buflen);
747 * Extract the serial device and options from the options linked list.
749 * @param options List of options passed from the command line.
750 * @param serial_device Pointer where to store the extracted serial device.
751 * @param serial_options Pointer where to store the optional extracted serial
754 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
755 * returned string should not be freed by the caller.
759 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
760 const char **serial_options)
763 struct sr_config *src;
765 *serial_device = NULL;
767 for (l = options; l; l = l->next) {
771 *serial_device = g_variant_get_string(src->data, NULL);
772 sr_dbg("Parsed serial device: %s.", *serial_device);
774 case SR_CONF_SERIALCOMM:
775 *serial_options = g_variant_get_string(src->data, NULL);
776 sr_dbg("Parsed serial options: %s.", *serial_options);
781 if (!*serial_device) {
782 sr_dbg("No serial device specified.");
791 typedef HANDLE event_handle;
793 typedef int event_handle;
798 SR_PRIV int serial_source_add(struct sr_session *session,
799 struct sr_serial_dev_inst *serial, int events, int timeout,
800 sr_receive_data_callback cb, void *cb_data)
802 struct sp_event_set *event_set;
804 unsigned int poll_events;
805 enum sp_event mask = 0;
807 if ((events & (G_IO_IN|G_IO_ERR)) && (events & G_IO_OUT)) {
808 sr_err("Cannot poll input/error and output simultaneously.");
812 if (sp_new_event_set(&event_set) != SP_OK)
815 if (events & G_IO_IN)
816 mask |= SP_EVENT_RX_READY;
817 if (events & G_IO_OUT)
818 mask |= SP_EVENT_TX_READY;
819 if (events & G_IO_ERR)
820 mask |= SP_EVENT_ERROR;
822 if (sp_add_port_events(event_set, serial->data, mask) != SP_OK) {
823 sp_free_event_set(event_set);
826 if (event_set->count != 1) {
827 sr_err("Unexpected number (%u) of event handles to poll.",
829 sp_free_event_set(event_set);
833 poll_fd = (gintptr) ((event_handle *)event_set->handles)[0];
834 mask = event_set->masks[0];
836 sp_free_event_set(event_set);
839 if (mask & SP_EVENT_RX_READY)
840 poll_events |= G_IO_IN;
841 if (mask & SP_EVENT_TX_READY)
842 poll_events |= G_IO_OUT;
843 if (mask & SP_EVENT_ERROR)
844 poll_events |= G_IO_ERR;
846 * Using serial->data as the key for the event source is not quite
847 * proper, as it makes it impossible to create another event source
848 * for the same serial port. However, these fixed keys will soon be
849 * removed from the API anyway, so this is OK for now.
851 return sr_session_fd_source_add(session, serial->data,
852 poll_fd, poll_events, timeout, cb, cb_data);
856 SR_PRIV int serial_source_remove(struct sr_session *session,
857 struct sr_serial_dev_inst *serial)
859 return sr_session_source_remove_internal(session, serial->data);
863 * Create/allocate a new sr_serial_port structure.
865 * @param name The OS dependent name of the serial port. Must not be NULL.
866 * @param description An end user friendly description for the serial port.
867 * Can be NULL (in that case the empty string is used
870 * @return The newly allocated sr_serial_port struct.
872 static struct sr_serial_port *sr_serial_new(const char *name,
873 const char *description)
875 struct sr_serial_port *serial;
880 serial = g_malloc(sizeof(struct sr_serial_port));
881 serial->name = g_strdup(name);
882 serial->description = g_strdup(description ? description : "");
888 * Free a previously allocated sr_serial_port structure.
890 * @param serial The sr_serial_port struct to free. Must not be NULL.
892 SR_API void sr_serial_free(struct sr_serial_port *serial)
896 g_free(serial->name);
897 g_free(serial->description);
902 * List available serial devices.
904 * @return A GSList of strings containing the path of the serial devices or
905 * NULL if no serial device is found. The returned list must be freed
908 SR_API GSList *sr_serial_list(const struct sr_dev_driver *driver)
910 GSList *tty_devs = NULL;
911 struct sp_port **ports;
912 struct sr_serial_port *port;
915 /* Currently unused, but will be used by some drivers later on. */
918 if (sp_list_ports(&ports) != SP_OK)
921 for (i = 0; ports[i]; i++) {
922 port = sr_serial_new(sp_get_port_name(ports[i]),
923 sp_get_port_description(ports[i]));
924 tty_devs = g_slist_append(tty_devs, port);
927 sp_free_port_list(ports);
933 * Find USB serial devices via the USB vendor ID and product ID.
935 * @param[in] vendor_id Vendor ID of the USB device.
936 * @param[in] product_id Product ID of the USB device.
938 * @return A GSList of strings containing the path of the serial device or
939 * NULL if no serial device is found. The returned list must be freed
944 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
946 GSList *tty_devs = NULL;
947 struct sp_port **ports;
950 if (sp_list_ports(&ports) != SP_OK)
953 for (i = 0; ports[i]; i++)
954 if (sp_get_port_transport(ports[i]) == SP_TRANSPORT_USB &&
955 sp_get_port_usb_vid_pid(ports[i], &vid, &pid) == SP_OK &&
956 vid == vendor_id && pid == product_id) {
957 tty_devs = g_slist_prepend(tty_devs,
958 g_strdup(sp_get_port_name(ports[i])));
961 sp_free_port_list(ports);
967 SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
969 struct sp_port_config *config;
970 int timeout_ms, bits, baud, tmp;
975 if (sp_new_config(&config) < 0)
980 if (sp_get_config(port->data, config) < 0)
985 if (sp_get_config_bits(config, &tmp) < 0)
988 if (sp_get_config_stopbits(config, &tmp) < 0)
991 if (sp_get_config_baudrate(config, &tmp) < 0)
997 /* Throw in 10ms for misc OS overhead. */
999 timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
1002 sp_free_config(config);