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