]> sigrok.org Git - libsigrok.git/blame_incremental - hardware/common/serial.c
teleinfo: Minor cleanups.
[libsigrok.git] / hardware / common / serial.c
... / ...
CommitLineData
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
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
22#include <string.h>
23#include <stdlib.h>
24#include <glib.h>
25#include <libserialport.h>
26#include "libsigrok.h"
27#include "libsigrok-internal.h"
28
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)
37
38/**
39 * Open the specified serial port.
40 *
41 * @param serial Previously initialized serial port structure.
42 * @param flags Flags to use when opening the serial port. Possible flags
43 * include SERIAL_RDWR, SERIAL_RDONLY, SERIAL_NONBLOCK.
44 *
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.
49 */
50SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
51{
52 int ret;
53 char *error;
54 int sp_flags = 0;
55
56 if (!serial) {
57 sr_dbg("Invalid serial port.");
58 return SR_ERR;
59 }
60
61 sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
62
63 sp_get_port_by_name(serial->port, &serial->data);
64
65 if (flags & SERIAL_RDWR)
66 sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
67 else if (flags & SERIAL_RDONLY)
68 sp_flags = SP_MODE_READ;
69
70 serial->nonblocking = (flags & SERIAL_NONBLOCK) ? 1 : 0;
71
72 ret = sp_open(serial->data, sp_flags);
73
74 switch (ret) {
75 case SP_ERR_ARG:
76 sr_err("Attempt to open serial port with invalid parameters.");
77 return SR_ERR_ARG;
78 case SP_ERR_FAIL:
79 error = sp_last_error_message();
80 sr_err("Error opening port (%d): %s.",
81 sp_last_error_code(), error);
82 sp_free_error_message(error);
83 return SR_ERR;
84 }
85
86 if (serial->serialcomm)
87 return serial_set_paramstr(serial, serial->serialcomm);
88 else
89 return SR_OK;
90}
91
92/**
93 * Close the specified serial port.
94 *
95 * @param serial Previously initialized serial port structure.
96 *
97 * @return SR_OK on success, SR_ERR on failure.
98 */
99SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
100{
101 int ret;
102 char *error;
103
104 if (!serial) {
105 sr_dbg("Invalid serial port.");
106 return SR_ERR;
107 }
108
109 if (!serial->data) {
110 sr_dbg("Cannot close unopened serial port %s.", serial->port);
111 return SR_ERR;
112 }
113
114 sr_spew("Closing serial port %s.", serial->port);
115
116 ret = sp_close(serial->data);
117
118 switch (ret) {
119 case SP_ERR_ARG:
120 sr_err("Attempt to close an invalid serial port.");
121 return SR_ERR_ARG;
122 case SP_ERR_FAIL:
123 error = sp_last_error_message();
124 sr_err("Error closing port (%d): %s.",
125 sp_last_error_code(), error);
126 sp_free_error_message(error);
127 return SR_ERR;
128 }
129
130 sp_free_port(serial->data);
131 serial->data = NULL;
132
133 return SR_OK;
134}
135
136/**
137 * Flush serial port buffers.
138 *
139 * @param serial Previously initialized serial port structure.
140 *
141 * @return SR_OK on success, SR_ERR on failure.
142 */
143SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
144{
145 int ret;
146 char *error;
147
148 if (!serial) {
149 sr_dbg("Invalid serial port.");
150 return SR_ERR;
151 }
152
153 if (!serial->data) {
154 sr_dbg("Cannot flush unopened serial port %s.", serial->port);
155 return SR_ERR;
156 }
157
158 sr_spew("Flushing serial port %s.", serial->port);
159
160 ret = sp_flush(serial->data, SP_BUF_BOTH);
161
162 switch (ret) {
163 case SP_ERR_ARG:
164 sr_err("Attempt to flush an invalid serial port.");
165 return SR_ERR_ARG;
166 case SP_ERR_FAIL:
167 error = sp_last_error_message();
168 sr_err("Error flushing port (%d): %s.",
169 sp_last_error_code(), error);
170 sp_free_error_message(error);
171 return SR_ERR;
172 }
173
174 return SR_OK;
175}
176
177/**
178 * Write a number of bytes to the specified serial port.
179 *
180 * @param serial Previously initialized serial port structure.
181 * @param buf Buffer containing the bytes to write.
182 * @param count Number of bytes to write.
183 *
184 * @return The number of bytes written, or a negative error code upon failure.
185 */
186SR_PRIV int serial_write(struct sr_serial_dev_inst *serial,
187 const void *buf, size_t count)
188{
189 ssize_t ret;
190 char *error;
191
192 if (!serial) {
193 sr_dbg("Invalid serial port.");
194 return SR_ERR;
195 }
196
197 if (!serial->data) {
198 sr_dbg("Cannot use unopened serial port %s.", serial->port);
199 return SR_ERR;
200 }
201
202 if (serial->nonblocking)
203 ret = sp_nonblocking_write(serial->data, buf, count);
204 else
205 ret = sp_blocking_write(serial->data, buf, count, 0);
206
207 switch (ret) {
208 case SP_ERR_ARG:
209 sr_err("Attempted serial port write with invalid arguments.");
210 return SR_ERR_ARG;
211 case SP_ERR_FAIL:
212 error = sp_last_error_message();
213 sr_err("Write error (%d): %s.", sp_last_error_code(), error);
214 sp_free_error_message(error);
215 return SR_ERR;
216 }
217
218 sr_spew("Wrote %d/%d bytes.", ret, count);
219
220 return ret;
221}
222
223/**
224 * Read a number of bytes from the specified serial port.
225 *
226 * @param serial Previously initialized serial port structure.
227 * @param buf Buffer where to store the bytes that are read.
228 * @param count The number of bytes to read.
229 *
230 * @return The number of bytes read, or a negative error code upon failure.
231 */
232SR_PRIV int serial_read(struct sr_serial_dev_inst *serial, void *buf,
233 size_t count)
234{
235 ssize_t ret;
236 char *error;
237
238 if (!serial) {
239 sr_dbg("Invalid serial port.");
240 return SR_ERR;
241 }
242
243 if (!serial->data) {
244 sr_dbg("Cannot use unopened serial port %s.", serial->port);
245 return SR_ERR;
246 }
247
248 if (serial->nonblocking)
249 ret = sp_nonblocking_read(serial->data, buf, count);
250 else
251 ret = sp_blocking_read(serial->data, buf, count, 0);
252
253 switch (ret) {
254 case SP_ERR_ARG:
255 sr_err("Attempted serial port read with invalid arguments.");
256 return SR_ERR_ARG;
257 case SP_ERR_FAIL:
258 error = sp_last_error_message();
259 sr_err("Read error (%d): %s.", sp_last_error_code(), error);
260 sp_free_error_message(error);
261 return SR_ERR;
262 }
263
264 if (ret > 0)
265 sr_spew("Read %d/%d bytes.", ret, count);
266
267 return ret;
268}
269
270/**
271 * Set serial parameters for the specified serial port.
272 *
273 * @param serial Previously initialized serial port structure.
274 * @param[in] baudrate The baudrate to set.
275 * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
276 * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
277 * @param[in] stopbits The number of stop bits to use (1 or 2).
278 * @param[in] flowcontrol The flow control settings to use (0 = none,
279 * 1 = RTS/CTS, 2 = XON/XOFF).
280 * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
281 * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
282 *
283 * @retval SR_OK Success
284 * @retval SR_ERR Failure.
285 */
286SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
287 int bits, int parity, int stopbits,
288 int flowcontrol, int rts, int dtr)
289{
290 int ret;
291 char *error;
292 struct sp_port_config *config;
293
294 if (!serial) {
295 sr_dbg("Invalid serial port.");
296 return SR_ERR;
297 }
298
299 if (!serial->data) {
300 sr_dbg("Cannot configure unopened serial port %s.", serial->port);
301 return SR_ERR;
302 }
303
304 sr_spew("Setting serial parameters on port %s.", serial->port);
305
306 sp_new_config(&config);
307 sp_set_config_baudrate(config, baudrate);
308 sp_set_config_bits(config, bits);
309 switch (parity) {
310 case 0:
311 sp_set_config_parity(config, SP_PARITY_NONE);
312 break;
313 case 1:
314 sp_set_config_parity(config, SP_PARITY_EVEN);
315 break;
316 case 2:
317 sp_set_config_parity(config, SP_PARITY_ODD);
318 break;
319 default:
320 return SR_ERR_ARG;
321 }
322 sp_set_config_stopbits(config, stopbits);
323 sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
324 sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
325 sp_set_config_dtr(config, dtr);
326 sp_set_config_dsr(config, SP_DSR_IGNORE);
327 sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
328
329 ret = sp_set_config(serial->data, config);
330 sp_free_config(config);
331
332 switch (ret) {
333 case SP_ERR_ARG:
334 sr_err("Invalid arguments for setting serial port parameters.");
335 return SR_ERR_ARG;
336 case SP_ERR_FAIL:
337 error = sp_last_error_message();
338 sr_err("Error setting serial port parameters (%d): %s.",
339 sp_last_error_code(), error);
340 sp_free_error_message(error);
341 return SR_ERR;
342 }
343
344 return SR_OK;
345}
346
347/**
348 * Set serial parameters for the specified serial port.
349 *
350 * @param serial Previously initialized serial port structure.
351 * @param[in] paramstr A serial communication parameters string, in the form
352 * of \<speed\>/\<data bits\>\<parity\>\<stopbits\>\<flow\>, for example
353 * "9600/8n1" or "600/7o2" or "460800/8n1/flow=2" where flow is 0 for none,
354 * 1 for rts/cts and 2 for xon/xoff.
355 *
356 * @retval SR_OK Success.
357 * @retval SR_ERR Failure.
358 */
359#define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
360SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
361 const char *paramstr)
362{
363 GRegex *reg;
364 GMatchInfo *match;
365 int speed, databits, parity, stopbits, flow, rts, dtr, i;
366 char *mstr, **opts, **kv;
367
368 speed = databits = parity = stopbits = flow = 0;
369 rts = dtr = -1;
370 sr_spew("Parsing parameters from \"%s\".", paramstr);
371 reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
372 if (g_regex_match(reg, paramstr, 0, &match)) {
373 if ((mstr = g_match_info_fetch(match, 1)))
374 speed = strtoul(mstr, NULL, 10);
375 g_free(mstr);
376 if ((mstr = g_match_info_fetch(match, 2)))
377 databits = strtoul(mstr, NULL, 10);
378 g_free(mstr);
379 if ((mstr = g_match_info_fetch(match, 3))) {
380 switch (mstr[0]) {
381 case 'n':
382 parity = SERIAL_PARITY_NONE;
383 break;
384 case 'e':
385 parity = SERIAL_PARITY_EVEN;
386 break;
387 case 'o':
388 parity = SERIAL_PARITY_ODD;
389 break;
390 }
391 }
392 g_free(mstr);
393 if ((mstr = g_match_info_fetch(match, 4)))
394 stopbits = strtoul(mstr, NULL, 10);
395 g_free(mstr);
396 if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
397 if (mstr[0] != '/') {
398 sr_dbg("missing separator before extra options");
399 speed = 0;
400 } else {
401 /* A set of "key=value" options separated by / */
402 opts = g_strsplit(mstr + 1, "/", 0);
403 for (i = 0; opts[i]; i++) {
404 kv = g_strsplit(opts[i], "=", 2);
405 if (!strncmp(kv[0], "rts", 3)) {
406 if (kv[1][0] == '1')
407 rts = 1;
408 else if (kv[1][0] == '0')
409 rts = 0;
410 else {
411 sr_dbg("invalid value for rts: %c", kv[1][0]);
412 speed = 0;
413 }
414 } else if (!strncmp(kv[0], "dtr", 3)) {
415 if (kv[1][0] == '1')
416 dtr = 1;
417 else if (kv[1][0] == '0')
418 dtr = 0;
419 else {
420 sr_dbg("invalid value for dtr: %c", kv[1][0]);
421 speed = 0;
422 }
423 } else if (!strncmp(kv[0], "flow", 4)) {
424 if (kv[1][0] == '0')
425 flow = 0;
426 else if (kv[1][0] == '1')
427 flow = 1;
428 else if (kv[1][0] == '2')
429 flow = 2;
430 else {
431 sr_dbg("invalid value for flow: %c", kv[1][0]);
432 speed = 0;
433 }
434 }
435 g_strfreev(kv);
436 }
437 g_strfreev(opts);
438 }
439 }
440 g_free(mstr);
441 }
442 g_match_info_unref(match);
443 g_regex_unref(reg);
444
445 if (speed) {
446 return serial_set_params(serial, speed, databits, parity,
447 stopbits, flow, rts, dtr);
448 } else {
449 sr_dbg("Could not infer speed from parameter string.");
450 return SR_ERR_ARG;
451 }
452}
453
454/**
455 * Read a line from the specified serial port.
456 *
457 * @param serial Previously initialized serial port structure.
458 * @param buf Buffer where to store the bytes that are read.
459 * @param buflen Size of the buffer.
460 * @param[in] timeout_ms How long to wait for a line to come in.
461 *
462 * Reading stops when CR of LR is found, which is stripped from the buffer.
463 *
464 * @retval SR_OK Success.
465 * @retval SR_ERR Failure.
466 */
467SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
468 int *buflen, gint64 timeout_ms)
469{
470 gint64 start;
471 int maxlen, len;
472
473 if (!serial) {
474 sr_dbg("Invalid serial port.");
475 return SR_ERR;
476 }
477
478 if (!serial->data) {
479 sr_dbg("Cannot use unopened serial port %s.", serial->port);
480 return -1;
481 }
482
483 timeout_ms *= 1000;
484 start = g_get_monotonic_time();
485
486 maxlen = *buflen;
487 *buflen = len = 0;
488 while(1) {
489 len = maxlen - *buflen - 1;
490 if (len < 1)
491 break;
492 len = serial_read(serial, *buf + *buflen, 1);
493 if (len > 0) {
494 *buflen += len;
495 *(*buf + *buflen) = '\0';
496 if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
497 || *(*buf + *buflen - 1) == '\n')) {
498 /* Strip CR/LF and terminate. */
499 *(*buf + --*buflen) = '\0';
500 break;
501 }
502 }
503 if (g_get_monotonic_time() - start > timeout_ms)
504 /* Timeout */
505 break;
506 if (len < 1)
507 g_usleep(2000);
508 }
509 if (*buflen)
510 sr_dbg("Received %d: '%s'.", *buflen, *buf);
511
512 return SR_OK;
513}
514
515/**
516 * Try to find a valid packet in a serial data stream.
517 *
518 * @param serial Previously initialized serial port structure.
519 * @param buf Buffer containing the bytes to write.
520 * @param buflen Size of the buffer.
521 * @param[in] packet_size Size, in bytes, of a valid packet.
522 * @param is_valid Callback that assesses whether the packet is valid or not.
523 * @param[in] timeout_ms The timeout after which, if no packet is detected, to
524 * abort scanning.
525 * @param[in] baudrate The baudrate of the serial port. This parameter is not
526 * critical, but it helps fine tune the serial port polling
527 * delay.
528 *
529 * @retval SR_OK Valid packet was found within the given timeout
530 * @retval SR_ERR Failure.
531 */
532SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
533 uint8_t *buf, size_t *buflen,
534 size_t packet_size, packet_valid_t is_valid,
535 uint64_t timeout_ms, int baudrate)
536{
537 uint64_t start, time, byte_delay_us;
538 size_t ibuf, i, maxlen;
539 int len;
540
541 maxlen = *buflen;
542
543 sr_dbg("Detecting packets on %s (timeout = %" PRIu64
544 "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
545
546 if (maxlen < (packet_size / 2) ) {
547 sr_err("Buffer size must be at least twice the packet size.");
548 return SR_ERR;
549 }
550
551 /* Assume 8n1 transmission. That is 10 bits for every byte. */
552 byte_delay_us = 10 * (1000000 / baudrate);
553 start = g_get_monotonic_time();
554
555 i = ibuf = len = 0;
556 while (ibuf < maxlen) {
557 len = serial_read(serial, &buf[ibuf], 1);
558 if (len > 0) {
559 ibuf += len;
560 } else if (len == 0) {
561 /* No logging, already done in serial_read(). */
562 } else {
563 /* Error reading byte, but continuing anyway. */
564 }
565
566 time = g_get_monotonic_time() - start;
567 time /= 1000;
568
569 if ((ibuf - i) >= packet_size) {
570 /* We have at least a packet's worth of data. */
571 if (is_valid(&buf[i])) {
572 sr_spew("Found valid %d-byte packet after "
573 "%" PRIu64 "ms.", (ibuf - i), time);
574 *buflen = ibuf;
575 return SR_OK;
576 } else {
577 sr_spew("Got %d bytes, but not a valid "
578 "packet.", (ibuf - i));
579 }
580 /* Not a valid packet. Continue searching. */
581 i++;
582 }
583 if (time >= timeout_ms) {
584 /* Timeout */
585 sr_dbg("Detection timed out after %dms.", time);
586 break;
587 }
588 if (len < 1)
589 g_usleep(byte_delay_us);
590 }
591
592 *buflen = ibuf;
593
594 sr_err("Didn't find a valid packet (read %d bytes).", *buflen);
595
596 return SR_ERR;
597}
598
599/**
600 * Extract the serial device and options from the options linked list.
601 *
602 * @param options List of options passed from the command line.
603 * @param serial_device Pointer where to store the exctracted serial device.
604 * @param serial_options Pointer where to store the optional extracted serial
605 * options.
606 *
607 * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
608 * returned string should not be freed by the caller.
609 */
610SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
611 const char **serial_options)
612{
613 GSList *l;
614 struct sr_config *src;
615
616 *serial_device = NULL;
617
618 for (l = options; l; l = l->next) {
619 src = l->data;
620 switch (src->key) {
621 case SR_CONF_CONN:
622 *serial_device = g_variant_get_string(src->data, NULL);
623 sr_dbg("Parsed serial device: %s", *serial_device);
624 break;
625
626 case SR_CONF_SERIALCOMM:
627 *serial_options = g_variant_get_string(src->data, NULL);
628 sr_dbg("Parsed serial options: %s", *serial_options);
629 break;
630 }
631 }
632
633 if (!*serial_device) {
634 sr_dbg("No serial device specified");
635 return SR_ERR;
636 }
637
638 return SR_OK;
639}
640
641#ifdef _WIN32
642typedef HANDLE event_handle;
643#else
644typedef int event_handle;
645#endif
646
647SR_PRIV int serial_source_add(struct sr_serial_dev_inst *serial, int events,
648 int timeout, sr_receive_data_callback_t cb, void *cb_data)
649{
650 enum sp_event mask = 0;
651 unsigned int i;
652
653 if (sp_new_event_set(&serial->event_set) != SP_OK)
654 return SR_ERR;
655
656 if (events & G_IO_IN)
657 mask |= SP_EVENT_RX_READY;
658 if (events & G_IO_OUT)
659 mask |= SP_EVENT_TX_READY;
660 if (events & G_IO_ERR)
661 mask |= SP_EVENT_ERROR;
662
663 if (sp_add_port_events(serial->event_set, serial->data, mask) != SP_OK) {
664 sp_free_event_set(serial->event_set);
665 return SR_ERR;
666 }
667
668 serial->pollfds = (GPollFD *) g_malloc0(sizeof(GPollFD) * serial->event_set->count);
669
670 for (i = 0; i < serial->event_set->count; i++) {
671
672 serial->pollfds[i].fd = ((event_handle *) serial->event_set->handles)[i];
673
674 mask = serial->event_set->masks[i];
675
676 if (mask & SP_EVENT_RX_READY)
677 serial->pollfds[i].events |= G_IO_IN;
678 if (mask & SP_EVENT_TX_READY)
679 serial->pollfds[i].events |= G_IO_OUT;
680 if (mask & SP_EVENT_ERROR)
681 serial->pollfds[i].events |= G_IO_ERR;
682
683 if (sr_session_source_add_pollfd(&serial->pollfds[i],
684 timeout, cb, cb_data) != SR_OK)
685 return SR_ERR;
686 }
687
688 return SR_OK;
689}
690
691SR_PRIV int serial_source_remove(struct sr_serial_dev_inst *serial)
692{
693 unsigned int i;
694
695 for (i = 0; i < serial->event_set->count; i++)
696 if (sr_session_source_remove_pollfd(&serial->pollfds[i]) != SR_OK)
697 return SR_ERR;
698
699 g_free(serial->pollfds);
700 sp_free_event_set(serial->event_set);
701
702 serial->pollfds = NULL;
703 serial->event_set = NULL;
704
705 return SR_OK;
706}