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