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);
171 * Write a number of bytes to the specified serial port.
173 * @param serial Previously initialized serial port structure.
174 * @param buf Buffer containing the bytes to write.
175 * @param count Number of bytes to write.
177 * @return The number of bytes written, or a negative error code upon failure.
179 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
180 const void *buf, size_t count)
186 sr_dbg("Invalid serial port.");
191 sr_dbg("Cannot use unopened serial port %s.", serial->port);
195 if (serial->nonblocking)
196 ret = sp_nonblocking_write(serial->data, buf, count);
198 ret = sp_blocking_write(serial->data, buf, count, 0);
202 sr_err("Attempted serial port write with invalid arguments.");
205 error = sp_last_error_message();
206 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
207 sp_free_error_message(error);
211 sr_spew("Wrote %d/%d bytes.", ret, count);
217 * Read a number of bytes from the specified serial port.
219 * @param serial Previously initialized serial port structure.
220 * @param buf Buffer where to store the bytes that are read.
221 * @param count The number of bytes to read.
223 * @return The number of bytes read, or a negative error code upon failure.
225 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
232 sr_dbg("Invalid serial port.");
237 sr_dbg("Cannot use unopened serial port %s.", serial->port);
241 if (serial->nonblocking)
242 ret = sp_nonblocking_read(serial->data, buf, count);
244 ret = sp_blocking_read(serial->data, buf, count, 0);
248 sr_err("Attempted serial port read with invalid arguments.");
251 error = sp_last_error_message();
252 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
253 sp_free_error_message(error);
258 sr_spew("Read %d/%d bytes.", ret, count);
264 * Set serial parameters for the specified serial port.
266 * @param serial Previously initialized serial port structure.
267 * @param[in] baudrate The baudrate to set.
268 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
269 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
270 * @param[in] stopbits The number of stop bits to use (1 or 2).
271 * @param[in] flowcontrol The flow control settings to use (0 = none,
272 * 1 = RTS/CTS, 2 = XON/XOFF).
273 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
274 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
276 * @retval SR_OK Success
277 * @retval SR_ERR Failure.
279 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
280 int bits, int parity, int stopbits,
281 int flowcontrol, int rts, int dtr)
285 struct sp_port_config *config;
288 sr_dbg("Invalid serial port.");
293 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
297 sr_spew("Setting serial parameters on port %s.", serial->port);
299 sp_new_config(&config);
300 sp_set_config_baudrate(config, baudrate);
301 sp_set_config_bits(config, bits);
304 sp_set_config_parity(config, SP_PARITY_NONE);
307 sp_set_config_parity(config, SP_PARITY_EVEN);
310 sp_set_config_parity(config, SP_PARITY_ODD);
315 sp_set_config_stopbits(config, stopbits);
316 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
317 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
318 sp_set_config_dtr(config, dtr);
319 sp_set_config_dsr(config, SP_DSR_IGNORE);
320 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
322 ret = sp_set_config(serial->data, config);
323 sp_free_config(config);
327 sr_err("Invalid arguments for setting serial port parameters.");
330 error = sp_last_error_message();
331 sr_err("Error setting serial port parameters (%d): %s.",
332 sp_last_error_code(), error);
333 sp_free_error_message(error);
341 * Set serial parameters for the specified serial port.
343 * @param serial Previously initialized serial port structure.
344 * @param[in] paramstr A serial communication parameters string, in the form
345 * of \<speed\>/\<data bits\>\<parity\>\<stopbits\>\<flow\>, for example
346 * "9600/8n1" or "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none,
347 * 1 for rts/cts and 2 for xon/xoff.
349 * @retval SR_OK Success.
350 * @retval SR_ERR Failure.
352 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
353 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
354 const char *paramstr)
358 int speed, databits, parity, stopbits, flow, rts, dtr, i;
359 char *mstr, **opts, **kv;
361 speed = databits = parity = stopbits = flow = 0;
363 sr_spew("Parsing parameters from \"%s\".", paramstr);
364 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
365 if (g_regex_match(reg, paramstr, 0, &match)) {
366 if ((mstr = g_match_info_fetch(match, 1)))
367 speed = strtoul(mstr, NULL, 10);
369 if ((mstr = g_match_info_fetch(match, 2)))
370 databits = strtoul(mstr, NULL, 10);
372 if ((mstr = g_match_info_fetch(match, 3))) {
375 parity = SERIAL_PARITY_NONE;
378 parity = SERIAL_PARITY_EVEN;
381 parity = SERIAL_PARITY_ODD;
386 if ((mstr = g_match_info_fetch(match, 4)))
387 stopbits = strtoul(mstr, NULL, 10);
389 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
390 if (mstr[0] != '/') {
391 sr_dbg("missing separator before extra options");
394 /* A set of "key=value" options separated by / */
395 opts = g_strsplit(mstr + 1, "/", 0);
396 for (i = 0; opts[i]; i++) {
397 kv = g_strsplit(opts[i], "=", 2);
398 if (!strncmp(kv[0], "rts", 3)) {
401 else if (kv[1][0] == '0')
404 sr_dbg("invalid value for rts: %c", kv[1][0]);
407 } else if (!strncmp(kv[0], "dtr", 3)) {
410 else if (kv[1][0] == '0')
413 sr_dbg("invalid value for dtr: %c", kv[1][0]);
416 } else if (!strncmp(kv[0], "flow", 4)) {
419 else if (kv[1][0] == '1')
421 else if (kv[1][0] == '2')
424 sr_dbg("invalid value for flow: %c", kv[1][0]);
435 g_match_info_unref(match);
439 return serial_set_params(serial, speed, databits, parity,
440 stopbits, flow, rts, dtr);
442 sr_dbg("Could not infer speed from parameter string.");
448 * Read a line from the specified serial port.
450 * @param serial Previously initialized serial port structure.
451 * @param buf Buffer where to store the bytes that are read.
452 * @param buflen Size of the buffer.
453 * @param[in] timeout_ms How long to wait for a line to come in.
455 * Reading stops when CR of LR is found, which is stripped from the buffer.
457 * @retval SR_OK Success.
458 * @retval SR_ERR Failure.
460 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
461 int *buflen, gint64 timeout_ms)
467 sr_dbg("Invalid serial port.");
472 sr_dbg("Cannot use unopened serial port %s.", serial->port);
477 start = g_get_monotonic_time();
482 len = maxlen - *buflen - 1;
485 len = serial_read(serial, *buf + *buflen, 1);
488 *(*buf + *buflen) = '\0';
489 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
490 || *(*buf + *buflen - 1) == '\n')) {
491 /* Strip CR/LF and terminate. */
492 *(*buf + --*buflen) = '\0';
496 if (g_get_monotonic_time() - start > timeout_ms)
503 sr_dbg("Received %d: '%s'.", *buflen, *buf);
509 * Try to find a valid packet in a serial data stream.
511 * @param serial Previously initialized serial port structure.
512 * @param buf Buffer containing the bytes to write.
513 * @param buflen Size of the buffer.
514 * @param[in] packet_size Size, in bytes, of a valid packet.
515 * @param is_valid Callback that assesses whether the packet is valid or not.
516 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
518 * @param[in] baudrate The baudrate of the serial port. This parameter is not
519 * critical, but it helps fine tune the serial port polling
522 * @retval SR_OK Valid packet was found within the given timeout
523 * @retval SR_ERR Failure.
525 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
526 uint8_t *buf, size_t *buflen,
527 size_t packet_size, packet_valid_t is_valid,
528 uint64_t timeout_ms, int baudrate)
530 uint64_t start, time, byte_delay_us;
531 size_t ibuf, i, maxlen;
536 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
537 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
539 if (maxlen < (packet_size / 2) ) {
540 sr_err("Buffer size must be at least twice the packet size.");
544 /* Assume 8n1 transmission. That is 10 bits for every byte. */
545 byte_delay_us = 10 * (1000000 / baudrate);
546 start = g_get_monotonic_time();
549 while (ibuf < maxlen) {
550 len = serial_read(serial, &buf[ibuf], 1);
553 } else if (len == 0) {
554 /* No logging, already done in serial_read(). */
556 /* Error reading byte, but continuing anyway. */
559 time = g_get_monotonic_time() - start;
562 if ((ibuf - i) >= packet_size) {
563 /* We have at least a packet's worth of data. */
564 if (is_valid(&buf[i])) {
565 sr_spew("Found valid %d-byte packet after "
566 "%" PRIu64 "ms.", (ibuf - i), time);
570 sr_spew("Got %d bytes, but not a valid "
571 "packet.", (ibuf - i));
573 /* Not a valid packet. Continue searching. */
576 if (time >= timeout_ms) {
578 sr_dbg("Detection timed out after %dms.", time);
582 g_usleep(byte_delay_us);
587 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
593 * Extract the serial device and options from the options linked list.
595 * @param options List of options passed from the command line.
596 * @param serial_device Pointer where to store the exctracted serial device.
597 * @param serial_options Pointer where to store the optional extracted serial
600 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
601 * returned string should not be freed by the caller.
603 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
604 const char **serial_options)
607 struct sr_config *src;
609 *serial_device = NULL;
611 for (l = options; l; l = l->next) {
615 *serial_device = g_variant_get_string(src->data, NULL);
616 sr_dbg("Parsed serial device: %s", *serial_device);
619 case SR_CONF_SERIALCOMM:
620 *serial_options = g_variant_get_string(src->data, NULL);
621 sr_dbg("Parsed serial options: %s", *serial_options);
626 if (!*serial_device) {
627 sr_dbg("No serial device specified");
635 typedef HANDLE event_handle;
637 typedef int event_handle;
640 SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
641 int timeout, sr_receive_data_callback_t cb, void *cb_data)
643 enum sp_event mask = 0;
646 if (sp_new_event_set(&serial->event_set) != SP_OK)
649 if (events & G_IO_IN)
650 mask |= SP_EVENT_RX_READY;
651 if (events & G_IO_OUT)
652 mask |= SP_EVENT_TX_READY;
653 if (events & G_IO_ERR)
654 mask |= SP_EVENT_ERROR;
656 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
657 sp_free_event_set(serial->event_set);
661 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
663 for (i = 0; i < serial->event_set->count; i++) {
665 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
667 mask = serial->event_set->masks[i];
669 if (mask & SP_EVENT_RX_READY)
670 serial->pollfds[i].events |= G_IO_IN;
671 if (mask & SP_EVENT_TX_READY)
672 serial->pollfds[i].events |= G_IO_OUT;
673 if (mask & SP_EVENT_ERROR)
674 serial->pollfds[i].events |= G_IO_ERR;
676 if (sr_session_source_add_pollfd(&serial->pollfds[i],
677 timeout, cb, cb_data) != SR_OK)
684 SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
688 for (i = 0; i < serial->event_set->count; i++)
689 if (sr_session_source_remove_pollfd(&serial->pollfds[i]) != SR_OK)
692 g_free(serial->pollfds);
693 sp_free_event_set(serial->event_set);
695 serial->pollfds = NULL;
696 serial->event_set = NULL;