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;
69 if (flags & SERIAL_NONBLOCK)
70 sp_flags |= SP_MODE_NONBLOCK;
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: %s.", error);
81 sp_free_error_message(error);
86 sp_get_port_handle(serial->data, &serial->fd);
89 if (serial->serialcomm)
90 return serial_set_paramstr(serial, serial->serialcomm);
96 * Close the specified serial port.
98 * @param serial Previously initialized serial port structure.
100 * @return SR_OK on success, SR_ERR on failure.
102 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
108 sr_dbg("Invalid serial port.");
112 if (serial->fd == -1) {
113 sr_dbg("Cannot close unopened serial port %s (fd %d).",
114 serial->port, serial->fd);
118 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
120 ret = sp_close(serial->data);
121 sp_free_port(serial->data);
125 sr_err("Attempt to close an invalid serial port.");
128 error = sp_last_error_message();
129 sr_err("Error closing port: %s.", error);
130 sp_free_error_message(error);
140 * Flush serial port buffers.
142 * @param serial Previously initialized serial port structure.
144 * @return SR_OK on success, SR_ERR on failure.
146 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
152 sr_dbg("Invalid serial port.");
156 if (serial->fd == -1) {
157 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
158 serial->port, serial->fd);
162 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
164 ret = sp_flush(serial->data, SP_BUF_BOTH);
168 sr_err("Attempt to flush an invalid serial port.");
171 error = sp_last_error_message();
172 sr_err("Error flushing port: %s.", error);
173 sp_free_error_message(error);
181 * Write a number of bytes to the specified serial port.
183 * @param serial Previously initialized serial port structure.
184 * @param buf Buffer containing the bytes to write.
185 * @param count Number of bytes to write.
187 * @return The number of bytes written, or a negative error code upon failure.
189 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
190 const void *buf, size_t count)
196 sr_dbg("Invalid serial port.");
200 if (serial->fd == -1) {
201 sr_dbg("Cannot use unopened serial port %s (fd %d).",
202 serial->port, serial->fd);
206 ret = sp_write(serial->data, buf, count);
210 sr_err("Attempted serial port write with invalid arguments.");
213 error = sp_last_error_message();
214 sr_err("Write error: %s.", error);
215 sp_free_error_message(error);
219 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
225 * Read a number of bytes from the specified serial port.
227 * @param serial Previously initialized serial port structure.
228 * @param buf Buffer where to store the bytes that are read.
229 * @param count The number of bytes to read.
231 * @return The number of bytes read, or a negative error code upon failure.
233 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
240 sr_dbg("Invalid serial port.");
244 if (serial->fd == -1) {
245 sr_dbg("Cannot use unopened serial port %s (fd %d).",
246 serial->port, serial->fd);
250 ret = sp_read(serial->data, buf, count);
254 sr_err("Attempted serial port read with invalid arguments.");
256 // Temporarily disabled, will come back later.
258 // error = sp_last_error_message();
259 // sr_err("Read error: %s.", error);
260 // sp_free_error_message(error);
265 sr_spew("Read %d/%d bytes (fd %d).", ret, count, serial->fd);
271 * Set serial parameters for the specified serial port.
273 * @param serial Previously initialized serial port structure.
274 * @param baudrate The baudrate to set.
275 * @param bits The number of data bits to use.
276 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
277 * @param stopbits The number of stop bits to use (1 or 2).
278 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
281 * @return SR_OK upon success, SR_ERR upon failure.
283 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
284 int bits, int parity, int stopbits,
285 int flowcontrol, int rts, int dtr)
289 struct sp_port_config config;
292 sr_dbg("Invalid serial port.");
296 if (serial->fd == -1) {
297 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
298 serial->port, serial->fd);
302 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
305 config.baudrate = baudrate;
309 config.parity = SP_PARITY_NONE;
312 config.parity = SP_PARITY_EVEN;
315 config.parity = SP_PARITY_ODD;
320 config.stopbits = stopbits;
321 config.rts = flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts;
322 config.cts = flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
324 config.dsr = SP_DSR_IGNORE;
325 config.xon_xoff = flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED;
327 ret = sp_set_config(serial->data, &config);
331 sr_err("Invalid arguments for setting serial port parameters.");
334 error = sp_last_error_message();
335 sr_err("Error setting serial port parameters: %s.", error);
336 sp_free_error_message(error);
344 * Set serial parameters for the specified serial port.
346 * @param serial Previously initialized serial port structure.
347 * @param paramstr A serial communication parameters string, in the form
348 * of <speed>/<data bits><parity><stopbits><flow>, for example "9600/8n1" or
349 * "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none, 1 for rts/cts and 2 for xon/xoff.
351 * @return SR_OK upon success, SR_ERR upon failure.
353 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
354 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
355 const char *paramstr)
359 int speed, databits, parity, stopbits, flow, rts, dtr, i;
360 char *mstr, **opts, **kv;
362 speed = databits = parity = stopbits = flow = 0;
364 sr_spew("Parsing parameters from \"%s\".", paramstr);
365 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
366 if (g_regex_match(reg, paramstr, 0, &match)) {
367 if ((mstr = g_match_info_fetch(match, 1)))
368 speed = strtoul(mstr, NULL, 10);
370 if ((mstr = g_match_info_fetch(match, 2)))
371 databits = strtoul(mstr, NULL, 10);
373 if ((mstr = g_match_info_fetch(match, 3))) {
376 parity = SERIAL_PARITY_NONE;
379 parity = SERIAL_PARITY_EVEN;
382 parity = SERIAL_PARITY_ODD;
387 if ((mstr = g_match_info_fetch(match, 4)))
388 stopbits = strtoul(mstr, NULL, 10);
390 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
391 if (mstr[0] != '/') {
392 sr_dbg("missing separator before extra options");
395 /* A set of "key=value" options separated by / */
396 opts = g_strsplit(mstr + 1, "/", 0);
397 for (i = 0; opts[i]; i++) {
398 kv = g_strsplit(opts[i], "=", 2);
399 if (!strncmp(kv[0], "rts", 3)) {
402 else if (kv[1][0] == '0')
405 sr_dbg("invalid value for rts: %c", kv[1][0]);
408 } else if (!strncmp(kv[0], "dtr", 3)) {
411 else if (kv[1][0] == '0')
414 sr_dbg("invalid value for dtr: %c", kv[1][0]);
417 } else if (!strncmp(kv[0], "flow", 4)) {
420 else if (kv[1][0] == '1')
422 else if (kv[1][0] == '2')
425 sr_dbg("invalid value for flow: %c", kv[1][0]);
436 g_match_info_unref(match);
440 return serial_set_params(serial, speed, databits, parity,
441 stopbits, flow, rts, dtr);
443 sr_dbg("Could not infer speed from parameter string.");
449 * Read a line from the specified serial port.
451 * @param serial Previously initialized serial port structure.
452 * @param buf Buffer where to store the bytes that are read.
453 * @param buflen Size of the buffer.
454 * @param timeout_ms How long to wait for a line to come in.
456 * Reading stops when CR of LR is found, which is stripped from the buffer.
458 * @return SR_OK on success, SR_ERR on failure.
460 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
461 int *buflen, gint64 timeout_ms)
466 if (!serial || serial->fd == -1) {
467 sr_dbg("Invalid serial port.");
471 if (serial->fd == -1) {
472 sr_dbg("Cannot use unopened serial port %s (fd %d).",
473 serial->port, serial->fd);
478 start = g_get_monotonic_time();
483 len = maxlen - *buflen - 1;
486 len = serial_read(serial, *buf + *buflen, 1);
489 *(*buf + *buflen) = '\0';
490 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
491 || *(*buf + *buflen - 1) == '\n')) {
492 /* Strip CR/LF and terminate. */
493 *(*buf + --*buflen) = '\0';
497 if (g_get_monotonic_time() - start > timeout_ms)
504 sr_dbg("Received %d: '%s'.", *buflen, *buf);
510 * Try to find a valid packet in a serial data stream.
512 * @param serial Previously initialized serial port structure.
513 * @param buf Buffer containing the bytes to write.
514 * @param count Size of the buffer.
515 * @param packet_size Size, in bytes, of a valid packet.
516 * @param is_valid Callback that assesses whether the packet is valid or not.
517 * @param timeout_ms The timeout after which, if no packet is detected, to
519 * @param baudrate The baudrate of the serial port. This parameter is not
520 * critical, but it helps fine tune the serial port polling
523 * @return SR_OK if a valid packet is found within the given timeout,
524 * SR_ERR upon failure.
526 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
527 uint8_t *buf, size_t *buflen,
528 size_t packet_size, packet_valid_t is_valid,
529 uint64_t timeout_ms, int baudrate)
531 uint64_t start, time, byte_delay_us;
532 size_t ibuf, i, maxlen;
537 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
538 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
540 if (maxlen < (packet_size / 2) ) {
541 sr_err("Buffer size must be at least twice the packet size.");
545 /* Assume 8n1 transmission. That is 10 bits for every byte. */
546 byte_delay_us = 10 * (1000000 / baudrate);
547 start = g_get_monotonic_time();
550 while (ibuf < maxlen) {
551 len = serial_read(serial, &buf[ibuf], 1);
554 } else if (len == 0) {
555 /* No logging, already done in serial_read(). */
557 /* Error reading byte, but continuing anyway. */
560 time = g_get_monotonic_time() - start;
563 if ((ibuf - i) >= packet_size) {
564 /* We have at least a packet's worth of data. */
565 if (is_valid(&buf[i])) {
566 sr_spew("Found valid %d-byte packet after "
567 "%" PRIu64 "ms.", (ibuf - i), time);
571 sr_spew("Got %d bytes, but not a valid "
572 "packet.", (ibuf - i));
574 /* Not a valid packet. Continue searching. */
577 if (time >= timeout_ms) {
579 sr_dbg("Detection timed out after %dms.", time);
583 g_usleep(byte_delay_us);
588 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);