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