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