]> sigrok.org Git - libsigrok.git/blob - src/serial.c
output/csv: use intermediate time_t var, silence compiler warning
[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  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23 #include <string.h>
24 #include <stdlib.h>
25 #include <glib.h>
26 #include <glib/gstdio.h>
27 #include <libserialport.h>
28 #include "libsigrok.h"
29 #include "libsigrok-internal.h"
30
31 #define LOG_PREFIX "serial"
32
33 /**
34  * Open the specified serial port.
35  *
36  * @param serial Previously initialized serial port structure.
37  * @param[in] flags Flags to use when opening the serial port. Possible flags
38  *              include SERIAL_RDWR, SERIAL_RDONLY.
39  *
40  * If the serial structure contains a serialcomm string, it will be
41  * passed to serial_set_paramstr() after the port is opened.
42  *
43  * @retval SR_OK Success.
44  * @retval SR_ERR Failure.
45  */
46 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
47 {
48         int ret;
49         char *error;
50         int sp_flags = 0;
51
52         if (!serial) {
53                 sr_dbg("Invalid serial port.");
54                 return SR_ERR;
55         }
56
57         sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
58
59         sp_get_port_by_name(serial->port, &serial->data);
60
61         if (flags & SERIAL_RDWR)
62                 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
63         else if (flags & SERIAL_RDONLY)
64                 sp_flags = SP_MODE_READ;
65
66         ret = sp_open(serial->data, sp_flags);
67
68         switch (ret) {
69         case SP_ERR_ARG:
70                 sr_err("Attempt to open serial port with invalid parameters.");
71                 return SR_ERR_ARG;
72         case SP_ERR_FAIL:
73                 error = sp_last_error_message();
74                 sr_err("Error opening port (%d): %s.",
75                         sp_last_error_code(), error);
76                 sp_free_error_message(error);
77                 return SR_ERR;
78         }
79
80         if (serial->serialcomm)
81                 return serial_set_paramstr(serial, serial->serialcomm);
82         else
83                 return SR_OK;
84 }
85
86 /**
87  * Close the specified serial port.
88  *
89  * @param serial Previously initialized serial port structure.
90  *
91  * @retval SR_OK Success.
92  * @retval SR_ERR Failure.
93  */
94 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
95 {
96         int ret;
97         char *error;
98
99         if (!serial) {
100                 sr_dbg("Invalid serial port.");
101                 return SR_ERR;
102         }
103
104         if (!serial->data) {
105                 sr_dbg("Cannot close unopened serial port %s.", serial->port);
106                 return SR_ERR;
107         }
108
109         sr_spew("Closing serial port %s.", serial->port);
110
111         ret = sp_close(serial->data);
112
113         switch (ret) {
114         case SP_ERR_ARG:
115                 sr_err("Attempt to close an invalid serial port.");
116                 return SR_ERR_ARG;
117         case SP_ERR_FAIL:
118                 error = sp_last_error_message();
119                 sr_err("Error closing port (%d): %s.",
120                         sp_last_error_code(), error);
121                 sp_free_error_message(error);
122                 return SR_ERR;
123         }
124
125         sp_free_port(serial->data);
126         serial->data = NULL;
127
128         return SR_OK;
129 }
130
131 /**
132  * Flush serial port buffers.
133  *
134  * @param serial Previously initialized serial port structure.
135  *
136  * @retval SR_OK Success.
137  * @retval SR_ERR Failure.
138  */
139 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
140 {
141         int ret;
142         char *error;
143
144         if (!serial) {
145                 sr_dbg("Invalid serial port.");
146                 return SR_ERR;
147         }
148
149         if (!serial->data) {
150                 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
151                 return SR_ERR;
152         }
153
154         sr_spew("Flushing serial port %s.", serial->port);
155
156         ret = sp_flush(serial->data, SP_BUF_BOTH);
157
158         switch (ret) {
159         case SP_ERR_ARG:
160                 sr_err("Attempt to flush an invalid serial port.");
161                 return SR_ERR_ARG;
162         case SP_ERR_FAIL:
163                 error = sp_last_error_message();
164                 sr_err("Error flushing port (%d): %s.",
165                         sp_last_error_code(), error);
166                 sp_free_error_message(error);
167                 return SR_ERR;
168         }
169
170         return SR_OK;
171 }
172
173 /**
174  * Drain serial port buffers.
175  *
176  * @param serial Previously initialized serial port structure.
177  *
178  * @retval SR_OK Success.
179  * @retval SR_ERR Failure.
180  */
181 SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
182 {
183         int ret;
184         char *error;
185
186         if (!serial) {
187                 sr_dbg("Invalid serial port.");
188                 return SR_ERR;
189         }
190
191         if (!serial->data) {
192                 sr_dbg("Cannot drain unopened serial port %s.", serial->port);
193                 return SR_ERR;
194         }
195
196         sr_spew("Draining serial port %s.", serial->port);
197
198         ret = sp_drain(serial->data);
199
200         if (ret == SP_ERR_FAIL) {
201                 error = sp_last_error_message();
202                 sr_err("Error draining port (%d): %s.",
203                         sp_last_error_code(), error);
204                 sp_free_error_message(error);
205                 return SR_ERR;
206         }
207
208         return SR_OK;
209 }
210
211 static int _serial_write(struct sr_serial_dev_inst *serial,
212                 const void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
213 {
214         ssize_t ret;
215         char *error;
216
217         if (!serial) {
218                 sr_dbg("Invalid serial port.");
219                 return SR_ERR;
220         }
221
222         if (!serial->data) {
223                 sr_dbg("Cannot use unopened serial port %s.", serial->port);
224                 return SR_ERR;
225         }
226
227         if (nonblocking)
228                 ret = sp_nonblocking_write(serial->data, buf, count);
229         else
230                 ret = sp_blocking_write(serial->data, buf, count, timeout_ms);
231
232         switch (ret) {
233         case SP_ERR_ARG:
234                 sr_err("Attempted serial port write with invalid arguments.");
235                 return SR_ERR_ARG;
236         case SP_ERR_FAIL:
237                 error = sp_last_error_message();
238                 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
239                 sp_free_error_message(error);
240                 return SR_ERR;
241         }
242
243         sr_spew("Wrote %d/%d bytes.", ret, count);
244
245         return ret;
246 }
247
248 /**
249  * Write a number of bytes to the specified serial port, blocking until finished.
250  *
251  * @param serial Previously initialized serial port structure.
252  * @param[in] buf Buffer containing the bytes to write.
253  * @param[in] count Number of bytes to write.
254  * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
255  *
256  * @retval SR_ERR_ARG Invalid argument.
257  * @retval SR_ERR Other error.
258  * @retval other The number of bytes written. If this is less than the number
259  * specified in the call, the timeout was reached.
260  */
261 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
262                 const void *buf, size_t count, unsigned int timeout_ms)
263 {
264         return _serial_write(serial, buf, count, 0, timeout_ms);
265 }
266
267 /**
268  * Write a number of bytes to the specified serial port, return immediately.
269  *
270  * @param serial Previously initialized serial port structure.
271  * @param[in] buf Buffer containing the bytes to write.
272  * @param[in] count Number of bytes to write.
273  *
274  * @retval SR_ERR_ARG Invalid argument.
275  * @retval SR_ERR Other error.
276  * @retval other The number of bytes written.
277 */
278 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
279                 const void *buf, size_t count)
280 {
281         return _serial_write(serial, buf, count, 1, 0);
282 }
283
284 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
285                 size_t count, int nonblocking, unsigned int timeout_ms)
286 {
287         ssize_t ret;
288         char *error;
289
290         if (!serial) {
291                 sr_dbg("Invalid serial port.");
292                 return SR_ERR;
293         }
294
295         if (!serial->data) {
296                 sr_dbg("Cannot use unopened serial port %s.", serial->port);
297                 return SR_ERR;
298         }
299
300         if (nonblocking)
301                 ret = sp_nonblocking_read(serial->data, buf, count);
302         else
303                 ret = sp_blocking_read(serial->data, buf, count, timeout_ms);
304
305         switch (ret) {
306         case SP_ERR_ARG:
307                 sr_err("Attempted serial port read with invalid arguments.");
308                 return SR_ERR_ARG;
309         case SP_ERR_FAIL:
310                 error = sp_last_error_message();
311                 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
312                 sp_free_error_message(error);
313                 return SR_ERR;
314         }
315
316         if (ret > 0)
317                 sr_spew("Read %d/%d bytes.", ret, count);
318
319         return ret;
320 }
321
322 /**
323  * Read a number of bytes from the specified serial port, block until finished.
324  *
325  * @param serial Previously initialized serial port structure.
326  * @param buf Buffer where to store the bytes that are read.
327  * @param[in] count The number of bytes to read.
328  * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
329  *
330  * @retval SR_ERR_ARG Invalid argument.
331  * @retval SR_ERR     Other error.
332  * @retval other      The number of bytes read. If this is less than the number
333  * requested, the timeout was reached.
334  */
335 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
336                 size_t count, unsigned int timeout_ms)
337 {
338         return _serial_read(serial, buf, count, 0, timeout_ms);
339 }
340
341 /**
342  * Try to read up to @a count bytes from the specified serial port, return
343  * immediately with what's available.
344  *
345  * @param serial Previously initialized serial port structure.
346  * @param buf Buffer where to store the bytes that are read.
347  * @param[in] count The number of bytes to read.
348  *
349  * @retval SR_ERR_ARG Invalid argument.
350  * @retval SR_ERR     Other error.
351  * @retval other      The number of bytes read.
352  */
353 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
354                 size_t count)
355 {
356         return _serial_read(serial, buf, count, 1, 0);
357 }
358
359 /**
360  * Set serial parameters for the specified serial port.
361  *
362  * @param serial Previously initialized serial port structure.
363  * @param[in] baudrate The baudrate to set.
364  * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
365  * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
366  * @param[in] stopbits The number of stop bits to use (1 or 2).
367  * @param[in] flowcontrol The flow control settings to use (0 = none,
368  *                      1 = RTS/CTS, 2 = XON/XOFF).
369  * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
370  * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
371  *
372  * @retval SR_OK Success.
373  * @retval SR_ERR Failure.
374  */
375 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
376                               int bits, int parity, int stopbits,
377                               int flowcontrol, int rts, int dtr)
378 {
379         int ret;
380         char *error;
381         struct sp_port_config *config;
382
383         if (!serial) {
384                 sr_dbg("Invalid serial port.");
385                 return SR_ERR;
386         }
387
388         if (!serial->data) {
389                 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
390                 return SR_ERR;
391         }
392
393         sr_spew("Setting serial parameters on port %s.", serial->port);
394
395         sp_new_config(&config);
396         sp_set_config_baudrate(config, baudrate);
397         sp_set_config_bits(config, bits);
398         switch (parity) {
399         case 0:
400                 sp_set_config_parity(config, SP_PARITY_NONE);
401                 break;
402         case 1:
403                 sp_set_config_parity(config, SP_PARITY_EVEN);
404                 break;
405         case 2:
406                 sp_set_config_parity(config, SP_PARITY_ODD);
407                 break;
408         default:
409                 return SR_ERR_ARG;
410         }
411         sp_set_config_stopbits(config, stopbits);
412         sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
413         sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
414         sp_set_config_dtr(config, dtr);
415         sp_set_config_dsr(config, SP_DSR_IGNORE);
416         sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
417
418         ret = sp_set_config(serial->data, config);
419         sp_free_config(config);
420
421         switch (ret) {
422         case SP_ERR_ARG:
423                 sr_err("Invalid arguments for setting serial port parameters.");
424                 return SR_ERR_ARG;
425         case SP_ERR_FAIL:
426                 error = sp_last_error_message();
427                 sr_err("Error setting serial port parameters (%d): %s.",
428                         sp_last_error_code(), error);
429                 sp_free_error_message(error);
430                 return SR_ERR;
431         }
432
433         return SR_OK;
434 }
435
436 /**
437  * Set serial parameters for the specified serial port from parameter string.
438  *
439  * @param serial Previously initialized serial port structure.
440  * @param[in] paramstr A serial communication parameters string of the form
441  * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
442  *  Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
443  * \<baudrate\>=integer Baud rate.\n
444  * \<bits\>=5|6|7|8 Number of data bits.\n
445  * \<parity\>=n|e|o None, even, odd.\n
446  * \<stopbits\>=1|2 One or two stop bits.\n
447  * Options:\n
448  * dtr=0|1 Set DTR off resp. on.\n
449  * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
450  * rts=0|1 Set RTS off resp. on.\n
451  * Please note that values and combinations of these parameters must be
452  * supported by the concrete serial interface hardware and the drivers for it.
453  * @retval SR_OK Success.
454  * @retval SR_ERR Failure.
455  */
456 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
457                 const char *paramstr)
458 {
459 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
460
461         GRegex *reg;
462         GMatchInfo *match;
463         int speed, databits, parity, stopbits, flow, rts, dtr, i;
464         char *mstr, **opts, **kv;
465
466         speed = databits = parity = stopbits = flow = 0;
467         rts = dtr = -1;
468         sr_spew("Parsing parameters from \"%s\".", paramstr);
469         reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
470         if (g_regex_match(reg, paramstr, 0, &match)) {
471                 if ((mstr = g_match_info_fetch(match, 1)))
472                         speed = strtoul(mstr, NULL, 10);
473                 g_free(mstr);
474                 if ((mstr = g_match_info_fetch(match, 2)))
475                         databits = strtoul(mstr, NULL, 10);
476                 g_free(mstr);
477                 if ((mstr = g_match_info_fetch(match, 3))) {
478                         switch (mstr[0]) {
479                         case 'n':
480                                 parity = SERIAL_PARITY_NONE;
481                                 break;
482                         case 'e':
483                                 parity = SERIAL_PARITY_EVEN;
484                                 break;
485                         case 'o':
486                                 parity = SERIAL_PARITY_ODD;
487                                 break;
488                         }
489                 }
490                 g_free(mstr);
491                 if ((mstr = g_match_info_fetch(match, 4)))
492                         stopbits = strtoul(mstr, NULL, 10);
493                 g_free(mstr);
494                 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
495                         if (mstr[0] != '/') {
496                                 sr_dbg("missing separator before extra options");
497                                 speed = 0;
498                         } else {
499                                 /* A set of "key=value" options separated by / */
500                                 opts = g_strsplit(mstr + 1, "/", 0);
501                                 for (i = 0; opts[i]; i++) {
502                                         kv = g_strsplit(opts[i], "=", 2);
503                                         if (!strncmp(kv[0], "rts", 3)) {
504                                                 if (kv[1][0] == '1')
505                                                         rts = 1;
506                                                 else if (kv[1][0] == '0')
507                                                         rts = 0;
508                                                 else {
509                                                         sr_dbg("invalid value for rts: %c", kv[1][0]);
510                                                         speed = 0;
511                                                 }
512                                         } else if (!strncmp(kv[0], "dtr", 3)) {
513                                                 if (kv[1][0] == '1')
514                                                         dtr = 1;
515                                                 else if (kv[1][0] == '0')
516                                                         dtr = 0;
517                                                 else {
518                                                         sr_dbg("invalid value for dtr: %c", kv[1][0]);
519                                                         speed = 0;
520                                                 }
521                                         } else if (!strncmp(kv[0], "flow", 4)) {
522                                                 if (kv[1][0] == '0')
523                                                         flow = 0;
524                                                 else if (kv[1][0] == '1')
525                                                         flow = 1;
526                                                 else if (kv[1][0] == '2')
527                                                         flow = 2;
528                                                 else {
529                                                         sr_dbg("invalid value for flow: %c", kv[1][0]);
530                                                         speed = 0;
531                                                 }
532                                         }
533                                         g_strfreev(kv);
534                                 }
535                                 g_strfreev(opts);
536                         }
537                 }
538                 g_free(mstr);
539         }
540         g_match_info_unref(match);
541         g_regex_unref(reg);
542
543         if (speed) {
544                 return serial_set_params(serial, speed, databits, parity,
545                                          stopbits, flow, rts, dtr);
546         } else {
547                 sr_dbg("Could not infer speed from parameter string.");
548                 return SR_ERR_ARG;
549         }
550 }
551
552 /**
553  * Read a line from the specified serial port.
554  *
555  * @param serial Previously initialized serial port structure.
556  * @param buf Buffer where to store the bytes that are read.
557  * @param buflen Size of the buffer.
558  * @param[in] timeout_ms How long to wait for a line to come in.
559  *
560  * Reading stops when CR of LR is found, which is stripped from the buffer.
561  *
562  * @retval SR_OK Success.
563  * @retval SR_ERR Failure.
564  */
565 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
566                 int *buflen, gint64 timeout_ms)
567 {
568         gint64 start, remaining;
569         int maxlen, len;
570
571         if (!serial) {
572                 sr_dbg("Invalid serial port.");
573                 return SR_ERR;
574         }
575
576         if (!serial->data) {
577                 sr_dbg("Cannot use unopened serial port %s.", serial->port);
578                 return -1;
579         }
580
581         start = g_get_monotonic_time();
582         remaining = timeout_ms;
583
584         maxlen = *buflen;
585         *buflen = len = 0;
586         while(1) {
587                 len = maxlen - *buflen - 1;
588                 if (len < 1)
589                         break;
590                 len = sp_blocking_read(serial->data, *buf + *buflen, 1, remaining);
591                 if (len > 0) {
592                         *buflen += len;
593                         *(*buf + *buflen) = '\0';
594                         if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
595                                         || *(*buf + *buflen - 1) == '\n')) {
596                                 /* Strip CR/LF and terminate. */
597                                 *(*buf + --*buflen) = '\0';
598                                 break;
599                         }
600                 }
601                 /* Reduce timeout by time elapsed. */
602                 remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
603                 if (remaining <= 0)
604                         /* Timeout */
605                         break;
606                 if (len < 1)
607                         g_usleep(2000);
608         }
609         if (*buflen)
610                 sr_dbg("Received %d: '%s'.", *buflen, *buf);
611
612         return SR_OK;
613 }
614
615 /**
616  * Try to find a valid packet in a serial data stream.
617  *
618  * @param serial Previously initialized serial port structure.
619  * @param buf Buffer containing the bytes to write.
620  * @param buflen Size of the buffer.
621  * @param[in] packet_size Size, in bytes, of a valid packet.
622  * @param is_valid Callback that assesses whether the packet is valid or not.
623  * @param[in] timeout_ms The timeout after which, if no packet is detected, to
624  *                   abort scanning.
625  * @param[in] baudrate The baudrate of the serial port. This parameter is not
626  *                 critical, but it helps fine tune the serial port polling
627  *                 delay.
628  *
629  * @retval SR_OK Valid packet was found within the given timeout.
630  * @retval SR_ERR Failure.
631  */
632 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
633                                  uint8_t *buf, size_t *buflen,
634                                  size_t packet_size,
635                                  packet_valid_callback is_valid,
636                                  uint64_t timeout_ms, int baudrate)
637 {
638         uint64_t start, time, byte_delay_us;
639         size_t ibuf, i, maxlen;
640         int len;
641
642         maxlen = *buflen;
643
644         sr_dbg("Detecting packets on %s (timeout = %" PRIu64
645                "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
646
647         if (maxlen < (packet_size / 2) ) {
648                 sr_err("Buffer size must be at least twice the packet size.");
649                 return SR_ERR;
650         }
651
652         /* Assume 8n1 transmission. That is 10 bits for every byte. */
653         byte_delay_us = 10 * (1000000 / baudrate);
654         start = g_get_monotonic_time();
655
656         i = ibuf = len = 0;
657         while (ibuf < maxlen) {
658                 len = serial_read_nonblocking(serial, &buf[ibuf], 1);
659                 if (len > 0) {
660                         ibuf += len;
661                 } else if (len == 0) {
662                         /* No logging, already done in serial_read(). */
663                 } else {
664                         /* Error reading byte, but continuing anyway. */
665                 }
666
667                 time = g_get_monotonic_time() - start;
668                 time /= 1000;
669
670                 if ((ibuf - i) >= packet_size) {
671                         /* We have at least a packet's worth of data. */
672                         if (is_valid(&buf[i])) {
673                                 sr_spew("Found valid %d-byte packet after "
674                                         "%" PRIu64 "ms.", (ibuf - i), time);
675                                 *buflen = ibuf;
676                                 return SR_OK;
677                         } else {
678                                 sr_spew("Got %d bytes, but not a valid "
679                                         "packet.", (ibuf - i));
680                         }
681                         /* Not a valid packet. Continue searching. */
682                         i++;
683                 }
684                 if (time >= timeout_ms) {
685                         /* Timeout */
686                         sr_dbg("Detection timed out after %dms.", time);
687                         break;
688                 }
689                 if (len < 1)
690                         g_usleep(byte_delay_us);
691         }
692
693         *buflen = ibuf;
694
695         sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
696
697         return SR_ERR;
698 }
699
700 /**
701  * Extract the serial device and options from the options linked list.
702  *
703  * @param options List of options passed from the command line.
704  * @param serial_device Pointer where to store the exctracted serial device.
705  * @param serial_options Pointer where to store the optional extracted serial
706  * options.
707  *
708  * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
709  * returned string should not be freed by the caller.
710  */
711 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
712                                       const char **serial_options)
713 {
714         GSList *l;
715         struct sr_config *src;
716
717         *serial_device = NULL;
718
719         for (l = options; l; l = l->next) {
720                 src = l->data;
721                 switch (src->key) {
722                 case SR_CONF_CONN:
723                         *serial_device = g_variant_get_string(src->data, NULL);
724                         sr_dbg("Parsed serial device: %s", *serial_device);
725                         break;
726
727                 case SR_CONF_SERIALCOMM:
728                         *serial_options = g_variant_get_string(src->data, NULL);
729                         sr_dbg("Parsed serial options: %s", *serial_options);
730                         break;
731                 }
732         }
733
734         if (!*serial_device) {
735                 sr_dbg("No serial device specified");
736                 return SR_ERR;
737         }
738
739         return SR_OK;
740 }
741
742 #ifdef _WIN32
743 typedef HANDLE event_handle;
744 #else
745 typedef int event_handle;
746 #endif
747
748 SR_PRIV int serial_source_add(struct sr_session *session,
749                 struct sr_serial_dev_inst *serial, int events, int timeout,
750                 sr_receive_data_callback cb, void *cb_data)
751 {
752         enum sp_event mask = 0;
753         unsigned int i;
754
755         if (sp_new_event_set(&serial->event_set) != SP_OK)
756                 return SR_ERR;
757
758         if (events & G_IO_IN)
759                 mask |= SP_EVENT_RX_READY;
760         if (events & G_IO_OUT)
761                 mask |= SP_EVENT_TX_READY;
762         if (events & G_IO_ERR)
763                 mask |= SP_EVENT_ERROR;
764
765         if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
766                 sp_free_event_set(serial->event_set);
767                 return SR_ERR;
768         }
769
770         serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
771
772         for (i = 0; i < serial->event_set->count; i++) {
773
774                 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
775
776                 mask = serial->event_set->masks[i];
777
778                 if (mask & SP_EVENT_RX_READY)
779                         serial->pollfds[i].events |= G_IO_IN;
780                 if (mask & SP_EVENT_TX_READY)
781                         serial->pollfds[i].events |= G_IO_OUT;
782                 if (mask & SP_EVENT_ERROR)
783                         serial->pollfds[i].events |= G_IO_ERR;
784
785                 if (sr_session_source_add_pollfd(session, &serial->pollfds[i],
786                                         timeout, cb, cb_data) != SR_OK)
787                         return SR_ERR;
788         }
789
790         return SR_OK;
791 }
792
793 SR_PRIV int serial_source_remove(struct sr_session *session,
794                 struct sr_serial_dev_inst *serial)
795 {
796         unsigned int i;
797
798         for (i = 0; i < serial->event_set->count; i++)
799                 if (sr_session_source_remove_pollfd(session, &serial->pollfds[i]) != SR_OK)
800                         return SR_ERR;
801
802         g_free(serial->pollfds);
803         sp_free_event_set(serial->event_set);
804
805         serial->pollfds = NULL;
806         serial->event_set = NULL;
807
808         return SR_OK;
809 }
810
811 /**
812  * Find USB serial devices via the USB vendor ID and product ID.
813  *
814  * @param[in] vendor_id Vendor ID of the USB device.
815  * @param[in] product_id Product ID of the USB device.
816  *
817  * @return A GSList of strings containing the path of the serial device or
818  *         NULL if no serial device is found. The returned list must be freed
819  *         by the caller.
820  */
821 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
822 {
823         GSList *tty_devs = NULL;
824         struct sp_port **ports;
825         int i, vid, pid;
826
827         if (sp_list_ports(&ports) != SP_OK)
828                 return NULL;
829
830         for (i=0; ports[i]; i++)
831                 if (sp_get_port_transport(ports[i]) == SP_TRANSPORT_USB &&
832                     sp_get_port_usb_vid_pid(ports[i], &vid, &pid) == SP_OK &&
833                     vid == vendor_id && pid == product_id)
834                         tty_devs = g_slist_prepend(tty_devs,
835                                                    g_strdup(sp_get_port_name(ports[i])));
836
837         sp_free_port_list(ports);
838         return tty_devs;
839 }
840
841 SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
842 {
843         struct sp_port_config *config;
844         int timeout_ms, bits, baud, tmp;
845
846         /* Default to 1s. */
847         timeout_ms = 1000;
848
849         if (sp_new_config(&config) < 0)
850                 return timeout_ms;
851
852         bits = baud = 0;
853         do {
854                 if (sp_get_config(port->data, config) < 0)
855                         break;
856
857                 /* Start bit. */
858                 bits = 1;
859                 if (sp_get_config_bits(config, &tmp) < 0)
860                         break;
861                 bits += tmp;
862                 if (sp_get_config_stopbits(config, &tmp) < 0)
863                         break;
864                 bits += tmp;
865                 if (sp_get_config_baudrate(config, &tmp) < 0)
866                         break;
867                 baud = tmp;
868         } while (FALSE);
869
870         if (bits && baud) {
871                 /* Throw in 10ms for misc OS overhead. */
872                 timeout_ms = 10;
873                 timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
874         }
875
876         sp_free_config(config);
877
878         return timeout_ms;
879 }