]> sigrok.org Git - libsigrok.git/blob - src/serial.c
serial: re-implement sr_serial_find_usb() using new libsp APIs
[libsigrok.git] / src / serial.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6  * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
7  *
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[in] 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[in] buf Buffer containing the bytes to write.
216  * @param[in] count Number of bytes to write.
217  *
218  * @retval SR_ERR_ARG Invalid argument.
219  * @retval SR_ERR Other error.
220  * @retval other The number of bytes written.
221  */
222 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
223                 const void *buf, size_t count)
224 {
225         return _serial_write(serial, buf, count, serial->nonblocking);
226 }
227
228 /**
229  * Write a number of bytes to the specified serial port, blocking until finished.
230  * @copydetails serial_write()
231  */
232 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
233                 const void *buf, size_t count)
234 {
235         return _serial_write(serial, buf, count, 0);
236 }
237
238 /**
239  * Write a number of bytes to the specified serial port, return immediately.
240  * @copydetails serial_write()
241 */
242 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
243                 const void *buf, size_t count)
244 {
245         return _serial_write(serial, buf, count, 1);
246 }
247
248 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
249                 size_t count, int nonblocking)
250 {
251         ssize_t ret;
252         char *error;
253
254         if (!serial) {
255                 sr_dbg("Invalid serial port.");
256                 return SR_ERR;
257         }
258
259         if (!serial->data) {
260                 sr_dbg("Cannot use unopened serial port %s.", serial->port);
261                 return SR_ERR;
262         }
263
264         if (nonblocking)
265                 ret = sp_nonblocking_read(serial->data, buf, count);
266         else
267                 ret = sp_blocking_read(serial->data, buf, count, 0);
268
269         switch (ret) {
270         case SP_ERR_ARG:
271                 sr_err("Attempted serial port read with invalid arguments.");
272                 return SR_ERR_ARG;
273         case SP_ERR_FAIL:
274                 error = sp_last_error_message();
275                 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
276                 sp_free_error_message(error);
277                 return SR_ERR;
278         }
279
280         if (ret > 0)
281                 sr_spew("Read %d/%d bytes.", ret, count);
282
283         return ret;
284 }
285
286 /**
287  * Read a number of bytes from the specified serial port.
288  *
289  * @param serial Previously initialized serial port structure.
290  * @param buf Buffer where to store the bytes that are read.
291  * @param[in] count The number of bytes to read.
292  *
293  * @retval SR_ERR_ARG Invalid argument.
294  * @retval SR_ERR     Other error.
295  * @retval other      The number of bytes read.
296  */
297 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
298                 size_t count)
299 {
300         return _serial_read(serial, buf, count, serial->nonblocking);
301 }
302
303 /**
304  * Read a number of bytes from the specified serial port, block until finished.
305  * @copydetails serial_read()
306  */
307 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
308                 size_t count)
309 {
310         return _serial_read(serial, buf, count, 0);
311 }
312
313 /**
314  * Try to read up to @a count bytes from the specified serial port, return
315  * immediately with what's available.
316  * @copydetails serial_read()
317  */
318 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
319                 size_t count)
320 {
321         return _serial_read(serial, buf, count, 1);
322 }
323
324 /**
325  * Set serial parameters for the specified serial port.
326  *
327  * @param serial Previously initialized serial port structure.
328  * @param[in] baudrate The baudrate to set.
329  * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
330  * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
331  * @param[in] stopbits The number of stop bits to use (1 or 2).
332  * @param[in] flowcontrol The flow control settings to use (0 = none,
333  *                      1 = RTS/CTS, 2 = XON/XOFF).
334  * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
335  * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
336  *
337  * @retval SR_OK Success.
338  * @retval SR_ERR Failure.
339  */
340 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
341                               int bits, int parity, int stopbits,
342                               int flowcontrol, int rts, int dtr)
343 {
344         int ret;
345         char *error;
346         struct sp_port_config *config;
347
348         if (!serial) {
349                 sr_dbg("Invalid serial port.");
350                 return SR_ERR;
351         }
352
353         if (!serial->data) {
354                 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
355                 return SR_ERR;
356         }
357
358         sr_spew("Setting serial parameters on port %s.", serial->port);
359
360         sp_new_config(&config);
361         sp_set_config_baudrate(config, baudrate);
362         sp_set_config_bits(config, bits);
363         switch (parity) {
364         case 0:
365                 sp_set_config_parity(config, SP_PARITY_NONE);
366                 break;
367         case 1:
368                 sp_set_config_parity(config, SP_PARITY_EVEN);
369                 break;
370         case 2:
371                 sp_set_config_parity(config, SP_PARITY_ODD);
372                 break;
373         default:
374                 return SR_ERR_ARG;
375         }
376         sp_set_config_stopbits(config, stopbits);
377         sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
378         sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
379         sp_set_config_dtr(config, dtr);
380         sp_set_config_dsr(config, SP_DSR_IGNORE);
381         sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
382
383         ret = sp_set_config(serial->data, config);
384         sp_free_config(config);
385
386         switch (ret) {
387         case SP_ERR_ARG:
388                 sr_err("Invalid arguments for setting serial port parameters.");
389                 return SR_ERR_ARG;
390         case SP_ERR_FAIL:
391                 error = sp_last_error_message();
392                 sr_err("Error setting serial port parameters (%d): %s.",
393                         sp_last_error_code(), error);
394                 sp_free_error_message(error);
395                 return SR_ERR;
396         }
397
398         return SR_OK;
399 }
400
401 /**
402  * Set serial parameters for the specified serial port from parameter string.
403  *
404  * @param serial Previously initialized serial port structure.
405  * @param[in] paramstr A serial communication parameters string of the form
406  * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
407  *  Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
408  * \<baudrate\>=integer Baud rate.\n
409  * \<bits\>=5|6|7|8 Number of data bits.\n
410  * \<parity\>=n|e|o None, even, odd.\n
411  * \<stopbits\>=1|2 One or two stop bits.\n
412  * Options:\n
413  * dtr=0|1 Set DTR off resp. on.\n
414  * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
415  * rts=0|1 Set RTS off resp. on.\n
416  * Please note that values and combinations of these parameters must be
417  * supported by the concrete serial interface hardware and the drivers for it.
418  * @retval SR_OK Success.
419  * @retval SR_ERR Failure.
420  */
421 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
422                 const char *paramstr)
423 {
424 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
425
426         GRegex *reg;
427         GMatchInfo *match;
428         int speed, databits, parity, stopbits, flow, rts, dtr, i;
429         char *mstr, **opts, **kv;
430
431         speed = databits = parity = stopbits = flow = 0;
432         rts = dtr = -1;
433         sr_spew("Parsing parameters from \"%s\".", paramstr);
434         reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
435         if (g_regex_match(reg, paramstr, 0, &match)) {
436                 if ((mstr = g_match_info_fetch(match, 1)))
437                         speed = strtoul(mstr, NULL, 10);
438                 g_free(mstr);
439                 if ((mstr = g_match_info_fetch(match, 2)))
440                         databits = strtoul(mstr, NULL, 10);
441                 g_free(mstr);
442                 if ((mstr = g_match_info_fetch(match, 3))) {
443                         switch (mstr[0]) {
444                         case 'n':
445                                 parity = SERIAL_PARITY_NONE;
446                                 break;
447                         case 'e':
448                                 parity = SERIAL_PARITY_EVEN;
449                                 break;
450                         case 'o':
451                                 parity = SERIAL_PARITY_ODD;
452                                 break;
453                         }
454                 }
455                 g_free(mstr);
456                 if ((mstr = g_match_info_fetch(match, 4)))
457                         stopbits = strtoul(mstr, NULL, 10);
458                 g_free(mstr);
459                 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
460                         if (mstr[0] != '/') {
461                                 sr_dbg("missing separator before extra options");
462                                 speed = 0;
463                         } else {
464                                 /* A set of "key=value" options separated by / */
465                                 opts = g_strsplit(mstr + 1, "/", 0);
466                                 for (i = 0; opts[i]; i++) {
467                                         kv = g_strsplit(opts[i], "=", 2);
468                                         if (!strncmp(kv[0], "rts", 3)) {
469                                                 if (kv[1][0] == '1')
470                                                         rts = 1;
471                                                 else if (kv[1][0] == '0')
472                                                         rts = 0;
473                                                 else {
474                                                         sr_dbg("invalid value for rts: %c", kv[1][0]);
475                                                         speed = 0;
476                                                 }
477                                         } else if (!strncmp(kv[0], "dtr", 3)) {
478                                                 if (kv[1][0] == '1')
479                                                         dtr = 1;
480                                                 else if (kv[1][0] == '0')
481                                                         dtr = 0;
482                                                 else {
483                                                         sr_dbg("invalid value for dtr: %c", kv[1][0]);
484                                                         speed = 0;
485                                                 }
486                                         } else if (!strncmp(kv[0], "flow", 4)) {
487                                                 if (kv[1][0] == '0')
488                                                         flow = 0;
489                                                 else if (kv[1][0] == '1')
490                                                         flow = 1;
491                                                 else if (kv[1][0] == '2')
492                                                         flow = 2;
493                                                 else {
494                                                         sr_dbg("invalid value for flow: %c", kv[1][0]);
495                                                         speed = 0;
496                                                 }
497                                         }
498                                         g_strfreev(kv);
499                                 }
500                                 g_strfreev(opts);
501                         }
502                 }
503                 g_free(mstr);
504         }
505         g_match_info_unref(match);
506         g_regex_unref(reg);
507
508         if (speed) {
509                 return serial_set_params(serial, speed, databits, parity,
510                                          stopbits, flow, rts, dtr);
511         } else {
512                 sr_dbg("Could not infer speed from parameter string.");
513                 return SR_ERR_ARG;
514         }
515 }
516
517 /**
518  * Read a line from the specified serial port.
519  *
520  * @param serial Previously initialized serial port structure.
521  * @param buf Buffer where to store the bytes that are read.
522  * @param buflen Size of the buffer.
523  * @param[in] timeout_ms How long to wait for a line to come in.
524  *
525  * Reading stops when CR of LR is found, which is stripped from the buffer.
526  *
527  * @retval SR_OK Success.
528  * @retval SR_ERR Failure.
529  */
530 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
531                 int *buflen, gint64 timeout_ms)
532 {
533         gint64 start;
534         int maxlen, len;
535
536         if (!serial) {
537                 sr_dbg("Invalid serial port.");
538                 return SR_ERR;
539         }
540
541         if (!serial->data) {
542                 sr_dbg("Cannot use unopened serial port %s.", serial->port);
543                 return -1;
544         }
545
546         timeout_ms *= 1000;
547         start = g_get_monotonic_time();
548
549         maxlen = *buflen;
550         *buflen = len = 0;
551         while(1) {
552                 len = maxlen - *buflen - 1;
553                 if (len < 1)
554                         break;
555                 len = serial_read(serial, *buf + *buflen, 1);
556                 if (len > 0) {
557                         *buflen += len;
558                         *(*buf + *buflen) = '\0';
559                         if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
560                                         || *(*buf + *buflen - 1) == '\n')) {
561                                 /* Strip CR/LF and terminate. */
562                                 *(*buf + --*buflen) = '\0';
563                                 break;
564                         }
565                 }
566                 if (g_get_monotonic_time() - start > timeout_ms)
567                         /* Timeout */
568                         break;
569                 if (len < 1)
570                         g_usleep(2000);
571         }
572         if (*buflen)
573                 sr_dbg("Received %d: '%s'.", *buflen, *buf);
574
575         return SR_OK;
576 }
577
578 /**
579  * Try to find a valid packet in a serial data stream.
580  *
581  * @param serial Previously initialized serial port structure.
582  * @param buf Buffer containing the bytes to write.
583  * @param buflen Size of the buffer.
584  * @param[in] packet_size Size, in bytes, of a valid packet.
585  * @param is_valid Callback that assesses whether the packet is valid or not.
586  * @param[in] timeout_ms The timeout after which, if no packet is detected, to
587  *                   abort scanning.
588  * @param[in] baudrate The baudrate of the serial port. This parameter is not
589  *                 critical, but it helps fine tune the serial port polling
590  *                 delay.
591  *
592  * @retval SR_OK Valid packet was found within the given timeout.
593  * @retval SR_ERR Failure.
594  */
595 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
596                                  uint8_t *buf, size_t *buflen,
597                                  size_t packet_size,
598                                  packet_valid_callback is_valid,
599                                  uint64_t timeout_ms, int baudrate)
600 {
601         uint64_t start, time, byte_delay_us;
602         size_t ibuf, i, maxlen;
603         int len;
604
605         maxlen = *buflen;
606
607         sr_dbg("Detecting packets on %s (timeout = %" PRIu64
608                "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
609
610         if (maxlen < (packet_size / 2) ) {
611                 sr_err("Buffer size must be at least twice the packet size.");
612                 return SR_ERR;
613         }
614
615         /* Assume 8n1 transmission. That is 10 bits for every byte. */
616         byte_delay_us = 10 * (1000000 / baudrate);
617         start = g_get_monotonic_time();
618
619         i = ibuf = len = 0;
620         while (ibuf < maxlen) {
621                 len = serial_read(serial, &buf[ibuf], 1);
622                 if (len > 0) {
623                         ibuf += len;
624                 } else if (len == 0) {
625                         /* No logging, already done in serial_read(). */
626                 } else {
627                         /* Error reading byte, but continuing anyway. */
628                 }
629
630                 time = g_get_monotonic_time() - start;
631                 time /= 1000;
632
633                 if ((ibuf - i) >= packet_size) {
634                         /* We have at least a packet's worth of data. */
635                         if (is_valid(&buf[i])) {
636                                 sr_spew("Found valid %d-byte packet after "
637                                         "%" PRIu64 "ms.", (ibuf - i), time);
638                                 *buflen = ibuf;
639                                 return SR_OK;
640                         } else {
641                                 sr_spew("Got %d bytes, but not a valid "
642                                         "packet.", (ibuf - i));
643                         }
644                         /* Not a valid packet. Continue searching. */
645                         i++;
646                 }
647                 if (time >= timeout_ms) {
648                         /* Timeout */
649                         sr_dbg("Detection timed out after %dms.", time);
650                         break;
651                 }
652                 if (len < 1)
653                         g_usleep(byte_delay_us);
654         }
655
656         *buflen = ibuf;
657
658         sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
659
660         return SR_ERR;
661 }
662
663 /**
664  * Extract the serial device and options from the options linked list.
665  *
666  * @param options List of options passed from the command line.
667  * @param serial_device Pointer where to store the exctracted serial device.
668  * @param serial_options Pointer where to store the optional extracted serial
669  * options.
670  *
671  * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
672  * returned string should not be freed by the caller.
673  */
674 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
675                                       const char **serial_options)
676 {
677         GSList *l;
678         struct sr_config *src;
679
680         *serial_device = NULL;
681
682         for (l = options; l; l = l->next) {
683                 src = l->data;
684                 switch (src->key) {
685                 case SR_CONF_CONN:
686                         *serial_device = g_variant_get_string(src->data, NULL);
687                         sr_dbg("Parsed serial device: %s", *serial_device);
688                         break;
689
690                 case SR_CONF_SERIALCOMM:
691                         *serial_options = g_variant_get_string(src->data, NULL);
692                         sr_dbg("Parsed serial options: %s", *serial_options);
693                         break;
694                 }
695         }
696
697         if (!*serial_device) {
698                 sr_dbg("No serial device specified");
699                 return SR_ERR;
700         }
701
702         return SR_OK;
703 }
704
705 #ifdef _WIN32
706 typedef HANDLE event_handle;
707 #else
708 typedef int event_handle;
709 #endif
710
711 SR_PRIV int serial_source_add(struct sr_session *session,
712                 struct sr_serial_dev_inst *serial, int events, int timeout,
713                 sr_receive_data_callback cb, void *cb_data)
714 {
715         enum sp_event mask = 0;
716         unsigned int i;
717
718         if (sp_new_event_set(&serial->event_set) != SP_OK)
719                 return SR_ERR;
720
721         if (events & G_IO_IN)
722                 mask |= SP_EVENT_RX_READY;
723         if (events & G_IO_OUT)
724                 mask |= SP_EVENT_TX_READY;
725         if (events & G_IO_ERR)
726                 mask |= SP_EVENT_ERROR;
727
728         if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
729                 sp_free_event_set(serial->event_set);
730                 return SR_ERR;
731         }
732
733         serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
734
735         for (i = 0; i < serial->event_set->count; i++) {
736
737                 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
738
739                 mask = serial->event_set->masks[i];
740
741                 if (mask & SP_EVENT_RX_READY)
742                         serial->pollfds[i].events |= G_IO_IN;
743                 if (mask & SP_EVENT_TX_READY)
744                         serial->pollfds[i].events |= G_IO_OUT;
745                 if (mask & SP_EVENT_ERROR)
746                         serial->pollfds[i].events |= G_IO_ERR;
747
748                 if (sr_session_source_add_pollfd(session, &serial->pollfds[i],
749                                         timeout, cb, cb_data) != SR_OK)
750                         return SR_ERR;
751         }
752
753         return SR_OK;
754 }
755
756 SR_PRIV int serial_source_remove(struct sr_session *session,
757                 struct sr_serial_dev_inst *serial)
758 {
759         unsigned int i;
760
761         for (i = 0; i < serial->event_set->count; i++)
762                 if (sr_session_source_remove_pollfd(session, &serial->pollfds[i]) != SR_OK)
763                         return SR_ERR;
764
765         g_free(serial->pollfds);
766         sp_free_event_set(serial->event_set);
767
768         serial->pollfds = NULL;
769         serial->event_set = NULL;
770
771         return SR_OK;
772 }
773
774 /**
775  * Find USB serial devices via the USB vendor ID and product ID.
776  *
777  * @param[in] vendor_id Vendor ID of the USB device.
778  * @param[in] product_id Product ID of the USB device.
779  *
780  * @return A GSList of strings containing the path of the serial device or
781  *         NULL if no serial device is found. The returned list must be freed
782  *         by the caller.
783  */
784 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
785 {
786         GSList *tty_devs = NULL;
787         struct sp_port **ports;
788         int i, vid, pid;
789
790         if (sp_list_ports(&ports) != SP_OK)
791                 return NULL;
792
793         for (i=0; ports[i]; i++)
794                 if (sp_get_port_transport(ports[i]) == SP_TRANSPORT_USB &&
795                     sp_get_port_usb_vid_pid(ports[i], &vid, &pid) == SP_OK &&
796                     vid == vendor_id && pid == product_id)
797                         tty_devs = g_slist_prepend(tty_devs,
798                                                    g_strdup(sp_get_port_name(ports[i])));
799
800         sp_free_port_list(ports);
801         return tty_devs;
802 }