]> sigrok.org Git - libsigrok.git/blame - hardware/common/serial.c
strutil: Now using base 10 in sr_atol(), sr_atoi() for compatibility to atoi(), atol...
[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.
a54dd31e
UH
36 * @param flags Flags to use when opening the serial port. Possible flags
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 *
42 * @return SR_OK on success, SR_ERR on failure.
b19f4622 43 */
299bdb24 44SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
d02a535e 45{
a9bce5a5
ML
46 int ret;
47 char *error;
13cd8197 48 int sp_flags = 0;
b19f4622 49
299bdb24
BV
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);
b19f4622 56
c9bc57b6
ML
57 sp_get_port_by_name(serial->port, &serial->data);
58
13cd8197
ML
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;
9647ce69
ML
63
64 serial->nonblocking = (flags & SERIAL_NONBLOCK) ? 1 : 0;
13cd8197
ML
65
66 ret = sp_open(serial->data, sp_flags);
a9bce5a5 67
a0dfaa6c
UH
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();
cb7b165b
UH
74 sr_err("Error opening port (%d): %s.",
75 sp_last_error_code(), error);
a0dfaa6c
UH
76 sp_free_error_message(error);
77 return SR_ERR;
a54dd31e
UH
78 }
79
299bdb24
BV
80 if (serial->serialcomm)
81 return serial_set_paramstr(serial, serial->serialcomm);
82 else
83 return SR_OK;
d02a535e
BV
84}
85
b19f4622
UH
86/**
87 * Close the specified serial port.
88 *
299bdb24 89 * @param serial Previously initialized serial port structure.
b19f4622 90 *
299bdb24 91 * @return SR_OK on success, SR_ERR on failure.
2119ab03 92 */
299bdb24 93SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
d02a535e 94{
299bdb24 95 int ret;
a9bce5a5 96 char *error;
299bdb24
BV
97
98 if (!serial) {
99 sr_dbg("Invalid serial port.");
100 return SR_ERR;
101 }
102
64ecf7ee
ML
103 if (!serial->data) {
104 sr_dbg("Cannot close unopened serial port %s.", serial->port);
299bdb24
BV
105 return SR_ERR;
106 }
107
64ecf7ee 108 sr_spew("Closing serial port %s.", serial->port);
b19f4622 109
c9bc57b6 110 ret = sp_close(serial->data);
a9bce5a5 111
a0dfaa6c
UH
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();
cb7b165b
UH
118 sr_err("Error closing port (%d): %s.",
119 sp_last_error_code(), error);
a0dfaa6c
UH
120 sp_free_error_message(error);
121 return SR_ERR;
b19f4622 122 }
299bdb24 123
64ecf7ee
ML
124 sp_free_port(serial->data);
125 serial->data = NULL;
126
6a76efeb 127 return SR_OK;
d02a535e
BV
128}
129
b19f4622 130/**
299bdb24 131 * Flush serial port buffers.
b19f4622 132 *
299bdb24 133 * @param serial Previously initialized serial port structure.
b19f4622 134 *
299bdb24 135 * @return SR_OK on success, SR_ERR on failure.
1fdb75e1 136 */
299bdb24 137SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
06d64eb8 138{
299bdb24 139 int ret;
a9bce5a5 140 char *error;
299bdb24
BV
141
142 if (!serial) {
143 sr_dbg("Invalid serial port.");
144 return SR_ERR;
145 }
146
64ecf7ee
ML
147 if (!serial->data) {
148 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
299bdb24
BV
149 return SR_ERR;
150 }
151
64ecf7ee 152 sr_spew("Flushing serial port %s.", serial->port);
b19f4622 153
13cd8197 154 ret = sp_flush(serial->data, SP_BUF_BOTH);
a9bce5a5 155
a0dfaa6c
UH
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();
cb7b165b
UH
162 sr_err("Error flushing port (%d): %s.",
163 sp_last_error_code(), error);
a0dfaa6c
UH
164 sp_free_error_message(error);
165 return SR_ERR;
299bdb24 166 }
b19f4622 167
6a76efeb 168 return SR_OK;
06d64eb8
BV
169}
170
9a474211
ML
171static int _serial_write(struct sr_serial_dev_inst *serial,
172 const void *buf, size_t count, int nonblocking)
2119ab03 173{
299bdb24 174 ssize_t ret;
a9bce5a5 175 char *error;
299bdb24
BV
176
177 if (!serial) {
178 sr_dbg("Invalid serial port.");
6a76efeb 179 return SR_ERR;
299bdb24
BV
180 }
181
64ecf7ee
ML
182 if (!serial->data) {
183 sr_dbg("Cannot use unopened serial port %s.", serial->port);
6a76efeb 184 return SR_ERR;
299bdb24
BV
185 }
186
9a474211 187 if (nonblocking)
9647ce69
ML
188 ret = sp_nonblocking_write(serial->data, buf, count);
189 else
190 ret = sp_blocking_write(serial->data, buf, count, 0);
a9bce5a5 191
a0dfaa6c
UH
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();
cb7b165b 198 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
a0dfaa6c
UH
199 sp_free_error_message(error);
200 return SR_ERR;
a9bce5a5
ML
201 }
202
64ecf7ee 203 sr_spew("Wrote %d/%d bytes.", ret, count);
b19f4622
UH
204
205 return ret;
2119ab03
UH
206}
207
b19f4622 208/**
9a474211 209 * Write a number of bytes to the specified serial port.
b19f4622 210 *
299bdb24 211 * @param serial Previously initialized serial port structure.
9a474211
ML
212 * @param buf Buffer containing the bytes to write.
213 * @param count Number of bytes to write.
b19f4622 214 *
9a474211 215 * @return The number of bytes written, or a negative error code upon failure.
2119ab03 216 */
9a474211
ML
217SR_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
223SR_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
229SR_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
235static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
236 size_t count, int nonblocking)
2119ab03 237{
299bdb24 238 ssize_t ret;
c4d85a40 239 char *error;
299bdb24
BV
240
241 if (!serial) {
242 sr_dbg("Invalid serial port.");
6a76efeb 243 return SR_ERR;
299bdb24
BV
244 }
245
64ecf7ee
ML
246 if (!serial->data) {
247 sr_dbg("Cannot use unopened serial port %s.", serial->port);
6a76efeb 248 return SR_ERR;
299bdb24
BV
249 }
250
9a474211 251 if (nonblocking)
9647ce69
ML
252 ret = sp_nonblocking_read(serial->data, buf, count);
253 else
254 ret = sp_blocking_read(serial->data, buf, count, 0);
2119ab03 255
a0dfaa6c
UH
256 switch (ret) {
257 case SP_ERR_ARG:
258 sr_err("Attempted serial port read with invalid arguments.");
259 return SR_ERR_ARG;
c4d85a40
UH
260 case SP_ERR_FAIL:
261 error = sp_last_error_message();
cb7b165b 262 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
c4d85a40
UH
263 sp_free_error_message(error);
264 return SR_ERR;
a9bce5a5
ML
265 }
266
c4d85a40 267 if (ret > 0)
64ecf7ee 268 sr_spew("Read %d/%d bytes.", ret, count);
b19f4622
UH
269
270 return ret;
2119ab03
UH
271}
272
9a474211
ML
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 */
282SR_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
288SR_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
294SR_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
b19f4622
UH
300/**
301 * Set serial parameters for the specified serial port.
302 *
299bdb24 303 * @param serial Previously initialized serial port structure.
04cb9157
MH
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).
2119ab03 312 *
04cb9157
MH
313 * @retval SR_OK Success
314 * @retval SR_ERR Failure.
1ff7712c 315 */
299bdb24 316SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
39e5d798
UH
317 int bits, int parity, int stopbits,
318 int flowcontrol, int rts, int dtr)
d02a535e 319{
a9bce5a5
ML
320 int ret;
321 char *error;
25b66c3c 322 struct sp_port_config *config;
a9bce5a5 323
299bdb24
BV
324 if (!serial) {
325 sr_dbg("Invalid serial port.");
326 return SR_ERR;
327 }
328
64ecf7ee
ML
329 if (!serial->data) {
330 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
299bdb24
BV
331 return SR_ERR;
332 }
333
64ecf7ee 334 sr_spew("Setting serial parameters on port %s.", serial->port);
b19f4622 335
25b66c3c
ML
336 sp_new_config(&config);
337 sp_set_config_baudrate(config, baudrate);
338 sp_set_config_bits(config, bits);
13cd8197
ML
339 switch (parity) {
340 case 0:
25b66c3c 341 sp_set_config_parity(config, SP_PARITY_NONE);
13cd8197
ML
342 break;
343 case 1:
25b66c3c 344 sp_set_config_parity(config, SP_PARITY_EVEN);
13cd8197
ML
345 break;
346 case 2:
25b66c3c 347 sp_set_config_parity(config, SP_PARITY_ODD);
13cd8197
ML
348 break;
349 default:
350 return SR_ERR_ARG;
351 }
25b66c3c
ML
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);
a9bce5a5 361
a0dfaa6c
UH
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();
cb7b165b
UH
368 sr_err("Error setting serial port parameters (%d): %s.",
369 sp_last_error_code(), error);
a0dfaa6c
UH
370 sp_free_error_message(error);
371 return SR_ERR;
700dcd5c
UH
372 }
373
e46b8fb1 374 return SR_OK;
d02a535e 375}
792fc686 376
299bdb24 377/**
48d3238e 378 * Set serial parameters for the specified serial port from parameter string.
299bdb24
BV
379 *
380 * @param serial Previously initialized serial port structure.
48d3238e
MH
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.
04cb9157
MH
394 * @retval SR_OK Success.
395 * @retval SR_ERR Failure.
299bdb24 396 */
299bdb24
BV
397SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
398 const char *paramstr)
792fc686 399{
48d3238e
MH
400#define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
401
792fc686
BV
402 GRegex *reg;
403 GMatchInfo *match;
26ddb5ba 404 int speed, databits, parity, stopbits, flow, rts, dtr, i;
71caaad4 405 char *mstr, **opts, **kv;
792fc686 406
26ddb5ba 407 speed = databits = parity = stopbits = flow = 0;
71caaad4 408 rts = dtr = -1;
ea088bb6 409 sr_spew("Parsing parameters from \"%s\".", paramstr);
792fc686
BV
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);
71caaad4
BV
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 }
26ddb5ba 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 }
71caaad4
BV
473 }
474 g_strfreev(kv);
475 }
476 g_strfreev(opts);
477 }
478 }
479 g_free(mstr);
792fc686
BV
480 }
481 g_match_info_unref(match);
482 g_regex_unref(reg);
483
ea088bb6
AG
484 if (speed) {
485 return serial_set_params(serial, speed, databits, parity,
26ddb5ba 486 stopbits, flow, rts, dtr);
ea088bb6
AG
487 } else {
488 sr_dbg("Could not infer speed from parameter string.");
792fc686 489 return SR_ERR_ARG;
ea088bb6 490 }
792fc686
BV
491}
492
299bdb24
BV
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.
04cb9157 499 * @param[in] timeout_ms How long to wait for a line to come in.
299bdb24
BV
500 *
501 * Reading stops when CR of LR is found, which is stripped from the buffer.
502 *
04cb9157
MH
503 * @retval SR_OK Success.
504 * @retval SR_ERR Failure.
299bdb24
BV
505 */
506SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
507 int *buflen, gint64 timeout_ms)
6f22a8ef 508{
b87f8504 509 gint64 start;
6f22a8ef
UH
510 int maxlen, len;
511
64ecf7ee 512 if (!serial) {
299bdb24
BV
513 sr_dbg("Invalid serial port.");
514 return SR_ERR;
515 }
516
64ecf7ee
ML
517 if (!serial->data) {
518 sr_dbg("Cannot use unopened serial port %s.", serial->port);
299bdb24
BV
519 return -1;
520 }
521
6f22a8ef
UH
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;
299bdb24 531 len = serial_read(serial, *buf + *buflen, 1);
6f22a8ef
UH
532 if (len > 0) {
533 *buflen += len;
534 *(*buf + *buflen) = '\0';
318dd53c
BV
535 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
536 || *(*buf + *buflen - 1) == '\n')) {
537 /* Strip CR/LF and terminate. */
6f22a8ef
UH
538 *(*buf + --*buflen) = '\0';
539 break;
540 }
541 }
542 if (g_get_monotonic_time() - start > timeout_ms)
543 /* Timeout */
544 break;
5715e84f
DT
545 if (len < 1)
546 g_usleep(2000);
6f22a8ef 547 }
318dd53c
BV
548 if (*buflen)
549 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
550
551 return SR_OK;
552}
766456be
UH
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.
04cb9157
MH
559 * @param buflen Size of the buffer.
560 * @param[in] packet_size Size, in bytes, of a valid packet.
766456be 561 * @param is_valid Callback that assesses whether the packet is valid or not.
04cb9157 562 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
766456be 563 * abort scanning.
04cb9157 564 * @param[in] baudrate The baudrate of the serial port. This parameter is not
766456be
UH
565 * critical, but it helps fine tune the serial port polling
566 * delay.
567 *
04cb9157
MH
568 * @retval SR_OK Valid packet was found within the given timeout
569 * @retval SR_ERR Failure.
766456be
UH
570 */
571SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
572 uint8_t *buf, size_t *buflen,
144f6660
UH
573 size_t packet_size,
574 packet_valid_callback is_valid,
766456be
UH
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
64ecf7ee
ML
583 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
584 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
766456be
UH
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
766456be
UH
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) {
006dbe55 601 /* No logging, already done in serial_read(). */
766456be
UH
602 } else {
603 /* Error reading byte, but continuing anyway. */
604 }
551c3d8c
AG
605
606 time = g_get_monotonic_time() - start;
607 time /= 1000;
608
766456be
UH
609 if ((ibuf - i) >= packet_size) {
610 /* We have at least a packet's worth of data. */
611 if (is_valid(&buf[i])) {
766456be
UH
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 }
551c3d8c 623 if (time >= timeout_ms) {
766456be 624 /* Timeout */
551c3d8c 625 sr_dbg("Detection timed out after %dms.", time);
766456be
UH
626 break;
627 }
5715e84f
DT
628 if (len < 1)
629 g_usleep(byte_delay_us);
766456be
UH
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}
1bd9e678
DJ
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 */
650SR_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}
abc4b335 680
a0a4c0fb 681#ifdef _WIN32
ba1949f5 682typedef HANDLE event_handle;
a0a4c0fb 683#else
ba1949f5 684typedef int event_handle;
a0a4c0fb 685#endif
ba1949f5
ML
686
687SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
144f6660 688 int timeout, sr_receive_data_callback cb, void *cb_data)
ba1949f5
ML
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;
abc4b335 729}
7faa3e88
ML
730
731SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
732{
ba1949f5
ML
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;
7faa3e88 746}
b541f837
AJ
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 */
758SR_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
824skip_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}