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