]> sigrok.org Git - libsigrok.git/blame - hardware/common/serial.c
serial: Use new sp_set_config instead of sp_set_params.
[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 23#include <stdlib.h>
a1bb33af 24#include <glib.h>
0d4405ce 25#include <libserialport.h>
45c59c8b
BV
26#include "libsigrok.h"
27#include "libsigrok-internal.h"
a1bb33af 28
29a27196
UH
29/* Message logging helpers with subsystem-specific prefix string. */
30#define LOG_PREFIX "serial: "
31#define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
32#define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
33#define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
34#define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
35#define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
36#define sr_err(s, args...) sr_err(LOG_PREFIX s, ## args)
b19f4622 37
b19f4622
UH
38/**
39 * Open the specified serial port.
40 *
299bdb24 41 * @param serial Previously initialized serial port structure.
a54dd31e
UH
42 * @param flags Flags to use when opening the serial port. Possible flags
43 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
b19f4622 44 *
299bdb24
BV
45 * If the serial structure contains a serialcomm string, it will be
46 * passed to serial_set_paramstr() after the port is opened.
47 *
48 * @return SR_OK on success, SR_ERR on failure.
b19f4622 49 */
299bdb24 50SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
d02a535e 51{
a9bce5a5
ML
52 int ret;
53 char *error;
b19f4622 54
299bdb24
BV
55 if (!serial) {
56 sr_dbg("Invalid serial port.");
57 return SR_ERR;
58 }
59
60 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
b19f4622 61
c9bc57b6
ML
62 sp_get_port_by_name(serial->port, &serial->data);
63
64 ret = sp_open(serial->data, flags);
a9bce5a5 65
a0dfaa6c
UH
66 switch (ret) {
67 case SP_ERR_ARG:
68 sr_err("Attempt to open serial port with invalid parameters.");
69 return SR_ERR_ARG;
70 case SP_ERR_FAIL:
71 error = sp_last_error_message();
72 sr_err("Error opening port: %s.", error);
73 sp_free_error_message(error);
74 return SR_ERR;
a54dd31e
UH
75 }
76
a9bce5a5 77#ifndef _WIN32
c9bc57b6 78 serial->fd = serial->data->fd;
926b866c 79#endif
299bdb24
BV
80
81 if (serial->serialcomm)
82 return serial_set_paramstr(serial, serial->serialcomm);
83 else
84 return SR_OK;
d02a535e
BV
85}
86
b19f4622
UH
87/**
88 * Close the specified serial port.
89 *
299bdb24 90 * @param serial Previously initialized serial port structure.
b19f4622 91 *
299bdb24 92 * @return SR_OK on success, SR_ERR on failure.
2119ab03 93 */
299bdb24 94SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
d02a535e 95{
299bdb24 96 int ret;
a9bce5a5 97 char *error;
299bdb24
BV
98
99 if (!serial) {
100 sr_dbg("Invalid serial port.");
101 return SR_ERR;
102 }
103
104 if (serial->fd == -1) {
105 sr_dbg("Cannot close unopened serial port %s (fd %d).",
106 serial->port, serial->fd);
107 return SR_ERR;
108 }
109
110 sr_spew("Closing serial port %s (fd %d).", serial->port, serial->fd);
b19f4622 111
c9bc57b6 112 ret = sp_close(serial->data);
066d42b1 113 sp_free_port(serial->data);
a9bce5a5 114
a0dfaa6c
UH
115 switch (ret) {
116 case SP_ERR_ARG:
117 sr_err("Attempt to close an invalid serial port.");
118 return SR_ERR_ARG;
119 case SP_ERR_FAIL:
120 error = sp_last_error_message();
121 sr_err("Error closing port: %s.", error);
122 sp_free_error_message(error);
123 return SR_ERR;
b19f4622 124 }
299bdb24
BV
125
126 serial->fd = -1;
b19f4622 127
6a76efeb 128 return SR_OK;
d02a535e
BV
129}
130
b19f4622 131/**
299bdb24 132 * Flush serial port buffers.
b19f4622 133 *
299bdb24 134 * @param serial Previously initialized serial port structure.
b19f4622 135 *
299bdb24 136 * @return SR_OK on success, SR_ERR on failure.
1fdb75e1 137 */
299bdb24 138SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
06d64eb8 139{
299bdb24 140 int ret;
a9bce5a5 141 char *error;
299bdb24
BV
142
143 if (!serial) {
144 sr_dbg("Invalid serial port.");
145 return SR_ERR;
146 }
147
148 if (serial->fd == -1) {
149 sr_dbg("Cannot flush unopened serial port %s (fd %d).",
150 serial->port, serial->fd);
151 return SR_ERR;
152 }
153
154 sr_spew("Flushing serial port %s (fd %d).", serial->port, serial->fd);
b19f4622 155
c9bc57b6 156 ret = sp_flush(serial->data);
a9bce5a5 157
a0dfaa6c
UH
158 switch (ret) {
159 case SP_ERR_ARG:
160 sr_err("Attempt to flush an invalid serial port.");
161 return SR_ERR_ARG;
162 case SP_ERR_FAIL:
163 error = sp_last_error_message();
164 sr_err("Error flushing port: %s.", error);
165 sp_free_error_message(error);
166 return SR_ERR;
299bdb24 167 }
b19f4622 168
6a76efeb 169 return SR_OK;
06d64eb8
BV
170}
171
b19f4622 172/**
2119ab03 173 * Write a number of bytes to the specified serial port.
b19f4622 174 *
299bdb24 175 * @param serial Previously initialized serial port structure.
b19f4622
UH
176 * @param buf Buffer containing the bytes to write.
177 * @param count Number of bytes to write.
178 *
6a76efeb 179 * @return The number of bytes written, or a negative error code upon failure.
2119ab03 180 */
299bdb24
BV
181SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
182 const void *buf, size_t count)
2119ab03 183{
299bdb24 184 ssize_t ret;
a9bce5a5 185 char *error;
299bdb24
BV
186
187 if (!serial) {
188 sr_dbg("Invalid serial port.");
6a76efeb 189 return SR_ERR;
299bdb24
BV
190 }
191
192 if (serial->fd == -1) {
193 sr_dbg("Cannot use unopened serial port %s (fd %d).",
194 serial->port, serial->fd);
6a76efeb 195 return SR_ERR;
299bdb24
BV
196 }
197
c9bc57b6 198 ret = sp_write(serial->data, buf, count);
a9bce5a5 199
a0dfaa6c
UH
200 switch (ret) {
201 case SP_ERR_ARG:
202 sr_err("Attempted serial port write with invalid arguments.");
203 return SR_ERR_ARG;
204 case SP_ERR_FAIL:
205 error = sp_last_error_message();
206 sr_err("Write error: %s.", error);
207 sp_free_error_message(error);
208 return SR_ERR;
a9bce5a5
ML
209 }
210
211 sr_spew("Wrote %d/%d bytes (fd %d).", ret, count, serial->fd);
b19f4622
UH
212
213 return ret;
2119ab03
UH
214}
215
b19f4622 216/**
2119ab03 217 * Read a number of bytes from the specified serial port.
b19f4622 218 *
299bdb24 219 * @param serial Previously initialized serial port structure.
b19f4622
UH
220 * @param buf Buffer where to store the bytes that are read.
221 * @param count The number of bytes to read.
222 *
6a76efeb 223 * @return The number of bytes read, or a negative error code upon failure.
2119ab03 224 */
299bdb24
BV
225SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
226 size_t count)
2119ab03 227{
299bdb24 228 ssize_t ret;
a9bce5a5 229 char *error;
299bdb24
BV
230
231 if (!serial) {
232 sr_dbg("Invalid serial port.");
6a76efeb 233 return SR_ERR;
299bdb24
BV
234 }
235
236 if (serial->fd == -1) {
237 sr_dbg("Cannot use unopened serial port %s (fd %d).",
238 serial->port, serial->fd);
6a76efeb 239 return SR_ERR;
299bdb24
BV
240 }
241
c9bc57b6 242 ret = sp_read(serial->data, buf, count);
2119ab03 243
a0dfaa6c
UH
244 switch (ret) {
245 case SP_ERR_ARG:
246 sr_err("Attempted serial port read with invalid arguments.");
247 return SR_ERR_ARG;
449cc16b
UH
248 // Temporarily disabled, will come back later.
249 // case SP_ERR_FAIL:
250 // error = sp_last_error_message();
251 // sr_err("Read error: %s.", error);
252 // sp_free_error_message(error);
253 // return SR_ERR;
a9bce5a5
ML
254 }
255
256 sr_spew("Read %d/%d bytes (fd %d).", ret, count, serial->fd);
b19f4622
UH
257
258 return ret;
2119ab03
UH
259}
260
b19f4622
UH
261/**
262 * Set serial parameters for the specified serial port.
263 *
299bdb24 264 * @param serial Previously initialized serial port structure.
b19f4622
UH
265 * @param baudrate The baudrate to set.
266 * @param bits The number of data bits to use.
267 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
268 * @param stopbits The number of stop bits to use (1 or 2).
269 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
270 * 2 = XON/XOFF).
2119ab03 271 *
b19f4622 272 * @return SR_OK upon success, SR_ERR upon failure.
1ff7712c 273 */
299bdb24 274SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
39e5d798
UH
275 int bits, int parity, int stopbits,
276 int flowcontrol, int rts, int dtr)
d02a535e 277{
a9bce5a5
ML
278 int ret;
279 char *error;
e385e2ed 280 struct sp_port_config config;
a9bce5a5 281
299bdb24
BV
282 if (!serial) {
283 sr_dbg("Invalid serial port.");
284 return SR_ERR;
285 }
286
287 if (serial->fd == -1) {
288 sr_dbg("Cannot configure unopened serial port %s (fd %d).",
39e5d798 289 serial->port, serial->fd);
299bdb24
BV
290 return SR_ERR;
291 }
292
293 sr_spew("Setting serial parameters on port %s (fd %d).", serial->port,
39e5d798 294 serial->fd);
b19f4622 295
e385e2ed
ML
296 config.baudrate = baudrate;
297 config.bits = bits;
298 config.parity = parity;
299 config.stopbits = stopbits;
300 config.flowcontrol = flowcontrol;
301 config.rts = rts;
302 config.dtr = dtr;
303
304 ret = sp_set_config(serial->data, &config);
a9bce5a5 305
a0dfaa6c
UH
306 switch (ret) {
307 case SP_ERR_ARG:
308 sr_err("Invalid arguments for setting serial port parameters.");
309 return SR_ERR_ARG;
310 case SP_ERR_FAIL:
311 error = sp_last_error_message();
312 sr_err("Error setting serial port parameters: %s.", error);
313 sp_free_error_message(error);
314 return SR_ERR;
700dcd5c
UH
315 }
316
e46b8fb1 317 return SR_OK;
d02a535e 318}
792fc686 319
299bdb24
BV
320/**
321 * Set serial parameters for the specified serial port.
322 *
323 * @param serial Previously initialized serial port structure.
324 * @param paramstr A serial communication parameters string, in the form
26ddb5ba 325 * of <speed>/<data bits><parity><stopbits><flow>, for example "9600/8n1" or
326 * "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none, 1 for rts/cts and 2 for xon/xoff.
299bdb24
BV
327 *
328 * @return SR_OK upon success, SR_ERR upon failure.
329 */
71caaad4 330#define SERIAL_COMM_SPEC "^(\\d+)/([78])([neo])([12])(.*)$"
299bdb24
BV
331SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
332 const char *paramstr)
792fc686
BV
333{
334 GRegex *reg;
335 GMatchInfo *match;
26ddb5ba 336 int speed, databits, parity, stopbits, flow, rts, dtr, i;
71caaad4 337 char *mstr, **opts, **kv;
792fc686 338
26ddb5ba 339 speed = databits = parity = stopbits = flow = 0;
71caaad4 340 rts = dtr = -1;
ea088bb6 341 sr_spew("Parsing parameters from \"%s\".", paramstr);
792fc686
BV
342 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
343 if (g_regex_match(reg, paramstr, 0, &match)) {
344 if ((mstr = g_match_info_fetch(match, 1)))
345 speed = strtoul(mstr, NULL, 10);
346 g_free(mstr);
347 if ((mstr = g_match_info_fetch(match, 2)))
348 databits = strtoul(mstr, NULL, 10);
349 g_free(mstr);
350 if ((mstr = g_match_info_fetch(match, 3))) {
351 switch (mstr[0]) {
352 case 'n':
353 parity = SERIAL_PARITY_NONE;
354 break;
355 case 'e':
356 parity = SERIAL_PARITY_EVEN;
357 break;
358 case 'o':
359 parity = SERIAL_PARITY_ODD;
360 break;
361 }
362 }
363 g_free(mstr);
364 if ((mstr = g_match_info_fetch(match, 4)))
365 stopbits = strtoul(mstr, NULL, 10);
366 g_free(mstr);
71caaad4
BV
367 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
368 if (mstr[0] != '/') {
369 sr_dbg("missing separator before extra options");
370 speed = 0;
371 } else {
372 /* A set of "key=value" options separated by / */
373 opts = g_strsplit(mstr + 1, "/", 0);
374 for (i = 0; opts[i]; i++) {
375 kv = g_strsplit(opts[i], "=", 2);
376 if (!strncmp(kv[0], "rts", 3)) {
377 if (kv[1][0] == '1')
378 rts = 1;
379 else if (kv[1][0] == '0')
380 rts = 0;
381 else {
382 sr_dbg("invalid value for rts: %c", kv[1][0]);
383 speed = 0;
384 }
385 } else if (!strncmp(kv[0], "dtr", 3)) {
386 if (kv[1][0] == '1')
387 dtr = 1;
388 else if (kv[1][0] == '0')
389 dtr = 0;
390 else {
391 sr_dbg("invalid value for dtr: %c", kv[1][0]);
392 speed = 0;
393 }
26ddb5ba 394 } else if (!strncmp(kv[0], "flow", 4)) {
395 if (kv[1][0] == '0')
396 flow = 0;
397 else if (kv[1][0] == '1')
398 flow = 1;
399 else if (kv[1][0] == '2')
400 flow = 2;
401 else {
402 sr_dbg("invalid value for flow: %c", kv[1][0]);
403 speed = 0;
404 }
71caaad4
BV
405 }
406 g_strfreev(kv);
407 }
408 g_strfreev(opts);
409 }
410 }
411 g_free(mstr);
792fc686
BV
412 }
413 g_match_info_unref(match);
414 g_regex_unref(reg);
415
ea088bb6
AG
416 if (speed) {
417 return serial_set_params(serial, speed, databits, parity,
26ddb5ba 418 stopbits, flow, rts, dtr);
ea088bb6
AG
419 } else {
420 sr_dbg("Could not infer speed from parameter string.");
792fc686 421 return SR_ERR_ARG;
ea088bb6 422 }
792fc686
BV
423}
424
299bdb24
BV
425/**
426 * Read a line from the specified serial port.
427 *
428 * @param serial Previously initialized serial port structure.
429 * @param buf Buffer where to store the bytes that are read.
430 * @param buflen Size of the buffer.
431 * @param timeout_ms How long to wait for a line to come in.
432 *
433 * Reading stops when CR of LR is found, which is stripped from the buffer.
434 *
435 * @return SR_OK on success, SR_ERR on failure.
436 */
437SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
438 int *buflen, gint64 timeout_ms)
6f22a8ef 439{
b87f8504 440 gint64 start;
6f22a8ef
UH
441 int maxlen, len;
442
299bdb24
BV
443 if (!serial || serial->fd == -1) {
444 sr_dbg("Invalid serial port.");
445 return SR_ERR;
446 }
447
448 if (serial->fd == -1) {
449 sr_dbg("Cannot use unopened serial port %s (fd %d).",
450 serial->port, serial->fd);
451 return -1;
452 }
453
6f22a8ef
UH
454 timeout_ms *= 1000;
455 start = g_get_monotonic_time();
456
457 maxlen = *buflen;
458 *buflen = len = 0;
459 while(1) {
460 len = maxlen - *buflen - 1;
461 if (len < 1)
462 break;
299bdb24 463 len = serial_read(serial, *buf + *buflen, 1);
6f22a8ef
UH
464 if (len > 0) {
465 *buflen += len;
466 *(*buf + *buflen) = '\0';
318dd53c
BV
467 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
468 || *(*buf + *buflen - 1) == '\n')) {
469 /* Strip CR/LF and terminate. */
6f22a8ef
UH
470 *(*buf + --*buflen) = '\0';
471 break;
472 }
473 }
474 if (g_get_monotonic_time() - start > timeout_ms)
475 /* Timeout */
476 break;
5715e84f
DT
477 if (len < 1)
478 g_usleep(2000);
6f22a8ef 479 }
318dd53c
BV
480 if (*buflen)
481 sr_dbg("Received %d: '%s'.", *buflen, *buf);
6f22a8ef
UH
482
483 return SR_OK;
484}
766456be
UH
485
486/**
487 * Try to find a valid packet in a serial data stream.
488 *
489 * @param serial Previously initialized serial port structure.
490 * @param buf Buffer containing the bytes to write.
491 * @param count Size of the buffer.
492 * @param packet_size Size, in bytes, of a valid packet.
493 * @param is_valid Callback that assesses whether the packet is valid or not.
494 * @param timeout_ms The timeout after which, if no packet is detected, to
495 * abort scanning.
496 * @param baudrate The baudrate of the serial port. This parameter is not
497 * critical, but it helps fine tune the serial port polling
498 * delay.
499 *
500 * @return SR_OK if a valid packet is found within the given timeout,
501 * SR_ERR upon failure.
502 */
503SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
504 uint8_t *buf, size_t *buflen,
505 size_t packet_size, packet_valid_t is_valid,
506 uint64_t timeout_ms, int baudrate)
507{
508 uint64_t start, time, byte_delay_us;
509 size_t ibuf, i, maxlen;
510 int len;
511
512 maxlen = *buflen;
513
514 sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
515 "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);
516
517 if (maxlen < (packet_size / 2) ) {
518 sr_err("Buffer size must be at least twice the packet size.");
519 return SR_ERR;
520 }
521
766456be
UH
522 /* Assume 8n1 transmission. That is 10 bits for every byte. */
523 byte_delay_us = 10 * (1000000 / baudrate);
524 start = g_get_monotonic_time();
525
526 i = ibuf = len = 0;
527 while (ibuf < maxlen) {
528 len = serial_read(serial, &buf[ibuf], 1);
529 if (len > 0) {
530 ibuf += len;
531 } else if (len == 0) {
006dbe55 532 /* No logging, already done in serial_read(). */
766456be
UH
533 } else {
534 /* Error reading byte, but continuing anyway. */
535 }
551c3d8c
AG
536
537 time = g_get_monotonic_time() - start;
538 time /= 1000;
539
766456be
UH
540 if ((ibuf - i) >= packet_size) {
541 /* We have at least a packet's worth of data. */
542 if (is_valid(&buf[i])) {
766456be
UH
543 sr_spew("Found valid %d-byte packet after "
544 "%" PRIu64 "ms.", (ibuf - i), time);
545 *buflen = ibuf;
546 return SR_OK;
547 } else {
548 sr_spew("Got %d bytes, but not a valid "
549 "packet.", (ibuf - i));
550 }
551 /* Not a valid packet. Continue searching. */
552 i++;
553 }
551c3d8c 554 if (time >= timeout_ms) {
766456be 555 /* Timeout */
551c3d8c 556 sr_dbg("Detection timed out after %dms.", time);
766456be
UH
557 break;
558 }
5715e84f
DT
559 if (len < 1)
560 g_usleep(byte_delay_us);
766456be
UH
561 }
562
563 *buflen = ibuf;
564
565 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
566
567 return SR_ERR;
568}