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)
56 sr_dbg("Invalid serial port.");
60 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
62 sp_get_port_by_name(serial->port, &serial->data);
64 ret = sp_open(serial->data, flags);
69 sr_err("Attempt to open serial port with invalid parameters.");
72 error = sp_last_error_message();
73 sr_err("Error opening port: %s.", error);
74 sp_free_error_message(error);
79 serial->fd = serial->data->fd;
82 if (serial->serialcomm)
83 return serial_set_paramstr(serial, serial->serialcomm);
89 * Close the specified serial port.
91 * @param serial Previously initialized serial port structure.
93 * @return SR_OK on success, SR_ERR on failure.
95 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
101 sr_dbg("Invalid serial port.");
105 if (serial->fd == -1) {
106 sr_dbg("Cannot close unopened serial port %s (fd %d).",
107 serial->port, serial->fd);
111 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
114 ret = sp_close(serial->data);
119 sr_err("Attempt to close an invalid serial port.");
122 error = sp_last_error_message();
123 sr_err("Error closing port: %s.", error);
124 sp_free_error_message(error);
134 * Flush serial port buffers.
136 * @param serial Previously initialized serial port structure.
138 * @return SR_OK on success, SR_ERR on failure.
140 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
146 sr_dbg("Invalid serial port.");
150 if (serial->fd == -1) {
151 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
152 serial->port, serial->fd);
156 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
158 ret = sp_flush(serial->data);
163 sr_err("Attempt to flush an invalid serial port.");
166 error = sp_last_error_message();
167 sr_err("Error flushing port: %s.", error);
168 sp_free_error_message(error);
176 * Write a number of bytes to the specified serial port.
178 * @param serial Previously initialized serial port structure.
179 * @param buf Buffer containing the bytes to write.
180 * @param count Number of bytes to write.
182 * @return The number of bytes written, or -1 upon failure.
184 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
185 const void *buf, size_t count)
191 sr_dbg("Invalid serial port.");
195 if (serial->fd == -1) {
196 sr_dbg("Cannot use unopened serial port %s (fd %d).",
197 serial->port, serial->fd);
201 ret = sp_write(serial->data, buf, count);
206 sr_err("Attempted serial port write with invalid arguments.");
209 error = sp_last_error_message();
210 sr_err("Write error: %s.", error);
211 sp_free_error_message(error);
215 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
221 * Read a number of bytes from the specified serial port.
223 * @param serial Previously initialized serial port structure.
224 * @param buf Buffer where to store the bytes that are read.
225 * @param count The number of bytes to read.
227 * @return The number of bytes read, or -1 upon failure.
229 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
236 sr_dbg("Invalid serial port.");
240 if (serial->fd == -1) {
241 sr_dbg("Cannot use unopened serial port %s (fd %d).",
242 serial->port, serial->fd);
246 ret = sp_read(serial->data, buf, count);
251 sr_err("Attempted serial port read with invalid arguments.");
254 error = sp_last_error_message();
255 sr_err("Read error: %s.", error);
256 sp_free_error_message(error);
260 sr_spew("Read %d/%d bytes (fd %d).", ret, count, serial->fd);
266 * Set serial parameters for the specified serial port.
268 * @param serial Previously initialized serial port structure.
269 * @param baudrate The baudrate to set.
270 * @param bits The number of data bits to use.
271 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
272 * @param stopbits The number of stop bits to use (1 or 2).
273 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
276 * @return SR_OK upon success, SR_ERR upon failure.
278 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
279 int bits, int parity, int stopbits,
280 int flowcontrol, int rts, int dtr)
286 sr_dbg("Invalid serial port.");
290 if (serial->fd == -1) {
291 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
292 serial->port, serial->fd);
296 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
299 ret = sp_set_params(serial->data, baudrate, bits, parity, stopbits,
300 flowcontrol, rts, dtr);
305 sr_err("Invalid arguments for setting serial port parameters.");
308 error = sp_last_error_message();
309 sr_err("Error setting serial port parameters: %s.", error);
310 sp_free_error_message(error);
318 * Set serial parameters for the specified serial port.
320 * @param serial Previously initialized serial port structure.
321 * @param paramstr A serial communication parameters string, in the form
322 * of <speed>/<data bits><parity><stopbits><flow>, for example "9600/8n1" or
323 * "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none, 1 for rts/cts and 2 for xon/xoff.
325 * @return SR_OK upon success, SR_ERR upon failure.
327 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
328 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
329 const char *paramstr)
333 int speed, databits, parity, stopbits, flow, rts, dtr, i;
334 char *mstr, **opts, **kv;
336 speed = databits = parity = stopbits = flow = 0;
338 sr_spew("Parsing parameters from \"%s\".", paramstr);
339 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
340 if (g_regex_match(reg, paramstr, 0, &match)) {
341 if ((mstr = g_match_info_fetch(match, 1)))
342 speed = strtoul(mstr, NULL, 10);
344 if ((mstr = g_match_info_fetch(match, 2)))
345 databits = strtoul(mstr, NULL, 10);
347 if ((mstr = g_match_info_fetch(match, 3))) {
350 parity = SERIAL_PARITY_NONE;
353 parity = SERIAL_PARITY_EVEN;
356 parity = SERIAL_PARITY_ODD;
361 if ((mstr = g_match_info_fetch(match, 4)))
362 stopbits = strtoul(mstr, NULL, 10);
364 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
365 if (mstr[0] != '/') {
366 sr_dbg("missing separator before extra options");
369 /* A set of "key=value" options separated by / */
370 opts = g_strsplit(mstr + 1, "/", 0);
371 for (i = 0; opts[i]; i++) {
372 kv = g_strsplit(opts[i], "=", 2);
373 if (!strncmp(kv[0], "rts", 3)) {
376 else if (kv[1][0] == '0')
379 sr_dbg("invalid value for rts: %c", kv[1][0]);
382 } else if (!strncmp(kv[0], "dtr", 3)) {
385 else if (kv[1][0] == '0')
388 sr_dbg("invalid value for dtr: %c", kv[1][0]);
391 } else if (!strncmp(kv[0], "flow", 4)) {
394 else if (kv[1][0] == '1')
396 else if (kv[1][0] == '2')
399 sr_dbg("invalid value for flow: %c", kv[1][0]);
410 g_match_info_unref(match);
414 return serial_set_params(serial, speed, databits, parity,
415 stopbits, flow, rts, dtr);
417 sr_dbg("Could not infer speed from parameter string.");
423 * Read a line from the specified serial port.
425 * @param serial Previously initialized serial port structure.
426 * @param buf Buffer where to store the bytes that are read.
427 * @param buflen Size of the buffer.
428 * @param timeout_ms How long to wait for a line to come in.
430 * Reading stops when CR of LR is found, which is stripped from the buffer.
432 * @return SR_OK on success, SR_ERR on failure.
434 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
435 int *buflen, gint64 timeout_ms)
440 if (!serial || serial->fd == -1) {
441 sr_dbg("Invalid serial port.");
445 if (serial->fd == -1) {
446 sr_dbg("Cannot use unopened serial port %s (fd %d).",
447 serial->port, serial->fd);
452 start = g_get_monotonic_time();
457 len = maxlen - *buflen - 1;
460 len = serial_read(serial, *buf + *buflen, 1);
463 *(*buf + *buflen) = '\0';
464 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
465 || *(*buf + *buflen - 1) == '\n')) {
466 /* Strip CR/LF and terminate. */
467 *(*buf + --*buflen) = '\0';
471 if (g_get_monotonic_time() - start > timeout_ms)
478 sr_dbg("Received %d: '%s'.", *buflen, *buf);
484 * Try to find a valid packet in a serial data stream.
486 * @param serial Previously initialized serial port structure.
487 * @param buf Buffer containing the bytes to write.
488 * @param count Size of the buffer.
489 * @param packet_size Size, in bytes, of a valid packet.
490 * @param is_valid Callback that assesses whether the packet is valid or not.
491 * @param timeout_ms The timeout after which, if no packet is detected, to
493 * @param baudrate The baudrate of the serial port. This parameter is not
494 * critical, but it helps fine tune the serial port polling
497 * @return SR_OK if a valid packet is found within the given timeout,
498 * SR_ERR upon failure.
500 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
501 uint8_t *buf, size_t *buflen,
502 size_t packet_size, packet_valid_t is_valid,
503 uint64_t timeout_ms, int baudrate)
505 uint64_t start, time, byte_delay_us;
506 size_t ibuf, i, maxlen;
511 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
512 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
514 if (maxlen < (packet_size / 2) ) {
515 sr_err("Buffer size must be at least twice the packet size.");
519 /* Assume 8n1 transmission. That is 10 bits for every byte. */
520 byte_delay_us = 10 * (1000000 / baudrate);
521 start = g_get_monotonic_time();
524 while (ibuf < maxlen) {
525 len = serial_read(serial, &buf[ibuf], 1);
528 } else if (len == 0) {
529 /* No logging, already done in serial_read(). */
531 /* Error reading byte, but continuing anyway. */
534 time = g_get_monotonic_time() - start;
537 if ((ibuf - i) >= packet_size) {
538 /* We have at least a packet's worth of data. */
539 if (is_valid(&buf[i])) {
540 sr_spew("Found valid %d-byte packet after "
541 "%" PRIu64 "ms.", (ibuf - i), time);
545 sr_spew("Got %d bytes, but not a valid "
546 "packet.", (ibuf - i));
548 /* Not a valid packet. Continue searching. */
551 if (time >= timeout_ms) {
553 sr_dbg("Detection timed out after %dms.", time);
557 g_usleep(byte_delay_us);
562 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);