27 #include <glib/gstdio.h>
28 #include <libserialport.h>
30 #include "libsigrok-internal.h"
36 #define LOG_PREFIX "serial"
68 SR_PRIV int serial_open(
struct sr_serial_dev_inst *serial,
int flags)
75 sr_dbg(
"Invalid serial port.");
79 sr_spew(
"Opening serial port '%s' (flags %d).", serial->port, flags);
81 sp_get_port_by_name(serial->port, &serial->data);
83 if (flags & SERIAL_RDWR)
84 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
85 else if (flags & SERIAL_RDONLY)
86 sp_flags = SP_MODE_READ;
88 ret = sp_open(serial->data, sp_flags);
92 sr_err(
"Attempt to open serial port with invalid parameters.");
95 error = sp_last_error_message();
96 sr_err(
"Error opening port (%d): %s.",
97 sp_last_error_code(), error);
98 sp_free_error_message(error);
102 if (serial->serialcomm)
103 return serial_set_paramstr(serial, serial->serialcomm);
118 SR_PRIV int serial_close(
struct sr_serial_dev_inst *serial)
124 sr_dbg(
"Invalid serial port.");
129 sr_dbg(
"Cannot close unopened serial port %s.", serial->port);
133 sr_spew(
"Closing serial port %s.", serial->port);
135 ret = sp_close(serial->data);
139 sr_err(
"Attempt to close an invalid serial port.");
142 error = sp_last_error_message();
143 sr_err(
"Error closing port (%d): %s.",
144 sp_last_error_code(), error);
145 sp_free_error_message(error);
149 sp_free_port(serial->data);
165 SR_PRIV int serial_flush(
struct sr_serial_dev_inst *serial)
171 sr_dbg(
"Invalid serial port.");
176 sr_dbg(
"Cannot flush unopened serial port %s.", serial->port);
180 sr_spew(
"Flushing serial port %s.", serial->port);
182 ret = sp_flush(serial->data, SP_BUF_BOTH);
186 sr_err(
"Attempt to flush an invalid serial port.");
189 error = sp_last_error_message();
190 sr_err(
"Error flushing port (%d): %s.",
191 sp_last_error_code(), error);
192 sp_free_error_message(error);
209 SR_PRIV int serial_drain(
struct sr_serial_dev_inst *serial)
215 sr_dbg(
"Invalid serial port.");
220 sr_dbg(
"Cannot drain unopened serial port %s.", serial->port);
224 sr_spew(
"Draining serial port %s.", serial->port);
226 ret = sp_drain(serial->data);
228 if (ret == SP_ERR_FAIL) {
229 error = sp_last_error_message();
230 sr_err(
"Error draining port (%d): %s.",
231 sp_last_error_code(), error);
232 sp_free_error_message(error);
239 static int _serial_write(
struct sr_serial_dev_inst *serial,
240 const void *buf,
size_t count,
int nonblocking,
unsigned int timeout_ms)
246 sr_dbg(
"Invalid serial port.");
251 sr_dbg(
"Cannot use unopened serial port %s.", serial->port);
256 ret = sp_nonblocking_write(serial->data, buf, count);
258 ret = sp_blocking_write(serial->data, buf, count, timeout_ms);
262 sr_err(
"Attempted serial port write with invalid arguments.");
265 error = sp_last_error_message();
266 sr_err(
"Write error (%d): %s.", sp_last_error_code(), error);
267 sp_free_error_message(error);
271 sr_spew(
"Wrote %zd/%zu bytes.", ret, count);
291 SR_PRIV int serial_write_blocking(
struct sr_serial_dev_inst *serial,
292 const void *buf,
size_t count,
unsigned int timeout_ms)
294 return _serial_write(serial, buf, count, 0, timeout_ms);
310 SR_PRIV int serial_write_nonblocking(
struct sr_serial_dev_inst *serial,
311 const void *buf,
size_t count)
313 return _serial_write(serial, buf, count, 1, 0);
316 static int _serial_read(
struct sr_serial_dev_inst *serial,
void *buf,
317 size_t count,
int nonblocking,
unsigned int timeout_ms)
323 sr_dbg(
"Invalid serial port.");
328 sr_dbg(
"Cannot use unopened serial port %s.", serial->port);
333 ret = sp_nonblocking_read(serial->data, buf, count);
335 ret = sp_blocking_read(serial->data, buf, count, timeout_ms);
339 sr_err(
"Attempted serial port read with invalid arguments.");
342 error = sp_last_error_message();
343 sr_err(
"Read error (%d): %s.", sp_last_error_code(), error);
344 sp_free_error_message(error);
349 sr_spew(
"Read %zd/%zu bytes.", ret, count);
369 SR_PRIV int serial_read_blocking(
struct sr_serial_dev_inst *serial,
void *buf,
370 size_t count,
unsigned int timeout_ms)
372 return _serial_read(serial, buf, count, 0, timeout_ms);
389 SR_PRIV int serial_read_nonblocking(
struct sr_serial_dev_inst *serial,
void *buf,
392 return _serial_read(serial, buf, count, 1, 0);
413 SR_PRIV int serial_set_params(
struct sr_serial_dev_inst *serial,
int baudrate,
414 int bits,
int parity,
int stopbits,
415 int flowcontrol,
int rts,
int dtr)
419 struct sp_port_config *config;
422 sr_dbg(
"Invalid serial port.");
427 sr_dbg(
"Cannot configure unopened serial port %s.", serial->port);
431 sr_spew(
"Setting serial parameters on port %s.", serial->port);
433 sp_new_config(&config);
434 sp_set_config_baudrate(config, baudrate);
435 sp_set_config_bits(config, bits);
438 sp_set_config_parity(config, SP_PARITY_NONE);
441 sp_set_config_parity(config, SP_PARITY_EVEN);
444 sp_set_config_parity(config, SP_PARITY_ODD);
449 sp_set_config_stopbits(config, stopbits);
450 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
451 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
452 sp_set_config_dtr(config, dtr);
453 sp_set_config_dsr(config, SP_DSR_IGNORE);
454 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
456 ret = sp_set_config(serial->data, config);
457 sp_free_config(config);
461 sr_err(
"Invalid arguments for setting serial port parameters.");
464 error = sp_last_error_message();
465 sr_err(
"Error setting serial port parameters (%d): %s.",
466 sp_last_error_code(), error);
467 sp_free_error_message(error);
497 SR_PRIV int serial_set_paramstr(
struct sr_serial_dev_inst *serial,
498 const char *paramstr)
501 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
506 int speed, databits, parity, stopbits, flow, rts, dtr, i;
507 char *mstr, **opts, **kv;
509 speed = databits = parity = stopbits = flow = 0;
511 sr_spew(
"Parsing parameters from \"%s\".", paramstr);
512 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
513 if (g_regex_match(reg, paramstr, 0, &match)) {
514 if ((mstr = g_match_info_fetch(match, 1)))
515 speed = strtoul(mstr, NULL, 10);
517 if ((mstr = g_match_info_fetch(match, 2)))
518 databits = strtoul(mstr, NULL, 10);
520 if ((mstr = g_match_info_fetch(match, 3))) {
523 parity = SP_PARITY_NONE;
526 parity = SP_PARITY_EVEN;
529 parity = SP_PARITY_ODD;
534 if ((mstr = g_match_info_fetch(match, 4)))
535 stopbits = strtoul(mstr, NULL, 10);
537 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] !=
'\0') {
538 if (mstr[0] !=
'/') {
539 sr_dbg(
"missing separator before extra options");
543 opts = g_strsplit(mstr + 1,
"/", 0);
544 for (i = 0; opts[i]; i++) {
545 kv = g_strsplit(opts[i],
"=", 2);
546 if (!strncmp(kv[0],
"rts", 3)) {
549 else if (kv[1][0] ==
'0')
552 sr_dbg(
"invalid value for rts: %c", kv[1][0]);
555 }
else if (!strncmp(kv[0],
"dtr", 3)) {
558 else if (kv[1][0] ==
'0')
561 sr_dbg(
"invalid value for dtr: %c", kv[1][0]);
564 }
else if (!strncmp(kv[0],
"flow", 4)) {
567 else if (kv[1][0] ==
'1')
569 else if (kv[1][0] ==
'2')
572 sr_dbg(
"invalid value for flow: %c", kv[1][0]);
583 g_match_info_unref(match);
587 return serial_set_params(serial, speed, databits, parity,
588 stopbits, flow, rts, dtr);
590 sr_dbg(
"Could not infer speed from parameter string.");
610 SR_PRIV int serial_readline(
struct sr_serial_dev_inst *serial,
char **buf,
611 int *buflen, gint64 timeout_ms)
613 gint64 start, remaining;
617 sr_dbg(
"Invalid serial port.");
622 sr_dbg(
"Cannot use unopened serial port %s.", serial->port);
626 start = g_get_monotonic_time();
627 remaining = timeout_ms;
632 len = maxlen - *buflen - 1;
635 len = sp_blocking_read(serial->data, *buf + *buflen, 1, remaining);
638 *(*buf + *buflen) =
'\0';
639 if (*buflen > 0 && (*(*buf + *buflen - 1) ==
'\r'
640 || *(*buf + *buflen - 1) ==
'\n')) {
642 *(*buf + --*buflen) =
'\0';
647 remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
655 sr_dbg(
"Received %d: '%s'.", *buflen, *buf);
679 SR_PRIV int serial_stream_detect(
struct sr_serial_dev_inst *serial,
680 uint8_t *buf,
size_t *buflen,
682 packet_valid_callback is_valid,
683 uint64_t timeout_ms,
int baudrate)
685 uint64_t start, time, byte_delay_us;
686 size_t ibuf, i, maxlen;
691 sr_dbg(
"Detecting packets on %s (timeout = %" PRIu64
692 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
694 if (maxlen < (packet_size / 2) ) {
695 sr_err(
"Buffer size must be at least twice the packet size.");
700 byte_delay_us = 10 * ((1000 * 1000) / baudrate);
701 start = g_get_monotonic_time();
704 while (ibuf < maxlen) {
705 len = serial_read_nonblocking(serial, &buf[ibuf], 1);
708 }
else if (len == 0) {
714 time = g_get_monotonic_time() - start;
717 if ((ibuf - i) >= packet_size) {
719 if (is_valid(&buf[i])) {
720 sr_spew(
"Found valid %zu-byte packet after "
721 "%" PRIu64
"ms.", (ibuf - i), time);
725 sr_spew(
"Got %zu bytes, but not a valid "
726 "packet.", (ibuf - i));
731 if (time >= timeout_ms) {
733 sr_dbg(
"Detection timed out after %" PRIu64
"ms.", time);
737 g_usleep(byte_delay_us);
742 sr_err(
"Didn't find a valid packet (read %zu bytes).", *buflen);
760 SR_PRIV int sr_serial_extract_options(GSList *options,
const char **serial_device,
761 const char **serial_options)
766 *serial_device = NULL;
768 for (l = options; l; l = l->next) {
772 *serial_device = g_variant_get_string(src->
data, NULL);
773 sr_dbg(
"Parsed serial device: %s.", *serial_device);
776 *serial_options = g_variant_get_string(src->
data, NULL);
777 sr_dbg(
"Parsed serial options: %s.", *serial_options);
782 if (!*serial_device) {
783 sr_dbg(
"No serial device specified.");
792 typedef HANDLE event_handle;
794 typedef int event_handle;
800 struct sr_serial_dev_inst *serial,
int events,
int timeout,
803 struct sp_event_set *event_set;
805 unsigned int poll_events;
806 enum sp_event mask = 0;
808 if ((events & (G_IO_IN|G_IO_ERR)) && (events & G_IO_OUT)) {
809 sr_err(
"Cannot poll input/error and output simultaneously.");
813 if (sp_new_event_set(&event_set) != SP_OK)
816 if (events & G_IO_IN)
817 mask |= SP_EVENT_RX_READY;
818 if (events & G_IO_OUT)
819 mask |= SP_EVENT_TX_READY;
820 if (events & G_IO_ERR)
821 mask |= SP_EVENT_ERROR;
823 if (sp_add_port_events(event_set, serial->data, mask) != SP_OK) {
824 sp_free_event_set(event_set);
827 if (event_set->count != 1) {
828 sr_err(
"Unexpected number (%u) of event handles to poll.",
830 sp_free_event_set(event_set);
834 poll_fd = (gintptr) ((event_handle *)event_set->handles)[0];
835 mask = event_set->masks[0];
837 sp_free_event_set(event_set);
840 if (mask & SP_EVENT_RX_READY)
841 poll_events |= G_IO_IN;
842 if (mask & SP_EVENT_TX_READY)
843 poll_events |= G_IO_OUT;
844 if (mask & SP_EVENT_ERROR)
845 poll_events |= G_IO_ERR;
853 poll_fd, poll_events, timeout, cb, cb_data);
858 struct sr_serial_dev_inst *serial)
860 return sr_session_source_remove_internal(session, serial->data);
882 serial->
name = g_strdup(name);
883 serial->
description = g_strdup(description ? description :
"");
897 g_free(serial->
name);
911 GSList *tty_devs = NULL;
912 struct sp_port **ports;
919 if (sp_list_ports(&ports) != SP_OK)
922 for (i = 0; ports[i]; i++) {
923 port = sr_serial_new(sp_get_port_name(ports[i]),
924 sp_get_port_description(ports[i]));
925 tty_devs = g_slist_append(tty_devs, port);
928 sp_free_port_list(ports);
945 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
947 GSList *tty_devs = NULL;
948 struct sp_port **ports;
951 if (sp_list_ports(&ports) != SP_OK)
954 for (i = 0; ports[i]; i++)
955 if (sp_get_port_transport(ports[i]) == SP_TRANSPORT_USB &&
956 sp_get_port_usb_vid_pid(ports[i], &vid, &pid) == SP_OK &&
957 vid == vendor_id && pid == product_id) {
958 tty_devs = g_slist_prepend(tty_devs,
959 g_strdup(sp_get_port_name(ports[i])));
962 sp_free_port_list(ports);
968 SR_PRIV int serial_timeout(
struct sr_serial_dev_inst *port,
int num_bytes)
970 struct sp_port_config *config;
971 int timeout_ms, bits, baud, tmp;
976 if (sp_new_config(&config) < 0)
981 if (sp_get_config(port->data, config) < 0)
986 if (sp_get_config_bits(config, &tmp) < 0)
989 if (sp_get_config_stopbits(config, &tmp) < 0)
992 if (sp_get_config_baudrate(config, &tmp) < 0)
1000 timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
1003 sp_free_config(config);
char * name
The OS dependent name of the serial port.
GSList * sr_serial_list(const struct sr_dev_driver *driver)
List available serial devices.
The public libsigrok header file to be used by frontends.
void sr_serial_free(struct sr_serial_port *serial)
Free a previously allocated sr_serial_port structure.
Generic/unspecified error.
Opaque structure representing a libsigrok session.
char * description
An end user friendly description for the serial port.
SR_PRIV int sr_session_fd_source_add(struct sr_session *session, void *key, gintptr fd, int events, int timeout, sr_receive_data_callback cb, void *cb_data)
GVariant * data
Key-specific data.
Specification on how to connect to a device.
int(* sr_receive_data_callback)(int fd, int revents, void *cb_data)
Type definition for callback function for data reception.
Serial communication specification, in the form:
uint32_t key
Config key like SR_CONF_CONN, etc.
Used for setting or getting value of a config item.