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