]> sigrok.org Git - libsigrok.git/blame - src/serial.c
unit tests: Drop unneeded check_ filename prefix.
[libsigrok.git] / src / 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>
bce75f94 7 * Copyright (C) 2014 Uffe Jakobsen <uffe@uffe.org>
a1bb33af
UH
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 */
22
54b38f64 23#include <string.h>
d02a535e 24#include <stdlib.h>
a1bb33af 25#include <glib.h>
b541f837 26#include <glib/gstdio.h>
0d4405ce 27#include <libserialport.h>
45c59c8b
BV
28#include "libsigrok.h"
29#include "libsigrok-internal.h"
a1bb33af 30
3544f848 31#define LOG_PREFIX "serial"
b19f4622 32
b19f4622
UH
33/**
34 * Open the specified serial port.
35 *
299bdb24 36 * @param serial Previously initialized serial port structure.
a9cf2035 37 * @param[in] flags Flags to use when opening the serial port. Possible flags
98edee79 38 * include SERIAL_RDWR, SERIAL_RDONLY.
b19f4622 39 *
299bdb24
BV
40 * If the serial structure contains a serialcomm string, it will be
41 * passed to serial_set_paramstr() after the port is opened.
42 *
d0a92abd
MH
43 * @retval SR_OK Success.
44 * @retval SR_ERR Failure.
b19f4622 45 */
299bdb24 46SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
d02a535e 47{
a9bce5a5
ML
48 int ret;
49 char *error;
13cd8197 50 int sp_flags = 0;
b19f4622 51
299bdb24
BV
52 if (!serial) {
53 sr_dbg("Invalid serial port.");
54 return SR_ERR;
55 }
56
57 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
b19f4622 58
c9bc57b6
ML
59 sp_get_port_by_name(serial->port, &serial->data);
60
13cd8197
ML
61 if (flags & SERIAL_RDWR)
62 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
63 else if (flags & SERIAL_RDONLY)
64 sp_flags = SP_MODE_READ;
9647ce69 65
13cd8197 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 *
d0a92abd
MH
91 * @retval SR_OK Success.
92 * @retval SR_ERR Failure.
2119ab03 93 */
299bdb24 94SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
d02a535e 95{
299bdb24 96 int ret;
a9bce5a5 97 char *error;
299bdb24
BV
98
99 if (!serial) {
100 sr_dbg("Invalid serial port.");
101 return SR_ERR;
102 }
103
64ecf7ee
ML
104 if (!serial->data) {
105 sr_dbg("Cannot close unopened serial port %s.", serial->port);
299bdb24
BV
106 return SR_ERR;
107 }
108
64ecf7ee 109 sr_spew("Closing serial port %s.", serial->port);
b19f4622 110
c9bc57b6 111 ret = sp_close(serial->data);
a9bce5a5 112
a0dfaa6c
UH
113 switch (ret) {
114 case SP_ERR_ARG:
115 sr_err("Attempt to close an invalid serial port.");
116 return SR_ERR_ARG;
117 case SP_ERR_FAIL:
118 error = sp_last_error_message();
cb7b165b
UH
119 sr_err("Error closing port (%d): %s.",
120 sp_last_error_code(), error);
a0dfaa6c
UH
121 sp_free_error_message(error);
122 return SR_ERR;
b19f4622 123 }
299bdb24 124
64ecf7ee
ML
125 sp_free_port(serial->data);
126 serial->data = NULL;
127
6a76efeb 128 return SR_OK;
d02a535e
BV
129}
130
b19f4622 131/**
299bdb24 132 * Flush serial port buffers.
b19f4622 133 *
299bdb24 134 * @param serial Previously initialized serial port structure.
b19f4622 135 *
d0a92abd
MH
136 * @retval SR_OK Success.
137 * @retval SR_ERR Failure.
1fdb75e1 138 */
299bdb24 139SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
06d64eb8 140{
299bdb24 141 int ret;
a9bce5a5 142 char *error;
299bdb24
BV
143
144 if (!serial) {
145 sr_dbg("Invalid serial port.");
146 return SR_ERR;
147 }
148
64ecf7ee
ML
149 if (!serial->data) {
150 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
299bdb24
BV
151 return SR_ERR;
152 }
153
64ecf7ee 154 sr_spew("Flushing serial port %s.", serial->port);
b19f4622 155
13cd8197 156 ret = sp_flush(serial->data, SP_BUF_BOTH);
a9bce5a5 157
a0dfaa6c
UH
158 switch (ret) {
159 case SP_ERR_ARG:
160 sr_err("Attempt to flush an invalid serial port.");
161 return SR_ERR_ARG;
162 case SP_ERR_FAIL:
163 error = sp_last_error_message();
cb7b165b
UH
164 sr_err("Error flushing port (%d): %s.",
165 sp_last_error_code(), error);
a0dfaa6c
UH
166 sp_free_error_message(error);
167 return SR_ERR;
299bdb24 168 }
b19f4622 169
6a76efeb 170 return SR_OK;
06d64eb8
BV
171}
172
bce75f94
UJ
173/**
174 * Drain serial port buffers.
175 *
176 * @param serial Previously initialized serial port structure.
177 *
178 * @retval SR_OK Success.
179 * @retval SR_ERR Failure.
180 */
181SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
182{
183 int ret;
184 char *error;
185
186 if (!serial) {
187 sr_dbg("Invalid serial port.");
188 return SR_ERR;
189 }
190
191 if (!serial->data) {
192 sr_dbg("Cannot drain unopened serial port %s.", serial->port);
193 return SR_ERR;
194 }
195
196 sr_spew("Draining serial port %s.", serial->port);
197
198 ret = sp_drain(serial->data);
199
200 if (ret == SP_ERR_FAIL) {
201 error = sp_last_error_message();
202 sr_err("Error draining port (%d): %s.",
203 sp_last_error_code(), error);
204 sp_free_error_message(error);
205 return SR_ERR;
206 }
207
208 return SR_OK;
209}
210
9a474211 211static int _serial_write(struct sr_serial_dev_inst *serial,
eead2782 212 const void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
2119ab03 213{
299bdb24 214 ssize_t ret;
a9bce5a5 215 char *error;
299bdb24
BV
216
217 if (!serial) {
218 sr_dbg("Invalid serial port.");
6a76efeb 219 return SR_ERR;
299bdb24
BV
220 }
221
64ecf7ee
ML
222 if (!serial->data) {
223 sr_dbg("Cannot use unopened serial port %s.", serial->port);
6a76efeb 224 return SR_ERR;
299bdb24
BV
225 }
226
9a474211 227 if (nonblocking)
9647ce69
ML
228 ret = sp_nonblocking_write(serial->data, buf, count);
229 else
eead2782 230 ret = sp_blocking_write(serial->data, buf, count, timeout_ms);
a9bce5a5 231
a0dfaa6c
UH
232 switch (ret) {
233 case SP_ERR_ARG:
234 sr_err("Attempted serial port write with invalid arguments.");
235 return SR_ERR_ARG;
236 case SP_ERR_FAIL:
237 error = sp_last_error_message();
cb7b165b 238 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
a0dfaa6c
UH
239 sp_free_error_message(error);
240 return SR_ERR;
a9bce5a5
ML
241 }
242
64ecf7ee 243 sr_spew("Wrote %d/%d bytes.", ret, count);
b19f4622
UH
244
245 return ret;
2119ab03
UH
246}
247
b19f4622 248/**
98edee79 249 * Write a number of bytes to the specified serial port, blocking until finished.
b19f4622 250 *
299bdb24 251 * @param serial Previously initialized serial port structure.
a9cf2035
MH
252 * @param[in] buf Buffer containing the bytes to write.
253 * @param[in] count Number of bytes to write.
eead2782 254 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
b19f4622 255 *
a9cf2035
MH
256 * @retval SR_ERR_ARG Invalid argument.
257 * @retval SR_ERR Other error.
eead2782
ML
258 * @retval other The number of bytes written. If this is less than the number
259 * specified in the call, the timeout was reached.
2119ab03 260 */
9a474211 261SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
eead2782 262 const void *buf, size_t count, unsigned int timeout_ms)
9a474211 263{
eead2782 264 return _serial_write(serial, buf, count, 0, timeout_ms);
9a474211
ML
265}
266
a9cf2035
MH
267/**
268 * Write a number of bytes to the specified serial port, return immediately.
98edee79
ML
269 *
270 * @param serial Previously initialized serial port structure.
271 * @param[in] buf Buffer containing the bytes to write.
272 * @param[in] count Number of bytes to write.
273 *
274 * @retval SR_ERR_ARG Invalid argument.
275 * @retval SR_ERR Other error.
276 * @retval other The number of bytes written.
a9cf2035 277*/
9a474211
ML
278SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
279 const void *buf, size_t count)
280{
eead2782 281 return _serial_write(serial, buf, count, 1, 0);
9a474211
ML
282}
283
284static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
eead2782 285 size_t count, int nonblocking, unsigned int timeout_ms)
2119ab03 286{
299bdb24 287 ssize_t ret;
c4d85a40 288 char *error;
299bdb24
BV
289
290 if (!serial) {
291 sr_dbg("Invalid serial port.");
6a76efeb 292 return SR_ERR;
299bdb24
BV
293 }
294
64ecf7ee
ML
295 if (!serial->data) {
296 sr_dbg("Cannot use unopened serial port %s.", serial->port);
6a76efeb 297 return SR_ERR;
299bdb24
BV
298 }
299
9a474211 300 if (nonblocking)
9647ce69
ML
301 ret = sp_nonblocking_read(serial->data, buf, count);
302 else
eead2782 303 ret = sp_blocking_read(serial->data, buf, count, timeout_ms);
2119ab03 304
a0dfaa6c
UH
305 switch (ret) {
306 case SP_ERR_ARG:
307 sr_err("Attempted serial port read with invalid arguments.");
308 return SR_ERR_ARG;
c4d85a40
UH
309 case SP_ERR_FAIL:
310 error = sp_last_error_message();
cb7b165b 311 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
c4d85a40
UH
312 sp_free_error_message(error);
313 return SR_ERR;
a9bce5a5
ML
314 }
315
c4d85a40 316 if (ret > 0)
64ecf7ee 317 sr_spew("Read %d/%d bytes.", ret, count);
b19f4622
UH
318
319 return ret;
2119ab03
UH
320}
321
9a474211 322/**
98edee79 323 * Read a number of bytes from the specified serial port, block until finished.
9a474211
ML
324 *
325 * @param serial Previously initialized serial port structure.
326 * @param buf Buffer where to store the bytes that are read.
a9cf2035 327 * @param[in] count The number of bytes to read.
eead2782 328 * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
9a474211 329 *
a9cf2035
MH
330 * @retval SR_ERR_ARG Invalid argument.
331 * @retval SR_ERR Other error.
eead2782
ML
332 * @retval other The number of bytes read. If this is less than the number
333 * requested, the timeout was reached.
9a474211 334 */
9a474211 335SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
eead2782 336 size_t count, unsigned int timeout_ms)
9a474211 337{
eead2782 338 return _serial_read(serial, buf, count, 0, timeout_ms);
9a474211
ML
339}
340
a9cf2035
MH
341/**
342 * Try to read up to @a count bytes from the specified serial port, return
343 * immediately with what's available.
98edee79
ML
344 *
345 * @param serial Previously initialized serial port structure.
346 * @param buf Buffer where to store the bytes that are read.
347 * @param[in] count The number of bytes to read.
348 *
349 * @retval SR_ERR_ARG Invalid argument.
350 * @retval SR_ERR Other error.
351 * @retval other The number of bytes read.
a9cf2035 352 */
9a474211
ML
353SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
354 size_t count)
355{
eead2782 356 return _serial_read(serial, buf, count, 1, 0);
9a474211
ML
357}
358
b19f4622
UH
359/**
360 * Set serial parameters for the specified serial port.
361 *
299bdb24 362 * @param serial Previously initialized serial port structure.
04cb9157
MH
363 * @param[in] baudrate The baudrate to set.
364 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
365 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
366 * @param[in] stopbits The number of stop bits to use (1 or 2).
367 * @param[in] flowcontrol The flow control settings to use (0 = none,
368 * 1 = RTS/CTS, 2 = XON/XOFF).
369 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
370 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
2119ab03 371 *
d0a92abd 372 * @retval SR_OK Success.
04cb9157 373 * @retval SR_ERR Failure.
1ff7712c 374 */
299bdb24 375SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
39e5d798
UH
376 int bits, int parity, int stopbits,
377 int flowcontrol, int rts, int dtr)
d02a535e 378{
a9bce5a5
ML
379 int ret;
380 char *error;
25b66c3c 381 struct sp_port_config *config;
a9bce5a5 382
299bdb24
BV
383 if (!serial) {
384 sr_dbg("Invalid serial port.");
385 return SR_ERR;
386 }
387
64ecf7ee
ML
388 if (!serial->data) {
389 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
299bdb24
BV
390 return SR_ERR;
391 }
392
64ecf7ee 393 sr_spew("Setting serial parameters on port %s.", serial->port);
b19f4622 394
25b66c3c
ML
395 sp_new_config(&config);
396 sp_set_config_baudrate(config, baudrate);
397 sp_set_config_bits(config, bits);
13cd8197
ML
398 switch (parity) {
399 case 0:
25b66c3c 400 sp_set_config_parity(config, SP_PARITY_NONE);
13cd8197
ML
401 break;
402 case 1:
25b66c3c 403 sp_set_config_parity(config, SP_PARITY_EVEN);
13cd8197
ML
404 break;
405 case 2:
25b66c3c 406 sp_set_config_parity(config, SP_PARITY_ODD);
13cd8197
ML
407 break;
408 default:
409 return SR_ERR_ARG;
410 }
25b66c3c
ML
411 sp_set_config_stopbits(config, stopbits);
412 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
413 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
414 sp_set_config_dtr(config, dtr);
415 sp_set_config_dsr(config, SP_DSR_IGNORE);
416 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
417
418 ret = sp_set_config(serial->data, config);
419 sp_free_config(config);
a9bce5a5 420
a0dfaa6c
UH
421 switch (ret) {
422 case SP_ERR_ARG:
423 sr_err("Invalid arguments for setting serial port parameters.");
424 return SR_ERR_ARG;
425 case SP_ERR_FAIL:
426 error = sp_last_error_message();
cb7b165b
UH
427 sr_err("Error setting serial port parameters (%d): %s.",
428 sp_last_error_code(), error);
a0dfaa6c
UH
429 sp_free_error_message(error);
430 return SR_ERR;
700dcd5c
UH
431 }
432
e46b8fb1 433 return SR_OK;
d02a535e 434}
792fc686 435
299bdb24 436/**
48d3238e 437 * Set serial parameters for the specified serial port from parameter string.
299bdb24
BV
438 *
439 * @param serial Previously initialized serial port structure.
48d3238e
MH
440 * @param[in] paramstr A serial communication parameters string of the form
441 * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
442 * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
443 * \<baudrate\>=integer Baud rate.\n
444 * \<bits\>=5|6|7|8 Number of data bits.\n
445 * \<parity\>=n|e|o None, even, odd.\n
446 * \<stopbits\>=1|2 One or two stop bits.\n
447 * Options:\n
448 * dtr=0|1 Set DTR off resp. on.\n
449 * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
450 * rts=0|1 Set RTS off resp. on.\n
451 * Please note that values and combinations of these parameters must be
452 * supported by the concrete serial interface hardware and the drivers for it.
04cb9157
MH
453 * @retval SR_OK Success.
454 * @retval SR_ERR Failure.
299bdb24 455 */
299bdb24
BV
456SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
457 const char *paramstr)
792fc686 458{
48d3238e
MH
459#define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
460
792fc686
BV
461 GRegex *reg;
462 GMatchInfo *match;
26ddb5ba 463 int speed, databits, parity, stopbits, flow, rts, dtr, i;
71caaad4 464 char *mstr, **opts, **kv;
792fc686 465
26ddb5ba 466 speed = databits = parity = stopbits = flow = 0;
71caaad4 467 rts = dtr = -1;
ea088bb6 468 sr_spew("Parsing parameters from \"%s\".", paramstr);
792fc686
BV
469 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
470 if (g_regex_match(reg, paramstr, 0, &match)) {
471 if ((mstr = g_match_info_fetch(match, 1)))
472 speed = strtoul(mstr, NULL, 10);
473 g_free(mstr);
474 if ((mstr = g_match_info_fetch(match, 2)))
475 databits = strtoul(mstr, NULL, 10);
476 g_free(mstr);
477 if ((mstr = g_match_info_fetch(match, 3))) {
478 switch (mstr[0]) {
479 case 'n':
480 parity = SERIAL_PARITY_NONE;
481 break;
482 case 'e':
483 parity = SERIAL_PARITY_EVEN;
484 break;
485 case 'o':
486 parity = SERIAL_PARITY_ODD;
487 break;
488 }
489 }
490 g_free(mstr);
491 if ((mstr = g_match_info_fetch(match, 4)))
492 stopbits = strtoul(mstr, NULL, 10);
493 g_free(mstr);
71caaad4
BV
494 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
495 if (mstr[0] != '/') {
496 sr_dbg("missing separator before extra options");
497 speed = 0;
498 } else {
499 /* A set of "key=value" options separated by / */
500 opts = g_strsplit(mstr + 1, "/", 0);
501 for (i = 0; opts[i]; i++) {
502 kv = g_strsplit(opts[i], "=", 2);
503 if (!strncmp(kv[0], "rts", 3)) {
504 if (kv[1][0] == '1')
505 rts = 1;
506 else if (kv[1][0] == '0')
507 rts = 0;
508 else {
509 sr_dbg("invalid value for rts: %c", kv[1][0]);
510 speed = 0;
511 }
512 } else if (!strncmp(kv[0], "dtr", 3)) {
513 if (kv[1][0] == '1')
514 dtr = 1;
515 else if (kv[1][0] == '0')
516 dtr = 0;
517 else {
518 sr_dbg("invalid value for dtr: %c", kv[1][0]);
519 speed = 0;
520 }
26ddb5ba 521 } else if (!strncmp(kv[0], "flow", 4)) {
522 if (kv[1][0] == '0')
523 flow = 0;
524 else if (kv[1][0] == '1')
525 flow = 1;
526 else if (kv[1][0] == '2')
527 flow = 2;
528 else {
529 sr_dbg("invalid value for flow: %c", kv[1][0]);
530 speed = 0;
531 }
71caaad4
BV
532 }
533 g_strfreev(kv);
534 }
535 g_strfreev(opts);
536 }
537 }
538 g_free(mstr);
792fc686
BV
539 }
540 g_match_info_unref(match);
541 g_regex_unref(reg);
542
ea088bb6
AG
543 if (speed) {
544 return serial_set_params(serial, speed, databits, parity,
26ddb5ba 545 stopbits, flow, rts, dtr);
ea088bb6
AG
546 } else {
547 sr_dbg("Could not infer speed from parameter string.");
792fc686 548 return SR_ERR_ARG;
ea088bb6 549 }
792fc686
BV
550}
551
299bdb24
BV
552/**
553 * Read a line from the specified serial port.
554 *
555 * @param serial Previously initialized serial port structure.
556 * @param buf Buffer where to store the bytes that are read.
557 * @param buflen Size of the buffer.
04cb9157 558 * @param[in] timeout_ms How long to wait for a line to come in.
299bdb24
BV
559 *
560 * Reading stops when CR of LR is found, which is stripped from the buffer.
561 *
04cb9157
MH
562 * @retval SR_OK Success.
563 * @retval SR_ERR Failure.
299bdb24
BV
564 */
565SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
566 int *buflen, gint64 timeout_ms)
6f22a8ef 567{
bf505eed 568 gint64 start, remaining;
6f22a8ef
UH
569 int maxlen, len;
570
64ecf7ee 571 if (!serial) {
299bdb24
BV
572 sr_dbg("Invalid serial port.");
573 return SR_ERR;
574 }
575
64ecf7ee
ML
576 if (!serial->data) {
577 sr_dbg("Cannot use unopened serial port %s.", serial->port);
299bdb24
BV
578 return -1;
579 }
580
6f22a8ef 581 start = g_get_monotonic_time();
bf505eed 582 remaining = timeout_ms;
6f22a8ef
UH
583
584 maxlen = *buflen;
585 *buflen = len = 0;
586 while(1) {
587 len = maxlen - *buflen - 1;
588 if (len < 1)
589 break;
bf505eed 590 len = sp_blocking_read(serial->data, *buf + *buflen, 1, remaining);
6f22a8ef
UH
591 if (len > 0) {
592 *buflen += len;
593 *(*buf + *buflen) = '\0';
318dd53c
BV
594 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
595 || *(*buf + *buflen - 1) == '\n')) {
596 /* Strip CR/LF and terminate. */
6f22a8ef
UH
597 *(*buf + --*buflen) = '\0';
598 break;
599 }
600 }
bf505eed
ML
601 /* Reduce timeout by time elapsed. */
602 remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
603 if (remaining <= 0)
6f22a8ef
UH
604 /* Timeout */
605 break;
5715e84f
DT
606 if (len < 1)
607 g_usleep(2000);
6f22a8ef 608 }
318dd53c
BV
609 if (*buflen)
610 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
611
612 return SR_OK;
613}
766456be
UH
614
615/**
616 * Try to find a valid packet in a serial data stream.
617 *
618 * @param serial Previously initialized serial port structure.
619 * @param buf Buffer containing the bytes to write.
04cb9157
MH
620 * @param buflen Size of the buffer.
621 * @param[in] packet_size Size, in bytes, of a valid packet.
766456be 622 * @param is_valid Callback that assesses whether the packet is valid or not.
04cb9157 623 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
766456be 624 * abort scanning.
04cb9157 625 * @param[in] baudrate The baudrate of the serial port. This parameter is not
766456be
UH
626 * critical, but it helps fine tune the serial port polling
627 * delay.
628 *
d0a92abd 629 * @retval SR_OK Valid packet was found within the given timeout.
04cb9157 630 * @retval SR_ERR Failure.
766456be
UH
631 */
632SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
633 uint8_t *buf, size_t *buflen,
144f6660
UH
634 size_t packet_size,
635 packet_valid_callback is_valid,
766456be
UH
636 uint64_t timeout_ms, int baudrate)
637{
638 uint64_t start, time, byte_delay_us;
639 size_t ibuf, i, maxlen;
640 int len;
641
642 maxlen = *buflen;
643
64ecf7ee
ML
644 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
645 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
766456be
UH
646
647 if (maxlen < (packet_size / 2) ) {
648 sr_err("Buffer size must be at least twice the packet size.");
649 return SR_ERR;
650 }
651
766456be
UH
652 /* Assume 8n1 transmission. That is 10 bits for every byte. */
653 byte_delay_us = 10 * (1000000 / baudrate);
654 start = g_get_monotonic_time();
655
656 i = ibuf = len = 0;
657 while (ibuf < maxlen) {
18e4d5bc 658 len = serial_read_nonblocking(serial, &buf[ibuf], 1);
766456be
UH
659 if (len > 0) {
660 ibuf += len;
661 } else if (len == 0) {
006dbe55 662 /* No logging, already done in serial_read(). */
766456be
UH
663 } else {
664 /* Error reading byte, but continuing anyway. */
665 }
551c3d8c
AG
666
667 time = g_get_monotonic_time() - start;
668 time /= 1000;
669
766456be
UH
670 if ((ibuf - i) >= packet_size) {
671 /* We have at least a packet's worth of data. */
672 if (is_valid(&buf[i])) {
766456be
UH
673 sr_spew("Found valid %d-byte packet after "
674 "%" PRIu64 "ms.", (ibuf - i), time);
675 *buflen = ibuf;
676 return SR_OK;
677 } else {
678 sr_spew("Got %d bytes, but not a valid "
679 "packet.", (ibuf - i));
680 }
681 /* Not a valid packet. Continue searching. */
682 i++;
683 }
551c3d8c 684 if (time >= timeout_ms) {
766456be 685 /* Timeout */
551c3d8c 686 sr_dbg("Detection timed out after %dms.", time);
766456be
UH
687 break;
688 }
5715e84f
DT
689 if (len < 1)
690 g_usleep(byte_delay_us);
766456be
UH
691 }
692
693 *buflen = ibuf;
694
695 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
696
697 return SR_ERR;
698}
1bd9e678
DJ
699
700/**
701 * Extract the serial device and options from the options linked list.
702 *
703 * @param options List of options passed from the command line.
704 * @param serial_device Pointer where to store the exctracted serial device.
705 * @param serial_options Pointer where to store the optional extracted serial
706 * options.
707 *
708 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
709 * returned string should not be freed by the caller.
710 */
711SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
712 const char **serial_options)
713{
714 GSList *l;
715 struct sr_config *src;
716
717 *serial_device = NULL;
718
719 for (l = options; l; l = l->next) {
720 src = l->data;
721 switch (src->key) {
722 case SR_CONF_CONN:
723 *serial_device = g_variant_get_string(src->data, NULL);
b1a7ca3b 724 sr_dbg("Parsed serial device: %s.", *serial_device);
1bd9e678 725 break;
1bd9e678
DJ
726 case SR_CONF_SERIALCOMM:
727 *serial_options = g_variant_get_string(src->data, NULL);
b1a7ca3b 728 sr_dbg("Parsed serial options: %s.", *serial_options);
1bd9e678
DJ
729 break;
730 }
731 }
732
733 if (!*serial_device) {
b1a7ca3b 734 sr_dbg("No serial device specified.");
1bd9e678
DJ
735 return SR_ERR;
736 }
737
738 return SR_OK;
739}
abc4b335 740
a0a4c0fb 741#ifdef _WIN32
ba1949f5 742typedef HANDLE event_handle;
a0a4c0fb 743#else
ba1949f5 744typedef int event_handle;
a0a4c0fb 745#endif
ba1949f5 746
102f1239
BV
747SR_PRIV int serial_source_add(struct sr_session *session,
748 struct sr_serial_dev_inst *serial, int events, int timeout,
749 sr_receive_data_callback cb, void *cb_data)
ba1949f5
ML
750{
751 enum sp_event mask = 0;
752 unsigned int i;
753
754 if (sp_new_event_set(&serial->event_set) != SP_OK)
755 return SR_ERR;
756
757 if (events & G_IO_IN)
758 mask |= SP_EVENT_RX_READY;
759 if (events & G_IO_OUT)
760 mask |= SP_EVENT_TX_READY;
761 if (events & G_IO_ERR)
762 mask |= SP_EVENT_ERROR;
763
764 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
765 sp_free_event_set(serial->event_set);
766 return SR_ERR;
767 }
768
769 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
770
771 for (i = 0; i < serial->event_set->count; i++) {
772
773 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
774
775 mask = serial->event_set->masks[i];
776
777 if (mask & SP_EVENT_RX_READY)
778 serial->pollfds[i].events |= G_IO_IN;
779 if (mask & SP_EVENT_TX_READY)
780 serial->pollfds[i].events |= G_IO_OUT;
781 if (mask & SP_EVENT_ERROR)
782 serial->pollfds[i].events |= G_IO_ERR;
783
102f1239
BV
784 if (sr_session_source_add_pollfd(session, &serial->pollfds[i],
785 timeout, cb, cb_data) != SR_OK)
ba1949f5
ML
786 return SR_ERR;
787 }
788
789 return SR_OK;
abc4b335 790}
7faa3e88 791
102f1239
BV
792SR_PRIV int serial_source_remove(struct sr_session *session,
793 struct sr_serial_dev_inst *serial)
7faa3e88 794{
ba1949f5
ML
795 unsigned int i;
796
797 for (i = 0; i < serial->event_set->count; i++)
102f1239 798 if (sr_session_source_remove_pollfd(session, &serial->pollfds[i]) != SR_OK)
ba1949f5
ML
799 return SR_ERR;
800
801 g_free(serial->pollfds);
802 sp_free_event_set(serial->event_set);
803
804 serial->pollfds = NULL;
805 serial->event_set = NULL;
806
807 return SR_OK;
7faa3e88 808}
b541f837 809
b1a7ca3b
UH
810/**
811 * Create/allocate a new sr_serial_port structure.
812 *
813 * @param name The OS dependent name of the serial port. Must not be NULL.
814 * @param description An end user friendly description for the serial port.
815 * Can be NULL (in that case the empty string is used
816 * as description).
817 *
818 * @return The newly allocated sr_serial_port struct.
819 */
24287ea9
AJ
820static struct sr_serial_port *sr_serial_new(const char *name,
821 const char *description)
822{
823 struct sr_serial_port *serial;
824
825 if (!name)
826 return NULL;
827
b1a7ca3b 828 serial = g_malloc(sizeof(struct sr_serial_port));
24287ea9
AJ
829 serial->name = g_strdup(name);
830 serial->description = g_strdup(description ? description : "");
b1a7ca3b 831
24287ea9
AJ
832 return serial;
833}
834
b1a7ca3b
UH
835/**
836 * Free a previously allocated sr_serial_port structure.
837 *
838 * @param serial The sr_serial_port struct to free. Must not be NULL.
839 */
24287ea9
AJ
840SR_API void sr_serial_free(struct sr_serial_port *serial)
841{
b1a7ca3b 842 if (!serial)
24287ea9
AJ
843 return;
844 g_free(serial->name);
845 g_free(serial->description);
846 g_free(serial);
847}
848
849/**
850 * List available serial devices.
851 *
852 * @return A GSList of strings containing the path of the serial devices or
853 * NULL if no serial device is found. The returned list must be freed
854 * by the caller.
855 */
856SR_API GSList *sr_serial_list(const struct sr_dev_driver *driver)
857{
858 GSList *tty_devs = NULL;
859 struct sp_port **ports;
b1a7ca3b 860 struct sr_serial_port *port;
24287ea9
AJ
861 int i;
862
b1a7ca3b 863 /* Currently unused, but will be used by some drivers later on. */
24287ea9
AJ
864 (void)driver;
865
866 if (sp_list_ports(&ports) != SP_OK)
867 return NULL;
868
b1a7ca3b
UH
869 for (i = 0; ports[i]; i++) {
870 port = sr_serial_new(sp_get_port_name(ports[i]),
871 sp_get_port_description(ports[i]));
24287ea9
AJ
872 tty_devs = g_slist_append(tty_devs, port);
873 }
874
875 sp_free_port_list(ports);
b1a7ca3b 876
24287ea9
AJ
877 return tty_devs;
878}
879
b541f837
AJ
880/**
881 * Find USB serial devices via the USB vendor ID and product ID.
882 *
d0a92abd
MH
883 * @param[in] vendor_id Vendor ID of the USB device.
884 * @param[in] product_id Product ID of the USB device.
b541f837
AJ
885 *
886 * @return A GSList of strings containing the path of the serial device or
887 * NULL if no serial device is found. The returned list must be freed
888 * by the caller.
889 */
890SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
891{
01f6e330
AJ
892 GSList *tty_devs = NULL;
893 struct sp_port **ports;
894 int i, vid, pid;
b541f837 895
01f6e330
AJ
896 if (sp_list_ports(&ports) != SP_OK)
897 return NULL;
b541f837 898
b1a7ca3b 899 for (i = 0; ports[i]; i++)
01f6e330
AJ
900 if (sp_get_port_transport(ports[i]) == SP_TRANSPORT_USB &&
901 sp_get_port_usb_vid_pid(ports[i], &vid, &pid) == SP_OK &&
b1a7ca3b 902 vid == vendor_id && pid == product_id) {
01f6e330 903 tty_devs = g_slist_prepend(tty_devs,
b1a7ca3b
UH
904 g_strdup(sp_get_port_name(ports[i])));
905 }
b541f837 906
01f6e330 907 sp_free_port_list(ports);
b1a7ca3b 908
b541f837 909 return tty_devs;
b541f837 910}
c5cfc735
BV
911
912SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
913{
914 struct sp_port_config *config;
915 int timeout_ms, bits, baud, tmp;
916
917 /* Default to 1s. */
918 timeout_ms = 1000;
919
920 if (sp_new_config(&config) < 0)
921 return timeout_ms;
922
923 bits = baud = 0;
924 do {
925 if (sp_get_config(port->data, config) < 0)
926 break;
927
928 /* Start bit. */
929 bits = 1;
930 if (sp_get_config_bits(config, &tmp) < 0)
931 break;
932 bits += tmp;
933 if (sp_get_config_stopbits(config, &tmp) < 0)
934 break;
935 bits += tmp;
936 if (sp_get_config_baudrate(config, &tmp) < 0)
937 break;
938 baud = tmp;
939 } while (FALSE);
940
941 if (bits && baud) {
942 /* Throw in 10ms for misc OS overhead. */
943 timeout_ms = 10;
944 timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
945 }
946
947 sp_free_config(config);
948
949 return timeout_ms;
950}