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