]> sigrok.org Git - libsigrok.git/blob - hardware/common/serial.c
Don't define names ending with _t (POSIX reserved).
[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,
574                                  packet_valid_callback is_valid,
575                                  uint64_t timeout_ms, int baudrate)
576 {
577         uint64_t start, time, byte_delay_us;
578         size_t ibuf, i, maxlen;
579         int len;
580
581         maxlen = *buflen;
582
583         sr_dbg("Detecting packets on %s (timeout = %" PRIu64
584                "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
585
586         if (maxlen < (packet_size / 2) ) {
587                 sr_err("Buffer size must be at least twice the packet size.");
588                 return SR_ERR;
589         }
590
591         /* Assume 8n1 transmission. That is 10 bits for every byte. */
592         byte_delay_us = 10 * (1000000 / baudrate);
593         start = g_get_monotonic_time();
594
595         i = ibuf = len = 0;
596         while (ibuf < maxlen) {
597                 len = serial_read(serial, &buf[ibuf], 1);
598                 if (len > 0) {
599                         ibuf += len;
600                 } else if (len == 0) {
601                         /* No logging, already done in serial_read(). */
602                 } else {
603                         /* Error reading byte, but continuing anyway. */
604                 }
605
606                 time = g_get_monotonic_time() - start;
607                 time /= 1000;
608
609                 if ((ibuf - i) >= packet_size) {
610                         /* We have at least a packet's worth of data. */
611                         if (is_valid(&buf[i])) {
612                                 sr_spew("Found valid %d-byte packet after "
613                                         "%" PRIu64 "ms.", (ibuf - i), time);
614                                 *buflen = ibuf;
615                                 return SR_OK;
616                         } else {
617                                 sr_spew("Got %d bytes, but not a valid "
618                                         "packet.", (ibuf - i));
619                         }
620                         /* Not a valid packet. Continue searching. */
621                         i++;
622                 }
623                 if (time >= timeout_ms) {
624                         /* Timeout */
625                         sr_dbg("Detection timed out after %dms.", time);
626                         break;
627                 }
628                 if (len < 1)
629                         g_usleep(byte_delay_us);
630         }
631
632         *buflen = ibuf;
633
634         sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
635
636         return SR_ERR;
637 }
638
639 /**
640  * Extract the serial device and options from the options linked list.
641  *
642  * @param options List of options passed from the command line.
643  * @param serial_device Pointer where to store the exctracted serial device.
644  * @param serial_options Pointer where to store the optional extracted serial
645  * options.
646  *
647  * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
648  * returned string should not be freed by the caller.
649  */
650 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
651                                       const char **serial_options)
652 {
653         GSList *l;
654         struct sr_config *src;
655
656         *serial_device = NULL;
657
658         for (l = options; l; l = l->next) {
659                 src = l->data;
660                 switch (src->key) {
661                 case SR_CONF_CONN:
662                         *serial_device = g_variant_get_string(src->data, NULL);
663                         sr_dbg("Parsed serial device: %s", *serial_device);
664                         break;
665
666                 case SR_CONF_SERIALCOMM:
667                         *serial_options = g_variant_get_string(src->data, NULL);
668                         sr_dbg("Parsed serial options: %s", *serial_options);
669                         break;
670                 }
671         }
672
673         if (!*serial_device) {
674                 sr_dbg("No serial device specified");
675                 return SR_ERR;
676         }
677
678         return SR_OK;
679 }
680
681 #ifdef _WIN32
682 typedef HANDLE event_handle;
683 #else
684 typedef int event_handle;
685 #endif
686
687 SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
688                 int timeout, sr_receive_data_callback cb, void *cb_data)
689 {
690         enum sp_event mask = 0;
691         unsigned int i;
692
693         if (sp_new_event_set(&serial->event_set) != SP_OK)
694                 return SR_ERR;
695
696         if (events & G_IO_IN)
697                 mask |= SP_EVENT_RX_READY;
698         if (events & G_IO_OUT)
699                 mask |= SP_EVENT_TX_READY;
700         if (events & G_IO_ERR)
701                 mask |= SP_EVENT_ERROR;
702
703         if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
704                 sp_free_event_set(serial->event_set);
705                 return SR_ERR;
706         }
707
708         serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
709
710         for (i = 0; i < serial->event_set->count; i++) {
711
712                 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
713
714                 mask = serial->event_set->masks[i];
715
716                 if (mask & SP_EVENT_RX_READY)
717                         serial->pollfds[i].events |= G_IO_IN;
718                 if (mask & SP_EVENT_TX_READY)
719                         serial->pollfds[i].events |= G_IO_OUT;
720                 if (mask & SP_EVENT_ERROR)
721                         serial->pollfds[i].events |= G_IO_ERR;
722
723                 if (sr_session_source_add_pollfd(&serial->pollfds[i],
724                                 timeout, cb, cb_data) != SR_OK)
725                         return SR_ERR;
726         }
727
728         return SR_OK;
729 }
730
731 SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
732 {
733         unsigned int i;
734
735         for (i = 0; i < serial->event_set->count; i++)
736                 if (sr_session_source_remove_pollfd(&serial->pollfds[i]) != SR_OK)
737                         return SR_ERR;
738
739         g_free(serial->pollfds);
740         sp_free_event_set(serial->event_set);
741
742         serial->pollfds = NULL;
743         serial->event_set = NULL;
744
745         return SR_OK;
746 }
747
748 /**
749  * Find USB serial devices via the USB vendor ID and product ID.
750  *
751  * @param vendor_id Vendor ID of the USB device.
752  * @param product_id Product ID of the USB device.
753  *
754  * @return A GSList of strings containing the path of the serial device or
755  *         NULL if no serial device is found. The returned list must be freed
756  *         by the caller.
757  */
758 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
759 {
760 #ifdef __linux__
761         const gchar *usb_dev;
762         const char device_tree[] = "/sys/bus/usb/devices/";
763         GDir *devices_dir, *device_dir;
764         GSList *l = NULL;
765         GSList *tty_devs;
766         GSList *matched_paths;
767         FILE *fd;
768         char tmp[5];
769         gchar *vendor_path, *product_path, *path_copy;
770         gchar *prefix, *subdir_path, *device_path, *tty_path;
771         unsigned long read_vendor_id, read_product_id;
772         const char *file;
773
774         l = NULL;
775         tty_devs = NULL;
776         matched_paths = NULL;
777
778         if (!(devices_dir = g_dir_open(device_tree, 0, NULL)))
779                 return NULL;
780
781         /*
782          * Find potential candidates using the vendor ID and product ID
783          * and store them in matched_paths.
784          */
785         while ((usb_dev = g_dir_read_name(devices_dir))) {
786                 vendor_path = g_strconcat(device_tree,
787                                           usb_dev, "/idVendor", NULL);
788                 product_path = g_strconcat(device_tree,
789                                            usb_dev, "/idProduct", NULL);
790
791                 if (!g_file_test(vendor_path, G_FILE_TEST_EXISTS) ||
792                     !g_file_test(product_path, G_FILE_TEST_EXISTS))
793                         goto skip_device;
794
795                 if ((fd = g_fopen(vendor_path, "r")) == NULL)
796                         goto skip_device;
797
798                 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
799                         fclose(fd);
800                         goto skip_device;
801                 }
802                 read_vendor_id = strtoul(tmp, NULL, 16);
803
804                 fclose(fd);
805
806                 if ((fd = g_fopen(product_path, "r")) == NULL)
807                         goto skip_device;
808
809                 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
810                         fclose(fd);
811                         goto skip_device;
812                 }
813                 read_product_id = strtoul(tmp, NULL, 16);
814
815                 fclose(fd);
816
817                 if (vendor_id == read_vendor_id &&
818                     product_id == read_product_id) {
819                         path_copy = g_strdup(usb_dev);
820                         matched_paths = g_slist_prepend(matched_paths,
821                                                         path_copy);
822                 }
823
824 skip_device:
825                 g_free(vendor_path);
826                 g_free(product_path);
827         }
828         g_dir_close(devices_dir);
829
830         /* For every matched device try to find a ttyUSBX subfolder. */
831         for (l = matched_paths; l; l = l->next) {
832                 subdir_path = NULL;
833
834                 device_path = g_strconcat(device_tree, l->data, NULL);
835
836                 if (!(device_dir = g_dir_open(device_path, 0, NULL))) {
837                         g_free(device_path);
838                         continue;
839                 }
840
841                 prefix = g_strconcat(l->data, ":", NULL);
842
843                 while ((file = g_dir_read_name(device_dir))) {
844                         if (g_str_has_prefix(file, prefix)) {
845                                 subdir_path = g_strconcat(device_path,
846                                                 "/", file, NULL);
847                                 break;
848                         }
849                 }
850                 g_dir_close(device_dir);
851
852                 g_free(prefix);
853                 g_free(device_path);
854
855                 if (subdir_path) {
856                         if (!(device_dir = g_dir_open(subdir_path, 0, NULL))) {
857                                 g_free(subdir_path);
858                                 continue;
859                         }
860                         g_free(subdir_path);
861
862                         while ((file = g_dir_read_name(device_dir))) {
863                                 if (g_str_has_prefix(file, "ttyUSB")) {
864                                         tty_path = g_strconcat("/dev/",
865                                                                file, NULL);
866                                         sr_dbg("Found USB device %04x:%04x attached to %s.",
867                                                vendor_id, product_id, tty_path);
868                                         tty_devs = g_slist_prepend(tty_devs,
869                                                         tty_path);
870                                         break;
871                                 }
872                         }
873                         g_dir_close(device_dir);
874                 }
875         }
876         g_slist_free_full(matched_paths, g_free);
877
878         return tty_devs;
879 #else
880         (void)vendor_id;
881         (void)product_id;
882
883         return NULL;
884 #endif
885 }