]> sigrok.org Git - libsigrok.git/blame - hardware/common/serial.c
manson-hcs-3xxx: Implemented setting voltage, current and output.
[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 *
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.
9a474211
ML
215 * @param buf Buffer containing the bytes to write.
216 * @param count Number of bytes to write.
b19f4622 217 *
9a474211 218 * @return The number of bytes written, or a negative error code upon failure.
2119ab03 219 */
9a474211
ML
220SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
221 const void *buf, size_t count)
222{
223 return _serial_write(serial, buf, count, serial->nonblocking);
224}
225
226SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
227 const void *buf, size_t count)
228{
229 return _serial_write(serial, buf, count, 0);
230}
231
232SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
233 const void *buf, size_t count)
234{
235 return _serial_write(serial, buf, count, 1);
236}
237
238static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
239 size_t count, int nonblocking)
2119ab03 240{
299bdb24 241 ssize_t ret;
c4d85a40 242 char *error;
299bdb24
BV
243
244 if (!serial) {
245 sr_dbg("Invalid serial port.");
6a76efeb 246 return SR_ERR;
299bdb24
BV
247 }
248
64ecf7ee
ML
249 if (!serial->data) {
250 sr_dbg("Cannot use unopened serial port %s.", serial->port);
6a76efeb 251 return SR_ERR;
299bdb24
BV
252 }
253
9a474211 254 if (nonblocking)
9647ce69
ML
255 ret = sp_nonblocking_read(serial->data, buf, count);
256 else
257 ret = sp_blocking_read(serial->data, buf, count, 0);
2119ab03 258
a0dfaa6c
UH
259 switch (ret) {
260 case SP_ERR_ARG:
261 sr_err("Attempted serial port read with invalid arguments.");
262 return SR_ERR_ARG;
c4d85a40
UH
263 case SP_ERR_FAIL:
264 error = sp_last_error_message();
cb7b165b 265 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
c4d85a40
UH
266 sp_free_error_message(error);
267 return SR_ERR;
a9bce5a5
ML
268 }
269
c4d85a40 270 if (ret > 0)
64ecf7ee 271 sr_spew("Read %d/%d bytes.", ret, count);
b19f4622
UH
272
273 return ret;
2119ab03
UH
274}
275
9a474211
ML
276/**
277 * Read a number of bytes from the specified serial port.
278 *
279 * @param serial Previously initialized serial port structure.
280 * @param buf Buffer where to store the bytes that are read.
281 * @param count The number of bytes to read.
282 *
283 * @return The number of bytes read, or a negative error code upon failure.
284 */
285SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
286 size_t count)
287{
288 return _serial_read(serial, buf, count, serial->nonblocking);
289}
290
291SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
292 size_t count)
293{
294 return _serial_read(serial, buf, count, 0);
295}
296
297SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
298 size_t count)
299{
300 return _serial_read(serial, buf, count, 1);
301}
302
b19f4622
UH
303/**
304 * Set serial parameters for the specified serial port.
305 *
299bdb24 306 * @param serial Previously initialized serial port structure.
04cb9157
MH
307 * @param[in] baudrate The baudrate to set.
308 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
309 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
310 * @param[in] stopbits The number of stop bits to use (1 or 2).
311 * @param[in] flowcontrol The flow control settings to use (0 = none,
312 * 1 = RTS/CTS, 2 = XON/XOFF).
313 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
314 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
2119ab03 315 *
d0a92abd 316 * @retval SR_OK Success.
04cb9157 317 * @retval SR_ERR Failure.
1ff7712c 318 */
299bdb24 319SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
39e5d798
UH
320 int bits, int parity, int stopbits,
321 int flowcontrol, int rts, int dtr)
d02a535e 322{
a9bce5a5
ML
323 int ret;
324 char *error;
25b66c3c 325 struct sp_port_config *config;
a9bce5a5 326
299bdb24
BV
327 if (!serial) {
328 sr_dbg("Invalid serial port.");
329 return SR_ERR;
330 }
331
64ecf7ee
ML
332 if (!serial->data) {
333 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
299bdb24
BV
334 return SR_ERR;
335 }
336
64ecf7ee 337 sr_spew("Setting serial parameters on port %s.", serial->port);
b19f4622 338
25b66c3c
ML
339 sp_new_config(&config);
340 sp_set_config_baudrate(config, baudrate);
341 sp_set_config_bits(config, bits);
13cd8197
ML
342 switch (parity) {
343 case 0:
25b66c3c 344 sp_set_config_parity(config, SP_PARITY_NONE);
13cd8197
ML
345 break;
346 case 1:
25b66c3c 347 sp_set_config_parity(config, SP_PARITY_EVEN);
13cd8197
ML
348 break;
349 case 2:
25b66c3c 350 sp_set_config_parity(config, SP_PARITY_ODD);
13cd8197
ML
351 break;
352 default:
353 return SR_ERR_ARG;
354 }
25b66c3c
ML
355 sp_set_config_stopbits(config, stopbits);
356 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
357 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
358 sp_set_config_dtr(config, dtr);
359 sp_set_config_dsr(config, SP_DSR_IGNORE);
360 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
361
362 ret = sp_set_config(serial->data, config);
363 sp_free_config(config);
a9bce5a5 364
a0dfaa6c
UH
365 switch (ret) {
366 case SP_ERR_ARG:
367 sr_err("Invalid arguments for setting serial port parameters.");
368 return SR_ERR_ARG;
369 case SP_ERR_FAIL:
370 error = sp_last_error_message();
cb7b165b
UH
371 sr_err("Error setting serial port parameters (%d): %s.",
372 sp_last_error_code(), error);
a0dfaa6c
UH
373 sp_free_error_message(error);
374 return SR_ERR;
700dcd5c
UH
375 }
376
e46b8fb1 377 return SR_OK;
d02a535e 378}
792fc686 379
299bdb24 380/**
48d3238e 381 * Set serial parameters for the specified serial port from parameter string.
299bdb24
BV
382 *
383 * @param serial Previously initialized serial port structure.
48d3238e
MH
384 * @param[in] paramstr A serial communication parameters string of the form
385 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
386 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
387 * \<baudrate\>=integer Baud rate.\n
388 * \<bits\>=5|6|7|8 Number of data bits.\n
389 * \<parity\>=n|e|o None, even, odd.\n
390 * \<stopbits\>=1|2 One or two stop bits.\n
391 * Options:\n
392 * dtr=0|1 Set DTR off resp. on.\n
393 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
394 * rts=0|1 Set RTS off resp. on.\n
395 * Please note that values and combinations of these parameters must be
396 * supported by the concrete serial interface hardware and the drivers for it.
04cb9157
MH
397 * @retval SR_OK Success.
398 * @retval SR_ERR Failure.
299bdb24 399 */
299bdb24
BV
400SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
401 const char *paramstr)
792fc686 402{
48d3238e
MH
403#define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
404
792fc686
BV
405 GRegex *reg;
406 GMatchInfo *match;
26ddb5ba 407 int speed, databits, parity, stopbits, flow, rts, dtr, i;
71caaad4 408 char *mstr, **opts, **kv;
792fc686 409
26ddb5ba 410 speed = databits = parity = stopbits = flow = 0;
71caaad4 411 rts = dtr = -1;
ea088bb6 412 sr_spew("Parsing parameters from \"%s\".", paramstr);
792fc686
BV
413 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
414 if (g_regex_match(reg, paramstr, 0, &match)) {
415 if ((mstr = g_match_info_fetch(match, 1)))
416 speed = strtoul(mstr, NULL, 10);
417 g_free(mstr);
418 if ((mstr = g_match_info_fetch(match, 2)))
419 databits = strtoul(mstr, NULL, 10);
420 g_free(mstr);
421 if ((mstr = g_match_info_fetch(match, 3))) {
422 switch (mstr[0]) {
423 case 'n':
424 parity = SERIAL_PARITY_NONE;
425 break;
426 case 'e':
427 parity = SERIAL_PARITY_EVEN;
428 break;
429 case 'o':
430 parity = SERIAL_PARITY_ODD;
431 break;
432 }
433 }
434 g_free(mstr);
435 if ((mstr = g_match_info_fetch(match, 4)))
436 stopbits = strtoul(mstr, NULL, 10);
437 g_free(mstr);
71caaad4
BV
438 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
439 if (mstr[0] != '/') {
440 sr_dbg("missing separator before extra options");
441 speed = 0;
442 } else {
443 /* A set of "key=value" options separated by / */
444 opts = g_strsplit(mstr + 1, "/", 0);
445 for (i = 0; opts[i]; i++) {
446 kv = g_strsplit(opts[i], "=", 2);
447 if (!strncmp(kv[0], "rts", 3)) {
448 if (kv[1][0] == '1')
449 rts = 1;
450 else if (kv[1][0] == '0')
451 rts = 0;
452 else {
453 sr_dbg("invalid value for rts: %c", kv[1][0]);
454 speed = 0;
455 }
456 } else if (!strncmp(kv[0], "dtr", 3)) {
457 if (kv[1][0] == '1')
458 dtr = 1;
459 else if (kv[1][0] == '0')
460 dtr = 0;
461 else {
462 sr_dbg("invalid value for dtr: %c", kv[1][0]);
463 speed = 0;
464 }
26ddb5ba 465 } else if (!strncmp(kv[0], "flow", 4)) {
466 if (kv[1][0] == '0')
467 flow = 0;
468 else if (kv[1][0] == '1')
469 flow = 1;
470 else if (kv[1][0] == '2')
471 flow = 2;
472 else {
473 sr_dbg("invalid value for flow: %c", kv[1][0]);
474 speed = 0;
475 }
71caaad4
BV
476 }
477 g_strfreev(kv);
478 }
479 g_strfreev(opts);
480 }
481 }
482 g_free(mstr);
792fc686
BV
483 }
484 g_match_info_unref(match);
485 g_regex_unref(reg);
486
ea088bb6
AG
487 if (speed) {
488 return serial_set_params(serial, speed, databits, parity,
26ddb5ba 489 stopbits, flow, rts, dtr);
ea088bb6
AG
490 } else {
491 sr_dbg("Could not infer speed from parameter string.");
792fc686 492 return SR_ERR_ARG;
ea088bb6 493 }
792fc686
BV
494}
495
299bdb24
BV
496/**
497 * Read a line from the specified serial port.
498 *
499 * @param serial Previously initialized serial port structure.
500 * @param buf Buffer where to store the bytes that are read.
501 * @param buflen Size of the buffer.
04cb9157 502 * @param[in] timeout_ms How long to wait for a line to come in.
299bdb24
BV
503 *
504 * Reading stops when CR of LR is found, which is stripped from the buffer.
505 *
04cb9157
MH
506 * @retval SR_OK Success.
507 * @retval SR_ERR Failure.
299bdb24
BV
508 */
509SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
510 int *buflen, gint64 timeout_ms)
6f22a8ef 511{
b87f8504 512 gint64 start;
6f22a8ef
UH
513 int maxlen, len;
514
64ecf7ee 515 if (!serial) {
299bdb24
BV
516 sr_dbg("Invalid serial port.");
517 return SR_ERR;
518 }
519
64ecf7ee
ML
520 if (!serial->data) {
521 sr_dbg("Cannot use unopened serial port %s.", serial->port);
299bdb24
BV
522 return -1;
523 }
524
6f22a8ef
UH
525 timeout_ms *= 1000;
526 start = g_get_monotonic_time();
527
528 maxlen = *buflen;
529 *buflen = len = 0;
530 while(1) {
531 len = maxlen - *buflen - 1;
532 if (len < 1)
533 break;
299bdb24 534 len = serial_read(serial, *buf + *buflen, 1);
6f22a8ef
UH
535 if (len > 0) {
536 *buflen += len;
537 *(*buf + *buflen) = '\0';
318dd53c
BV
538 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
539 || *(*buf + *buflen - 1) == '\n')) {
540 /* Strip CR/LF and terminate. */
6f22a8ef
UH
541 *(*buf + --*buflen) = '\0';
542 break;
543 }
544 }
545 if (g_get_monotonic_time() - start > timeout_ms)
546 /* Timeout */
547 break;
5715e84f
DT
548 if (len < 1)
549 g_usleep(2000);
6f22a8ef 550 }
318dd53c
BV
551 if (*buflen)
552 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
553
554 return SR_OK;
555}
766456be
UH
556
557/**
558 * Try to find a valid packet in a serial data stream.
559 *
560 * @param serial Previously initialized serial port structure.
561 * @param buf Buffer containing the bytes to write.
04cb9157
MH
562 * @param buflen Size of the buffer.
563 * @param[in] packet_size Size, in bytes, of a valid packet.
766456be 564 * @param is_valid Callback that assesses whether the packet is valid or not.
04cb9157 565 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
766456be 566 * abort scanning.
04cb9157 567 * @param[in] baudrate The baudrate of the serial port. This parameter is not
766456be
UH
568 * critical, but it helps fine tune the serial port polling
569 * delay.
570 *
d0a92abd 571 * @retval SR_OK Valid packet was found within the given timeout.
04cb9157 572 * @retval SR_ERR Failure.
766456be
UH
573 */
574SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
575 uint8_t *buf, size_t *buflen,
144f6660
UH
576 size_t packet_size,
577 packet_valid_callback is_valid,
766456be
UH
578 uint64_t timeout_ms, int baudrate)
579{
580 uint64_t start, time, byte_delay_us;
581 size_t ibuf, i, maxlen;
582 int len;
583
584 maxlen = *buflen;
585
64ecf7ee
ML
586 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
587 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
766456be
UH
588
589 if (maxlen < (packet_size / 2) ) {
590 sr_err("Buffer size must be at least twice the packet size.");
591 return SR_ERR;
592 }
593
766456be
UH
594 /* Assume 8n1 transmission. That is 10 bits for every byte. */
595 byte_delay_us = 10 * (1000000 / baudrate);
596 start = g_get_monotonic_time();
597
598 i = ibuf = len = 0;
599 while (ibuf < maxlen) {
600 len = serial_read(serial, &buf[ibuf], 1);
601 if (len > 0) {
602 ibuf += len;
603 } else if (len == 0) {
006dbe55 604 /* No logging, already done in serial_read(). */
766456be
UH
605 } else {
606 /* Error reading byte, but continuing anyway. */
607 }
551c3d8c
AG
608
609 time = g_get_monotonic_time() - start;
610 time /= 1000;
611
766456be
UH
612 if ((ibuf - i) >= packet_size) {
613 /* We have at least a packet's worth of data. */
614 if (is_valid(&buf[i])) {
766456be
UH
615 sr_spew("Found valid %d-byte packet after "
616 "%" PRIu64 "ms.", (ibuf - i), time);
617 *buflen = ibuf;
618 return SR_OK;
619 } else {
620 sr_spew("Got %d bytes, but not a valid "
621 "packet.", (ibuf - i));
622 }
623 /* Not a valid packet. Continue searching. */
624 i++;
625 }
551c3d8c 626 if (time >= timeout_ms) {
766456be 627 /* Timeout */
551c3d8c 628 sr_dbg("Detection timed out after %dms.", time);
766456be
UH
629 break;
630 }
5715e84f
DT
631 if (len < 1)
632 g_usleep(byte_delay_us);
766456be
UH
633 }
634
635 *buflen = ibuf;
636
637 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
638
639 return SR_ERR;
640}
1bd9e678
DJ
641
642/**
643 * Extract the serial device and options from the options linked list.
644 *
645 * @param options List of options passed from the command line.
646 * @param serial_device Pointer where to store the exctracted serial device.
647 * @param serial_options Pointer where to store the optional extracted serial
648 * options.
649 *
650 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
651 * returned string should not be freed by the caller.
652 */
653SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
654 const char **serial_options)
655{
656 GSList *l;
657 struct sr_config *src;
658
659 *serial_device = NULL;
660
661 for (l = options; l; l = l->next) {
662 src = l->data;
663 switch (src->key) {
664 case SR_CONF_CONN:
665 *serial_device = g_variant_get_string(src->data, NULL);
666 sr_dbg("Parsed serial device: %s", *serial_device);
667 break;
668
669 case SR_CONF_SERIALCOMM:
670 *serial_options = g_variant_get_string(src->data, NULL);
671 sr_dbg("Parsed serial options: %s", *serial_options);
672 break;
673 }
674 }
675
676 if (!*serial_device) {
677 sr_dbg("No serial device specified");
678 return SR_ERR;
679 }
680
681 return SR_OK;
682}
abc4b335 683
a0a4c0fb 684#ifdef _WIN32
ba1949f5 685typedef HANDLE event_handle;
a0a4c0fb 686#else
ba1949f5 687typedef int event_handle;
a0a4c0fb 688#endif
ba1949f5
ML
689
690SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
144f6660 691 int timeout, sr_receive_data_callback cb, void *cb_data)
ba1949f5
ML
692{
693 enum sp_event mask = 0;
694 unsigned int i;
695
696 if (sp_new_event_set(&serial->event_set) != SP_OK)
697 return SR_ERR;
698
699 if (events & G_IO_IN)
700 mask |= SP_EVENT_RX_READY;
701 if (events & G_IO_OUT)
702 mask |= SP_EVENT_TX_READY;
703 if (events & G_IO_ERR)
704 mask |= SP_EVENT_ERROR;
705
706 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
707 sp_free_event_set(serial->event_set);
708 return SR_ERR;
709 }
710
711 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
712
713 for (i = 0; i < serial->event_set->count; i++) {
714
715 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
716
717 mask = serial->event_set->masks[i];
718
719 if (mask & SP_EVENT_RX_READY)
720 serial->pollfds[i].events |= G_IO_IN;
721 if (mask & SP_EVENT_TX_READY)
722 serial->pollfds[i].events |= G_IO_OUT;
723 if (mask & SP_EVENT_ERROR)
724 serial->pollfds[i].events |= G_IO_ERR;
725
726 if (sr_session_source_add_pollfd(&serial->pollfds[i],
727 timeout, cb, cb_data) != SR_OK)
728 return SR_ERR;
729 }
730
731 return SR_OK;
abc4b335 732}
7faa3e88
ML
733
734SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
735{
ba1949f5
ML
736 unsigned int i;
737
738 for (i = 0; i < serial->event_set->count; i++)
739 if (sr_session_source_remove_pollfd(&serial->pollfds[i]) != SR_OK)
740 return SR_ERR;
741
742 g_free(serial->pollfds);
743 sp_free_event_set(serial->event_set);
744
745 serial->pollfds = NULL;
746 serial->event_set = NULL;
747
748 return SR_OK;
7faa3e88 749}
b541f837
AJ
750
751/**
752 * Find USB serial devices via the USB vendor ID and product ID.
753 *
d0a92abd
MH
754 * @param[in] vendor_id Vendor ID of the USB device.
755 * @param[in] product_id Product ID of the USB device.
b541f837
AJ
756 *
757 * @return A GSList of strings containing the path of the serial device or
758 * NULL if no serial device is found. The returned list must be freed
759 * by the caller.
760 */
761SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
762{
763#ifdef __linux__
764 const gchar *usb_dev;
765 const char device_tree[] = "/sys/bus/usb/devices/";
766 GDir *devices_dir, *device_dir;
767 GSList *l = NULL;
768 GSList *tty_devs;
769 GSList *matched_paths;
770 FILE *fd;
771 char tmp[5];
772 gchar *vendor_path, *product_path, *path_copy;
773 gchar *prefix, *subdir_path, *device_path, *tty_path;
774 unsigned long read_vendor_id, read_product_id;
775 const char *file;
776
777 l = NULL;
778 tty_devs = NULL;
779 matched_paths = NULL;
780
781 if (!(devices_dir = g_dir_open(device_tree, 0, NULL)))
782 return NULL;
783
784 /*
785 * Find potential candidates using the vendor ID and product ID
786 * and store them in matched_paths.
787 */
788 while ((usb_dev = g_dir_read_name(devices_dir))) {
789 vendor_path = g_strconcat(device_tree,
790 usb_dev, "/idVendor", NULL);
791 product_path = g_strconcat(device_tree,
792 usb_dev, "/idProduct", NULL);
793
794 if (!g_file_test(vendor_path, G_FILE_TEST_EXISTS) ||
795 !g_file_test(product_path, G_FILE_TEST_EXISTS))
796 goto skip_device;
797
798 if ((fd = g_fopen(vendor_path, "r")) == NULL)
799 goto skip_device;
800
801 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
802 fclose(fd);
803 goto skip_device;
804 }
805 read_vendor_id = strtoul(tmp, NULL, 16);
806
807 fclose(fd);
808
809 if ((fd = g_fopen(product_path, "r")) == NULL)
810 goto skip_device;
811
812 if (fgets(tmp, sizeof(tmp), fd) == NULL) {
813 fclose(fd);
814 goto skip_device;
815 }
816 read_product_id = strtoul(tmp, NULL, 16);
817
818 fclose(fd);
819
820 if (vendor_id == read_vendor_id &&
821 product_id == read_product_id) {
822 path_copy = g_strdup(usb_dev);
823 matched_paths = g_slist_prepend(matched_paths,
824 path_copy);
825 }
826
827skip_device:
828 g_free(vendor_path);
829 g_free(product_path);
830 }
831 g_dir_close(devices_dir);
832
833 /* For every matched device try to find a ttyUSBX subfolder. */
834 for (l = matched_paths; l; l = l->next) {
835 subdir_path = NULL;
836
837 device_path = g_strconcat(device_tree, l->data, NULL);
838
839 if (!(device_dir = g_dir_open(device_path, 0, NULL))) {
840 g_free(device_path);
841 continue;
842 }
843
844 prefix = g_strconcat(l->data, ":", NULL);
845
846 while ((file = g_dir_read_name(device_dir))) {
847 if (g_str_has_prefix(file, prefix)) {
848 subdir_path = g_strconcat(device_path,
849 "/", file, NULL);
850 break;
851 }
852 }
853 g_dir_close(device_dir);
854
855 g_free(prefix);
856 g_free(device_path);
857
858 if (subdir_path) {
859 if (!(device_dir = g_dir_open(subdir_path, 0, NULL))) {
860 g_free(subdir_path);
861 continue;
862 }
863 g_free(subdir_path);
864
865 while ((file = g_dir_read_name(device_dir))) {
866 if (g_str_has_prefix(file, "ttyUSB")) {
867 tty_path = g_strconcat("/dev/",
868 file, NULL);
869 sr_dbg("Found USB device %04x:%04x attached to %s.",
870 vendor_id, product_id, tty_path);
871 tty_devs = g_slist_prepend(tty_devs,
872 tty_path);
873 break;
874 }
875 }
876 g_dir_close(device_dir);
877 }
878 }
879 g_slist_free_full(matched_paths, g_free);
880
881 return tty_devs;
882#else
883 (void)vendor_id;
884 (void)product_id;
885
886 return NULL;
887#endif
888}