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