]> sigrok.org Git - libsigrok.git/blame - src/serial.c
serial: prepare for the absence of libserialport
[libsigrok.git] / src / serial.c
CommitLineData
a1bb33af 1/*
50985c20 2 * This file is part of the libsigrok project.
a1bb33af 3 *
c73d2ea4 4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
b19f4622 5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
766456be 6 * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
bce75f94 7 * Copyright (C) 2014 Uffe Jakobsen <uffe@uffe.org>
a1bb33af
UH
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 */
22
6ec6c43b 23#include <config.h>
54b38f64 24#include <string.h>
d02a535e 25#include <stdlib.h>
a1bb33af 26#include <glib.h>
b541f837 27#include <glib/gstdio.h>
1ac8c218 28#ifdef HAVE_LIBSERIALPORT
0d4405ce 29#include <libserialport.h>
1ac8c218 30#endif
c1aae900 31#include <libsigrok/libsigrok.h>
45c59c8b 32#include "libsigrok-internal.h"
00f0016c 33#ifdef _WIN32
041b579d
DE
34#include <windows.h> /* for HANDLE */
35#endif
a1bb33af 36
e00b3f58 37/** @cond PRIVATE */
3544f848 38#define LOG_PREFIX "serial"
e00b3f58
UH
39/** @endcond */
40
41/**
42 * @file
43 *
44 * Serial port handling.
45 */
46
47/**
48 * @defgroup grp_serial Serial port handling
49 *
50 * Serial port handling functions.
51 *
52 * @{
53 */
b19f4622 54
1ac8c218
GS
55#ifdef HAVE_SERIAL_COMM
56
a7b8692e
GS
57/* See if a (assumed opened) serial port is of any supported type. */
58static int dev_is_supported(struct sr_serial_dev_inst *serial)
59{
60 if (!serial)
61 return 0;
62 if (!serial->lib_funcs)
63 return 0;
64
65 return 1;
66}
67
b19f4622
UH
68/**
69 * Open the specified serial port.
70 *
299bdb24 71 * @param serial Previously initialized serial port structure.
a9cf2035 72 * @param[in] flags Flags to use when opening the serial port. Possible flags
d9251a2c 73 * include SERIAL_RDWR, SERIAL_RDONLY.
b19f4622 74 *
299bdb24
BV
75 * If the serial structure contains a serialcomm string, it will be
76 * passed to serial_set_paramstr() after the port is opened.
77 *
d0a92abd
MH
78 * @retval SR_OK Success.
79 * @retval SR_ERR Failure.
e00b3f58
UH
80 *
81 * @private
b19f4622 82 */
299bdb24 83SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
d02a535e 84{
a9bce5a5 85 int ret;
b19f4622 86
299bdb24
BV
87 if (!serial) {
88 sr_dbg("Invalid serial port.");
89 return SR_ERR;
90 }
91
92 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
b19f4622 93
a7b8692e
GS
94 /* Default to the libserialport transport layer. */
95 serial->lib_funcs = ser_lib_funcs_libsp;
96 if (!serial->lib_funcs)
97 return SR_ERR_NA;
98
99 /*
100 * Run the transport's open routine. Setup the bitrate and the
101 * UART frame format.
102 */
103 if (!serial->lib_funcs->open)
104 return SR_ERR_NA;
105 ret = serial->lib_funcs->open(serial, flags);
ae4c1fb6
GS
106 if (ret != SR_OK)
107 return ret;
a54dd31e 108
299bdb24
BV
109 if (serial->serialcomm)
110 return serial_set_paramstr(serial, serial->serialcomm);
111 else
112 return SR_OK;
d02a535e
BV
113}
114
b19f4622
UH
115/**
116 * Close the specified serial port.
117 *
299bdb24 118 * @param serial Previously initialized serial port structure.
b19f4622 119 *
d0a92abd
MH
120 * @retval SR_OK Success.
121 * @retval SR_ERR Failure.
e00b3f58
UH
122 *
123 * @private
2119ab03 124 */
299bdb24 125SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
d02a535e 126{
299bdb24
BV
127 if (!serial) {
128 sr_dbg("Invalid serial port.");
129 return SR_ERR;
130 }
131
64ecf7ee 132 sr_spew("Closing serial port %s.", serial->port);
b19f4622 133
a7b8692e
GS
134 if (!serial->lib_funcs || !serial->lib_funcs->close)
135 return SR_ERR_NA;
136
137 return serial->lib_funcs->close(serial);
d02a535e
BV
138}
139
b19f4622 140/**
6213c38e 141 * Flush serial port buffers. Empty buffers, discard pending RX and TX data.
b19f4622 142 *
299bdb24 143 * @param serial Previously initialized serial port structure.
b19f4622 144 *
d0a92abd
MH
145 * @retval SR_OK Success.
146 * @retval SR_ERR Failure.
e00b3f58
UH
147 *
148 * @private
1fdb75e1 149 */
299bdb24 150SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
06d64eb8 151{
299bdb24
BV
152 if (!serial) {
153 sr_dbg("Invalid serial port.");
154 return SR_ERR;
155 }
156
64ecf7ee 157 sr_spew("Flushing serial port %s.", serial->port);
b19f4622 158
a7b8692e
GS
159 if (!serial->lib_funcs || !serial->lib_funcs->flush)
160 return SR_ERR_NA;
161
162 return serial->lib_funcs->flush(serial);
06d64eb8
BV
163}
164
bce75f94 165/**
6213c38e 166 * Drain serial port buffers. Wait for pending TX data to be sent.
bce75f94
UJ
167 *
168 * @param serial Previously initialized serial port structure.
169 *
170 * @retval SR_OK Success.
171 * @retval SR_ERR Failure.
e00b3f58
UH
172 *
173 * @private
bce75f94
UJ
174 */
175SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
176{
bce75f94
UJ
177 if (!serial) {
178 sr_dbg("Invalid serial port.");
179 return SR_ERR;
180 }
181
bce75f94
UJ
182 sr_spew("Draining serial port %s.", serial->port);
183
a7b8692e
GS
184 if (!serial->lib_funcs || !serial->lib_funcs->drain)
185 return SR_ERR_NA;
186
187 return serial->lib_funcs->drain(serial);
bce75f94
UJ
188}
189
8c3df6e5
GS
190/**
191 * Check for available receive data.
192 *
193 * @param[in] serial Previously opened serial port instance.
194 *
195 * @returns The number of (known) available RX data bytes.
196 *
197 * Returns 0 if no receive data is available, or if the amount of
198 * available receive data cannot get determined.
199 */
200SR_PRIV size_t serial_has_receive_data(struct sr_serial_dev_inst *serial)
201{
a7b8692e
GS
202 size_t lib_count;
203
204 if (!serial)
205 return 0;
206
207 lib_count = 0;
208 if (serial->lib_funcs && serial->lib_funcs->get_rx_avail)
209 lib_count = serial->lib_funcs->get_rx_avail(serial);
210
211 return lib_count;
8c3df6e5
GS
212}
213
9a474211 214static int _serial_write(struct sr_serial_dev_inst *serial,
ae4c1fb6
GS
215 const void *buf, size_t count,
216 int nonblocking, unsigned int timeout_ms)
2119ab03 217{
299bdb24
BV
218 ssize_t ret;
219
220 if (!serial) {
221 sr_dbg("Invalid serial port.");
6a76efeb 222 return SR_ERR;
299bdb24
BV
223 }
224
a7b8692e
GS
225 if (!serial->lib_funcs || !serial->lib_funcs->write)
226 return SR_ERR_NA;
227 ret = serial->lib_funcs->write(serial, buf, count,
228 nonblocking, timeout_ms);
6433156c 229 sr_spew("Wrote %zd/%zu bytes.", ret, count);
b19f4622
UH
230
231 return ret;
2119ab03
UH
232}
233
b19f4622 234/**
98edee79 235 * Write a number of bytes to the specified serial port, blocking until finished.
b19f4622 236 *
299bdb24 237 * @param serial Previously initialized serial port structure.
a9cf2035
MH
238 * @param[in] buf Buffer containing the bytes to write.
239 * @param[in] count Number of bytes to write.
eead2782 240 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
b19f4622 241 *
a9cf2035
MH
242 * @retval SR_ERR_ARG Invalid argument.
243 * @retval SR_ERR Other error.
eead2782
ML
244 * @retval other The number of bytes written. If this is less than the number
245 * specified in the call, the timeout was reached.
e00b3f58
UH
246 *
247 * @private
2119ab03 248 */
9a474211 249SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
ae4c1fb6 250 const void *buf, size_t count, unsigned int timeout_ms)
9a474211 251{
eead2782 252 return _serial_write(serial, buf, count, 0, timeout_ms);
9a474211
ML
253}
254
a9cf2035
MH
255/**
256 * Write a number of bytes to the specified serial port, return immediately.
98edee79
ML
257 *
258 * @param serial Previously initialized serial port structure.
259 * @param[in] buf Buffer containing the bytes to write.
260 * @param[in] count Number of bytes to write.
261 *
262 * @retval SR_ERR_ARG Invalid argument.
263 * @retval SR_ERR Other error.
264 * @retval other The number of bytes written.
e00b3f58
UH
265 *
266 * @private
267 */
9a474211 268SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
ae4c1fb6 269 const void *buf, size_t count)
9a474211 270{
eead2782 271 return _serial_write(serial, buf, count, 1, 0);
9a474211
ML
272}
273
ae4c1fb6
GS
274static int _serial_read(struct sr_serial_dev_inst *serial,
275 void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
2119ab03 276{
299bdb24
BV
277 ssize_t ret;
278
279 if (!serial) {
280 sr_dbg("Invalid serial port.");
6a76efeb 281 return SR_ERR;
299bdb24
BV
282 }
283
a7b8692e
GS
284 if (!serial->lib_funcs || !serial->lib_funcs->read)
285 return SR_ERR_NA;
286 ret = serial->lib_funcs->read(serial, buf, count,
287 nonblocking, timeout_ms);
c4d85a40 288 if (ret > 0)
6433156c 289 sr_spew("Read %zd/%zu bytes.", ret, count);
b19f4622
UH
290
291 return ret;
2119ab03
UH
292}
293
9a474211 294/**
98edee79 295 * Read a number of bytes from the specified serial port, block until finished.
9a474211
ML
296 *
297 * @param serial Previously initialized serial port structure.
298 * @param buf Buffer where to store the bytes that are read.
a9cf2035 299 * @param[in] count The number of bytes to read.
eead2782 300 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
9a474211 301 *
a9cf2035 302 * @retval SR_ERR_ARG Invalid argument.
d9251a2c
UH
303 * @retval SR_ERR Other error.
304 * @retval other The number of bytes read. If this is less than the number
eead2782 305 * requested, the timeout was reached.
e00b3f58
UH
306 *
307 * @private
9a474211 308 */
ae4c1fb6
GS
309SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial,
310 void *buf, size_t count, unsigned int timeout_ms)
9a474211 311{
eead2782 312 return _serial_read(serial, buf, count, 0, timeout_ms);
9a474211
ML
313}
314
a9cf2035
MH
315/**
316 * Try to read up to @a count bytes from the specified serial port, return
317 * immediately with what's available.
98edee79
ML
318 *
319 * @param serial Previously initialized serial port structure.
320 * @param buf Buffer where to store the bytes that are read.
321 * @param[in] count The number of bytes to read.
322 *
323 * @retval SR_ERR_ARG Invalid argument.
d9251a2c
UH
324 * @retval SR_ERR Other error.
325 * @retval other The number of bytes read.
e00b3f58
UH
326 *
327 * @private
a9cf2035 328 */
ae4c1fb6
GS
329SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial,
330 void *buf, size_t count)
9a474211 331{
eead2782 332 return _serial_read(serial, buf, count, 1, 0);
9a474211
ML
333}
334
b19f4622
UH
335/**
336 * Set serial parameters for the specified serial port.
337 *
299bdb24 338 * @param serial Previously initialized serial port structure.
04cb9157
MH
339 * @param[in] baudrate The baudrate to set.
340 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
341 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
342 * @param[in] stopbits The number of stop bits to use (1 or 2).
343 * @param[in] flowcontrol The flow control settings to use (0 = none,
d9251a2c 344 * 1 = RTS/CTS, 2 = XON/XOFF).
04cb9157
MH
345 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
346 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
2119ab03 347 *
d0a92abd 348 * @retval SR_OK Success.
04cb9157 349 * @retval SR_ERR Failure.
e00b3f58
UH
350 *
351 * @private
1ff7712c 352 */
ae4c1fb6
GS
353SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial,
354 int baudrate, int bits, int parity, int stopbits,
355 int flowcontrol, int rts, int dtr)
d02a535e 356{
a9bce5a5 357 int ret;
a9bce5a5 358
299bdb24
BV
359 if (!serial) {
360 sr_dbg("Invalid serial port.");
361 return SR_ERR;
362 }
363
64ecf7ee 364 sr_spew("Setting serial parameters on port %s.", serial->port);
b19f4622 365
a7b8692e
GS
366 if (!serial->lib_funcs || !serial->lib_funcs->set_params)
367 return SR_ERR_NA;
368 ret = serial->lib_funcs->set_params(serial,
369 baudrate, bits, parity, stopbits,
370 flowcontrol, rts, dtr);
ae4c1fb6
GS
371 if (ret == SR_OK) {
372 serial->comm_params.bit_rate = baudrate;
373 serial->comm_params.data_bits = bits;
374 serial->comm_params.parity_bits = parity ? 1 : 0;
375 serial->comm_params.stop_bits = stopbits;
376 sr_dbg("DBG: %s() rate %d, %d%s%d", __func__,
377 baudrate, bits,
378 (parity == 0) ? "n" : "x",
379 stopbits);
13cd8197 380 }
639c6f61 381
ae4c1fb6 382 return ret;
d02a535e 383}
792fc686 384
299bdb24 385/**
48d3238e 386 * Set serial parameters for the specified serial port from parameter string.
299bdb24
BV
387 *
388 * @param serial Previously initialized serial port structure.
48d3238e
MH
389 * @param[in] paramstr A serial communication parameters string of the form
390 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
d9251a2c 391 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
48d3238e
MH
392 * \<baudrate\>=integer Baud rate.\n
393 * \<bits\>=5|6|7|8 Number of data bits.\n
394 * \<parity\>=n|e|o None, even, odd.\n
395 * \<stopbits\>=1|2 One or two stop bits.\n
396 * Options:\n
397 * dtr=0|1 Set DTR off resp. on.\n
398 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
399 * rts=0|1 Set RTS off resp. on.\n
400 * Please note that values and combinations of these parameters must be
401 * supported by the concrete serial interface hardware and the drivers for it.
e00b3f58 402 *
04cb9157
MH
403 * @retval SR_OK Success.
404 * @retval SR_ERR Failure.
e00b3f58
UH
405 *
406 * @private
299bdb24 407 */
299bdb24 408SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
ae4c1fb6 409 const char *paramstr)
792fc686 410{
e00b3f58 411/** @cond PRIVATE */
48d3238e 412#define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
e00b3f58 413/** @endcond */
48d3238e 414
792fc686
BV
415 GRegex *reg;
416 GMatchInfo *match;
26ddb5ba 417 int speed, databits, parity, stopbits, flow, rts, dtr, i;
71caaad4 418 char *mstr, **opts, **kv;
792fc686 419
26ddb5ba 420 speed = databits = parity = stopbits = flow = 0;
71caaad4 421 rts = dtr = -1;
ea088bb6 422 sr_spew("Parsing parameters from \"%s\".", paramstr);
792fc686
BV
423 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
424 if (g_regex_match(reg, paramstr, 0, &match)) {
425 if ((mstr = g_match_info_fetch(match, 1)))
426 speed = strtoul(mstr, NULL, 10);
427 g_free(mstr);
428 if ((mstr = g_match_info_fetch(match, 2)))
429 databits = strtoul(mstr, NULL, 10);
430 g_free(mstr);
431 if ((mstr = g_match_info_fetch(match, 3))) {
432 switch (mstr[0]) {
433 case 'n':
4d6a5008 434 parity = SP_PARITY_NONE;
792fc686
BV
435 break;
436 case 'e':
4d6a5008 437 parity = SP_PARITY_EVEN;
792fc686
BV
438 break;
439 case 'o':
4d6a5008 440 parity = SP_PARITY_ODD;
792fc686
BV
441 break;
442 }
443 }
444 g_free(mstr);
445 if ((mstr = g_match_info_fetch(match, 4)))
446 stopbits = strtoul(mstr, NULL, 10);
447 g_free(mstr);
71caaad4
BV
448 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
449 if (mstr[0] != '/') {
450 sr_dbg("missing separator before extra options");
451 speed = 0;
452 } else {
453 /* A set of "key=value" options separated by / */
454 opts = g_strsplit(mstr + 1, "/", 0);
455 for (i = 0; opts[i]; i++) {
456 kv = g_strsplit(opts[i], "=", 2);
457 if (!strncmp(kv[0], "rts", 3)) {
458 if (kv[1][0] == '1')
459 rts = 1;
460 else if (kv[1][0] == '0')
461 rts = 0;
462 else {
463 sr_dbg("invalid value for rts: %c", kv[1][0]);
464 speed = 0;
465 }
466 } else if (!strncmp(kv[0], "dtr", 3)) {
467 if (kv[1][0] == '1')
468 dtr = 1;
469 else if (kv[1][0] == '0')
470 dtr = 0;
471 else {
472 sr_dbg("invalid value for dtr: %c", kv[1][0]);
473 speed = 0;
474 }
26ddb5ba 475 } else if (!strncmp(kv[0], "flow", 4)) {
476 if (kv[1][0] == '0')
477 flow = 0;
478 else if (kv[1][0] == '1')
479 flow = 1;
480 else if (kv[1][0] == '2')
481 flow = 2;
482 else {
483 sr_dbg("invalid value for flow: %c", kv[1][0]);
484 speed = 0;
485 }
71caaad4
BV
486 }
487 g_strfreev(kv);
488 }
489 g_strfreev(opts);
490 }
491 }
492 g_free(mstr);
792fc686
BV
493 }
494 g_match_info_unref(match);
495 g_regex_unref(reg);
496
ea088bb6
AG
497 if (speed) {
498 return serial_set_params(serial, speed, databits, parity,
26ddb5ba 499 stopbits, flow, rts, dtr);
ea088bb6
AG
500 } else {
501 sr_dbg("Could not infer speed from parameter string.");
792fc686 502 return SR_ERR_ARG;
ea088bb6 503 }
792fc686
BV
504}
505
299bdb24
BV
506/**
507 * Read a line from the specified serial port.
508 *
6213c38e
GS
509 * @param[in] serial Previously initialized serial port structure.
510 * @param[out] buf Buffer where to store the bytes that are read.
511 * @param[in] buflen Size of the buffer.
04cb9157 512 * @param[in] timeout_ms How long to wait for a line to come in.
299bdb24 513 *
6213c38e 514 * Reading stops when CR or LF is found, which is stripped from the buffer.
299bdb24 515 *
04cb9157
MH
516 * @retval SR_OK Success.
517 * @retval SR_ERR Failure.
e00b3f58
UH
518 *
519 * @private
299bdb24 520 */
ae4c1fb6
GS
521SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial,
522 char **buf, int *buflen, gint64 timeout_ms)
6f22a8ef 523{
bf505eed 524 gint64 start, remaining;
6f22a8ef
UH
525 int maxlen, len;
526
64ecf7ee 527 if (!serial) {
299bdb24
BV
528 sr_dbg("Invalid serial port.");
529 return SR_ERR;
530 }
531
a7b8692e 532 if (!dev_is_supported(serial)) {
64ecf7ee 533 sr_dbg("Cannot use unopened serial port %s.", serial->port);
299bdb24
BV
534 return -1;
535 }
536
6f22a8ef 537 start = g_get_monotonic_time();
bf505eed 538 remaining = timeout_ms;
6f22a8ef
UH
539
540 maxlen = *buflen;
541 *buflen = len = 0;
0c5f2abc 542 while (1) {
6f22a8ef
UH
543 len = maxlen - *buflen - 1;
544 if (len < 1)
545 break;
ae4c1fb6 546 len = serial_read_blocking(serial, *buf + *buflen, 1, remaining);
6f22a8ef
UH
547 if (len > 0) {
548 *buflen += len;
549 *(*buf + *buflen) = '\0';
318dd53c
BV
550 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
551 || *(*buf + *buflen - 1) == '\n')) {
552 /* Strip CR/LF and terminate. */
6f22a8ef
UH
553 *(*buf + --*buflen) = '\0';
554 break;
555 }
556 }
bf505eed
ML
557 /* Reduce timeout by time elapsed. */
558 remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
559 if (remaining <= 0)
6f22a8ef
UH
560 /* Timeout */
561 break;
5715e84f
DT
562 if (len < 1)
563 g_usleep(2000);
6f22a8ef 564 }
318dd53c
BV
565 if (*buflen)
566 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
567
568 return SR_OK;
569}
766456be
UH
570
571/**
572 * Try to find a valid packet in a serial data stream.
573 *
574 * @param serial Previously initialized serial port structure.
575 * @param buf Buffer containing the bytes to write.
04cb9157
MH
576 * @param buflen Size of the buffer.
577 * @param[in] packet_size Size, in bytes, of a valid packet.
766456be 578 * @param is_valid Callback that assesses whether the packet is valid or not.
04cb9157 579 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
d9251a2c 580 * abort scanning.
04cb9157 581 * @param[in] baudrate The baudrate of the serial port. This parameter is not
d9251a2c
UH
582 * critical, but it helps fine tune the serial port polling
583 * delay.
766456be 584 *
d0a92abd 585 * @retval SR_OK Valid packet was found within the given timeout.
04cb9157 586 * @retval SR_ERR Failure.
e00b3f58
UH
587 *
588 * @private
766456be
UH
589 */
590SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
ae4c1fb6
GS
591 uint8_t *buf, size_t *buflen,
592 size_t packet_size,
593 packet_valid_callback is_valid,
594 uint64_t timeout_ms, int baudrate)
766456be
UH
595{
596 uint64_t start, time, byte_delay_us;
597 size_t ibuf, i, maxlen;
6433156c 598 ssize_t len;
766456be
UH
599
600 maxlen = *buflen;
601
64ecf7ee
ML
602 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
603 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
766456be
UH
604
605 if (maxlen < (packet_size / 2) ) {
606 sr_err("Buffer size must be at least twice the packet size.");
607 return SR_ERR;
608 }
609
766456be 610 /* Assume 8n1 transmission. That is 10 bits for every byte. */
1a46cc62 611 byte_delay_us = 10 * ((1000 * 1000) / baudrate);
766456be
UH
612 start = g_get_monotonic_time();
613
614 i = ibuf = len = 0;
615 while (ibuf < maxlen) {
18e4d5bc 616 len = serial_read_nonblocking(serial, &buf[ibuf], 1);
766456be
UH
617 if (len > 0) {
618 ibuf += len;
619 } else if (len == 0) {
006dbe55 620 /* No logging, already done in serial_read(). */
766456be
UH
621 } else {
622 /* Error reading byte, but continuing anyway. */
623 }
551c3d8c
AG
624
625 time = g_get_monotonic_time() - start;
626 time /= 1000;
627
766456be 628 if ((ibuf - i) >= packet_size) {
e5fa47c1 629 GString *text;
766456be 630 /* We have at least a packet's worth of data. */
e5fa47c1 631 text = sr_hexdump_new(&buf[i], packet_size);
59cae77e 632 sr_spew("Trying packet: %s", text->str);
e5fa47c1 633 sr_hexdump_free(text);
766456be 634 if (is_valid(&buf[i])) {
6433156c 635 sr_spew("Found valid %zu-byte packet after "
766456be
UH
636 "%" PRIu64 "ms.", (ibuf - i), time);
637 *buflen = ibuf;
638 return SR_OK;
639 } else {
6433156c 640 sr_spew("Got %zu bytes, but not a valid "
766456be
UH
641 "packet.", (ibuf - i));
642 }
643 /* Not a valid packet. Continue searching. */
644 i++;
645 }
551c3d8c 646 if (time >= timeout_ms) {
766456be 647 /* Timeout */
6433156c 648 sr_dbg("Detection timed out after %" PRIu64 "ms.", time);
766456be
UH
649 break;
650 }
5715e84f
DT
651 if (len < 1)
652 g_usleep(byte_delay_us);
766456be
UH
653 }
654
655 *buflen = ibuf;
656
6433156c 657 sr_err("Didn't find a valid packet (read %zu bytes).", *buflen);
766456be
UH
658
659 return SR_ERR;
660}
1bd9e678
DJ
661
662/**
663 * Extract the serial device and options from the options linked list.
664 *
665 * @param options List of options passed from the command line.
f3f19d11 666 * @param serial_device Pointer where to store the extracted serial device.
1bd9e678
DJ
667 * @param serial_options Pointer where to store the optional extracted serial
668 * options.
669 *
670 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
671 * returned string should not be freed by the caller.
e00b3f58
UH
672 *
673 * @private
1bd9e678 674 */
ae4c1fb6
GS
675SR_PRIV int sr_serial_extract_options(GSList *options,
676 const char **serial_device, const char **serial_options)
1bd9e678
DJ
677{
678 GSList *l;
679 struct sr_config *src;
680
681 *serial_device = NULL;
682
683 for (l = options; l; l = l->next) {
684 src = l->data;
685 switch (src->key) {
686 case SR_CONF_CONN:
687 *serial_device = g_variant_get_string(src->data, NULL);
b1a7ca3b 688 sr_dbg("Parsed serial device: %s.", *serial_device);
1bd9e678 689 break;
1bd9e678
DJ
690 case SR_CONF_SERIALCOMM:
691 *serial_options = g_variant_get_string(src->data, NULL);
b1a7ca3b 692 sr_dbg("Parsed serial options: %s.", *serial_options);
1bd9e678
DJ
693 break;
694 }
695 }
696
697 if (!*serial_device) {
b1a7ca3b 698 sr_dbg("No serial device specified.");
1bd9e678
DJ
699 return SR_ERR;
700 }
701
702 return SR_OK;
703}
abc4b335 704
e00b3f58 705/** @private */
102f1239 706SR_PRIV int serial_source_add(struct sr_session *session,
ae4c1fb6
GS
707 struct sr_serial_dev_inst *serial, int events, int timeout,
708 sr_receive_data_callback cb, void *cb_data)
ba1949f5 709{
ae4c1fb6 710 if ((events & (G_IO_IN | G_IO_ERR)) && (events & G_IO_OUT)) {
cbc1413f
DE
711 sr_err("Cannot poll input/error and output simultaneously.");
712 return SR_ERR_ARG;
713 }
714
a7b8692e 715 if (!dev_is_supported(serial)) {
ae4c1fb6
GS
716 sr_err("Invalid serial port.");
717 return SR_ERR_ARG;
ba1949f5
ML
718 }
719
a7b8692e
GS
720 if (!serial->lib_funcs || !serial->lib_funcs->setup_source_add)
721 return SR_ERR_NA;
722
723 return serial->lib_funcs->setup_source_add(session, serial,
ae4c1fb6 724 events, timeout, cb, cb_data);
abc4b335 725}
7faa3e88 726
e00b3f58 727/** @private */
102f1239 728SR_PRIV int serial_source_remove(struct sr_session *session,
ae4c1fb6 729 struct sr_serial_dev_inst *serial)
7faa3e88 730{
a7b8692e 731 if (!dev_is_supported(serial)) {
ae4c1fb6
GS
732 sr_err("Invalid serial port.");
733 return SR_ERR_ARG;
734 }
735
a7b8692e
GS
736 if (!serial->lib_funcs || !serial->lib_funcs->setup_source_remove)
737 return SR_ERR_NA;
738
739 return serial->lib_funcs->setup_source_remove(session, serial);
7faa3e88 740}
b541f837 741
b1a7ca3b
UH
742/**
743 * Create/allocate a new sr_serial_port structure.
744 *
745 * @param name The OS dependent name of the serial port. Must not be NULL.
746 * @param description An end user friendly description for the serial port.
747 * Can be NULL (in that case the empty string is used
748 * as description).
749 *
750 * @return The newly allocated sr_serial_port struct.
751 */
24287ea9 752static struct sr_serial_port *sr_serial_new(const char *name,
ae4c1fb6 753 const char *description)
24287ea9
AJ
754{
755 struct sr_serial_port *serial;
756
757 if (!name)
758 return NULL;
759
e47a9562 760 serial = g_malloc0(sizeof(*serial));
24287ea9
AJ
761 serial->name = g_strdup(name);
762 serial->description = g_strdup(description ? description : "");
b1a7ca3b 763
24287ea9
AJ
764 return serial;
765}
766
b1a7ca3b
UH
767/**
768 * Free a previously allocated sr_serial_port structure.
769 *
770 * @param serial The sr_serial_port struct to free. Must not be NULL.
771 */
24287ea9
AJ
772SR_API void sr_serial_free(struct sr_serial_port *serial)
773{
b1a7ca3b 774 if (!serial)
24287ea9
AJ
775 return;
776 g_free(serial->name);
777 g_free(serial->description);
778 g_free(serial);
779}
780
ae4c1fb6
GS
781static GSList *append_port_list(GSList *devs, const char *name, const char *desc)
782{
783 return g_slist_append(devs, sr_serial_new(name, desc));
784}
785
24287ea9
AJ
786/**
787 * List available serial devices.
788 *
789 * @return A GSList of strings containing the path of the serial devices or
790 * NULL if no serial device is found. The returned list must be freed
791 * by the caller.
792 */
793SR_API GSList *sr_serial_list(const struct sr_dev_driver *driver)
794{
ae4c1fb6 795 GSList *tty_devs;
a7b8692e 796 GSList *(*list_func)(GSList *list, sr_ser_list_append_t append);
24287ea9 797
b1a7ca3b 798 /* Currently unused, but will be used by some drivers later on. */
24287ea9
AJ
799 (void)driver;
800
ae4c1fb6 801 tty_devs = NULL;
a7b8692e
GS
802 if (ser_lib_funcs_libsp && ser_lib_funcs_libsp->list) {
803 list_func = ser_lib_funcs_libsp->list;
804 tty_devs = list_func(tty_devs, append_port_list);
805 }
24287ea9 806
ae4c1fb6
GS
807 return tty_devs;
808}
24287ea9 809
ae4c1fb6
GS
810static GSList *append_port_find(GSList *devs, const char *name)
811{
812 if (!name || !*name)
813 return devs;
b1a7ca3b 814
ae4c1fb6 815 return g_slist_append(devs, g_strdup(name));
24287ea9
AJ
816}
817
b541f837
AJ
818/**
819 * Find USB serial devices via the USB vendor ID and product ID.
820 *
d0a92abd
MH
821 * @param[in] vendor_id Vendor ID of the USB device.
822 * @param[in] product_id Product ID of the USB device.
b541f837
AJ
823 *
824 * @return A GSList of strings containing the path of the serial device or
825 * NULL if no serial device is found. The returned list must be freed
826 * by the caller.
e00b3f58
UH
827 *
828 * @private
b541f837
AJ
829 */
830SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
831{
ae4c1fb6 832 GSList *tty_devs;
a7b8692e
GS
833 GSList *(*find_func)(GSList *list, sr_ser_find_append_t append,
834 uint16_t vid, uint16_t pid);
b541f837 835
ae4c1fb6 836 tty_devs = NULL;
a7b8692e
GS
837 if (ser_lib_funcs_libsp && ser_lib_funcs_libsp->find_usb) {
838 find_func = ser_lib_funcs_libsp->find_usb;
839 tty_devs = find_func(tty_devs, append_port_find,
840 vendor_id, product_id);
841 }
b1a7ca3b 842
b541f837 843 return tty_devs;
b541f837 844}
c5cfc735 845
e00b3f58 846/** @private */
c5cfc735
BV
847SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
848{
ae4c1fb6
GS
849 int bits, baud;
850 int ret;
851 int timeout_ms;
c5cfc735 852
639c6f61 853 /* Get the bitrate and frame length. */
c5cfc735 854 bits = baud = 0;
a7b8692e
GS
855 if (port->lib_funcs && port->lib_funcs->get_frame_format) {
856 ret = port->lib_funcs->get_frame_format(port, &baud, &bits);
857 if (ret != SR_OK)
858 bits = baud = 0;
859 } else {
639c6f61
GS
860 baud = port->comm_params.bit_rate;
861 bits = 1 + port->comm_params.data_bits +
862 port->comm_params.parity_bits +
863 port->comm_params.stop_bits;
864 }
c5cfc735 865
ae4c1fb6
GS
866 /* Derive the timeout. Default to 1s. */
867 timeout_ms = 1000;
c5cfc735
BV
868 if (bits && baud) {
869 /* Throw in 10ms for misc OS overhead. */
870 timeout_ms = 10;
871 timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
872 }
873
c5cfc735
BV
874 return timeout_ms;
875}
e00b3f58 876
1ac8c218
GS
877#else
878
879/* TODO Put fallback.c content here? */
880
881#endif
882
e00b3f58 883/** @} */