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