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