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