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