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