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