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