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