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