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