]> sigrok.org Git - libsigrok.git/blame - hardware/common/serial.c
serial: Use OS-independent flags for serial port opening.
[libsigrok.git] / hardware / common / serial.c
CommitLineData
a1bb33af
UH
1/*
2 * This file is part of the sigrok project.
3 *
c73d2ea4 4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
b19f4622 5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
766456be 6 * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
a1bb33af
UH
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
54b38f64 22#include <string.h>
d02a535e
BV
23#include <sys/types.h>
24#include <sys/stat.h>
25#include <fcntl.h>
26#include <unistd.h>
926b866c 27#ifdef _WIN32
a9f54bcd 28#include <windows.h>
926b866c
UH
29#else
30#include <glob.h>
d02a535e 31#include <termios.h>
0f84cda0 32#include <sys/ioctl.h>
926b866c 33#endif
d02a535e 34#include <stdlib.h>
b19f4622 35#include <errno.h>
a1bb33af 36#include <glib.h>
45c59c8b
BV
37#include "libsigrok.h"
38#include "libsigrok-internal.h"
a1bb33af 39
b19f4622
UH
40/* Message logging helpers with driver-specific prefix string. */
41#define DRIVER_LOG_DOMAIN "serial: "
42#define sr_log(l, s, args...) sr_log(l, DRIVER_LOG_DOMAIN s, ## args)
43#define sr_spew(s, args...) sr_spew(DRIVER_LOG_DOMAIN s, ## args)
44#define sr_dbg(s, args...) sr_dbg(DRIVER_LOG_DOMAIN s, ## args)
45#define sr_info(s, args...) sr_info(DRIVER_LOG_DOMAIN s, ## args)
46#define sr_warn(s, args...) sr_warn(DRIVER_LOG_DOMAIN s, ## args)
47#define sr_err(s, args...) sr_err(DRIVER_LOG_DOMAIN s, ## args)
48
926b866c
UH
49// FIXME: Must be moved, or rather passed as function argument.
50#ifdef _WIN32
a0ecd83b 51static HANDLE hdl;
926b866c
UH
52#endif
53
b19f4622
UH
54/**
55 * Open the specified serial port.
56 *
299bdb24 57 * @param serial Previously initialized serial port structure.
a54dd31e
UH
58 * @param flags Flags to use when opening the serial port. Possible flags
59 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
b19f4622 60 *
299bdb24
BV
61 * If the serial structure contains a serialcomm string, it will be
62 * passed to serial_set_paramstr() after the port is opened.
63 *
64 * @return SR_OK on success, SR_ERR on failure.
b19f4622 65 */
299bdb24 66SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
d02a535e 67{
a54dd31e
UH
68 int flags_local = 0;
69#ifdef _WIN32
70 DWORD desired_access = 0, flags_and_attributes = 0;
71#endif
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
926b866c 80#ifdef _WIN32
a54dd31e
UH
81 /* Map 'flags' to the OS-specific settings. */
82 desired_access |= GENERIC_READ;
83 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
84 if (flags & SERIAL_RDWR)
85 desired_access |= GENERIC_WRITE;
86 if (flags & SERIAL_NONBLOCK)
87 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
88
89 hdl = CreateFile(serial->port, desired_access, 0, 0,
90 OPEN_EXISTING, flags_and_attributes, 0);
926b866c 91 if (hdl == INVALID_HANDLE_VALUE) {
299bdb24
BV
92 sr_err("Error opening serial port '%s'.", serial->port);
93 return SR_ERR;
926b866c 94 }
926b866c 95#else
a54dd31e
UH
96 /* Map 'flags' to the OS-specific settings. */
97 if (flags & SERIAL_RDWR)
98 flags_local |= O_RDWR;
99 if (flags & SERIAL_RDONLY)
100 flags_local |= O_RDONLY;
101 if (flags & SERIAL_NONBLOCK)
102 flags_local |= O_NONBLOCK;
103
104 if ((serial->fd = open(serial->port, flags_local)) < 0) {
299bdb24 105 sr_err("Error opening serial port '%s': %s.", serial->port,
b19f4622 106 strerror(errno));
299bdb24 107 return SR_ERR;
a54dd31e
UH
108 }
109
110 sr_spew("Opened serial port '%s' (fd %d).", serial->port, serial->fd);
926b866c 111#endif
299bdb24
BV
112
113 if (serial->serialcomm)
114 return serial_set_paramstr(serial, serial->serialcomm);
115 else
116 return SR_OK;
d02a535e
BV
117}
118
b19f4622
UH
119/**
120 * Close the specified serial port.
121 *
299bdb24 122 * @param serial Previously initialized serial port structure.
b19f4622 123 *
299bdb24 124 * @return SR_OK on success, SR_ERR on failure.
2119ab03 125 */
299bdb24 126SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
d02a535e 127{
299bdb24
BV
128 int ret;
129
130 if (!serial) {
131 sr_dbg("Invalid serial port.");
132 return SR_ERR;
133 }
134
135 if (serial->fd == -1) {
136 sr_dbg("Cannot close unopened serial port %s (fd %d).",
137 serial->port, serial->fd);
138 return SR_ERR;
139 }
140
141 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
142 ret = SR_OK;
b19f4622 143
926b866c 144#ifdef _WIN32
2119ab03 145 /* Returns non-zero upon success, 0 upon failure. */
299bdb24
BV
146 if (CloseHandle(hdl) == 0)
147 ret = SR_ERR;
926b866c 148#else
2119ab03 149 /* Returns 0 upon success, -1 upon failure. */
299bdb24
BV
150 if (close(serial->fd) < 0) {
151 sr_err("Error closing serial port: %s (fd %d).", strerror(errno),
152 serial->fd);
153 ret = SR_ERR;
b19f4622 154 }
299bdb24
BV
155#endif
156
157 serial->fd = -1;
b19f4622
UH
158
159 return ret;
d02a535e
BV
160}
161
b19f4622 162/**
299bdb24 163 * Flush serial port buffers.
b19f4622 164 *
299bdb24 165 * @param serial Previously initialized serial port structure.
b19f4622 166 *
299bdb24 167 * @return SR_OK on success, SR_ERR on failure.
1fdb75e1 168 */
299bdb24 169SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
06d64eb8 170{
299bdb24
BV
171 int ret;
172
173 if (!serial) {
174 sr_dbg("Invalid serial port.");
175 return SR_ERR;
176 }
177
178 if (serial->fd == -1) {
179 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
180 serial->port, serial->fd);
181 return SR_ERR;
182 }
183
184 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
185 ret = SR_OK;
b19f4622 186
1fdb75e1
UH
187#ifdef _WIN32
188 /* Returns non-zero upon success, 0 upon failure. */
4da1a800 189 if (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) {
299bdb24
BV
190 sr_err("Error flushing serial port: %s.", strerror(errno));
191 ret = SR_ERR;
192 }
1fdb75e1
UH
193#else
194 /* Returns 0 upon success, -1 upon failure. */
299bdb24 195 if (tcflush(serial->fd, TCIOFLUSH) < 0) {
b19f4622 196 sr_err("Error flushing serial port: %s.", strerror(errno));
299bdb24
BV
197 ret = SR_ERR;
198 }
b19f4622
UH
199
200 return ret;
1fdb75e1 201#endif
06d64eb8
BV
202}
203
b19f4622 204/**
2119ab03 205 * Write a number of bytes to the specified serial port.
b19f4622 206 *
299bdb24 207 * @param serial Previously initialized serial port structure.
b19f4622
UH
208 * @param buf Buffer containing the bytes to write.
209 * @param count Number of bytes to write.
210 *
211 * @return The number of bytes written, or -1 upon failure.
2119ab03 212 */
299bdb24
BV
213SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
214 const void *buf, size_t count)
2119ab03 215{
299bdb24
BV
216 ssize_t ret;
217
218 if (!serial) {
219 sr_dbg("Invalid serial port.");
220 return -1;
221 }
222
223 if (serial->fd == -1) {
224 sr_dbg("Cannot use unopened serial port %s (fd %d).",
225 serial->port, serial->fd);
226 return -1;
227 }
228
2119ab03
UH
229#ifdef _WIN32
230 DWORD tmp = 0;
231
232 /* FIXME */
233 /* Returns non-zero upon success, 0 upon failure. */
234 WriteFile(hdl, buf, count, &tmp, NULL);
235#else
236 /* Returns the number of bytes written, or -1 upon failure. */
299bdb24 237 ret = write(serial->fd, buf, count);
b19f4622 238 if (ret < 0)
299bdb24 239 sr_err("Write error: %s.", strerror(errno));
302c4b5a 240 else
299bdb24
BV
241 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
242#endif
b19f4622
UH
243
244 return ret;
2119ab03
UH
245}
246
b19f4622 247/**
2119ab03 248 * Read a number of bytes from the specified serial port.
b19f4622 249 *
299bdb24 250 * @param serial Previously initialized serial port structure.
b19f4622
UH
251 * @param buf Buffer where to store the bytes that are read.
252 * @param count The number of bytes to read.
253 *
254 * @return The number of bytes read, or -1 upon failure.
2119ab03 255 */
299bdb24
BV
256SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
257 size_t count)
2119ab03 258{
299bdb24
BV
259 ssize_t ret;
260
261 if (!serial) {
262 sr_dbg("Invalid serial port.");
263 return -1;
264 }
265
266 if (serial->fd == -1) {
267 sr_dbg("Cannot use unopened serial port %s (fd %d).",
268 serial->port, serial->fd);
269 return -1;
270 }
271
2119ab03
UH
272#ifdef _WIN32
273 DWORD tmp = 0;
274
275 /* FIXME */
276 /* Returns non-zero upon success, 0 upon failure. */
277 return ReadFile(hdl, buf, count, &tmp, NULL);
278#else
279 /* Returns the number of bytes read, or -1 upon failure. */
299bdb24
BV
280 ret = read(serial->fd, buf, count);
281 if (ret < 0)
b19f4622
UH
282 /*
283 * Should be sr_err(), but that would yield lots of
284 * "Resource temporarily unavailable" messages.
285 */
299bdb24
BV
286 sr_spew("Read error: %s (fd %d).", strerror(errno), serial->fd);
287 else
288 sr_spew("Read %d/%d bytes (fd %d).", ret, count, serial->fd);
289#endif
b19f4622
UH
290
291 return ret;
2119ab03
UH
292}
293
b19f4622
UH
294/**
295 * Set serial parameters for the specified serial port.
296 *
299bdb24 297 * @param serial Previously initialized serial port structure.
b19f4622
UH
298 * @param baudrate The baudrate to set.
299 * @param bits The number of data bits to use.
300 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
301 * @param stopbits The number of stop bits to use (1 or 2).
302 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
303 * 2 = XON/XOFF).
2119ab03 304 *
b19f4622 305 * @return SR_OK upon success, SR_ERR upon failure.
1ff7712c 306 */
299bdb24 307SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
71caaad4 308 int bits, int parity, int stopbits, int flowcontrol, int rts, int dtr)
d02a535e 309{
299bdb24
BV
310 if (!serial) {
311 sr_dbg("Invalid serial port.");
312 return SR_ERR;
313 }
314
315 if (serial->fd == -1) {
316 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
317 serial->port, serial->fd);
318 return SR_ERR;
319 }
320
321 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
322 serial->fd);
b19f4622 323
926b866c
UH
324#ifdef _WIN32
325 DCB dcb;
326
299bdb24 327 if (!GetCommState(hdl, &dcb))
e46b8fb1 328 return SR_ERR;
926b866c 329
0abee507 330 switch (baudrate) {
926b866c
UH
331 case 115200:
332 dcb.BaudRate = CBR_115200;
333 break;
334 case 57600:
335 dcb.BaudRate = CBR_57600;
336 break;
337 case 38400:
338 dcb.BaudRate = CBR_38400;
339 break;
340 case 19200:
341 dcb.BaudRate = CBR_19200;
342 break;
343 case 9600:
344 dcb.BaudRate = CBR_9600;
345 break;
e8e9dcdd
AG
346 case 4800:
347 dcb.BaudRate = CBR_4800;
348 break;
0f708301
AG
349 case 2400:
350 dcb.BaudRate = CBR_2400;
351 break;
926b866c 352 default:
299bdb24 353 sr_err("Unsupported baudrate %d.", baudrate);
b19f4622 354 return SR_ERR;
926b866c
UH
355 }
356 dcb.ByteSize = bits;
357 dcb.Parity = NOPARITY; /* TODO: Don't hardcode. */
358 dcb.StopBits = ONESTOPBIT; /* TODO: Don't hardcode. */
359
299bdb24 360 if (!SetCommState(hdl, &dcb))
e46b8fb1 361 return SR_ERR;
926b866c 362#else
d02a535e 363 struct termios term;
1ff7712c 364 speed_t baud;
700dcd5c 365 int ret, controlbits;
d02a535e 366
299bdb24
BV
367 if (tcgetattr(serial->fd, &term) < 0) {
368 sr_err("tcgetattr() error on port %s (fd %d): %s.",
369 serial->port, serial->fd, strerror(errno));
6a6e23ab 370 return SR_ERR;
b19f4622 371 }
6a6e23ab 372
0abee507 373 switch (baudrate) {
b19f4622
UH
374 case 50:
375 baud = B50;
376 break;
377 case 75:
378 baud = B75;
379 break;
380 case 110:
381 baud = B110;
382 break;
383 case 134:
384 baud = B134;
385 break;
386 case 150:
387 baud = B150;
388 break;
389 case 200:
390 baud = B200;
391 break;
392 case 300:
393 baud = B300;
394 break;
395 case 600:
396 baud = B600;
397 break;
398 case 1200:
399 baud = B1200;
400 break;
401 case 1800:
402 baud = B1800;
403 break;
0f708301
AG
404 case 2400:
405 baud = B2400;
406 break;
e8e9dcdd
AG
407 case 4800:
408 baud = B4800;
409 break;
1ff7712c
DR
410 case 9600:
411 baud = B9600;
412 break;
b19f4622
UH
413 case 19200:
414 baud = B19200;
415 break;
1ff7712c
DR
416 case 38400:
417 baud = B38400;
418 break;
419 case 57600:
420 baud = B57600;
421 break;
422 case 115200:
423 baud = B115200;
424 break;
b19f4622
UH
425 case 230400:
426 baud = B230400;
427 break;
9a751023 428#ifndef __APPLE__
1ff7712c
DR
429 case 460800:
430 baud = B460800;
431 break;
9a751023 432#endif
1ff7712c 433 default:
299bdb24 434 sr_err("Unsupported baudrate %d.", baudrate);
e46b8fb1 435 return SR_ERR;
1ff7712c 436 }
b19f4622 437
299bdb24 438 sr_spew("Configuring output baudrate to %d (%d).", baudrate, baud);
b19f4622 439 if (cfsetospeed(&term, baud) < 0) {
5df7b201 440 sr_err("cfsetospeed() error: %s.", strerror(errno));
e46b8fb1 441 return SR_ERR;
b19f4622
UH
442 }
443
299bdb24 444 sr_spew("Configuring input baudrate to %d (%d).", baudrate, baud);
b19f4622 445 if (cfsetispeed(&term, baud) < 0) {
5df7b201 446 sr_err("cfsetispeed() error: %s.", strerror(errno));
e46b8fb1 447 return SR_ERR;
b19f4622 448 }
1ff7712c 449
299bdb24 450 sr_spew("Configuring %d data bits.", bits);
d02a535e 451 term.c_cflag &= ~CSIZE;
1ff7712c
DR
452 switch (bits) {
453 case 8:
454 term.c_cflag |= CS8;
455 break;
456 case 7:
457 term.c_cflag |= CS7;
458 break;
459 default:
299bdb24 460 sr_err("Unsupported data bits number %d.", bits);
e46b8fb1 461 return SR_ERR;
1ff7712c
DR
462 }
463
299bdb24 464 sr_spew("Configuring %d stop bits.", stopbits);
d02a535e 465 term.c_cflag &= ~CSTOPB;
1ff7712c
DR
466 switch (stopbits) {
467 case 1:
299bdb24 468 term.c_cflag &= ~CSTOPB;
1ff7712c
DR
469 break;
470 case 2:
471 term.c_cflag |= CSTOPB;
d7c776b9 472 break;
1ff7712c 473 default:
299bdb24 474 sr_err("Unsupported stopbits number %d.", stopbits);
e46b8fb1 475 return SR_ERR;
1ff7712c
DR
476 }
477
f38b9763
BV
478 term.c_iflag &= ~(IXON | IXOFF);
479 term.c_cflag &= ~CRTSCTS;
1ff7712c 480 switch (flowcontrol) {
f38b9763
BV
481 case 0:
482 /* No flow control. */
299bdb24 483 sr_spew("Configuring no flow control.");
1ff7712c
DR
484 break;
485 case 1:
299bdb24 486 sr_spew("Configuring RTS/CTS flow control.");
1ff7712c 487 term.c_cflag |= CRTSCTS;
d7c776b9 488 break;
f38b9763 489 case 2:
299bdb24 490 sr_spew("Configuring XON/XOFF flow control.");
f38b9763
BV
491 term.c_iflag |= IXON | IXOFF;
492 break;
1ff7712c 493 default:
299bdb24 494 sr_err("Unsupported flow control setting %d.", flowcontrol);
e46b8fb1 495 return SR_ERR;
1ff7712c
DR
496 }
497
ac4a2ea4
DR
498 term.c_iflag &= ~IGNPAR;
499 term.c_cflag &= ~(PARODD | PARENB);
1ff7712c 500 switch (parity) {
f8c1fcda 501 case SERIAL_PARITY_NONE:
299bdb24 502 sr_spew("Configuring no parity.");
1ff7712c
DR
503 term.c_iflag |= IGNPAR;
504 break;
f8c1fcda 505 case SERIAL_PARITY_EVEN:
299bdb24 506 sr_spew("Configuring even parity.");
ac4a2ea4 507 term.c_cflag |= PARENB;
1ff7712c 508 break;
f8c1fcda 509 case SERIAL_PARITY_ODD:
299bdb24 510 sr_spew("Configuring odd parity.");
ac4a2ea4 511 term.c_cflag |= PARENB | PARODD;
1ff7712c
DR
512 break;
513 default:
299bdb24 514 sr_err("Unsupported parity setting %d.", parity);
e46b8fb1 515 return SR_ERR;
1ff7712c
DR
516 }
517
299bdb24 518 /* Do not translate carriage return to newline on input. */
fb9d3bf9 519 term.c_iflag &= ~(ICRNL);
b19f4622
UH
520
521 /* Disable canonical mode, and don't echo input characters. */
5c51e098
BV
522 term.c_lflag &= ~(ICANON | ECHO);
523
b19f4622 524 /* Write the configured settings. */
299bdb24
BV
525 if (tcsetattr(serial->fd, TCSADRAIN, &term) < 0) {
526 sr_err("tcsetattr() error: %s.", strerror(errno));
e46b8fb1 527 return SR_ERR;
b19f4622 528 }
700dcd5c 529
71caaad4
BV
530 if (rts != -1) {
531 sr_spew("Setting RTS %s.", rts ? "high" : "low");
532 controlbits = TIOCM_RTS;
533 if ((ret = ioctl(serial->fd, rts ? TIOCMBIS : TIOCMBIC,
534 &controlbits)) < 0) {
535 sr_err("Error setting RTS: %s.", strerror(errno));
536 return SR_ERR;
537 }
700dcd5c
UH
538 }
539
71caaad4
BV
540 if (dtr != -1) {
541 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
542 controlbits = TIOCM_DTR;
543 if ((ret = ioctl(serial->fd, dtr ? TIOCMBIS : TIOCMBIC,
544 &controlbits)) < 0) {
545 sr_err("Error setting DTR: %s.", strerror(errno));
546 return SR_ERR;
547 }
700dcd5c 548 }
700dcd5c 549
926b866c 550#endif
d02a535e 551
e46b8fb1 552 return SR_OK;
d02a535e 553}
792fc686 554
299bdb24
BV
555/**
556 * Set serial parameters for the specified serial port.
557 *
558 * @param serial Previously initialized serial port structure.
559 * @param paramstr A serial communication parameters string, in the form
560 * of <speed>/<data bits><parity><stopbits>, for example "9600/8n1" or
561 * "600/7o2".
562 *
563 * @return SR_OK upon success, SR_ERR upon failure.
564 */
71caaad4 565#define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
299bdb24
BV
566SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
567 const char *paramstr)
792fc686
BV
568{
569 GRegex *reg;
570 GMatchInfo *match;
71caaad4
BV
571 int speed, databits, parity, stopbits, rts, dtr, i;
572 char *mstr, **opts, **kv;
792fc686
BV
573
574 speed = databits = parity = stopbits = 0;
71caaad4 575 rts = dtr = -1;
792fc686
BV
576 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
577 if (g_regex_match(reg, paramstr, 0, &match)) {
578 if ((mstr = g_match_info_fetch(match, 1)))
579 speed = strtoul(mstr, NULL, 10);
580 g_free(mstr);
581 if ((mstr = g_match_info_fetch(match, 2)))
582 databits = strtoul(mstr, NULL, 10);
583 g_free(mstr);
584 if ((mstr = g_match_info_fetch(match, 3))) {
585 switch (mstr[0]) {
586 case 'n':
587 parity = SERIAL_PARITY_NONE;
588 break;
589 case 'e':
590 parity = SERIAL_PARITY_EVEN;
591 break;
592 case 'o':
593 parity = SERIAL_PARITY_ODD;
594 break;
595 }
596 }
597 g_free(mstr);
598 if ((mstr = g_match_info_fetch(match, 4)))
599 stopbits = strtoul(mstr, NULL, 10);
600 g_free(mstr);
71caaad4
BV
601 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
602 if (mstr[0] != '/') {
603 sr_dbg("missing separator before extra options");
604 speed = 0;
605 } else {
606 /* A set of "key=value" options separated by / */
607 opts = g_strsplit(mstr + 1, "/", 0);
608 for (i = 0; opts[i]; i++) {
609 kv = g_strsplit(opts[i], "=", 2);
610 if (!strncmp(kv[0], "rts", 3)) {
611 if (kv[1][0] == '1')
612 rts = 1;
613 else if (kv[1][0] == '0')
614 rts = 0;
615 else {
616 sr_dbg("invalid value for rts: %c", kv[1][0]);
617 speed = 0;
618 }
619 } else if (!strncmp(kv[0], "dtr", 3)) {
620 if (kv[1][0] == '1')
621 dtr = 1;
622 else if (kv[1][0] == '0')
623 dtr = 0;
624 else {
625 sr_dbg("invalid value for dtr: %c", kv[1][0]);
626 speed = 0;
627 }
628 }
629 g_strfreev(kv);
630 }
631 g_strfreev(opts);
632 }
633 }
634 g_free(mstr);
792fc686
BV
635 }
636 g_match_info_unref(match);
637 g_regex_unref(reg);
638
639 if (speed)
71caaad4
BV
640 return serial_set_params(serial, speed, databits, parity, stopbits,
641 0, rts, dtr);
792fc686
BV
642 else
643 return SR_ERR_ARG;
644}
645
299bdb24
BV
646/**
647 * Read a line from the specified serial port.
648 *
649 * @param serial Previously initialized serial port structure.
650 * @param buf Buffer where to store the bytes that are read.
651 * @param buflen Size of the buffer.
652 * @param timeout_ms How long to wait for a line to come in.
653 *
654 * Reading stops when CR of LR is found, which is stripped from the buffer.
655 *
656 * @return SR_OK on success, SR_ERR on failure.
657 */
658SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
659 int *buflen, gint64 timeout_ms)
6f22a8ef 660{
b87f8504 661 gint64 start;
6f22a8ef
UH
662 int maxlen, len;
663
299bdb24
BV
664 if (!serial || serial->fd == -1) {
665 sr_dbg("Invalid serial port.");
666 return SR_ERR;
667 }
668
669 if (serial->fd == -1) {
670 sr_dbg("Cannot use unopened serial port %s (fd %d).",
671 serial->port, serial->fd);
672 return -1;
673 }
674
6f22a8ef
UH
675 timeout_ms *= 1000;
676 start = g_get_monotonic_time();
677
678 maxlen = *buflen;
679 *buflen = len = 0;
680 while(1) {
681 len = maxlen - *buflen - 1;
682 if (len < 1)
683 break;
299bdb24 684 len = serial_read(serial, *buf + *buflen, 1);
6f22a8ef
UH
685 if (len > 0) {
686 *buflen += len;
687 *(*buf + *buflen) = '\0';
318dd53c
BV
688 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
689 || *(*buf + *buflen - 1) == '\n')) {
690 /* Strip CR/LF and terminate. */
6f22a8ef
UH
691 *(*buf + --*buflen) = '\0';
692 break;
693 }
694 }
695 if (g_get_monotonic_time() - start > timeout_ms)
696 /* Timeout */
697 break;
698 g_usleep(2000);
699 }
318dd53c
BV
700 if (*buflen)
701 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
702
703 return SR_OK;
704}
766456be
UH
705
706/**
707 * Try to find a valid packet in a serial data stream.
708 *
709 * @param serial Previously initialized serial port structure.
710 * @param buf Buffer containing the bytes to write.
711 * @param count Size of the buffer.
712 * @param packet_size Size, in bytes, of a valid packet.
713 * @param is_valid Callback that assesses whether the packet is valid or not.
714 * @param timeout_ms The timeout after which, if no packet is detected, to
715 * abort scanning.
716 * @param baudrate The baudrate of the serial port. This parameter is not
717 * critical, but it helps fine tune the serial port polling
718 * delay.
719 *
720 * @return SR_OK if a valid packet is found within the given timeout,
721 * SR_ERR upon failure.
722 */
723SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
724 uint8_t *buf, size_t *buflen,
725 size_t packet_size, packet_valid_t is_valid,
726 uint64_t timeout_ms, int baudrate)
727{
728 uint64_t start, time, byte_delay_us;
729 size_t ibuf, i, maxlen;
730 int len;
731
732 maxlen = *buflen;
733
734 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
735 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
736
737 if (maxlen < (packet_size / 2) ) {
738 sr_err("Buffer size must be at least twice the packet size.");
739 return SR_ERR;
740 }
741
766456be
UH
742 /* Assume 8n1 transmission. That is 10 bits for every byte. */
743 byte_delay_us = 10 * (1000000 / baudrate);
744 start = g_get_monotonic_time();
745
746 i = ibuf = len = 0;
747 while (ibuf < maxlen) {
748 len = serial_read(serial, &buf[ibuf], 1);
749 if (len > 0) {
750 ibuf += len;
751 } else if (len == 0) {
752 sr_spew("Error: Only read 0 bytes.");
753 } else {
754 /* Error reading byte, but continuing anyway. */
755 }
551c3d8c
AG
756
757 time = g_get_monotonic_time() - start;
758 time /= 1000;
759
766456be
UH
760 if ((ibuf - i) >= packet_size) {
761 /* We have at least a packet's worth of data. */
762 if (is_valid(&buf[i])) {
766456be
UH
763 sr_spew("Found valid %d-byte packet after "
764 "%" PRIu64 "ms.", (ibuf - i), time);
765 *buflen = ibuf;
766 return SR_OK;
767 } else {
768 sr_spew("Got %d bytes, but not a valid "
769 "packet.", (ibuf - i));
770 }
771 /* Not a valid packet. Continue searching. */
772 i++;
773 }
551c3d8c 774 if (time >= timeout_ms) {
766456be 775 /* Timeout */
551c3d8c 776 sr_dbg("Detection timed out after %dms.", time);
766456be
UH
777 break;
778 }
779 g_usleep(byte_delay_us);
780 }
781
782 *buflen = ibuf;
783
784 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
785
786 return SR_ERR;
787}