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 /* Message logging helpers with subsystem-specific prefix string. */
30 #define LOG_PREFIX "serial: "
31 #define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
32 #define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
33 #define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
34 #define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
35 #define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
36 #define sr_err(s, args...) sr_err(LOG_PREFIX s, ## args)
39 * Open the specified serial port.
41 * @param serial Previously initialized serial port structure.
42 * @param flags Flags to use when opening the serial port. Possible flags
43 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
45 * If the serial structure contains a serialcomm string, it will be
46 * passed to serial_set_paramstr() after the port is opened.
48 * @return SR_OK on success, SR_ERR on failure.
50 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
57 sr_dbg("Invalid serial port.");
61 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
63 sp_get_port_by_name(serial->port, &serial->data);
65 if (flags & SERIAL_RDWR)
66 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
67 else if (flags & SERIAL_RDONLY)
68 sp_flags = SP_MODE_READ;
70 serial->nonblocking = (flags & SERIAL_NONBLOCK) ? 1 : 0;
72 ret = sp_open(serial->data, sp_flags);
76 sr_err("Attempt to open serial port with invalid parameters.");
79 error = sp_last_error_message();
80 sr_err("Error opening port (%d): %s.",
81 sp_last_error_code(), error);
82 sp_free_error_message(error);
86 if (serial->serialcomm)
87 return serial_set_paramstr(serial, serial->serialcomm);
93 * Close the specified serial port.
95 * @param serial Previously initialized serial port structure.
97 * @return SR_OK on success, SR_ERR on failure.
99 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
105 sr_dbg("Invalid serial port.");
110 sr_dbg("Cannot close unopened serial port %s.", serial->port);
114 sr_spew("Closing serial port %s.", serial->port);
116 ret = sp_close(serial->data);
120 sr_err("Attempt to close an invalid serial port.");
123 error = sp_last_error_message();
124 sr_err("Error closing port (%d): %s.",
125 sp_last_error_code(), error);
126 sp_free_error_message(error);
130 sp_free_port(serial->data);
137 * Flush serial port buffers.
139 * @param serial Previously initialized serial port structure.
141 * @return SR_OK on success, SR_ERR on failure.
143 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
149 sr_dbg("Invalid serial port.");
154 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
158 sr_spew("Flushing serial port %s.", serial->port);
160 ret = sp_flush(serial->data, SP_BUF_BOTH);
164 sr_err("Attempt to flush an invalid serial port.");
167 error = sp_last_error_message();
168 sr_err("Error flushing port (%d): %s.",
169 sp_last_error_code(), error);
170 sp_free_error_message(error);
178 * Write a number of bytes to the specified serial port.
180 * @param serial Previously initialized serial port structure.
181 * @param buf Buffer containing the bytes to write.
182 * @param count Number of bytes to write.
184 * @return The number of bytes written, or a negative error code upon failure.
186 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
187 const void *buf, size_t count)
193 sr_dbg("Invalid serial port.");
198 sr_dbg("Cannot use unopened serial port %s.", serial->port);
202 if (serial->nonblocking)
203 ret = sp_nonblocking_write(serial->data, buf, count);
205 ret = sp_blocking_write(serial->data, buf, count, 0);
209 sr_err("Attempted serial port write with invalid arguments.");
212 error = sp_last_error_message();
213 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
214 sp_free_error_message(error);
218 sr_spew("Wrote %d/%d bytes.", ret, count);
224 * Read a number of bytes from the specified serial port.
226 * @param serial Previously initialized serial port structure.
227 * @param buf Buffer where to store the bytes that are read.
228 * @param count The number of bytes to read.
230 * @return The number of bytes read, or a negative error code upon failure.
232 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
239 sr_dbg("Invalid serial port.");
244 sr_dbg("Cannot use unopened serial port %s.", serial->port);
248 if (serial->nonblocking)
249 ret = sp_nonblocking_read(serial->data, buf, count);
251 ret = sp_blocking_read(serial->data, buf, count, 0);
255 sr_err("Attempted serial port read with invalid arguments.");
258 error = sp_last_error_message();
259 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
260 sp_free_error_message(error);
265 sr_spew("Read %d/%d bytes.", ret, count);
271 * Set serial parameters for the specified serial port.
273 * @param serial Previously initialized serial port structure.
274 * @param[in] baudrate The baudrate to set.
275 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
276 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
277 * @param[in] stopbits The number of stop bits to use (1 or 2).
278 * @param[in] flowcontrol The flow control settings to use (0 = none,
279 * 1 = RTS/CTS, 2 = XON/XOFF).
280 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
281 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
283 * @retval SR_OK Success
284 * @retval SR_ERR Failure.
286 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
287 int bits, int parity, int stopbits,
288 int flowcontrol, int rts, int dtr)
292 struct sp_port_config *config;
295 sr_dbg("Invalid serial port.");
300 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
304 sr_spew("Setting serial parameters on port %s.", serial->port);
306 sp_new_config(&config);
307 sp_set_config_baudrate(config, baudrate);
308 sp_set_config_bits(config, bits);
311 sp_set_config_parity(config, SP_PARITY_NONE);
314 sp_set_config_parity(config, SP_PARITY_EVEN);
317 sp_set_config_parity(config, SP_PARITY_ODD);
322 sp_set_config_stopbits(config, stopbits);
323 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
324 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
325 sp_set_config_dtr(config, dtr);
326 sp_set_config_dsr(config, SP_DSR_IGNORE);
327 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
329 ret = sp_set_config(serial->data, config);
330 sp_free_config(config);
334 sr_err("Invalid arguments for setting serial port parameters.");
337 error = sp_last_error_message();
338 sr_err("Error setting serial port parameters (%d): %s.",
339 sp_last_error_code(), error);
340 sp_free_error_message(error);
348 * Set serial parameters for the specified serial port.
350 * @param serial Previously initialized serial port structure.
351 * @param[in] paramstr A serial communication parameters string, in the form
352 * of \<speed\>/\<data bits\>\<parity\>\<stopbits\>\<flow\>, for example
353 * "9600/8n1" or "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none,
354 * 1 for rts/cts and 2 for xon/xoff.
356 * @retval SR_OK Success.
357 * @retval SR_ERR Failure.
359 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
360 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
361 const char *paramstr)
365 int speed, databits, parity, stopbits, flow, rts, dtr, i;
366 char *mstr, **opts, **kv;
368 speed = databits = parity = stopbits = flow = 0;
370 sr_spew("Parsing parameters from \"%s\".", paramstr);
371 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
372 if (g_regex_match(reg, paramstr, 0, &match)) {
373 if ((mstr = g_match_info_fetch(match, 1)))
374 speed = strtoul(mstr, NULL, 10);
376 if ((mstr = g_match_info_fetch(match, 2)))
377 databits = strtoul(mstr, NULL, 10);
379 if ((mstr = g_match_info_fetch(match, 3))) {
382 parity = SERIAL_PARITY_NONE;
385 parity = SERIAL_PARITY_EVEN;
388 parity = SERIAL_PARITY_ODD;
393 if ((mstr = g_match_info_fetch(match, 4)))
394 stopbits = strtoul(mstr, NULL, 10);
396 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
397 if (mstr[0] != '/') {
398 sr_dbg("missing separator before extra options");
401 /* A set of "key=value" options separated by / */
402 opts = g_strsplit(mstr + 1, "/", 0);
403 for (i = 0; opts[i]; i++) {
404 kv = g_strsplit(opts[i], "=", 2);
405 if (!strncmp(kv[0], "rts", 3)) {
408 else if (kv[1][0] == '0')
411 sr_dbg("invalid value for rts: %c", kv[1][0]);
414 } else if (!strncmp(kv[0], "dtr", 3)) {
417 else if (kv[1][0] == '0')
420 sr_dbg("invalid value for dtr: %c", kv[1][0]);
423 } else if (!strncmp(kv[0], "flow", 4)) {
426 else if (kv[1][0] == '1')
428 else if (kv[1][0] == '2')
431 sr_dbg("invalid value for flow: %c", kv[1][0]);
442 g_match_info_unref(match);
446 return serial_set_params(serial, speed, databits, parity,
447 stopbits, flow, rts, dtr);
449 sr_dbg("Could not infer speed from parameter string.");
455 * Read a line from the specified serial port.
457 * @param serial Previously initialized serial port structure.
458 * @param buf Buffer where to store the bytes that are read.
459 * @param buflen Size of the buffer.
460 * @param[in] timeout_ms How long to wait for a line to come in.
462 * Reading stops when CR of LR is found, which is stripped from the buffer.
464 * @retval SR_OK Success.
465 * @retval SR_ERR Failure.
467 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
468 int *buflen, gint64 timeout_ms)
474 sr_dbg("Invalid serial port.");
479 sr_dbg("Cannot use unopened serial port %s.", serial->port);
484 start = g_get_monotonic_time();
489 len = maxlen - *buflen - 1;
492 len = serial_read(serial, *buf + *buflen, 1);
495 *(*buf + *buflen) = '\0';
496 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
497 || *(*buf + *buflen - 1) == '\n')) {
498 /* Strip CR/LF and terminate. */
499 *(*buf + --*buflen) = '\0';
503 if (g_get_monotonic_time() - start > timeout_ms)
510 sr_dbg("Received %d: '%s'.", *buflen, *buf);
516 * Try to find a valid packet in a serial data stream.
518 * @param serial Previously initialized serial port structure.
519 * @param buf Buffer containing the bytes to write.
520 * @param buflen Size of the buffer.
521 * @param[in] packet_size Size, in bytes, of a valid packet.
522 * @param is_valid Callback that assesses whether the packet is valid or not.
523 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
525 * @param[in] baudrate The baudrate of the serial port. This parameter is not
526 * critical, but it helps fine tune the serial port polling
529 * @retval SR_OK Valid packet was found within the given timeout
530 * @retval SR_ERR Failure.
532 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
533 uint8_t *buf, size_t *buflen,
534 size_t packet_size, packet_valid_t is_valid,
535 uint64_t timeout_ms, int baudrate)
537 uint64_t start, time, byte_delay_us;
538 size_t ibuf, i, maxlen;
543 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
544 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
546 if (maxlen < (packet_size / 2) ) {
547 sr_err("Buffer size must be at least twice the packet size.");
551 /* Assume 8n1 transmission. That is 10 bits for every byte. */
552 byte_delay_us = 10 * (1000000 / baudrate);
553 start = g_get_monotonic_time();
556 while (ibuf < maxlen) {
557 len = serial_read(serial, &buf[ibuf], 1);
560 } else if (len == 0) {
561 /* No logging, already done in serial_read(). */
563 /* Error reading byte, but continuing anyway. */
566 time = g_get_monotonic_time() - start;
569 if ((ibuf - i) >= packet_size) {
570 /* We have at least a packet's worth of data. */
571 if (is_valid(&buf[i])) {
572 sr_spew("Found valid %d-byte packet after "
573 "%" PRIu64 "ms.", (ibuf - i), time);
577 sr_spew("Got %d bytes, but not a valid "
578 "packet.", (ibuf - i));
580 /* Not a valid packet. Continue searching. */
583 if (time >= timeout_ms) {
585 sr_dbg("Detection timed out after %dms.", time);
589 g_usleep(byte_delay_us);
594 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
600 * Extract the serial device and options from the options linked list.
602 * @param options List of options passed from the command line.
603 * @param serial_device Pointer where to store the exctracted serial device.
604 * @param serial_options Pointer where to store the optional extracted serial
607 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
608 * returned string should not be freed by the caller.
610 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
611 const char **serial_options)
614 struct sr_config *src;
616 *serial_device = NULL;
618 for (l = options; l; l = l->next) {
622 *serial_device = g_variant_get_string(src->data, NULL);
623 sr_dbg("Parsed serial device: %s", *serial_device);
626 case SR_CONF_SERIALCOMM:
627 *serial_options = g_variant_get_string(src->data, NULL);
628 sr_dbg("Parsed serial options: %s", *serial_options);
633 if (!*serial_device) {
634 sr_dbg("No serial device specified");
641 SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
642 int timeout, sr_receive_data_callback_t cb, void *cb_data)
648 sp_get_port_handle(serial->data, &fd);
649 return sr_source_add(fd, events, timeout, cb, cb_data);
653 SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
659 sp_get_port_handle(serial->data, &fd);
660 return sr_source_remove(fd);