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