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 <libserialport.h>
26 #include "libsigrok.h"
27 #include "libsigrok-internal.h"
29 #define LOG_PREFIX "serial"
32 * Open the specified serial port.
34 * @param serial Previously initialized serial port structure.
35 * @param flags Flags to use when opening the serial port. Possible flags
36 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
38 * If the serial structure contains a serialcomm string, it will be
39 * passed to serial_set_paramstr() after the port is opened.
41 * @return SR_OK on success, SR_ERR on failure.
43 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
50 sr_dbg("Invalid serial port.");
54 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
56 sp_get_port_by_name(serial->port, &serial->data);
58 if (flags & SERIAL_RDWR)
59 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
60 else if (flags & SERIAL_RDONLY)
61 sp_flags = SP_MODE_READ;
63 serial->nonblocking = (flags & SERIAL_NONBLOCK) ? 1 : 0;
65 ret = sp_open(serial->data, sp_flags);
69 sr_err("Attempt to open serial port with invalid parameters.");
72 error = sp_last_error_message();
73 sr_err("Error opening port (%d): %s.",
74 sp_last_error_code(), error);
75 sp_free_error_message(error);
79 if (serial->serialcomm)
80 return serial_set_paramstr(serial, serial->serialcomm);
86 * Close the specified serial port.
88 * @param serial Previously initialized serial port structure.
90 * @return SR_OK on success, SR_ERR on failure.
92 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
98 sr_dbg("Invalid serial port.");
103 sr_dbg("Cannot close unopened serial port %s.", serial->port);
107 sr_spew("Closing serial port %s.", serial->port);
109 ret = sp_close(serial->data);
113 sr_err("Attempt to close an invalid serial port.");
116 error = sp_last_error_message();
117 sr_err("Error closing port (%d): %s.",
118 sp_last_error_code(), error);
119 sp_free_error_message(error);
123 sp_free_port(serial->data);
130 * Flush serial port buffers.
132 * @param serial Previously initialized serial port structure.
134 * @return SR_OK on success, SR_ERR on failure.
136 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
142 sr_dbg("Invalid serial port.");
147 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
151 sr_spew("Flushing serial port %s.", serial->port);
153 ret = sp_flush(serial->data, SP_BUF_BOTH);
157 sr_err("Attempt to flush an invalid serial port.");
160 error = sp_last_error_message();
161 sr_err("Error flushing port (%d): %s.",
162 sp_last_error_code(), error);
163 sp_free_error_message(error);
170 static int _serial_write(struct sr_serial_dev_inst *serial,
171 const void *buf, size_t count, int nonblocking)
177 sr_dbg("Invalid serial port.");
182 sr_dbg("Cannot use unopened serial port %s.", serial->port);
187 ret = sp_nonblocking_write(serial->data, buf, count);
189 ret = sp_blocking_write(serial->data, buf, count, 0);
193 sr_err("Attempted serial port write with invalid arguments.");
196 error = sp_last_error_message();
197 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
198 sp_free_error_message(error);
202 sr_spew("Wrote %d/%d bytes.", ret, count);
208 * Write a number of bytes to the specified serial port.
210 * @param serial Previously initialized serial port structure.
211 * @param buf Buffer containing the bytes to write.
212 * @param count Number of bytes to write.
214 * @return The number of bytes written, or a negative error code upon failure.
216 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
217 const void *buf, size_t count)
219 return _serial_write(serial, buf, count, serial->nonblocking);
222 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
223 const void *buf, size_t count)
225 return _serial_write(serial, buf, count, 0);
228 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
229 const void *buf, size_t count)
231 return _serial_write(serial, buf, count, 1);
234 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
235 size_t count, int nonblocking)
241 sr_dbg("Invalid serial port.");
246 sr_dbg("Cannot use unopened serial port %s.", serial->port);
251 ret = sp_nonblocking_read(serial->data, buf, count);
253 ret = sp_blocking_read(serial->data, buf, count, 0);
257 sr_err("Attempted serial port read with invalid arguments.");
260 error = sp_last_error_message();
261 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
262 sp_free_error_message(error);
267 sr_spew("Read %d/%d bytes.", ret, count);
273 * Read a number of bytes from the specified serial port.
275 * @param serial Previously initialized serial port structure.
276 * @param buf Buffer where to store the bytes that are read.
277 * @param count The number of bytes to read.
279 * @return The number of bytes read, or a negative error code upon failure.
281 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
284 return _serial_read(serial, buf, count, serial->nonblocking);
287 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
290 return _serial_read(serial, buf, count, 0);
293 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
296 return _serial_read(serial, buf, count, 1);
300 * Set serial parameters for the specified serial port.
302 * @param serial Previously initialized serial port structure.
303 * @param[in] baudrate The baudrate to set.
304 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
305 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
306 * @param[in] stopbits The number of stop bits to use (1 or 2).
307 * @param[in] flowcontrol The flow control settings to use (0 = none,
308 * 1 = RTS/CTS, 2 = XON/XOFF).
309 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
310 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
312 * @retval SR_OK Success
313 * @retval SR_ERR Failure.
315 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
316 int bits, int parity, int stopbits,
317 int flowcontrol, int rts, int dtr)
321 struct sp_port_config *config;
324 sr_dbg("Invalid serial port.");
329 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
333 sr_spew("Setting serial parameters on port %s.", serial->port);
335 sp_new_config(&config);
336 sp_set_config_baudrate(config, baudrate);
337 sp_set_config_bits(config, bits);
340 sp_set_config_parity(config, SP_PARITY_NONE);
343 sp_set_config_parity(config, SP_PARITY_EVEN);
346 sp_set_config_parity(config, SP_PARITY_ODD);
351 sp_set_config_stopbits(config, stopbits);
352 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
353 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
354 sp_set_config_dtr(config, dtr);
355 sp_set_config_dsr(config, SP_DSR_IGNORE);
356 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
358 ret = sp_set_config(serial->data, config);
359 sp_free_config(config);
363 sr_err("Invalid arguments for setting serial port parameters.");
366 error = sp_last_error_message();
367 sr_err("Error setting serial port parameters (%d): %s.",
368 sp_last_error_code(), error);
369 sp_free_error_message(error);
377 * Set serial parameters for the specified serial port.
379 * @param serial Previously initialized serial port structure.
380 * @param[in] paramstr A serial communication parameters string, in the form
381 * of \<speed\>/\<data bits\>\<parity\>\<stopbits\>\<flow\>, for example
382 * "9600/8n1" or "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none,
383 * 1 for rts/cts and 2 for xon/xoff.
385 * @retval SR_OK Success.
386 * @retval SR_ERR Failure.
388 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
389 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
390 const char *paramstr)
394 int speed, databits, parity, stopbits, flow, rts, dtr, i;
395 char *mstr, **opts, **kv;
397 speed = databits = parity = stopbits = flow = 0;
399 sr_spew("Parsing parameters from \"%s\".", paramstr);
400 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
401 if (g_regex_match(reg, paramstr, 0, &match)) {
402 if ((mstr = g_match_info_fetch(match, 1)))
403 speed = strtoul(mstr, NULL, 10);
405 if ((mstr = g_match_info_fetch(match, 2)))
406 databits = strtoul(mstr, NULL, 10);
408 if ((mstr = g_match_info_fetch(match, 3))) {
411 parity = SERIAL_PARITY_NONE;
414 parity = SERIAL_PARITY_EVEN;
417 parity = SERIAL_PARITY_ODD;
422 if ((mstr = g_match_info_fetch(match, 4)))
423 stopbits = strtoul(mstr, NULL, 10);
425 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
426 if (mstr[0] != '/') {
427 sr_dbg("missing separator before extra options");
430 /* A set of "key=value" options separated by / */
431 opts = g_strsplit(mstr + 1, "/", 0);
432 for (i = 0; opts[i]; i++) {
433 kv = g_strsplit(opts[i], "=", 2);
434 if (!strncmp(kv[0], "rts", 3)) {
437 else if (kv[1][0] == '0')
440 sr_dbg("invalid value for rts: %c", kv[1][0]);
443 } else if (!strncmp(kv[0], "dtr", 3)) {
446 else if (kv[1][0] == '0')
449 sr_dbg("invalid value for dtr: %c", kv[1][0]);
452 } else if (!strncmp(kv[0], "flow", 4)) {
455 else if (kv[1][0] == '1')
457 else if (kv[1][0] == '2')
460 sr_dbg("invalid value for flow: %c", kv[1][0]);
471 g_match_info_unref(match);
475 return serial_set_params(serial, speed, databits, parity,
476 stopbits, flow, rts, dtr);
478 sr_dbg("Could not infer speed from parameter string.");
484 * Read a line from the specified serial port.
486 * @param serial Previously initialized serial port structure.
487 * @param buf Buffer where to store the bytes that are read.
488 * @param buflen Size of the buffer.
489 * @param[in] timeout_ms How long to wait for a line to come in.
491 * Reading stops when CR of LR is found, which is stripped from the buffer.
493 * @retval SR_OK Success.
494 * @retval SR_ERR Failure.
496 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
497 int *buflen, gint64 timeout_ms)
503 sr_dbg("Invalid serial port.");
508 sr_dbg("Cannot use unopened serial port %s.", serial->port);
513 start = g_get_monotonic_time();
518 len = maxlen - *buflen - 1;
521 len = serial_read(serial, *buf + *buflen, 1);
524 *(*buf + *buflen) = '\0';
525 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
526 || *(*buf + *buflen - 1) == '\n')) {
527 /* Strip CR/LF and terminate. */
528 *(*buf + --*buflen) = '\0';
532 if (g_get_monotonic_time() - start > timeout_ms)
539 sr_dbg("Received %d: '%s'.", *buflen, *buf);
545 * Try to find a valid packet in a serial data stream.
547 * @param serial Previously initialized serial port structure.
548 * @param buf Buffer containing the bytes to write.
549 * @param buflen Size of the buffer.
550 * @param[in] packet_size Size, in bytes, of a valid packet.
551 * @param is_valid Callback that assesses whether the packet is valid or not.
552 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
554 * @param[in] baudrate The baudrate of the serial port. This parameter is not
555 * critical, but it helps fine tune the serial port polling
558 * @retval SR_OK Valid packet was found within the given timeout
559 * @retval SR_ERR Failure.
561 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
562 uint8_t *buf, size_t *buflen,
563 size_t packet_size, packet_valid_t is_valid,
564 uint64_t timeout_ms, int baudrate)
566 uint64_t start, time, byte_delay_us;
567 size_t ibuf, i, maxlen;
572 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
573 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
575 if (maxlen < (packet_size / 2) ) {
576 sr_err("Buffer size must be at least twice the packet size.");
580 /* Assume 8n1 transmission. That is 10 bits for every byte. */
581 byte_delay_us = 10 * (1000000 / baudrate);
582 start = g_get_monotonic_time();
585 while (ibuf < maxlen) {
586 len = serial_read(serial, &buf[ibuf], 1);
589 } else if (len == 0) {
590 /* No logging, already done in serial_read(). */
592 /* Error reading byte, but continuing anyway. */
595 time = g_get_monotonic_time() - start;
598 if ((ibuf - i) >= packet_size) {
599 /* We have at least a packet's worth of data. */
600 if (is_valid(&buf[i])) {
601 sr_spew("Found valid %d-byte packet after "
602 "%" PRIu64 "ms.", (ibuf - i), time);
606 sr_spew("Got %d bytes, but not a valid "
607 "packet.", (ibuf - i));
609 /* Not a valid packet. Continue searching. */
612 if (time >= timeout_ms) {
614 sr_dbg("Detection timed out after %dms.", time);
618 g_usleep(byte_delay_us);
623 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
629 * Extract the serial device and options from the options linked list.
631 * @param options List of options passed from the command line.
632 * @param serial_device Pointer where to store the exctracted serial device.
633 * @param serial_options Pointer where to store the optional extracted serial
636 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
637 * returned string should not be freed by the caller.
639 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
640 const char **serial_options)
643 struct sr_config *src;
645 *serial_device = NULL;
647 for (l = options; l; l = l->next) {
651 *serial_device = g_variant_get_string(src->data, NULL);
652 sr_dbg("Parsed serial device: %s", *serial_device);
655 case SR_CONF_SERIALCOMM:
656 *serial_options = g_variant_get_string(src->data, NULL);
657 sr_dbg("Parsed serial options: %s", *serial_options);
662 if (!*serial_device) {
663 sr_dbg("No serial device specified");
671 typedef HANDLE event_handle;
673 typedef int event_handle;
676 SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
677 int timeout, sr_receive_data_callback_t cb, void *cb_data)
679 enum sp_event mask = 0;
682 if (sp_new_event_set(&serial->event_set) != SP_OK)
685 if (events & G_IO_IN)
686 mask |= SP_EVENT_RX_READY;
687 if (events & G_IO_OUT)
688 mask |= SP_EVENT_TX_READY;
689 if (events & G_IO_ERR)
690 mask |= SP_EVENT_ERROR;
692 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
693 sp_free_event_set(serial->event_set);
697 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
699 for (i = 0; i < serial->event_set->count; i++) {
701 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
703 mask = serial->event_set->masks[i];
705 if (mask & SP_EVENT_RX_READY)
706 serial->pollfds[i].events |= G_IO_IN;
707 if (mask & SP_EVENT_TX_READY)
708 serial->pollfds[i].events |= G_IO_OUT;
709 if (mask & SP_EVENT_ERROR)
710 serial->pollfds[i].events |= G_IO_ERR;
712 if (sr_session_source_add_pollfd(&serial->pollfds[i],
713 timeout, cb, cb_data) != SR_OK)
720 SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
724 for (i = 0; i < serial->event_set->count; i++)
725 if (sr_session_source_remove_pollfd(&serial->pollfds[i]) != SR_OK)
728 g_free(serial->pollfds);
729 sp_free_event_set(serial->event_set);
731 serial->pollfds = NULL;
732 serial->event_set = NULL;