]> sigrok.org Git - libsigrok.git/blame - hardware/common/serial.c
build: Portability fixes.
[libsigrok.git] / hardware / common / serial.c
CommitLineData
a1bb33af 1/*
50985c20 2 * This file is part of the libsigrok project.
a1bb33af 3 *
c73d2ea4 4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
b19f4622 5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
766456be 6 * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
a1bb33af
UH
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
54b38f64 22#include <string.h>
d02a535e 23#include <stdlib.h>
a1bb33af 24#include <glib.h>
b541f837 25#include <glib/gstdio.h>
0d4405ce 26#include <libserialport.h>
45c59c8b
BV
27#include "libsigrok.h"
28#include "libsigrok-internal.h"
a1bb33af 29
3544f848 30#define LOG_PREFIX "serial"
b19f4622 31
b19f4622
UH
32/**
33 * Open the specified serial port.
34 *
299bdb24 35 * @param serial Previously initialized serial port structure.
a9cf2035 36 * @param[in] flags Flags to use when opening the serial port. Possible flags
a54dd31e 37 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
b19f4622 38 *
299bdb24
BV
39 * If the serial structure contains a serialcomm string, it will be
40 * passed to serial_set_paramstr() after the port is opened.
41 *
d0a92abd
MH
42 * @retval SR_OK Success.
43 * @retval SR_ERR Failure.
b19f4622 44 */
299bdb24 45SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
d02a535e 46{
a9bce5a5
ML
47 int ret;
48 char *error;
13cd8197 49 int sp_flags = 0;
b19f4622 50
299bdb24
BV
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);
b19f4622 57
c9bc57b6
ML
58 sp_get_port_by_name(serial->port, &serial->data);
59
13cd8197
ML
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;
9647ce69
ML
64
65 serial->nonblocking = (flags & SERIAL_NONBLOCK) ? 1 : 0;
13cd8197
ML
66
67 ret = sp_open(serial->data, sp_flags);
a9bce5a5 68
a0dfaa6c
UH
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();
cb7b165b
UH
75 sr_err("Error opening port (%d): %s.",
76 sp_last_error_code(), error);
a0dfaa6c
UH
77 sp_free_error_message(error);
78 return SR_ERR;
a54dd31e
UH
79 }
80
299bdb24
BV
81 if (serial->serialcomm)
82 return serial_set_paramstr(serial, serial->serialcomm);
83 else
84 return SR_OK;
d02a535e
BV
85}
86
b19f4622
UH
87/**
88 * Close the specified serial port.
89 *
299bdb24 90 * @param serial Previously initialized serial port structure.
b19f4622 91 *
d0a92abd
MH
92 * @retval SR_OK Success.
93 * @retval SR_ERR Failure.
2119ab03 94 */
299bdb24 95SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
d02a535e 96{
299bdb24 97 int ret;
a9bce5a5 98 char *error;
299bdb24
BV
99
100 if (!serial) {
101 sr_dbg("Invalid serial port.");
102 return SR_ERR;
103 }
104
64ecf7ee
ML
105 if (!serial->data) {
106 sr_dbg("Cannot close unopened serial port %s.", serial->port);
299bdb24
BV
107 return SR_ERR;
108 }
109
64ecf7ee 110 sr_spew("Closing serial port %s.", serial->port);
b19f4622 111
c9bc57b6 112 ret = sp_close(serial->data);
a9bce5a5 113
a0dfaa6c
UH
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();
cb7b165b
UH
120 sr_err("Error closing port (%d): %s.",
121 sp_last_error_code(), error);
a0dfaa6c
UH
122 sp_free_error_message(error);
123 return SR_ERR;
b19f4622 124 }
299bdb24 125
64ecf7ee
ML
126 sp_free_port(serial->data);
127 serial->data = NULL;
128
6a76efeb 129 return SR_OK;
d02a535e
BV
130}
131
b19f4622 132/**
299bdb24 133 * Flush serial port buffers.
b19f4622 134 *
299bdb24 135 * @param serial Previously initialized serial port structure.
b19f4622 136 *
d0a92abd
MH
137 * @retval SR_OK Success.
138 * @retval SR_ERR Failure.
1fdb75e1 139 */
299bdb24 140SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
06d64eb8 141{
299bdb24 142 int ret;
a9bce5a5 143 char *error;
299bdb24
BV
144
145 if (!serial) {
146 sr_dbg("Invalid serial port.");
147 return SR_ERR;
148 }
149
64ecf7ee
ML
150 if (!serial->data) {
151 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
299bdb24
BV
152 return SR_ERR;
153 }
154
64ecf7ee 155 sr_spew("Flushing serial port %s.", serial->port);
b19f4622 156
13cd8197 157 ret = sp_flush(serial->data, SP_BUF_BOTH);
a9bce5a5 158
a0dfaa6c
UH
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();
cb7b165b
UH
165 sr_err("Error flushing port (%d): %s.",
166 sp_last_error_code(), error);
a0dfaa6c
UH
167 sp_free_error_message(error);
168 return SR_ERR;
299bdb24 169 }
b19f4622 170
6a76efeb 171 return SR_OK;
06d64eb8
BV
172}
173
9a474211
ML
174static int _serial_write(struct sr_serial_dev_inst *serial,
175 const void *buf, size_t count, int nonblocking)
2119ab03 176{
299bdb24 177 ssize_t ret;
a9bce5a5 178 char *error;
299bdb24
BV
179
180 if (!serial) {
181 sr_dbg("Invalid serial port.");
6a76efeb 182 return SR_ERR;
299bdb24
BV
183 }
184
64ecf7ee
ML
185 if (!serial->data) {
186 sr_dbg("Cannot use unopened serial port %s.", serial->port);
6a76efeb 187 return SR_ERR;
299bdb24
BV
188 }
189
9a474211 190 if (nonblocking)
9647ce69
ML
191 ret = sp_nonblocking_write(serial->data, buf, count);
192 else
193 ret = sp_blocking_write(serial->data, buf, count, 0);
a9bce5a5 194
a0dfaa6c
UH
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();
cb7b165b 201 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
a0dfaa6c
UH
202 sp_free_error_message(error);
203 return SR_ERR;
a9bce5a5
ML
204 }
205
64ecf7ee 206 sr_spew("Wrote %d/%d bytes.", ret, count);
b19f4622
UH
207
208 return ret;
2119ab03
UH
209}
210
b19f4622 211/**
9a474211 212 * Write a number of bytes to the specified serial port.
b19f4622 213 *
299bdb24 214 * @param serial Previously initialized serial port structure.
a9cf2035
MH
215 * @param[in] buf Buffer containing the bytes to write.
216 * @param[in] count Number of bytes to write.
b19f4622 217 *
a9cf2035
MH
218 * @retval SR_ERR_ARG Invalid argument.
219 * @retval SR_ERR Other error.
220 * @retval other The number of bytes written.
2119ab03 221 */
9a474211
ML
222SR_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
a9cf2035
MH
228/**
229 * Write a number of bytes to the specified serial port, blocking until finished.
230 * @copydetails serial_write()
231 */
9a474211
ML
232SR_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
a9cf2035
MH
238/**
239 * Write a number of bytes to the specified serial port, return immediately.
240 * @copydetails serial_write()
241*/
9a474211
ML
242SR_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
248static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
249 size_t count, int nonblocking)
2119ab03 250{
299bdb24 251 ssize_t ret;
c4d85a40 252 char *error;
299bdb24
BV
253
254 if (!serial) {
255 sr_dbg("Invalid serial port.");
6a76efeb 256 return SR_ERR;
299bdb24
BV
257 }
258
64ecf7ee
ML
259 if (!serial->data) {
260 sr_dbg("Cannot use unopened serial port %s.", serial->port);
6a76efeb 261 return SR_ERR;
299bdb24
BV
262 }
263
9a474211 264 if (nonblocking)
9647ce69
ML
265 ret = sp_nonblocking_read(serial->data, buf, count);
266 else
267 ret = sp_blocking_read(serial->data, buf, count, 0);
2119ab03 268
a0dfaa6c
UH
269 switch (ret) {
270 case SP_ERR_ARG:
271 sr_err("Attempted serial port read with invalid arguments.");
272 return SR_ERR_ARG;
c4d85a40
UH
273 case SP_ERR_FAIL:
274 error = sp_last_error_message();
cb7b165b 275 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
c4d85a40
UH
276 sp_free_error_message(error);
277 return SR_ERR;
a9bce5a5
ML
278 }
279
c4d85a40 280 if (ret > 0)
64ecf7ee 281 sr_spew("Read %d/%d bytes.", ret, count);
b19f4622
UH
282
283 return ret;
2119ab03
UH
284}
285
9a474211
ML
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.
a9cf2035 291 * @param[in] count The number of bytes to read.
9a474211 292 *
a9cf2035
MH
293 * @retval SR_ERR_ARG Invalid argument.
294 * @retval SR_ERR Other error.
295 * @retval other The number of bytes read.
9a474211
ML
296 */
297SR_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
a9cf2035
MH
303/**
304 * Read a number of bytes from the specified serial port, block until finished.
305 * @copydetails serial_read()
306 */
9a474211
ML
307SR_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
a9cf2035
MH
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 */
9a474211
ML
318SR_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
b19f4622
UH
324/**
325 * Set serial parameters for the specified serial port.
326 *
299bdb24 327 * @param serial Previously initialized serial port structure.
04cb9157
MH
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).
2119ab03 336 *
d0a92abd 337 * @retval SR_OK Success.
04cb9157 338 * @retval SR_ERR Failure.
1ff7712c 339 */
299bdb24 340SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
39e5d798
UH
341 int bits, int parity, int stopbits,
342 int flowcontrol, int rts, int dtr)
d02a535e 343{
a9bce5a5
ML
344 int ret;
345 char *error;
25b66c3c 346 struct sp_port_config *config;
a9bce5a5 347
299bdb24
BV
348 if (!serial) {
349 sr_dbg("Invalid serial port.");
350 return SR_ERR;
351 }
352
64ecf7ee
ML
353 if (!serial->data) {
354 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
299bdb24
BV
355 return SR_ERR;
356 }
357
64ecf7ee 358 sr_spew("Setting serial parameters on port %s.", serial->port);
b19f4622 359
25b66c3c
ML
360 sp_new_config(&config);
361 sp_set_config_baudrate(config, baudrate);
362 sp_set_config_bits(config, bits);
13cd8197
ML
363 switch (parity) {
364 case 0:
25b66c3c 365 sp_set_config_parity(config, SP_PARITY_NONE);
13cd8197
ML
366 break;
367 case 1:
25b66c3c 368 sp_set_config_parity(config, SP_PARITY_EVEN);
13cd8197
ML
369 break;
370 case 2:
25b66c3c 371 sp_set_config_parity(config, SP_PARITY_ODD);
13cd8197
ML
372 break;
373 default:
374 return SR_ERR_ARG;
375 }
25b66c3c
ML
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);
a9bce5a5 385
a0dfaa6c
UH
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();
cb7b165b
UH
392 sr_err("Error setting serial port parameters (%d): %s.",
393 sp_last_error_code(), error);
a0dfaa6c
UH
394 sp_free_error_message(error);
395 return SR_ERR;
700dcd5c
UH
396 }
397
e46b8fb1 398 return SR_OK;
d02a535e 399}
792fc686 400
299bdb24 401/**
48d3238e 402 * Set serial parameters for the specified serial port from parameter string.
299bdb24
BV
403 *
404 * @param serial Previously initialized serial port structure.
48d3238e
MH
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.
04cb9157
MH
418 * @retval SR_OK Success.
419 * @retval SR_ERR Failure.
299bdb24 420 */
299bdb24
BV
421SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
422 const char *paramstr)
792fc686 423{
48d3238e
MH
424#define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
425
792fc686
BV
426 GRegex *reg;
427 GMatchInfo *match;
26ddb5ba 428 int speed, databits, parity, stopbits, flow, rts, dtr, i;
71caaad4 429 char *mstr, **opts, **kv;
792fc686 430
26ddb5ba 431 speed = databits = parity = stopbits = flow = 0;
71caaad4 432 rts = dtr = -1;
ea088bb6 433 sr_spew("Parsing parameters from \"%s\".", paramstr);
792fc686
BV
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);
71caaad4
BV
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 }
26ddb5ba 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 }
71caaad4
BV
497 }
498 g_strfreev(kv);
499 }
500 g_strfreev(opts);
501 }
502 }
503 g_free(mstr);
792fc686
BV
504 }
505 g_match_info_unref(match);
506 g_regex_unref(reg);
507
ea088bb6
AG
508 if (speed) {
509 return serial_set_params(serial, speed, databits, parity,
26ddb5ba 510 stopbits, flow, rts, dtr);
ea088bb6
AG
511 } else {
512 sr_dbg("Could not infer speed from parameter string.");
792fc686 513 return SR_ERR_ARG;
ea088bb6 514 }
792fc686
BV
515}
516
299bdb24
BV
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.
04cb9157 523 * @param[in] timeout_ms How long to wait for a line to come in.
299bdb24
BV
524 *
525 * Reading stops when CR of LR is found, which is stripped from the buffer.
526 *
04cb9157
MH
527 * @retval SR_OK Success.
528 * @retval SR_ERR Failure.
299bdb24
BV
529 */
530SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
531 int *buflen, gint64 timeout_ms)
6f22a8ef 532{
b87f8504 533 gint64 start;
6f22a8ef
UH
534 int maxlen, len;
535
64ecf7ee 536 if (!serial) {
299bdb24
BV
537 sr_dbg("Invalid serial port.");
538 return SR_ERR;
539 }
540
64ecf7ee
ML
541 if (!serial->data) {
542 sr_dbg("Cannot use unopened serial port %s.", serial->port);
299bdb24
BV
543 return -1;
544 }
545
6f22a8ef
UH
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;
299bdb24 555 len = serial_read(serial, *buf + *buflen, 1);
6f22a8ef
UH
556 if (len > 0) {
557 *buflen += len;
558 *(*buf + *buflen) = '\0';
318dd53c
BV
559 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
560 || *(*buf + *buflen - 1) == '\n')) {
561 /* Strip CR/LF and terminate. */
6f22a8ef
UH
562 *(*buf + --*buflen) = '\0';
563 break;
564 }
565 }
566 if (g_get_monotonic_time() - start > timeout_ms)
567 /* Timeout */
568 break;
5715e84f
DT
569 if (len < 1)
570 g_usleep(2000);
6f22a8ef 571 }
318dd53c
BV
572 if (*buflen)
573 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
574
575 return SR_OK;
576}
766456be
UH
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.
04cb9157
MH
583 * @param buflen Size of the buffer.
584 * @param[in] packet_size Size, in bytes, of a valid packet.
766456be 585 * @param is_valid Callback that assesses whether the packet is valid or not.
04cb9157 586 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
766456be 587 * abort scanning.
04cb9157 588 * @param[in] baudrate The baudrate of the serial port. This parameter is not
766456be
UH
589 * critical, but it helps fine tune the serial port polling
590 * delay.
591 *
d0a92abd 592 * @retval SR_OK Valid packet was found within the given timeout.
04cb9157 593 * @retval SR_ERR Failure.
766456be
UH
594 */
595SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
596 uint8_t *buf, size_t *buflen,
144f6660
UH
597 size_t packet_size,
598 packet_valid_callback is_valid,
766456be
UH
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
64ecf7ee
ML
607 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
608 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
766456be
UH
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
766456be
UH
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) {
006dbe55 625 /* No logging, already done in serial_read(). */
766456be
UH
626 } else {
627 /* Error reading byte, but continuing anyway. */
628 }
551c3d8c
AG
629
630 time = g_get_monotonic_time() - start;
631 time /= 1000;
632
766456be
UH
633 if ((ibuf - i) >= packet_size) {
634 /* We have at least a packet's worth of data. */
635 if (is_valid(&buf[i])) {
766456be
UH
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 }
551c3d8c 647 if (time >= timeout_ms) {
766456be 648 /* Timeout */
551c3d8c 649 sr_dbg("Detection timed out after %dms.", time);
766456be
UH
650 break;
651 }
5715e84f
DT
652 if (len < 1)
653 g_usleep(byte_delay_us);
766456be
UH
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}
1bd9e678
DJ
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 */
674SR_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}
abc4b335 704
a0a4c0fb 705#ifdef _WIN32
ba1949f5 706typedef HANDLE event_handle;
a0a4c0fb 707#else
ba1949f5 708typedef int event_handle;
a0a4c0fb 709#endif
ba1949f5 710
102f1239
BV
711SR_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)
ba1949f5
ML
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
102f1239
BV
748 if (sr_session_source_add_pollfd(session, &serial->pollfds[i],
749 timeout, cb, cb_data) != SR_OK)
ba1949f5
ML
750 return SR_ERR;
751 }
752
753 return SR_OK;
abc4b335 754}
7faa3e88 755
102f1239
BV
756SR_PRIV int serial_source_remove(struct sr_session *session,
757 struct sr_serial_dev_inst *serial)
7faa3e88 758{
ba1949f5
ML
759 unsigned int i;
760
761 for (i = 0; i < serial->event_set->count; i++)
102f1239 762 if (sr_session_source_remove_pollfd(session, &serial->pollfds[i]) != SR_OK)
ba1949f5
ML
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;
7faa3e88 772}
b541f837
AJ
773
774/**
775 * Find USB serial devices via the USB vendor ID and product ID.
776 *
d0a92abd
MH
777 * @param[in] vendor_id Vendor ID of the USB device.
778 * @param[in] product_id Product ID of the USB device.
b541f837
AJ
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 */
784SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
785{
786#ifdef __linux__
787 const gchar *usb_dev;
788 const char device_tree[] = "/sys/bus/usb/devices/";
789 GDir *devices_dir, *device_dir;
790 GSList *l = NULL;
791 GSList *tty_devs;
792 GSList *matched_paths;
793 FILE *fd;
794 char tmp[5];
795 gchar *vendor_path, *product_path, *path_copy;
796 gchar *prefix, *subdir_path, *device_path, *tty_path;
797 unsigned long read_vendor_id, read_product_id;
798 const char *file;
799
800 l = NULL;
801 tty_devs = NULL;
802 matched_paths = NULL;
803
804 if (!(devices_dir = g_dir_open(device_tree, 0, NULL)))
805 return NULL;
806
807 /*
808 * Find potential candidates using the vendor ID and product ID
809 * and store them in matched_paths.
810 */
811 while ((usb_dev = g_dir_read_name(devices_dir))) {
812 vendor_path = g_strconcat(device_tree,
813 usb_dev, "/idVendor", NULL);
814 product_path = g_strconcat(device_tree,
815 usb_dev, "/idProduct", NULL);
816
817 if (!g_file_test(vendor_path, G_FILE_TEST_EXISTS) ||
818 !g_file_test(product_path, G_FILE_TEST_EXISTS))
819 goto skip_device;
820
821 if ((fd = g_fopen(vendor_path, "r")) == NULL)
822 goto skip_device;
823
824 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
825 fclose(fd);
826 goto skip_device;
827 }
828 read_vendor_id = strtoul(tmp, NULL, 16);
829
830 fclose(fd);
831
832 if ((fd = g_fopen(product_path, "r")) == NULL)
833 goto skip_device;
834
835 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
836 fclose(fd);
837 goto skip_device;
838 }
839 read_product_id = strtoul(tmp, NULL, 16);
840
841 fclose(fd);
842
843 if (vendor_id == read_vendor_id &&
844 product_id == read_product_id) {
845 path_copy = g_strdup(usb_dev);
846 matched_paths = g_slist_prepend(matched_paths,
847 path_copy);
848 }
849
850skip_device:
851 g_free(vendor_path);
852 g_free(product_path);
853 }
854 g_dir_close(devices_dir);
855
856 /* For every matched device try to find a ttyUSBX subfolder. */
857 for (l = matched_paths; l; l = l->next) {
858 subdir_path = NULL;
859
860 device_path = g_strconcat(device_tree, l->data, NULL);
861
862 if (!(device_dir = g_dir_open(device_path, 0, NULL))) {
863 g_free(device_path);
864 continue;
865 }
866
867 prefix = g_strconcat(l->data, ":", NULL);
868
869 while ((file = g_dir_read_name(device_dir))) {
870 if (g_str_has_prefix(file, prefix)) {
871 subdir_path = g_strconcat(device_path,
872 "/", file, NULL);
873 break;
874 }
875 }
876 g_dir_close(device_dir);
877
878 g_free(prefix);
879 g_free(device_path);
880
881 if (subdir_path) {
882 if (!(device_dir = g_dir_open(subdir_path, 0, NULL))) {
883 g_free(subdir_path);
884 continue;
885 }
886 g_free(subdir_path);
887
888 while ((file = g_dir_read_name(device_dir))) {
889 if (g_str_has_prefix(file, "ttyUSB")) {
890 tty_path = g_strconcat("/dev/",
891 file, NULL);
892 sr_dbg("Found USB device %04x:%04x attached to %s.",
893 vendor_id, product_id, tty_path);
894 tty_devs = g_slist_prepend(tty_devs,
895 tty_path);
896 break;
897 }
898 }
899 g_dir_close(device_dir);
900 }
901 }
902 g_slist_free_full(matched_paths, g_free);
903
904 return tty_devs;
905#else
906 (void)vendor_id;
907 (void)product_id;
908
909 return NULL;
910#endif
911}