]> sigrok.org Git - libsigrok.git/blob - hardware/common/serial.c
Add blocking and nonblocking versions of serial_read and serial_write.
[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 <libserialport.h>
26 #include "libsigrok.h"
27 #include "libsigrok-internal.h"
28
29 #define LOG_PREFIX "serial"
30
31 /**
32  * Open the specified serial port.
33  *
34  * @param serial Previously initialized serial port structure.
35  * @param flags Flags to use when opening the serial port. Possible flags
36  *              include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
37  *
38  * If the serial structure contains a serialcomm string, it will be
39  * passed to serial_set_paramstr() after the port is opened.
40  *
41  * @return SR_OK on success, SR_ERR on failure.
42  */
43 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
44 {
45         int ret;
46         char *error;
47         int sp_flags = 0;
48
49         if (!serial) {
50                 sr_dbg("Invalid serial port.");
51                 return SR_ERR;
52         }
53
54         sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
55
56         sp_get_port_by_name(serial->port, &serial->data);
57
58         if (flags & SERIAL_RDWR)
59                 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
60         else if (flags & SERIAL_RDONLY)
61                 sp_flags = SP_MODE_READ;
62
63         serial->nonblocking = (flags & SERIAL_NONBLOCK) ? 1 : 0;
64
65         ret = sp_open(serial->data, sp_flags);
66
67         switch (ret) {
68         case SP_ERR_ARG:
69                 sr_err("Attempt to open serial port with invalid parameters.");
70                 return SR_ERR_ARG;
71         case SP_ERR_FAIL:
72                 error = sp_last_error_message();
73                 sr_err("Error opening port (%d): %s.",
74                         sp_last_error_code(), error);
75                 sp_free_error_message(error);
76                 return SR_ERR;
77         }
78
79         if (serial->serialcomm)
80                 return serial_set_paramstr(serial, serial->serialcomm);
81         else
82                 return SR_OK;
83 }
84
85 /**
86  * Close the specified serial port.
87  *
88  * @param serial Previously initialized serial port structure.
89  *
90  * @return SR_OK on success, SR_ERR on failure.
91  */
92 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
93 {
94         int ret;
95         char *error;
96
97         if (!serial) {
98                 sr_dbg("Invalid serial port.");
99                 return SR_ERR;
100         }
101
102         if (!serial->data) {
103                 sr_dbg("Cannot close unopened serial port %s.", serial->port);
104                 return SR_ERR;
105         }
106
107         sr_spew("Closing serial port %s.", serial->port);
108
109         ret = sp_close(serial->data);
110
111         switch (ret) {
112         case SP_ERR_ARG:
113                 sr_err("Attempt to close an invalid serial port.");
114                 return SR_ERR_ARG;
115         case SP_ERR_FAIL:
116                 error = sp_last_error_message();
117                 sr_err("Error closing port (%d): %s.",
118                         sp_last_error_code(), error);
119                 sp_free_error_message(error);
120                 return SR_ERR;
121         }
122
123         sp_free_port(serial->data);
124         serial->data = NULL;
125
126         return SR_OK;
127 }
128
129 /**
130  * Flush serial port buffers.
131  *
132  * @param serial Previously initialized serial port structure.
133  *
134  * @return SR_OK on success, SR_ERR on failure.
135  */
136 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
137 {
138         int ret;
139         char *error;
140
141         if (!serial) {
142                 sr_dbg("Invalid serial port.");
143                 return SR_ERR;
144         }
145
146         if (!serial->data) {
147                 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
148                 return SR_ERR;
149         }
150
151         sr_spew("Flushing serial port %s.", serial->port);
152
153         ret = sp_flush(serial->data, SP_BUF_BOTH);
154
155         switch (ret) {
156         case SP_ERR_ARG:
157                 sr_err("Attempt to flush an invalid serial port.");
158                 return SR_ERR_ARG;
159         case SP_ERR_FAIL:
160                 error = sp_last_error_message();
161                 sr_err("Error flushing port (%d): %s.",
162                         sp_last_error_code(), error);
163                 sp_free_error_message(error);
164                 return SR_ERR;
165         }
166
167         return SR_OK;
168 }
169
170 static int _serial_write(struct sr_serial_dev_inst *serial,
171                 const void *buf, size_t count, int nonblocking)
172 {
173         ssize_t ret;
174         char *error;
175
176         if (!serial) {
177                 sr_dbg("Invalid serial port.");
178                 return SR_ERR;
179         }
180
181         if (!serial->data) {
182                 sr_dbg("Cannot use unopened serial port %s.", serial->port);
183                 return SR_ERR;
184         }
185
186         if (nonblocking)
187                 ret = sp_nonblocking_write(serial->data, buf, count);
188         else
189                 ret = sp_blocking_write(serial->data, buf, count, 0);
190
191         switch (ret) {
192         case SP_ERR_ARG:
193                 sr_err("Attempted serial port write with invalid arguments.");
194                 return SR_ERR_ARG;
195         case SP_ERR_FAIL:
196                 error = sp_last_error_message();
197                 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
198                 sp_free_error_message(error);
199                 return SR_ERR;
200         }
201
202         sr_spew("Wrote %d/%d bytes.", ret, count);
203
204         return ret;
205 }
206
207 /**
208  * Write a number of bytes to the specified serial port.
209  *
210  * @param serial Previously initialized serial port structure.
211  * @param buf Buffer containing the bytes to write.
212  * @param count Number of bytes to write.
213  *
214  * @return The number of bytes written, or a negative error code upon failure.
215  */
216 SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
217                 const void *buf, size_t count)
218 {
219         return _serial_write(serial, buf, count, serial->nonblocking);
220 }
221
222 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
223                 const void *buf, size_t count)
224 {
225         return _serial_write(serial, buf, count, 0);
226 }
227
228 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
229                 const void *buf, size_t count)
230 {
231         return _serial_write(serial, buf, count, 1);
232 }
233
234 static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
235                 size_t count, int nonblocking)
236 {
237         ssize_t ret;
238         char *error;
239
240         if (!serial) {
241                 sr_dbg("Invalid serial port.");
242                 return SR_ERR;
243         }
244
245         if (!serial->data) {
246                 sr_dbg("Cannot use unopened serial port %s.", serial->port);
247                 return SR_ERR;
248         }
249
250         if (nonblocking)
251                 ret = sp_nonblocking_read(serial->data, buf, count);
252         else
253                 ret = sp_blocking_read(serial->data, buf, count, 0);
254
255         switch (ret) {
256         case SP_ERR_ARG:
257                 sr_err("Attempted serial port read with invalid arguments.");
258                 return SR_ERR_ARG;
259         case SP_ERR_FAIL:
260                 error = sp_last_error_message();
261                 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
262                 sp_free_error_message(error);
263                 return SR_ERR;
264         }
265
266         if (ret > 0)
267                 sr_spew("Read %d/%d bytes.", ret, count);
268
269         return ret;
270 }
271
272 /**
273  * Read a number of bytes from the specified serial port.
274  *
275  * @param serial Previously initialized serial port structure.
276  * @param buf Buffer where to store the bytes that are read.
277  * @param count The number of bytes to read.
278  *
279  * @return The number of bytes read, or a negative error code upon failure.
280  */
281 SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
282                 size_t count)
283 {
284         return _serial_read(serial, buf, count, serial->nonblocking);
285 }
286
287 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
288                 size_t count)
289 {
290         return _serial_read(serial, buf, count, 0);
291 }
292
293 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
294                 size_t count)
295 {
296         return _serial_read(serial, buf, count, 1);
297 }
298
299 /**
300  * Set serial parameters for the specified serial port.
301  *
302  * @param serial Previously initialized serial port structure.
303  * @param[in] baudrate The baudrate to set.
304  * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
305  * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
306  * @param[in] stopbits The number of stop bits to use (1 or 2).
307  * @param[in] flowcontrol The flow control settings to use (0 = none,
308  *                      1 = RTS/CTS, 2 = XON/XOFF).
309  * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
310  * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
311  *
312  * @retval SR_OK Success
313  * @retval SR_ERR Failure.
314  */
315 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
316                               int bits, int parity, int stopbits,
317                               int flowcontrol, int rts, int dtr)
318 {
319         int ret;
320         char *error;
321         struct sp_port_config *config;
322
323         if (!serial) {
324                 sr_dbg("Invalid serial port.");
325                 return SR_ERR;
326         }
327
328         if (!serial->data) {
329                 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
330                 return SR_ERR;
331         }
332
333         sr_spew("Setting serial parameters on port %s.", serial->port);
334
335         sp_new_config(&config);
336         sp_set_config_baudrate(config, baudrate);
337         sp_set_config_bits(config, bits);
338         switch (parity) {
339         case 0:
340                 sp_set_config_parity(config, SP_PARITY_NONE);
341                 break;
342         case 1:
343                 sp_set_config_parity(config, SP_PARITY_EVEN);
344                 break;
345         case 2:
346                 sp_set_config_parity(config, SP_PARITY_ODD);
347                 break;
348         default:
349                 return SR_ERR_ARG;
350         }
351         sp_set_config_stopbits(config, stopbits);
352         sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
353         sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
354         sp_set_config_dtr(config, dtr);
355         sp_set_config_dsr(config, SP_DSR_IGNORE);
356         sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
357
358         ret = sp_set_config(serial->data, config);
359         sp_free_config(config);
360
361         switch (ret) {
362         case SP_ERR_ARG:
363                 sr_err("Invalid arguments for setting serial port parameters.");
364                 return SR_ERR_ARG;
365         case SP_ERR_FAIL:
366                 error = sp_last_error_message();
367                 sr_err("Error setting serial port parameters (%d): %s.",
368                         sp_last_error_code(), error);
369                 sp_free_error_message(error);
370                 return SR_ERR;
371         }
372
373         return SR_OK;
374 }
375
376 /**
377  * Set serial parameters for the specified serial port.
378  *
379  * @param serial Previously initialized serial port structure.
380  * @param[in] paramstr A serial communication parameters string, in the form
381  * of \<speed\>/\<data bits\>\<parity\>\<stopbits\>\<flow\>, for example
382  * "9600/8n1" or "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none,
383  * 1 for rts/cts and 2 for xon/xoff.
384  *
385  * @retval SR_OK Success.
386  * @retval SR_ERR Failure.
387  */
388 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
389 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
390                 const char *paramstr)
391 {
392         GRegex *reg;
393         GMatchInfo *match;
394         int speed, databits, parity, stopbits, flow, rts, dtr, i;
395         char *mstr, **opts, **kv;
396
397         speed = databits = parity = stopbits = flow = 0;
398         rts = dtr = -1;
399         sr_spew("Parsing parameters from \"%s\".", paramstr);
400         reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
401         if (g_regex_match(reg, paramstr, 0, &match)) {
402                 if ((mstr = g_match_info_fetch(match, 1)))
403                         speed = strtoul(mstr, NULL, 10);
404                 g_free(mstr);
405                 if ((mstr = g_match_info_fetch(match, 2)))
406                         databits = strtoul(mstr, NULL, 10);
407                 g_free(mstr);
408                 if ((mstr = g_match_info_fetch(match, 3))) {
409                         switch (mstr[0]) {
410                         case 'n':
411                                 parity = SERIAL_PARITY_NONE;
412                                 break;
413                         case 'e':
414                                 parity = SERIAL_PARITY_EVEN;
415                                 break;
416                         case 'o':
417                                 parity = SERIAL_PARITY_ODD;
418                                 break;
419                         }
420                 }
421                 g_free(mstr);
422                 if ((mstr = g_match_info_fetch(match, 4)))
423                         stopbits = strtoul(mstr, NULL, 10);
424                 g_free(mstr);
425                 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
426                         if (mstr[0] != '/') {
427                                 sr_dbg("missing separator before extra options");
428                                 speed = 0;
429                         } else {
430                                 /* A set of "key=value" options separated by / */
431                                 opts = g_strsplit(mstr + 1, "/", 0);
432                                 for (i = 0; opts[i]; i++) {
433                                         kv = g_strsplit(opts[i], "=", 2);
434                                         if (!strncmp(kv[0], "rts", 3)) {
435                                                 if (kv[1][0] == '1')
436                                                         rts = 1;
437                                                 else if (kv[1][0] == '0')
438                                                         rts = 0;
439                                                 else {
440                                                         sr_dbg("invalid value for rts: %c", kv[1][0]);
441                                                         speed = 0;
442                                                 }
443                                         } else if (!strncmp(kv[0], "dtr", 3)) {
444                                                 if (kv[1][0] == '1')
445                                                         dtr = 1;
446                                                 else if (kv[1][0] == '0')
447                                                         dtr = 0;
448                                                 else {
449                                                         sr_dbg("invalid value for dtr: %c", kv[1][0]);
450                                                         speed = 0;
451                                                 }
452                                         } else if (!strncmp(kv[0], "flow", 4)) {
453                                                 if (kv[1][0] == '0')
454                                                         flow = 0;
455                                                 else if (kv[1][0] == '1')
456                                                         flow = 1;
457                                                 else if (kv[1][0] == '2')
458                                                         flow = 2;
459                                                 else {
460                                                         sr_dbg("invalid value for flow: %c", kv[1][0]);
461                                                         speed = 0;
462                                                 }
463                                         }
464                                         g_strfreev(kv);
465                                 }
466                                 g_strfreev(opts);
467                         }
468                 }
469                 g_free(mstr);
470         }
471         g_match_info_unref(match);
472         g_regex_unref(reg);
473
474         if (speed) {
475                 return serial_set_params(serial, speed, databits, parity,
476                                          stopbits, flow, rts, dtr);
477         } else {
478                 sr_dbg("Could not infer speed from parameter string.");
479                 return SR_ERR_ARG;
480         }
481 }
482
483 /**
484  * Read a line from the specified serial port.
485  *
486  * @param serial Previously initialized serial port structure.
487  * @param buf Buffer where to store the bytes that are read.
488  * @param buflen Size of the buffer.
489  * @param[in] timeout_ms How long to wait for a line to come in.
490  *
491  * Reading stops when CR of LR is found, which is stripped from the buffer.
492  *
493  * @retval SR_OK Success.
494  * @retval SR_ERR Failure.
495  */
496 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
497                 int *buflen, gint64 timeout_ms)
498 {
499         gint64 start;
500         int maxlen, len;
501
502         if (!serial) {
503                 sr_dbg("Invalid serial port.");
504                 return SR_ERR;
505         }
506
507         if (!serial->data) {
508                 sr_dbg("Cannot use unopened serial port %s.", serial->port);
509                 return -1;
510         }
511
512         timeout_ms *= 1000;
513         start = g_get_monotonic_time();
514
515         maxlen = *buflen;
516         *buflen = len = 0;
517         while(1) {
518                 len = maxlen - *buflen - 1;
519                 if (len < 1)
520                         break;
521                 len = serial_read(serial, *buf + *buflen, 1);
522                 if (len > 0) {
523                         *buflen += len;
524                         *(*buf + *buflen) = '\0';
525                         if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
526                                         || *(*buf + *buflen - 1) == '\n')) {
527                                 /* Strip CR/LF and terminate. */
528                                 *(*buf + --*buflen) = '\0';
529                                 break;
530                         }
531                 }
532                 if (g_get_monotonic_time() - start > timeout_ms)
533                         /* Timeout */
534                         break;
535                 if (len < 1)
536                         g_usleep(2000);
537         }
538         if (*buflen)
539                 sr_dbg("Received %d: '%s'.", *buflen, *buf);
540
541         return SR_OK;
542 }
543
544 /**
545  * Try to find a valid packet in a serial data stream.
546  *
547  * @param serial Previously initialized serial port structure.
548  * @param buf Buffer containing the bytes to write.
549  * @param buflen Size of the buffer.
550  * @param[in] packet_size Size, in bytes, of a valid packet.
551  * @param is_valid Callback that assesses whether the packet is valid or not.
552  * @param[in] timeout_ms The timeout after which, if no packet is detected, to
553  *                   abort scanning.
554  * @param[in] baudrate The baudrate of the serial port. This parameter is not
555  *                 critical, but it helps fine tune the serial port polling
556  *                 delay.
557  *
558  * @retval SR_OK Valid packet was found within the given timeout
559  * @retval SR_ERR Failure.
560  */
561 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
562                                  uint8_t *buf, size_t *buflen,
563                                  size_t packet_size, packet_valid_t is_valid,
564                                  uint64_t timeout_ms, int baudrate)
565 {
566         uint64_t start, time, byte_delay_us;
567         size_t ibuf, i, maxlen;
568         int len;
569
570         maxlen = *buflen;
571
572         sr_dbg("Detecting packets on %s (timeout = %" PRIu64
573                "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
574
575         if (maxlen < (packet_size / 2) ) {
576                 sr_err("Buffer size must be at least twice the packet size.");
577                 return SR_ERR;
578         }
579
580         /* Assume 8n1 transmission. That is 10 bits for every byte. */
581         byte_delay_us = 10 * (1000000 / baudrate);
582         start = g_get_monotonic_time();
583
584         i = ibuf = len = 0;
585         while (ibuf < maxlen) {
586                 len = serial_read(serial, &buf[ibuf], 1);
587                 if (len > 0) {
588                         ibuf += len;
589                 } else if (len == 0) {
590                         /* No logging, already done in serial_read(). */
591                 } else {
592                         /* Error reading byte, but continuing anyway. */
593                 }
594
595                 time = g_get_monotonic_time() - start;
596                 time /= 1000;
597
598                 if ((ibuf - i) >= packet_size) {
599                         /* We have at least a packet's worth of data. */
600                         if (is_valid(&buf[i])) {
601                                 sr_spew("Found valid %d-byte packet after "
602                                         "%" PRIu64 "ms.", (ibuf - i), time);
603                                 *buflen = ibuf;
604                                 return SR_OK;
605                         } else {
606                                 sr_spew("Got %d bytes, but not a valid "
607                                         "packet.", (ibuf - i));
608                         }
609                         /* Not a valid packet. Continue searching. */
610                         i++;
611                 }
612                 if (time >= timeout_ms) {
613                         /* Timeout */
614                         sr_dbg("Detection timed out after %dms.", time);
615                         break;
616                 }
617                 if (len < 1)
618                         g_usleep(byte_delay_us);
619         }
620
621         *buflen = ibuf;
622
623         sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
624
625         return SR_ERR;
626 }
627
628 /**
629  * Extract the serial device and options from the options linked list.
630  *
631  * @param options List of options passed from the command line.
632  * @param serial_device Pointer where to store the exctracted serial device.
633  * @param serial_options Pointer where to store the optional extracted serial
634  * options.
635  *
636  * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
637  * returned string should not be freed by the caller.
638  */
639 SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
640                                       const char **serial_options)
641 {
642         GSList *l;
643         struct sr_config *src;
644
645         *serial_device = NULL;
646
647         for (l = options; l; l = l->next) {
648                 src = l->data;
649                 switch (src->key) {
650                 case SR_CONF_CONN:
651                         *serial_device = g_variant_get_string(src->data, NULL);
652                         sr_dbg("Parsed serial device: %s", *serial_device);
653                         break;
654
655                 case SR_CONF_SERIALCOMM:
656                         *serial_options = g_variant_get_string(src->data, NULL);
657                         sr_dbg("Parsed serial options: %s", *serial_options);
658                         break;
659                 }
660         }
661
662         if (!*serial_device) {
663                 sr_dbg("No serial device specified");
664                 return SR_ERR;
665         }
666
667         return SR_OK;
668 }
669
670 #ifdef _WIN32
671 typedef HANDLE event_handle;
672 #else
673 typedef int event_handle;
674 #endif
675
676 SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
677                 int timeout, sr_receive_data_callback_t cb, void *cb_data)
678 {
679         enum sp_event mask = 0;
680         unsigned int i;
681
682         if (sp_new_event_set(&serial->event_set) != SP_OK)
683                 return SR_ERR;
684
685         if (events & G_IO_IN)
686                 mask |= SP_EVENT_RX_READY;
687         if (events & G_IO_OUT)
688                 mask |= SP_EVENT_TX_READY;
689         if (events & G_IO_ERR)
690                 mask |= SP_EVENT_ERROR;
691
692         if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
693                 sp_free_event_set(serial->event_set);
694                 return SR_ERR;
695         }
696
697         serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
698
699         for (i = 0; i < serial->event_set->count; i++) {
700
701                 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
702
703                 mask = serial->event_set->masks[i];
704
705                 if (mask & SP_EVENT_RX_READY)
706                         serial->pollfds[i].events |= G_IO_IN;
707                 if (mask & SP_EVENT_TX_READY)
708                         serial->pollfds[i].events |= G_IO_OUT;
709                 if (mask & SP_EVENT_ERROR)
710                         serial->pollfds[i].events |= G_IO_ERR;
711
712                 if (sr_session_source_add_pollfd(&serial->pollfds[i],
713                                 timeout, cb, cb_data) != SR_OK)
714                         return SR_ERR;
715         }
716
717         return SR_OK;
718 }
719
720 SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
721 {
722         unsigned int i;
723
724         for (i = 0; i < serial->event_set->count; i++)
725                 if (sr_session_source_remove_pollfd(&serial->pollfds[i]) != SR_OK)
726                         return SR_ERR;
727
728         g_free(serial->pollfds);
729         sp_free_event_set(serial->event_set);
730
731         serial->pollfds = NULL;
732         serial->event_set = NULL;
733
734         return SR_OK;
735 }