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