]> sigrok.org Git - libsigrok.git/blame - hardware/common/serial.c
serial-dmm: Use sr_dev_inst to store connection handle.
[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 280 ret = read(serial->fd, buf, count);
299bdb24 281#endif
b19f4622
UH
282
283 return ret;
2119ab03
UH
284}
285
b19f4622
UH
286/**
287 * Set serial parameters for the specified serial port.
288 *
299bdb24 289 * @param serial Previously initialized serial port structure.
b19f4622
UH
290 * @param baudrate The baudrate to set.
291 * @param bits The number of data bits to use.
292 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
293 * @param stopbits The number of stop bits to use (1 or 2).
294 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
295 * 2 = XON/XOFF).
2119ab03 296 *
b19f4622 297 * @return SR_OK upon success, SR_ERR upon failure.
1ff7712c 298 */
299bdb24 299SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
39e5d798
UH
300 int bits, int parity, int stopbits,
301 int flowcontrol, int rts, int dtr)
d02a535e 302{
299bdb24
BV
303 if (!serial) {
304 sr_dbg("Invalid serial port.");
305 return SR_ERR;
306 }
307
308 if (serial->fd == -1) {
309 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
39e5d798 310 serial->port, serial->fd);
299bdb24
BV
311 return SR_ERR;
312 }
313
314 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
39e5d798 315 serial->fd);
b19f4622 316
926b866c
UH
317#ifdef _WIN32
318 DCB dcb;
319
5ddb0cc7
UH
320 if (!GetCommState(hdl, &dcb)) {
321 sr_err("Failed to get comm state on port %s (fd %d): %d.",
322 serial->port, serial->fd, GetLastError());
e46b8fb1 323 return SR_ERR;
5ddb0cc7 324 }
926b866c 325
0abee507 326 switch (baudrate) {
5ae35c29
UH
327 /*
328 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
329 * have documented CBR_* macros.
330 */
331 case 110:
332 dcb.BaudRate = CBR_110;
926b866c 333 break;
5ae35c29
UH
334 case 300:
335 dcb.BaudRate = CBR_300;
926b866c 336 break;
5ae35c29
UH
337 case 600:
338 dcb.BaudRate = CBR_600;
926b866c 339 break;
5ae35c29
UH
340 case 1200:
341 dcb.BaudRate = CBR_1200;
926b866c 342 break;
5ae35c29
UH
343 case 2400:
344 dcb.BaudRate = CBR_2400;
926b866c 345 break;
e8e9dcdd
AG
346 case 4800:
347 dcb.BaudRate = CBR_4800;
348 break;
5ae35c29
UH
349 case 9600:
350 dcb.BaudRate = CBR_9600;
351 break;
352 case 14400:
353 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
354 break;
355 case 19200:
356 dcb.BaudRate = CBR_19200;
357 break;
358 case 38400:
359 dcb.BaudRate = CBR_38400;
360 break;
361 case 57600:
362 dcb.BaudRate = CBR_57600;
363 break;
364 case 115200:
365 dcb.BaudRate = CBR_115200;
366 break;
367 case 128000:
368 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
369 break;
370 case 256000:
371 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
0f708301 372 break;
926b866c 373 default:
5ae35c29 374 sr_err("Unsupported baudrate: %d.", baudrate);
b19f4622 375 return SR_ERR;
926b866c 376 }
5ae35c29
UH
377 sr_spew("Configuring baudrate to %d (%d).", baudrate, dcb.BaudRate);
378
5ddb0cc7 379 sr_spew("Configuring %d data bits.", bits);
926b866c 380 dcb.ByteSize = bits;
5ddb0cc7
UH
381
382 sr_spew("Configuring %d stop bits.", stopbits);
383 switch (stopbits) {
384 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
385 case 1:
386 dcb.StopBits = ONESTOPBIT;
387 break;
388 case 2:
389 dcb.StopBits = TWOSTOPBITS;
390 break;
391 default:
392 sr_err("Unsupported stopbits number: %d.", stopbits);
393 return SR_ERR;
394 }
395
396 switch (parity) {
397 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
398 case SERIAL_PARITY_NONE:
399 sr_spew("Configuring no parity.");
400 dcb.Parity = NOPARITY;
401 break;
402 case SERIAL_PARITY_EVEN:
403 sr_spew("Configuring even parity.");
404 dcb.Parity = EVENPARITY;
405 break;
406 case SERIAL_PARITY_ODD:
407 sr_spew("Configuring odd parity.");
408 dcb.Parity = ODDPARITY;
409 break;
410 default:
411 sr_err("Unsupported parity setting: %d.", parity);
412 return SR_ERR;
413 }
926b866c 414
39e5d798
UH
415 if (rts != -1) {
416 sr_spew("Setting RTS %s.", rts ? "high" : "low");
417 if (rts)
418 dcb.fRtsControl = RTS_CONTROL_ENABLE;
419 else
420 dcb.fRtsControl = RTS_CONTROL_DISABLE;
421 }
422
423 if (dtr != -1) {
424 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
86c02e65 425 if (dtr)
39e5d798
UH
426 dcb.fDtrControl = DTR_CONTROL_ENABLE;
427 else
428 dcb.fDtrControl = DTR_CONTROL_DISABLE;
429 }
430
5ddb0cc7
UH
431 if (!SetCommState(hdl, &dcb)) {
432 sr_err("Failed to set comm state on port %s (fd %d): %d.",
433 serial->port, serial->fd, GetLastError());
e46b8fb1 434 return SR_ERR;
5ddb0cc7 435 }
926b866c 436#else
d02a535e 437 struct termios term;
1ff7712c 438 speed_t baud;
700dcd5c 439 int ret, controlbits;
d02a535e 440
299bdb24
BV
441 if (tcgetattr(serial->fd, &term) < 0) {
442 sr_err("tcgetattr() error on port %s (fd %d): %s.",
443 serial->port, serial->fd, strerror(errno));
6a6e23ab 444 return SR_ERR;
b19f4622 445 }
6a6e23ab 446
0abee507 447 switch (baudrate) {
b19f4622
UH
448 case 50:
449 baud = B50;
450 break;
451 case 75:
452 baud = B75;
453 break;
454 case 110:
455 baud = B110;
456 break;
457 case 134:
458 baud = B134;
459 break;
460 case 150:
461 baud = B150;
462 break;
463 case 200:
464 baud = B200;
465 break;
466 case 300:
467 baud = B300;
468 break;
469 case 600:
470 baud = B600;
471 break;
472 case 1200:
473 baud = B1200;
474 break;
475 case 1800:
476 baud = B1800;
477 break;
0f708301
AG
478 case 2400:
479 baud = B2400;
480 break;
e8e9dcdd
AG
481 case 4800:
482 baud = B4800;
483 break;
1ff7712c
DR
484 case 9600:
485 baud = B9600;
486 break;
b19f4622
UH
487 case 19200:
488 baud = B19200;
489 break;
1ff7712c
DR
490 case 38400:
491 baud = B38400;
492 break;
493 case 57600:
494 baud = B57600;
495 break;
496 case 115200:
497 baud = B115200;
498 break;
b19f4622
UH
499 case 230400:
500 baud = B230400;
501 break;
b97cbca6 502#if !defined(__APPLE__) && !defined(__OpenBSD__)
1ff7712c
DR
503 case 460800:
504 baud = B460800;
505 break;
9a751023 506#endif
1ff7712c 507 default:
5ae35c29 508 sr_err("Unsupported baudrate: %d.", baudrate);
e46b8fb1 509 return SR_ERR;
1ff7712c 510 }
b19f4622 511
299bdb24 512 sr_spew("Configuring output baudrate to %d (%d).", baudrate, baud);
b19f4622 513 if (cfsetospeed(&term, baud) < 0) {
5df7b201 514 sr_err("cfsetospeed() error: %s.", strerror(errno));
e46b8fb1 515 return SR_ERR;
b19f4622
UH
516 }
517
299bdb24 518 sr_spew("Configuring input baudrate to %d (%d).", baudrate, baud);
b19f4622 519 if (cfsetispeed(&term, baud) < 0) {
5df7b201 520 sr_err("cfsetispeed() error: %s.", strerror(errno));
e46b8fb1 521 return SR_ERR;
b19f4622 522 }
1ff7712c 523
299bdb24 524 sr_spew("Configuring %d data bits.", bits);
d02a535e 525 term.c_cflag &= ~CSIZE;
1ff7712c
DR
526 switch (bits) {
527 case 8:
528 term.c_cflag |= CS8;
529 break;
530 case 7:
531 term.c_cflag |= CS7;
532 break;
533 default:
299bdb24 534 sr_err("Unsupported data bits number %d.", bits);
e46b8fb1 535 return SR_ERR;
1ff7712c
DR
536 }
537
299bdb24 538 sr_spew("Configuring %d stop bits.", stopbits);
d02a535e 539 term.c_cflag &= ~CSTOPB;
1ff7712c
DR
540 switch (stopbits) {
541 case 1:
299bdb24 542 term.c_cflag &= ~CSTOPB;
1ff7712c
DR
543 break;
544 case 2:
545 term.c_cflag |= CSTOPB;
d7c776b9 546 break;
1ff7712c 547 default:
299bdb24 548 sr_err("Unsupported stopbits number %d.", stopbits);
e46b8fb1 549 return SR_ERR;
1ff7712c
DR
550 }
551
f38b9763
BV
552 term.c_iflag &= ~(IXON | IXOFF);
553 term.c_cflag &= ~CRTSCTS;
1ff7712c 554 switch (flowcontrol) {
f38b9763
BV
555 case 0:
556 /* No flow control. */
299bdb24 557 sr_spew("Configuring no flow control.");
1ff7712c
DR
558 break;
559 case 1:
299bdb24 560 sr_spew("Configuring RTS/CTS flow control.");
1ff7712c 561 term.c_cflag |= CRTSCTS;
d7c776b9 562 break;
f38b9763 563 case 2:
299bdb24 564 sr_spew("Configuring XON/XOFF flow control.");
f38b9763
BV
565 term.c_iflag |= IXON | IXOFF;
566 break;
1ff7712c 567 default:
299bdb24 568 sr_err("Unsupported flow control setting %d.", flowcontrol);
e46b8fb1 569 return SR_ERR;
1ff7712c
DR
570 }
571
ac4a2ea4
DR
572 term.c_iflag &= ~IGNPAR;
573 term.c_cflag &= ~(PARODD | PARENB);
1ff7712c 574 switch (parity) {
f8c1fcda 575 case SERIAL_PARITY_NONE:
299bdb24 576 sr_spew("Configuring no parity.");
1ff7712c
DR
577 term.c_iflag |= IGNPAR;
578 break;
f8c1fcda 579 case SERIAL_PARITY_EVEN:
299bdb24 580 sr_spew("Configuring even parity.");
ac4a2ea4 581 term.c_cflag |= PARENB;
1ff7712c 582 break;
f8c1fcda 583 case SERIAL_PARITY_ODD:
299bdb24 584 sr_spew("Configuring odd parity.");
ac4a2ea4 585 term.c_cflag |= PARENB | PARODD;
1ff7712c
DR
586 break;
587 default:
299bdb24 588 sr_err("Unsupported parity setting %d.", parity);
e46b8fb1 589 return SR_ERR;
1ff7712c
DR
590 }
591
b1a05154
BV
592 /* Turn off all serial port cooking. */
593 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
7d4abe5a 594 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
cc840ab6 595#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
7d4abe5a
UH
596 term.c_oflag &= ~OFILL;
597#endif
b19f4622
UH
598
599 /* Disable canonical mode, and don't echo input characters. */
5c51e098
BV
600 term.c_lflag &= ~(ICANON | ECHO);
601
b19f4622 602 /* Write the configured settings. */
299bdb24
BV
603 if (tcsetattr(serial->fd, TCSADRAIN, &term) < 0) {
604 sr_err("tcsetattr() error: %s.", strerror(errno));
e46b8fb1 605 return SR_ERR;
b19f4622 606 }
700dcd5c 607
71caaad4
BV
608 if (rts != -1) {
609 sr_spew("Setting RTS %s.", rts ? "high" : "low");
610 controlbits = TIOCM_RTS;
611 if ((ret = ioctl(serial->fd, rts ? TIOCMBIS : TIOCMBIC,
612 &controlbits)) < 0) {
613 sr_err("Error setting RTS: %s.", strerror(errno));
614 return SR_ERR;
615 }
700dcd5c
UH
616 }
617
71caaad4
BV
618 if (dtr != -1) {
619 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
620 controlbits = TIOCM_DTR;
621 if ((ret = ioctl(serial->fd, dtr ? TIOCMBIS : TIOCMBIC,
622 &controlbits)) < 0) {
623 sr_err("Error setting DTR: %s.", strerror(errno));
624 return SR_ERR;
625 }
700dcd5c 626 }
700dcd5c 627
926b866c 628#endif
d02a535e 629
e46b8fb1 630 return SR_OK;
d02a535e 631}
792fc686 632
299bdb24
BV
633/**
634 * Set serial parameters for the specified serial port.
635 *
636 * @param serial Previously initialized serial port structure.
637 * @param paramstr A serial communication parameters string, in the form
26ddb5ba 638 * of <speed>/<data bits><parity><stopbits><flow>, for example "9600/8n1" or
639 * "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none, 1 for rts/cts and 2 for xon/xoff.
299bdb24
BV
640 *
641 * @return SR_OK upon success, SR_ERR upon failure.
642 */
71caaad4 643#define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
299bdb24
BV
644SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
645 const char *paramstr)
792fc686
BV
646{
647 GRegex *reg;
648 GMatchInfo *match;
26ddb5ba 649 int speed, databits, parity, stopbits, flow, rts, dtr, i;
71caaad4 650 char *mstr, **opts, **kv;
792fc686 651
26ddb5ba 652 speed = databits = parity = stopbits = flow = 0;
71caaad4 653 rts = dtr = -1;
ea088bb6 654 sr_spew("Parsing parameters from \"%s\".", paramstr);
792fc686
BV
655 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
656 if (g_regex_match(reg, paramstr, 0, &match)) {
657 if ((mstr = g_match_info_fetch(match, 1)))
658 speed = strtoul(mstr, NULL, 10);
659 g_free(mstr);
660 if ((mstr = g_match_info_fetch(match, 2)))
661 databits = strtoul(mstr, NULL, 10);
662 g_free(mstr);
663 if ((mstr = g_match_info_fetch(match, 3))) {
664 switch (mstr[0]) {
665 case 'n':
666 parity = SERIAL_PARITY_NONE;
667 break;
668 case 'e':
669 parity = SERIAL_PARITY_EVEN;
670 break;
671 case 'o':
672 parity = SERIAL_PARITY_ODD;
673 break;
674 }
675 }
676 g_free(mstr);
677 if ((mstr = g_match_info_fetch(match, 4)))
678 stopbits = strtoul(mstr, NULL, 10);
679 g_free(mstr);
71caaad4
BV
680 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
681 if (mstr[0] != '/') {
682 sr_dbg("missing separator before extra options");
683 speed = 0;
684 } else {
685 /* A set of "key=value" options separated by / */
686 opts = g_strsplit(mstr + 1, "/", 0);
687 for (i = 0; opts[i]; i++) {
688 kv = g_strsplit(opts[i], "=", 2);
689 if (!strncmp(kv[0], "rts", 3)) {
690 if (kv[1][0] == '1')
691 rts = 1;
692 else if (kv[1][0] == '0')
693 rts = 0;
694 else {
695 sr_dbg("invalid value for rts: %c", kv[1][0]);
696 speed = 0;
697 }
698 } else if (!strncmp(kv[0], "dtr", 3)) {
699 if (kv[1][0] == '1')
700 dtr = 1;
701 else if (kv[1][0] == '0')
702 dtr = 0;
703 else {
704 sr_dbg("invalid value for dtr: %c", kv[1][0]);
705 speed = 0;
706 }
26ddb5ba 707 } else if (!strncmp(kv[0], "flow", 4)) {
708 if (kv[1][0] == '0')
709 flow = 0;
710 else if (kv[1][0] == '1')
711 flow = 1;
712 else if (kv[1][0] == '2')
713 flow = 2;
714 else {
715 sr_dbg("invalid value for flow: %c", kv[1][0]);
716 speed = 0;
717 }
71caaad4
BV
718 }
719 g_strfreev(kv);
720 }
721 g_strfreev(opts);
722 }
723 }
724 g_free(mstr);
792fc686
BV
725 }
726 g_match_info_unref(match);
727 g_regex_unref(reg);
728
ea088bb6
AG
729 if (speed) {
730 return serial_set_params(serial, speed, databits, parity,
26ddb5ba 731 stopbits, flow, rts, dtr);
ea088bb6
AG
732 } else {
733 sr_dbg("Could not infer speed from parameter string.");
792fc686 734 return SR_ERR_ARG;
ea088bb6 735 }
792fc686
BV
736}
737
299bdb24
BV
738/**
739 * Read a line from the specified serial port.
740 *
741 * @param serial Previously initialized serial port structure.
742 * @param buf Buffer where to store the bytes that are read.
743 * @param buflen Size of the buffer.
744 * @param timeout_ms How long to wait for a line to come in.
745 *
746 * Reading stops when CR of LR is found, which is stripped from the buffer.
747 *
748 * @return SR_OK on success, SR_ERR on failure.
749 */
750SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
751 int *buflen, gint64 timeout_ms)
6f22a8ef 752{
b87f8504 753 gint64 start;
6f22a8ef
UH
754 int maxlen, len;
755
299bdb24
BV
756 if (!serial || serial->fd == -1) {
757 sr_dbg("Invalid serial port.");
758 return SR_ERR;
759 }
760
761 if (serial->fd == -1) {
762 sr_dbg("Cannot use unopened serial port %s (fd %d).",
763 serial->port, serial->fd);
764 return -1;
765 }
766
6f22a8ef
UH
767 timeout_ms *= 1000;
768 start = g_get_monotonic_time();
769
770 maxlen = *buflen;
771 *buflen = len = 0;
772 while(1) {
773 len = maxlen - *buflen - 1;
774 if (len < 1)
775 break;
299bdb24 776 len = serial_read(serial, *buf + *buflen, 1);
6f22a8ef
UH
777 if (len > 0) {
778 *buflen += len;
779 *(*buf + *buflen) = '\0';
318dd53c
BV
780 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
781 || *(*buf + *buflen - 1) == '\n')) {
782 /* Strip CR/LF and terminate. */
6f22a8ef
UH
783 *(*buf + --*buflen) = '\0';
784 break;
785 }
786 }
787 if (g_get_monotonic_time() - start > timeout_ms)
788 /* Timeout */
789 break;
790 g_usleep(2000);
791 }
318dd53c
BV
792 if (*buflen)
793 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
794
795 return SR_OK;
796}
766456be
UH
797
798/**
799 * Try to find a valid packet in a serial data stream.
800 *
801 * @param serial Previously initialized serial port structure.
802 * @param buf Buffer containing the bytes to write.
803 * @param count Size of the buffer.
804 * @param packet_size Size, in bytes, of a valid packet.
805 * @param is_valid Callback that assesses whether the packet is valid or not.
806 * @param timeout_ms The timeout after which, if no packet is detected, to
807 * abort scanning.
808 * @param baudrate The baudrate of the serial port. This parameter is not
809 * critical, but it helps fine tune the serial port polling
810 * delay.
811 *
812 * @return SR_OK if a valid packet is found within the given timeout,
813 * SR_ERR upon failure.
814 */
815SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
816 uint8_t *buf, size_t *buflen,
817 size_t packet_size, packet_valid_t is_valid,
818 uint64_t timeout_ms, int baudrate)
819{
820 uint64_t start, time, byte_delay_us;
821 size_t ibuf, i, maxlen;
822 int len;
823
824 maxlen = *buflen;
825
826 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
827 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
828
829 if (maxlen < (packet_size / 2) ) {
830 sr_err("Buffer size must be at least twice the packet size.");
831 return SR_ERR;
832 }
833
766456be
UH
834 /* Assume 8n1 transmission. That is 10 bits for every byte. */
835 byte_delay_us = 10 * (1000000 / baudrate);
836 start = g_get_monotonic_time();
837
838 i = ibuf = len = 0;
839 while (ibuf < maxlen) {
840 len = serial_read(serial, &buf[ibuf], 1);
841 if (len > 0) {
842 ibuf += len;
843 } else if (len == 0) {
006dbe55 844 /* No logging, already done in serial_read(). */
766456be
UH
845 } else {
846 /* Error reading byte, but continuing anyway. */
847 }
551c3d8c
AG
848
849 time = g_get_monotonic_time() - start;
850 time /= 1000;
851
766456be
UH
852 if ((ibuf - i) >= packet_size) {
853 /* We have at least a packet's worth of data. */
854 if (is_valid(&buf[i])) {
766456be
UH
855 sr_spew("Found valid %d-byte packet after "
856 "%" PRIu64 "ms.", (ibuf - i), time);
857 *buflen = ibuf;
858 return SR_OK;
859 } else {
860 sr_spew("Got %d bytes, but not a valid "
861 "packet.", (ibuf - i));
862 }
863 /* Not a valid packet. Continue searching. */
864 i++;
865 }
551c3d8c 866 if (time >= timeout_ms) {
766456be 867 /* Timeout */
551c3d8c 868 sr_dbg("Detection timed out after %dms.", time);
766456be
UH
869 break;
870 }
871 g_usleep(byte_delay_us);
872 }
873
874 *buflen = ibuf;
875
876 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
877
878 return SR_ERR;
879}