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