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