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