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