]> sigrok.org Git - libsigrok.git/blame - hardware/common/serial.c
error.c: Add SR_ERR_PROBE_GROUP handling.
[libsigrok.git] / hardware / common / 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>
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 29#else
d02a535e 30#include <termios.h>
0f84cda0 31#include <sys/ioctl.h>
926b866c 32#endif
d02a535e 33#include <stdlib.h>
b19f4622 34#include <errno.h>
a1bb33af 35#include <glib.h>
45c59c8b
BV
36#include "libsigrok.h"
37#include "libsigrok-internal.h"
a1bb33af 38
29a27196
UH
39/* Message logging helpers with subsystem-specific prefix string. */
40#define LOG_PREFIX "serial: "
41#define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
42#define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
43#define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
44#define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
45#define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
46#define sr_err(s, args...) sr_err(LOG_PREFIX s, ## args)
b19f4622 47
926b866c
UH
48// FIXME: Must be moved, or rather passed as function argument.
49#ifdef _WIN32
a0ecd83b 50static HANDLE hdl;
926b866c
UH
51#endif
52
b19f4622
UH
53/**
54 * Open the specified serial port.
55 *
299bdb24 56 * @param serial Previously initialized serial port structure.
a54dd31e
UH
57 * @param flags Flags to use when opening the serial port. Possible flags
58 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
b19f4622 59 *
299bdb24
BV
60 * If the serial structure contains a serialcomm string, it will be
61 * passed to serial_set_paramstr() after the port is opened.
62 *
63 * @return SR_OK on success, SR_ERR on failure.
b19f4622 64 */
299bdb24 65SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
d02a535e 66{
a54dd31e
UH
67 int flags_local = 0;
68#ifdef _WIN32
69 DWORD desired_access = 0, flags_and_attributes = 0;
70#endif
b19f4622 71
299bdb24
BV
72 if (!serial) {
73 sr_dbg("Invalid serial port.");
74 return SR_ERR;
75 }
76
77 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
b19f4622 78
926b866c 79#ifdef _WIN32
a54dd31e
UH
80 /* Map 'flags' to the OS-specific settings. */
81 desired_access |= GENERIC_READ;
82 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
83 if (flags & SERIAL_RDWR)
84 desired_access |= GENERIC_WRITE;
85 if (flags & SERIAL_NONBLOCK)
86 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
87
88 hdl = CreateFile(serial->port, desired_access, 0, 0,
89 OPEN_EXISTING, flags_and_attributes, 0);
926b866c 90 if (hdl == INVALID_HANDLE_VALUE) {
299bdb24
BV
91 sr_err("Error opening serial port '%s'.", serial->port);
92 return SR_ERR;
926b866c 93 }
926b866c 94#else
a54dd31e
UH
95 /* Map 'flags' to the OS-specific settings. */
96 if (flags & SERIAL_RDWR)
97 flags_local |= O_RDWR;
98 if (flags & SERIAL_RDONLY)
99 flags_local |= O_RDONLY;
100 if (flags & SERIAL_NONBLOCK)
101 flags_local |= O_NONBLOCK;
102
103 if ((serial->fd = open(serial->port, flags_local)) < 0) {
299bdb24 104 sr_err("Error opening serial port '%s': %s.", serial->port,
b19f4622 105 strerror(errno));
299bdb24 106 return SR_ERR;
a54dd31e
UH
107 }
108
109 sr_spew("Opened serial port '%s' (fd %d).", serial->port, serial->fd);
926b866c 110#endif
299bdb24
BV
111
112 if (serial->serialcomm)
113 return serial_set_paramstr(serial, serial->serialcomm);
114 else
115 return SR_OK;
d02a535e
BV
116}
117
b19f4622
UH
118/**
119 * Close the specified serial port.
120 *
299bdb24 121 * @param serial Previously initialized serial port structure.
b19f4622 122 *
299bdb24 123 * @return SR_OK on success, SR_ERR on failure.
2119ab03 124 */
299bdb24 125SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
d02a535e 126{
299bdb24
BV
127 int ret;
128
129 if (!serial) {
130 sr_dbg("Invalid serial port.");
131 return SR_ERR;
132 }
133
134 if (serial->fd == -1) {
135 sr_dbg("Cannot close unopened serial port %s (fd %d).",
136 serial->port, serial->fd);
137 return SR_ERR;
138 }
139
140 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
141 ret = SR_OK;
b19f4622 142
926b866c 143#ifdef _WIN32
2119ab03 144 /* Returns non-zero upon success, 0 upon failure. */
299bdb24
BV
145 if (CloseHandle(hdl) == 0)
146 ret = SR_ERR;
926b866c 147#else
2119ab03 148 /* Returns 0 upon success, -1 upon failure. */
299bdb24
BV
149 if (close(serial->fd) < 0) {
150 sr_err("Error closing serial port: %s (fd %d).", strerror(errno),
151 serial->fd);
152 ret = SR_ERR;
b19f4622 153 }
299bdb24
BV
154#endif
155
156 serial->fd = -1;
b19f4622
UH
157
158 return ret;
d02a535e
BV
159}
160
b19f4622 161/**
299bdb24 162 * Flush serial port buffers.
b19f4622 163 *
299bdb24 164 * @param serial Previously initialized serial port structure.
b19f4622 165 *
299bdb24 166 * @return SR_OK on success, SR_ERR on failure.
1fdb75e1 167 */
299bdb24 168SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
06d64eb8 169{
299bdb24
BV
170 int ret;
171
172 if (!serial) {
173 sr_dbg("Invalid serial port.");
174 return SR_ERR;
175 }
176
177 if (serial->fd == -1) {
178 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
179 serial->port, serial->fd);
180 return SR_ERR;
181 }
182
183 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
184 ret = SR_OK;
b19f4622 185
1fdb75e1
UH
186#ifdef _WIN32
187 /* Returns non-zero upon success, 0 upon failure. */
4da1a800 188 if (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) {
299bdb24
BV
189 sr_err("Error flushing serial port: %s.", strerror(errno));
190 ret = SR_ERR;
191 }
1fdb75e1
UH
192#else
193 /* Returns 0 upon success, -1 upon failure. */
299bdb24 194 if (tcflush(serial->fd, TCIOFLUSH) < 0) {
b19f4622 195 sr_err("Error flushing serial port: %s.", strerror(errno));
299bdb24
BV
196 ret = SR_ERR;
197 }
b19f4622
UH
198
199 return ret;
1fdb75e1 200#endif
06d64eb8
BV
201}
202
b19f4622 203/**
2119ab03 204 * Write a number of bytes to the specified serial port.
b19f4622 205 *
299bdb24 206 * @param serial Previously initialized serial port structure.
b19f4622
UH
207 * @param buf Buffer containing the bytes to write.
208 * @param count Number of bytes to write.
209 *
210 * @return The number of bytes written, or -1 upon failure.
2119ab03 211 */
299bdb24
BV
212SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
213 const void *buf, size_t count)
2119ab03 214{
299bdb24
BV
215 ssize_t ret;
216
217 if (!serial) {
218 sr_dbg("Invalid serial port.");
219 return -1;
220 }
221
222 if (serial->fd == -1) {
223 sr_dbg("Cannot use unopened serial port %s (fd %d).",
224 serial->port, serial->fd);
225 return -1;
226 }
227
2119ab03
UH
228#ifdef _WIN32
229 DWORD tmp = 0;
230
231 /* FIXME */
232 /* Returns non-zero upon success, 0 upon failure. */
233 WriteFile(hdl, buf, count, &tmp, NULL);
234#else
235 /* Returns the number of bytes written, or -1 upon failure. */
299bdb24 236 ret = write(serial->fd, buf, count);
b19f4622 237 if (ret < 0)
299bdb24 238 sr_err("Write error: %s.", strerror(errno));
302c4b5a 239 else
299bdb24
BV
240 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
241#endif
b19f4622
UH
242
243 return ret;
2119ab03
UH
244}
245
b19f4622 246/**
2119ab03 247 * Read a number of bytes from the specified serial port.
b19f4622 248 *
299bdb24 249 * @param serial Previously initialized serial port structure.
b19f4622
UH
250 * @param buf Buffer where to store the bytes that are read.
251 * @param count The number of bytes to read.
252 *
253 * @return The number of bytes read, or -1 upon failure.
2119ab03 254 */
299bdb24
BV
255SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
256 size_t count)
2119ab03 257{
299bdb24
BV
258 ssize_t ret;
259
260 if (!serial) {
261 sr_dbg("Invalid serial port.");
262 return -1;
263 }
264
265 if (serial->fd == -1) {
266 sr_dbg("Cannot use unopened serial port %s (fd %d).",
267 serial->port, serial->fd);
268 return -1;
269 }
270
2119ab03
UH
271#ifdef _WIN32
272 DWORD tmp = 0;
273
274 /* FIXME */
275 /* Returns non-zero upon success, 0 upon failure. */
276 return ReadFile(hdl, buf, count, &tmp, NULL);
277#else
278 /* Returns the number of bytes read, or -1 upon failure. */
299bdb24 279 ret = read(serial->fd, buf, count);
299bdb24 280#endif
b19f4622
UH
281
282 return ret;
2119ab03
UH
283}
284
b19f4622
UH
285/**
286 * Set serial parameters for the specified serial port.
287 *
299bdb24 288 * @param serial Previously initialized serial port structure.
b19f4622
UH
289 * @param baudrate The baudrate to set.
290 * @param bits The number of data bits to use.
291 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
292 * @param stopbits The number of stop bits to use (1 or 2).
293 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
294 * 2 = XON/XOFF).
2119ab03 295 *
b19f4622 296 * @return SR_OK upon success, SR_ERR upon failure.
1ff7712c 297 */
299bdb24 298SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
39e5d798
UH
299 int bits, int parity, int stopbits,
300 int flowcontrol, int rts, int dtr)
d02a535e 301{
299bdb24
BV
302 if (!serial) {
303 sr_dbg("Invalid serial port.");
304 return SR_ERR;
305 }
306
307 if (serial->fd == -1) {
308 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
39e5d798 309 serial->port, serial->fd);
299bdb24
BV
310 return SR_ERR;
311 }
312
313 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
39e5d798 314 serial->fd);
b19f4622 315
926b866c
UH
316#ifdef _WIN32
317 DCB dcb;
318
5ddb0cc7
UH
319 if (!GetCommState(hdl, &dcb)) {
320 sr_err("Failed to get comm state on port %s (fd %d): %d.",
321 serial->port, serial->fd, GetLastError());
e46b8fb1 322 return SR_ERR;
5ddb0cc7 323 }
926b866c 324
0abee507 325 switch (baudrate) {
5ae35c29
UH
326 /*
327 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
328 * have documented CBR_* macros.
329 */
330 case 110:
331 dcb.BaudRate = CBR_110;
926b866c 332 break;
5ae35c29
UH
333 case 300:
334 dcb.BaudRate = CBR_300;
926b866c 335 break;
5ae35c29
UH
336 case 600:
337 dcb.BaudRate = CBR_600;
926b866c 338 break;
5ae35c29
UH
339 case 1200:
340 dcb.BaudRate = CBR_1200;
926b866c 341 break;
5ae35c29
UH
342 case 2400:
343 dcb.BaudRate = CBR_2400;
926b866c 344 break;
e8e9dcdd
AG
345 case 4800:
346 dcb.BaudRate = CBR_4800;
347 break;
5ae35c29
UH
348 case 9600:
349 dcb.BaudRate = CBR_9600;
350 break;
351 case 14400:
352 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
353 break;
354 case 19200:
355 dcb.BaudRate = CBR_19200;
356 break;
357 case 38400:
358 dcb.BaudRate = CBR_38400;
359 break;
360 case 57600:
361 dcb.BaudRate = CBR_57600;
362 break;
363 case 115200:
364 dcb.BaudRate = CBR_115200;
365 break;
366 case 128000:
367 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
368 break;
369 case 256000:
370 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
0f708301 371 break;
926b866c 372 default:
5ae35c29 373 sr_err("Unsupported baudrate: %d.", baudrate);
b19f4622 374 return SR_ERR;
926b866c 375 }
5ae35c29
UH
376 sr_spew("Configuring baudrate to %d (%d).", baudrate, dcb.BaudRate);
377
5ddb0cc7 378 sr_spew("Configuring %d data bits.", bits);
926b866c 379 dcb.ByteSize = bits;
5ddb0cc7
UH
380
381 sr_spew("Configuring %d stop bits.", stopbits);
382 switch (stopbits) {
383 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
384 case 1:
385 dcb.StopBits = ONESTOPBIT;
386 break;
387 case 2:
388 dcb.StopBits = TWOSTOPBITS;
389 break;
390 default:
391 sr_err("Unsupported stopbits number: %d.", stopbits);
392 return SR_ERR;
393 }
394
395 switch (parity) {
396 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
397 case SERIAL_PARITY_NONE:
398 sr_spew("Configuring no parity.");
399 dcb.Parity = NOPARITY;
400 break;
401 case SERIAL_PARITY_EVEN:
402 sr_spew("Configuring even parity.");
403 dcb.Parity = EVENPARITY;
404 break;
405 case SERIAL_PARITY_ODD:
406 sr_spew("Configuring odd parity.");
407 dcb.Parity = ODDPARITY;
408 break;
409 default:
410 sr_err("Unsupported parity setting: %d.", parity);
411 return SR_ERR;
412 }
926b866c 413
39e5d798
UH
414 if (rts != -1) {
415 sr_spew("Setting RTS %s.", rts ? "high" : "low");
416 if (rts)
417 dcb.fRtsControl = RTS_CONTROL_ENABLE;
418 else
419 dcb.fRtsControl = RTS_CONTROL_DISABLE;
420 }
421
422 if (dtr != -1) {
423 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
86c02e65 424 if (dtr)
39e5d798
UH
425 dcb.fDtrControl = DTR_CONTROL_ENABLE;
426 else
427 dcb.fDtrControl = DTR_CONTROL_DISABLE;
428 }
429
5ddb0cc7
UH
430 if (!SetCommState(hdl, &dcb)) {
431 sr_err("Failed to set comm state on port %s (fd %d): %d.",
432 serial->port, serial->fd, GetLastError());
e46b8fb1 433 return SR_ERR;
5ddb0cc7 434 }
926b866c 435#else
d02a535e 436 struct termios term;
1ff7712c 437 speed_t baud;
700dcd5c 438 int ret, controlbits;
d02a535e 439
299bdb24
BV
440 if (tcgetattr(serial->fd, &term) < 0) {
441 sr_err("tcgetattr() error on port %s (fd %d): %s.",
442 serial->port, serial->fd, strerror(errno));
6a6e23ab 443 return SR_ERR;
b19f4622 444 }
6a6e23ab 445
0abee507 446 switch (baudrate) {
b19f4622
UH
447 case 50:
448 baud = B50;
449 break;
450 case 75:
451 baud = B75;
452 break;
453 case 110:
454 baud = B110;
455 break;
456 case 134:
457 baud = B134;
458 break;
459 case 150:
460 baud = B150;
461 break;
462 case 200:
463 baud = B200;
464 break;
465 case 300:
466 baud = B300;
467 break;
468 case 600:
469 baud = B600;
470 break;
471 case 1200:
472 baud = B1200;
473 break;
474 case 1800:
475 baud = B1800;
476 break;
0f708301
AG
477 case 2400:
478 baud = B2400;
479 break;
e8e9dcdd
AG
480 case 4800:
481 baud = B4800;
482 break;
1ff7712c
DR
483 case 9600:
484 baud = B9600;
485 break;
b19f4622
UH
486 case 19200:
487 baud = B19200;
488 break;
1ff7712c
DR
489 case 38400:
490 baud = B38400;
491 break;
492 case 57600:
493 baud = B57600;
494 break;
495 case 115200:
496 baud = B115200;
497 break;
b19f4622
UH
498 case 230400:
499 baud = B230400;
500 break;
b97cbca6 501#if !defined(__APPLE__) && !defined(__OpenBSD__)
1ff7712c
DR
502 case 460800:
503 baud = B460800;
504 break;
9a751023 505#endif
1ff7712c 506 default:
5ae35c29 507 sr_err("Unsupported baudrate: %d.", baudrate);
e46b8fb1 508 return SR_ERR;
1ff7712c 509 }
b19f4622 510
299bdb24 511 sr_spew("Configuring output baudrate to %d (%d).", baudrate, baud);
b19f4622 512 if (cfsetospeed(&term, baud) < 0) {
5df7b201 513 sr_err("cfsetospeed() error: %s.", strerror(errno));
e46b8fb1 514 return SR_ERR;
b19f4622
UH
515 }
516
299bdb24 517 sr_spew("Configuring input baudrate to %d (%d).", baudrate, baud);
b19f4622 518 if (cfsetispeed(&term, baud) < 0) {
5df7b201 519 sr_err("cfsetispeed() error: %s.", strerror(errno));
e46b8fb1 520 return SR_ERR;
b19f4622 521 }
1ff7712c 522
299bdb24 523 sr_spew("Configuring %d data bits.", bits);
d02a535e 524 term.c_cflag &= ~CSIZE;
1ff7712c
DR
525 switch (bits) {
526 case 8:
527 term.c_cflag |= CS8;
528 break;
529 case 7:
530 term.c_cflag |= CS7;
531 break;
532 default:
299bdb24 533 sr_err("Unsupported data bits number %d.", bits);
e46b8fb1 534 return SR_ERR;
1ff7712c
DR
535 }
536
299bdb24 537 sr_spew("Configuring %d stop bits.", stopbits);
d02a535e 538 term.c_cflag &= ~CSTOPB;
1ff7712c
DR
539 switch (stopbits) {
540 case 1:
299bdb24 541 term.c_cflag &= ~CSTOPB;
1ff7712c
DR
542 break;
543 case 2:
544 term.c_cflag |= CSTOPB;
d7c776b9 545 break;
1ff7712c 546 default:
299bdb24 547 sr_err("Unsupported stopbits number %d.", stopbits);
e46b8fb1 548 return SR_ERR;
1ff7712c
DR
549 }
550
1b943b6d 551 term.c_iflag &= ~(IXON | IXOFF | IXANY);
f38b9763 552 term.c_cflag &= ~CRTSCTS;
1ff7712c 553 switch (flowcontrol) {
f38b9763
BV
554 case 0:
555 /* No flow control. */
299bdb24 556 sr_spew("Configuring no flow control.");
1ff7712c
DR
557 break;
558 case 1:
299bdb24 559 sr_spew("Configuring RTS/CTS flow control.");
1ff7712c 560 term.c_cflag |= CRTSCTS;
d7c776b9 561 break;
f38b9763 562 case 2:
299bdb24 563 sr_spew("Configuring XON/XOFF flow control.");
1b943b6d 564 term.c_iflag |= (IXON | IXOFF | IXANY);
f38b9763 565 break;
1ff7712c 566 default:
299bdb24 567 sr_err("Unsupported flow control setting %d.", flowcontrol);
e46b8fb1 568 return SR_ERR;
1ff7712c
DR
569 }
570
ac4a2ea4 571 term.c_iflag &= ~IGNPAR;
b21d7eeb 572 term.c_cflag &= ~(PARENB | PARODD);
1ff7712c 573 switch (parity) {
f8c1fcda 574 case SERIAL_PARITY_NONE:
299bdb24 575 sr_spew("Configuring no parity.");
1ff7712c
DR
576 term.c_iflag |= IGNPAR;
577 break;
f8c1fcda 578 case SERIAL_PARITY_EVEN:
299bdb24 579 sr_spew("Configuring even parity.");
ac4a2ea4 580 term.c_cflag |= PARENB;
1ff7712c 581 break;
f8c1fcda 582 case SERIAL_PARITY_ODD:
299bdb24 583 sr_spew("Configuring odd parity.");
ac4a2ea4 584 term.c_cflag |= PARENB | PARODD;
1ff7712c
DR
585 break;
586 default:
299bdb24 587 sr_err("Unsupported parity setting %d.", parity);
e46b8fb1 588 return SR_ERR;
1ff7712c
DR
589 }
590
b1a05154
BV
591 /* Turn off all serial port cooking. */
592 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
50a9aba2 593 term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR);
cc840ab6 594#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
7d4abe5a
UH
595 term.c_oflag &= ~OFILL;
596#endif
b19f4622
UH
597
598 /* Disable canonical mode, and don't echo input characters. */
5c51e098
BV
599 term.c_lflag &= ~(ICANON | ECHO);
600
a510d555
MH
601 /* Ignore modem status lines; enable receiver */
602 term.c_cflag |= (CLOCAL | CREAD);
603
b19f4622 604 /* Write the configured settings. */
299bdb24
BV
605 if (tcsetattr(serial->fd, TCSADRAIN, &term) < 0) {
606 sr_err("tcsetattr() error: %s.", strerror(errno));
e46b8fb1 607 return SR_ERR;
b19f4622 608 }
700dcd5c 609
71caaad4
BV
610 if (rts != -1) {
611 sr_spew("Setting RTS %s.", rts ? "high" : "low");
612 controlbits = TIOCM_RTS;
613 if ((ret = ioctl(serial->fd, rts ? TIOCMBIS : TIOCMBIC,
614 &controlbits)) < 0) {
615 sr_err("Error setting RTS: %s.", strerror(errno));
616 return SR_ERR;
617 }
700dcd5c
UH
618 }
619
71caaad4
BV
620 if (dtr != -1) {
621 sr_spew("Setting DTR %s.", dtr ? "high" : "low");
622 controlbits = TIOCM_DTR;
623 if ((ret = ioctl(serial->fd, dtr ? TIOCMBIS : TIOCMBIC,
624 &controlbits)) < 0) {
625 sr_err("Error setting DTR: %s.", strerror(errno));
626 return SR_ERR;
627 }
700dcd5c 628 }
700dcd5c 629
926b866c 630#endif
d02a535e 631
e46b8fb1 632 return SR_OK;
d02a535e 633}
792fc686 634
299bdb24
BV
635/**
636 * Set serial parameters for the specified serial port.
637 *
638 * @param serial Previously initialized serial port structure.
639 * @param paramstr A serial communication parameters string, in the form
26ddb5ba 640 * of <speed>/<data bits><parity><stopbits><flow>, for example "9600/8n1" or
641 * "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none, 1 for rts/cts and 2 for xon/xoff.
299bdb24
BV
642 *
643 * @return SR_OK upon success, SR_ERR upon failure.
644 */
71caaad4 645#define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
299bdb24
BV
646SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
647 const char *paramstr)
792fc686
BV
648{
649 GRegex *reg;
650 GMatchInfo *match;
26ddb5ba 651 int speed, databits, parity, stopbits, flow, rts, dtr, i;
71caaad4 652 char *mstr, **opts, **kv;
792fc686 653
26ddb5ba 654 speed = databits = parity = stopbits = flow = 0;
71caaad4 655 rts = dtr = -1;
ea088bb6 656 sr_spew("Parsing parameters from \"%s\".", paramstr);
792fc686
BV
657 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
658 if (g_regex_match(reg, paramstr, 0, &match)) {
659 if ((mstr = g_match_info_fetch(match, 1)))
660 speed = strtoul(mstr, NULL, 10);
661 g_free(mstr);
662 if ((mstr = g_match_info_fetch(match, 2)))
663 databits = strtoul(mstr, NULL, 10);
664 g_free(mstr);
665 if ((mstr = g_match_info_fetch(match, 3))) {
666 switch (mstr[0]) {
667 case 'n':
668 parity = SERIAL_PARITY_NONE;
669 break;
670 case 'e':
671 parity = SERIAL_PARITY_EVEN;
672 break;
673 case 'o':
674 parity = SERIAL_PARITY_ODD;
675 break;
676 }
677 }
678 g_free(mstr);
679 if ((mstr = g_match_info_fetch(match, 4)))
680 stopbits = strtoul(mstr, NULL, 10);
681 g_free(mstr);
71caaad4
BV
682 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
683 if (mstr[0] != '/') {
684 sr_dbg("missing separator before extra options");
685 speed = 0;
686 } else {
687 /* A set of "key=value" options separated by / */
688 opts = g_strsplit(mstr + 1, "/", 0);
689 for (i = 0; opts[i]; i++) {
690 kv = g_strsplit(opts[i], "=", 2);
691 if (!strncmp(kv[0], "rts", 3)) {
692 if (kv[1][0] == '1')
693 rts = 1;
694 else if (kv[1][0] == '0')
695 rts = 0;
696 else {
697 sr_dbg("invalid value for rts: %c", kv[1][0]);
698 speed = 0;
699 }
700 } else if (!strncmp(kv[0], "dtr", 3)) {
701 if (kv[1][0] == '1')
702 dtr = 1;
703 else if (kv[1][0] == '0')
704 dtr = 0;
705 else {
706 sr_dbg("invalid value for dtr: %c", kv[1][0]);
707 speed = 0;
708 }
26ddb5ba 709 } else if (!strncmp(kv[0], "flow", 4)) {
710 if (kv[1][0] == '0')
711 flow = 0;
712 else if (kv[1][0] == '1')
713 flow = 1;
714 else if (kv[1][0] == '2')
715 flow = 2;
716 else {
717 sr_dbg("invalid value for flow: %c", kv[1][0]);
718 speed = 0;
719 }
71caaad4
BV
720 }
721 g_strfreev(kv);
722 }
723 g_strfreev(opts);
724 }
725 }
726 g_free(mstr);
792fc686
BV
727 }
728 g_match_info_unref(match);
729 g_regex_unref(reg);
730
ea088bb6
AG
731 if (speed) {
732 return serial_set_params(serial, speed, databits, parity,
26ddb5ba 733 stopbits, flow, rts, dtr);
ea088bb6
AG
734 } else {
735 sr_dbg("Could not infer speed from parameter string.");
792fc686 736 return SR_ERR_ARG;
ea088bb6 737 }
792fc686
BV
738}
739
299bdb24
BV
740/**
741 * Read a line from the specified serial port.
742 *
743 * @param serial Previously initialized serial port structure.
744 * @param buf Buffer where to store the bytes that are read.
745 * @param buflen Size of the buffer.
746 * @param timeout_ms How long to wait for a line to come in.
747 *
748 * Reading stops when CR of LR is found, which is stripped from the buffer.
749 *
750 * @return SR_OK on success, SR_ERR on failure.
751 */
752SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
753 int *buflen, gint64 timeout_ms)
6f22a8ef 754{
b87f8504 755 gint64 start;
6f22a8ef
UH
756 int maxlen, len;
757
299bdb24
BV
758 if (!serial || serial->fd == -1) {
759 sr_dbg("Invalid serial port.");
760 return SR_ERR;
761 }
762
763 if (serial->fd == -1) {
764 sr_dbg("Cannot use unopened serial port %s (fd %d).",
765 serial->port, serial->fd);
766 return -1;
767 }
768
6f22a8ef
UH
769 timeout_ms *= 1000;
770 start = g_get_monotonic_time();
771
772 maxlen = *buflen;
773 *buflen = len = 0;
774 while(1) {
775 len = maxlen - *buflen - 1;
776 if (len < 1)
777 break;
299bdb24 778 len = serial_read(serial, *buf + *buflen, 1);
6f22a8ef
UH
779 if (len > 0) {
780 *buflen += len;
781 *(*buf + *buflen) = '\0';
318dd53c
BV
782 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
783 || *(*buf + *buflen - 1) == '\n')) {
784 /* Strip CR/LF and terminate. */
6f22a8ef
UH
785 *(*buf + --*buflen) = '\0';
786 break;
787 }
788 }
789 if (g_get_monotonic_time() - start > timeout_ms)
790 /* Timeout */
791 break;
5715e84f
DT
792 if (len < 1)
793 g_usleep(2000);
6f22a8ef 794 }
318dd53c
BV
795 if (*buflen)
796 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
797
798 return SR_OK;
799}
766456be
UH
800
801/**
802 * Try to find a valid packet in a serial data stream.
803 *
804 * @param serial Previously initialized serial port structure.
805 * @param buf Buffer containing the bytes to write.
806 * @param count Size of the buffer.
807 * @param packet_size Size, in bytes, of a valid packet.
808 * @param is_valid Callback that assesses whether the packet is valid or not.
809 * @param timeout_ms The timeout after which, if no packet is detected, to
810 * abort scanning.
811 * @param baudrate The baudrate of the serial port. This parameter is not
812 * critical, but it helps fine tune the serial port polling
813 * delay.
814 *
815 * @return SR_OK if a valid packet is found within the given timeout,
816 * SR_ERR upon failure.
817 */
818SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
819 uint8_t *buf, size_t *buflen,
820 size_t packet_size, packet_valid_t is_valid,
821 uint64_t timeout_ms, int baudrate)
822{
823 uint64_t start, time, byte_delay_us;
824 size_t ibuf, i, maxlen;
825 int len;
826
827 maxlen = *buflen;
828
829 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
830 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
831
832 if (maxlen < (packet_size / 2) ) {
833 sr_err("Buffer size must be at least twice the packet size.");
834 return SR_ERR;
835 }
836
766456be
UH
837 /* Assume 8n1 transmission. That is 10 bits for every byte. */
838 byte_delay_us = 10 * (1000000 / baudrate);
839 start = g_get_monotonic_time();
840
841 i = ibuf = len = 0;
842 while (ibuf < maxlen) {
843 len = serial_read(serial, &buf[ibuf], 1);
844 if (len > 0) {
845 ibuf += len;
846 } else if (len == 0) {
006dbe55 847 /* No logging, already done in serial_read(). */
766456be
UH
848 } else {
849 /* Error reading byte, but continuing anyway. */
850 }
551c3d8c
AG
851
852 time = g_get_monotonic_time() - start;
853 time /= 1000;
854
766456be
UH
855 if ((ibuf - i) >= packet_size) {
856 /* We have at least a packet's worth of data. */
857 if (is_valid(&buf[i])) {
766456be
UH
858 sr_spew("Found valid %d-byte packet after "
859 "%" PRIu64 "ms.", (ibuf - i), time);
860 *buflen = ibuf;
861 return SR_OK;
862 } else {
863 sr_spew("Got %d bytes, but not a valid "
864 "packet.", (ibuf - i));
865 }
866 /* Not a valid packet. Continue searching. */
867 i++;
868 }
551c3d8c 869 if (time >= timeout_ms) {
766456be 870 /* Timeout */
551c3d8c 871 sr_dbg("Detection timed out after %dms.", time);
766456be
UH
872 break;
873 }
5715e84f
DT
874 if (len < 1)
875 g_usleep(byte_delay_us);
766456be
UH
876 }
877
878 *buflen = ibuf;
879
880 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
881
882 return SR_ERR;
883}