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);
68 sr_err("Attempt to open serial port with invalid parameters.");
71 error = sp_last_error_message();
72 sr_err("Error opening port: %s.", error);
73 sp_free_error_message(error);
78 serial->fd = serial->data->fd;
81 if (serial->serialcomm)
82 return serial_set_paramstr(serial, serial->serialcomm);
88 * Close the specified serial port.
90 * @param serial Previously initialized serial port structure.
92 * @return SR_OK on success, SR_ERR on failure.
94 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
100 sr_dbg("Invalid serial port.");
104 if (serial->fd == -1) {
105 sr_dbg("Cannot close unopened serial port %s (fd %d).",
106 serial->port, serial->fd);
110 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
112 ret = sp_close(serial->data);
113 sp_free_port(serial->data);
117 sr_err("Attempt to close an invalid serial port.");
120 error = sp_last_error_message();
121 sr_err("Error closing port: %s.", error);
122 sp_free_error_message(error);
132 * Flush serial port buffers.
134 * @param serial Previously initialized serial port structure.
136 * @return SR_OK on success, SR_ERR on failure.
138 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
144 sr_dbg("Invalid serial port.");
148 if (serial->fd == -1) {
149 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
150 serial->port, serial->fd);
154 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
156 ret = sp_flush(serial->data);
160 sr_err("Attempt to flush an invalid serial port.");
163 error = sp_last_error_message();
164 sr_err("Error flushing port: %s.", error);
165 sp_free_error_message(error);
173 * Write a number of bytes to the specified serial port.
175 * @param serial Previously initialized serial port structure.
176 * @param buf Buffer containing the bytes to write.
177 * @param count Number of bytes to write.
179 * @return The number of bytes written, or a negative error code upon failure.
181 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
182 const void *buf, size_t count)
188 sr_dbg("Invalid serial port.");
192 if (serial->fd == -1) {
193 sr_dbg("Cannot use unopened serial port %s (fd %d).",
194 serial->port, serial->fd);
198 ret = sp_write(serial->data, buf, count);
202 sr_err("Attempted serial port write with invalid arguments.");
205 error = sp_last_error_message();
206 sr_err("Write error: %s.", error);
207 sp_free_error_message(error);
211 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
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.");
236 if (serial->fd == -1) {
237 sr_dbg("Cannot use unopened serial port %s (fd %d).",
238 serial->port, serial->fd);
242 ret = sp_read(serial->data, buf, count);
246 sr_err("Attempted serial port read with invalid arguments.");
248 // Temporarily disabled, will come back later.
250 // error = sp_last_error_message();
251 // sr_err("Read error: %s.", error);
252 // sp_free_error_message(error);
256 sr_spew("Read %d/%d bytes (fd %d).", ret, count, serial->fd);
262 * Set serial parameters for the specified serial port.
264 * @param serial Previously initialized serial port structure.
265 * @param baudrate The baudrate to set.
266 * @param bits The number of data bits to use.
267 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
268 * @param stopbits The number of stop bits to use (1 or 2).
269 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
272 * @return SR_OK upon success, SR_ERR upon failure.
274 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
275 int bits, int parity, int stopbits,
276 int flowcontrol, int rts, int dtr)
282 sr_dbg("Invalid serial port.");
286 if (serial->fd == -1) {
287 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
288 serial->port, serial->fd);
292 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
295 ret = sp_set_params(serial->data, baudrate, bits, parity, stopbits,
296 flowcontrol, rts, dtr);
300 sr_err("Invalid arguments for setting serial port parameters.");
303 error = sp_last_error_message();
304 sr_err("Error setting serial port parameters: %s.", error);
305 sp_free_error_message(error);
313 * Set serial parameters for the specified serial port.
315 * @param serial Previously initialized serial port structure.
316 * @param paramstr A serial communication parameters string, in the form
317 * of <speed>/<data bits><parity><stopbits><flow>, for example "9600/8n1" or
318 * "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none, 1 for rts/cts and 2 for xon/xoff.
320 * @return SR_OK upon success, SR_ERR upon failure.
322 #define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
323 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
324 const char *paramstr)
328 int speed, databits, parity, stopbits, flow, rts, dtr, i;
329 char *mstr, **opts, **kv;
331 speed = databits = parity = stopbits = flow = 0;
333 sr_spew("Parsing parameters from \"%s\".", paramstr);
334 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
335 if (g_regex_match(reg, paramstr, 0, &match)) {
336 if ((mstr = g_match_info_fetch(match, 1)))
337 speed = strtoul(mstr, NULL, 10);
339 if ((mstr = g_match_info_fetch(match, 2)))
340 databits = strtoul(mstr, NULL, 10);
342 if ((mstr = g_match_info_fetch(match, 3))) {
345 parity = SERIAL_PARITY_NONE;
348 parity = SERIAL_PARITY_EVEN;
351 parity = SERIAL_PARITY_ODD;
356 if ((mstr = g_match_info_fetch(match, 4)))
357 stopbits = strtoul(mstr, NULL, 10);
359 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
360 if (mstr[0] != '/') {
361 sr_dbg("missing separator before extra options");
364 /* A set of "key=value" options separated by / */
365 opts = g_strsplit(mstr + 1, "/", 0);
366 for (i = 0; opts[i]; i++) {
367 kv = g_strsplit(opts[i], "=", 2);
368 if (!strncmp(kv[0], "rts", 3)) {
371 else if (kv[1][0] == '0')
374 sr_dbg("invalid value for rts: %c", kv[1][0]);
377 } else if (!strncmp(kv[0], "dtr", 3)) {
380 else if (kv[1][0] == '0')
383 sr_dbg("invalid value for dtr: %c", kv[1][0]);
386 } else if (!strncmp(kv[0], "flow", 4)) {
389 else if (kv[1][0] == '1')
391 else if (kv[1][0] == '2')
394 sr_dbg("invalid value for flow: %c", kv[1][0]);
405 g_match_info_unref(match);
409 return serial_set_params(serial, speed, databits, parity,
410 stopbits, flow, rts, dtr);
412 sr_dbg("Could not infer speed from parameter string.");
418 * Read a line from the specified serial port.
420 * @param serial Previously initialized serial port structure.
421 * @param buf Buffer where to store the bytes that are read.
422 * @param buflen Size of the buffer.
423 * @param timeout_ms How long to wait for a line to come in.
425 * Reading stops when CR of LR is found, which is stripped from the buffer.
427 * @return SR_OK on success, SR_ERR on failure.
429 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
430 int *buflen, gint64 timeout_ms)
435 if (!serial || serial->fd == -1) {
436 sr_dbg("Invalid serial port.");
440 if (serial->fd == -1) {
441 sr_dbg("Cannot use unopened serial port %s (fd %d).",
442 serial->port, serial->fd);
447 start = g_get_monotonic_time();
452 len = maxlen - *buflen - 1;
455 len = serial_read(serial, *buf + *buflen, 1);
458 *(*buf + *buflen) = '\0';
459 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
460 || *(*buf + *buflen - 1) == '\n')) {
461 /* Strip CR/LF and terminate. */
462 *(*buf + --*buflen) = '\0';
466 if (g_get_monotonic_time() - start > timeout_ms)
473 sr_dbg("Received %d: '%s'.", *buflen, *buf);
479 * Try to find a valid packet in a serial data stream.
481 * @param serial Previously initialized serial port structure.
482 * @param buf Buffer containing the bytes to write.
483 * @param count Size of the buffer.
484 * @param packet_size Size, in bytes, of a valid packet.
485 * @param is_valid Callback that assesses whether the packet is valid or not.
486 * @param timeout_ms The timeout after which, if no packet is detected, to
488 * @param baudrate The baudrate of the serial port. This parameter is not
489 * critical, but it helps fine tune the serial port polling
492 * @return SR_OK if a valid packet is found within the given timeout,
493 * SR_ERR upon failure.
495 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
496 uint8_t *buf, size_t *buflen,
497 size_t packet_size, packet_valid_t is_valid,
498 uint64_t timeout_ms, int baudrate)
500 uint64_t start, time, byte_delay_us;
501 size_t ibuf, i, maxlen;
506 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
507 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
509 if (maxlen < (packet_size / 2) ) {
510 sr_err("Buffer size must be at least twice the packet size.");
514 /* Assume 8n1 transmission. That is 10 bits for every byte. */
515 byte_delay_us = 10 * (1000000 / baudrate);
516 start = g_get_monotonic_time();
519 while (ibuf < maxlen) {
520 len = serial_read(serial, &buf[ibuf], 1);
523 } else if (len == 0) {
524 /* No logging, already done in serial_read(). */
526 /* Error reading byte, but continuing anyway. */
529 time = g_get_monotonic_time() - start;
532 if ((ibuf - i) >= packet_size) {
533 /* We have at least a packet's worth of data. */
534 if (is_valid(&buf[i])) {
535 sr_spew("Found valid %d-byte packet after "
536 "%" PRIu64 "ms.", (ibuf - i), time);
540 sr_spew("Got %d bytes, but not a valid "
541 "packet.", (ibuf - i));
543 /* Not a valid packet. Continue searching. */
546 if (time >= timeout_ms) {
548 sr_dbg("Detection timed out after %dms.", time);
552 g_usleep(byte_delay_us);
557 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);