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