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  * Copyright (C) 2014 Uffe Jakobsen <uffe@uffe.org>
8  * Copyright (C) 2017-2019 Gerhard Sittig <gerhard.sittig@gmx.net>
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23 
24 #include <config.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <glib.h>
28 #include <glib/gstdio.h>
29 #ifdef HAVE_LIBSERIALPORT
30 #include <libserialport.h>
31 #endif
32 #include <libsigrok/libsigrok.h>
33 #include "libsigrok-internal.h"
34 #ifdef _WIN32
35 #include <windows.h> /* for HANDLE */
36 #endif
37 
38 /** @cond PRIVATE */
39 #define LOG_PREFIX "serial"
40 /** @endcond */
41 
42 /**
43  * @file
44  *
45  * Serial port handling.
46  */
47 
48 /**
49  * @defgroup grp_serial Serial port handling
50  *
51  * Serial port handling functions.
52  *
53  * @{
54  */
55 
56 #ifdef HAVE_SERIAL_COMM
57 
58 /* See if an (assumed opened) serial port is of any supported type. */
dev_is_supported(struct sr_serial_dev_inst * serial)59 static int dev_is_supported(struct sr_serial_dev_inst *serial)
60 {
61 	if (!serial || !serial->lib_funcs)
62 		return 0;
63 
64 	return 1;
65 }
66 
67 /**
68  * Open the specified serial port.
69  *
70  * @param serial Previously initialized serial port structure.
71  * @param[in] flags Flags to use when opening the serial port. Possible flags
72  *                  include SERIAL_RDWR, SERIAL_RDONLY.
73  *
74  * If the serial structure contains a serialcomm string, it will be
75  * passed to serial_set_paramstr() after the port is opened.
76  *
77  * @retval SR_OK Success.
78  * @retval SR_ERR Failure.
79  *
80  * @private
81  */
serial_open(struct sr_serial_dev_inst * serial,int flags)82 SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
83 {
84 	int ret;
85 
86 	if (!serial) {
87 		sr_dbg("Invalid serial port.");
88 		return SR_ERR;
89 	}
90 
91 	sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
92 
93 	/*
94 	 * Determine which serial transport library to use. Derive the
95 	 * variant from the serial port's name. Default to libserialport
96 	 * for backwards compatibility.
97 	 */
98 	if (ser_name_is_hid(serial))
99 		serial->lib_funcs = ser_lib_funcs_hid;
100 	else if (ser_name_is_bt(serial))
101 		serial->lib_funcs = ser_lib_funcs_bt;
102 	else
103 		serial->lib_funcs = ser_lib_funcs_libsp;
104 	if (!serial->lib_funcs)
105 		return SR_ERR_NA;
106 
107 	/*
108 	 * Note that use of the 'rcv_buffer' is optional, and the buffer's
109 	 * size heavily depends on the specific transport. That's why the
110 	 * buffer's content gets accessed and the buffer is released here in
111 	 * common code, but the buffer gets allocated in libraries' open()
112 	 * routines.
113 	 */
114 
115 	/*
116 	 * Run the transport's open routine. Setup the bitrate and the
117 	 * UART frame format.
118 	 */
119 	if (!serial->lib_funcs->open)
120 		return SR_ERR_NA;
121 	ret = serial->lib_funcs->open(serial, flags);
122 	if (ret != SR_OK)
123 		return ret;
124 
125 	if (serial->serialcomm)
126 		return serial_set_paramstr(serial, serial->serialcomm);
127 	else
128 		return SR_OK;
129 }
130 
131 /**
132  * Close the specified serial port.
133  *
134  * @param serial Previously initialized serial port structure.
135  *
136  * @retval SR_OK Success.
137  * @retval SR_ERR Failure.
138  *
139  * @private
140  */
serial_close(struct sr_serial_dev_inst * serial)141 SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
142 {
143 	int rc;
144 
145 	if (!serial) {
146 		sr_dbg("Invalid serial port.");
147 		return SR_ERR;
148 	}
149 
150 	sr_spew("Closing serial port %s.", serial->port);
151 
152 	if (!serial->lib_funcs || !serial->lib_funcs->close)
153 		return SR_ERR_NA;
154 
155 	rc = serial->lib_funcs->close(serial);
156 	if (rc == SR_OK && serial->rcv_buffer) {
157 		g_string_free(serial->rcv_buffer, TRUE);
158 		serial->rcv_buffer = NULL;
159 	}
160 
161 	return rc;
162 }
163 
164 /**
165  * Flush serial port buffers. Empty buffers, discard pending RX and TX data.
166  *
167  * @param serial Previously initialized serial port structure.
168  *
169  * @retval SR_OK Success.
170  * @retval SR_ERR Failure.
171  *
172  * @private
173  */
serial_flush(struct sr_serial_dev_inst * serial)174 SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
175 {
176 	if (!serial) {
177 		sr_dbg("Invalid serial port.");
178 		return SR_ERR;
179 	}
180 
181 	sr_spew("Flushing serial port %s.", serial->port);
182 
183 	sr_ser_discard_queued_data(serial);
184 
185 	if (!serial->lib_funcs || !serial->lib_funcs->flush)
186 		return SR_ERR_NA;
187 
188 	return serial->lib_funcs->flush(serial);
189 }
190 
191 /**
192  * Drain serial port buffers. Wait for pending TX data to be sent.
193  *
194  * @param serial Previously initialized serial port structure.
195  *
196  * @retval SR_OK Success.
197  * @retval SR_ERR Failure.
198  *
199  * @private
200  */
serial_drain(struct sr_serial_dev_inst * serial)201 SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
202 {
203 	if (!serial) {
204 		sr_dbg("Invalid serial port.");
205 		return SR_ERR;
206 	}
207 
208 	sr_spew("Draining serial port %s.", serial->port);
209 
210 	if (!serial->lib_funcs || !serial->lib_funcs->drain)
211 		return SR_ERR_NA;
212 
213 	return serial->lib_funcs->drain(serial);
214 }
215 
216 /*
217  * Provide an internal RX data buffer for the serial port. This is not
218  * supposed to be used directly by applications. Instead optional and
219  * alternative transports for serial communication can use this buffer
220  * if their progress is driven from background activity, and is not
221  * (directly) driven by external API calls.
222  *
223  * BEWARE! This implementation assumes that data which gets communicated
224  * via UART can get stored in a GString (which is a char array). Since
225  * the API hides this detail, we can address this issue later when needed.
226  * Callers use the API which communicates bytes.
227  *
228  * Applications optionally can register a "per RX chunk" callback, when
229  * they depend on the frame boundaries of the respective physical layer.
230  * Most callers just want the stream of RX data, and can use the buffer.
231  *
232  * The availability of RX chunks to callbacks, as well as the capability
233  * to pass on exact frames as chunks or potential re-assembly of chunks
234  * to a single data block, depend on each transport's implementation.
235  */
236 
237 /**
238  * Register application callback for RX data chunks.
239  *
240  * @param[in] serial Previously initialized serial port instance.
241  * @param[in] cb Routine to call as RX data becomes available.
242  * @param[in] cb_data User data to pass to the callback in addition to RX data.
243  *
244  * @retval SR_ERR_ARG Invalid parameters.
245  * @retval SR_OK Successful registration.
246  *
247  * Callbacks get unregistered by specifying #NULL for the 'cb' parameter.
248  */
serial_set_read_chunk_cb(struct sr_serial_dev_inst * serial,serial_rx_chunk_callback cb,void * cb_data)249 SR_PRIV int serial_set_read_chunk_cb(struct sr_serial_dev_inst *serial,
250 	serial_rx_chunk_callback cb, void *cb_data)
251 {
252 	if (!serial)
253 		return SR_ERR_ARG;
254 
255 	serial->rx_chunk_cb_func = cb;
256 	serial->rx_chunk_cb_data = cb_data;
257 
258 	return SR_OK;
259 }
260 
261 /**
262  * Discard previously queued RX data. Internal to the serial subsystem,
263  * coordination between common and transport specific support code.
264  *
265  * @param[in] serial Previously opened serial port instance.
266  *
267  * @internal
268  */
sr_ser_discard_queued_data(struct sr_serial_dev_inst * serial)269 SR_PRIV void sr_ser_discard_queued_data(struct sr_serial_dev_inst *serial)
270 {
271 	if (!serial || !serial->rcv_buffer)
272 		return;
273 
274 	g_string_truncate(serial->rcv_buffer, 0);
275 }
276 
277 /**
278  * Get amount of queued RX data. Internal to the serial subsystem,
279  * coordination between common and transport specific support code.
280  *
281  * @param[in] serial Previously opened serial port instance.
282  *
283  * @internal
284  */
sr_ser_has_queued_data(struct sr_serial_dev_inst * serial)285 SR_PRIV size_t sr_ser_has_queued_data(struct sr_serial_dev_inst *serial)
286 {
287 	if (!serial || !serial->rcv_buffer)
288 		return 0;
289 
290 	return serial->rcv_buffer->len;
291 }
292 
293 /**
294  * Queue received data. Internal to the serial subsystem, coordination
295  * between common and transport specific support code.
296  *
297  * @param[in] serial Previously opened serial port instance.
298  * @param[in] data Pointer to data bytes to queue.
299  * @param[in] len Number of data bytes to queue.
300  *
301  * @internal
302  */
sr_ser_queue_rx_data(struct sr_serial_dev_inst * serial,const uint8_t * data,size_t len)303 SR_PRIV void sr_ser_queue_rx_data(struct sr_serial_dev_inst *serial,
304 	const uint8_t *data, size_t len)
305 {
306 	if (!serial || !data || !len)
307 		return;
308 
309 	if (serial->rx_chunk_cb_func)
310 		serial->rx_chunk_cb_func(serial, serial->rx_chunk_cb_data, data, len);
311 	else if (serial->rcv_buffer)
312 		g_string_append_len(serial->rcv_buffer, (const gchar *)data, len);
313 }
314 
315 /**
316  * Retrieve previously queued RX data. Internal to the serial subsystem,
317  * coordination between common and transport specific support code.
318  *
319  * @param[in] serial Previously opened serial port instance.
320  * @param[out] data Pointer to store retrieved data bytes into.
321  * @param[in] len Number of data bytes to retrieve.
322  *
323  * @internal
324  */
sr_ser_unqueue_rx_data(struct sr_serial_dev_inst * serial,uint8_t * data,size_t len)325 SR_PRIV size_t sr_ser_unqueue_rx_data(struct sr_serial_dev_inst *serial,
326 	uint8_t *data, size_t len)
327 {
328 	size_t qlen;
329 	GString *buf;
330 
331 	if (!serial || !data || !len)
332 		return 0;
333 
334 	qlen = sr_ser_has_queued_data(serial);
335 	if (!qlen)
336 		return 0;
337 
338 	buf = serial->rcv_buffer;
339 	if (len > buf->len)
340 		len = buf->len;
341 	if (len) {
342 		memcpy(data, buf->str, len);
343 		g_string_erase(buf, 0, len);
344 	}
345 
346 	return len;
347 }
348 
349 /**
350  * Check for available receive data.
351  *
352  * @param[in] serial Previously opened serial port instance.
353  *
354  * @returns The number of (known) available RX data bytes.
355  *
356  * Returns 0 if no receive data is available, or if the amount of
357  * available receive data cannot get determined.
358  */
serial_has_receive_data(struct sr_serial_dev_inst * serial)359 SR_PRIV size_t serial_has_receive_data(struct sr_serial_dev_inst *serial)
360 {
361 	size_t lib_count, buf_count;
362 
363 	if (!serial)
364 		return 0;
365 
366 	lib_count = 0;
367 	if (serial->lib_funcs && serial->lib_funcs->get_rx_avail)
368 		lib_count = serial->lib_funcs->get_rx_avail(serial);
369 
370 	buf_count = sr_ser_has_queued_data(serial);
371 
372 	return lib_count + buf_count;
373 }
374 
_serial_write(struct sr_serial_dev_inst * serial,const void * buf,size_t count,int nonblocking,unsigned int timeout_ms)375 static int _serial_write(struct sr_serial_dev_inst *serial,
376 	const void *buf, size_t count,
377 	int nonblocking, unsigned int timeout_ms)
378 {
379 	ssize_t ret;
380 
381 	if (!serial) {
382 		sr_dbg("Invalid serial port.");
383 		return SR_ERR;
384 	}
385 
386 	if (!serial->lib_funcs || !serial->lib_funcs->write)
387 		return SR_ERR_NA;
388 	ret = serial->lib_funcs->write(serial, buf, count,
389 		nonblocking, timeout_ms);
390 	sr_spew("Wrote %zd/%zu bytes.", ret, count);
391 
392 	return ret;
393 }
394 
395 /**
396  * Write a number of bytes to the specified serial port, blocking until finished.
397  *
398  * @param serial Previously initialized serial port structure.
399  * @param[in] buf Buffer containing the bytes to write.
400  * @param[in] count Number of bytes to write.
401  * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
402  *
403  * @retval SR_ERR_ARG Invalid argument.
404  * @retval SR_ERR Other error.
405  * @retval other The number of bytes written. If this is less than the number
406  * specified in the call, the timeout was reached.
407  *
408  * @private
409  */
serial_write_blocking(struct sr_serial_dev_inst * serial,const void * buf,size_t count,unsigned int timeout_ms)410 SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
411 	const void *buf, size_t count, unsigned int timeout_ms)
412 {
413 	return _serial_write(serial, buf, count, 0, timeout_ms);
414 }
415 
416 /**
417  * Write a number of bytes to the specified serial port, return immediately.
418  *
419  * @param serial Previously initialized serial port structure.
420  * @param[in] buf Buffer containing the bytes to write.
421  * @param[in] count Number of bytes to write.
422  *
423  * @retval SR_ERR_ARG Invalid argument.
424  * @retval SR_ERR Other error.
425  * @retval other The number of bytes written.
426  *
427  * @private
428  */
serial_write_nonblocking(struct sr_serial_dev_inst * serial,const void * buf,size_t count)429 SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
430 	const void *buf, size_t count)
431 {
432 	return _serial_write(serial, buf, count, 1, 0);
433 }
434 
_serial_read(struct sr_serial_dev_inst * serial,void * buf,size_t count,int nonblocking,unsigned int timeout_ms)435 static int _serial_read(struct sr_serial_dev_inst *serial,
436 	void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
437 {
438 	ssize_t ret;
439 
440 	if (!serial) {
441 		sr_dbg("Invalid serial port.");
442 		return SR_ERR;
443 	}
444 
445 	if (!serial->lib_funcs || !serial->lib_funcs->read)
446 		return SR_ERR_NA;
447 	ret = serial->lib_funcs->read(serial, buf, count,
448 		nonblocking, timeout_ms);
449 	if (ret > 0)
450 		sr_spew("Read %zd/%zu bytes.", ret, count);
451 
452 	return ret;
453 }
454 
455 /**
456  * Read a number of bytes from the specified serial port, block until finished.
457  *
458  * @param serial Previously initialized serial port structure.
459  * @param buf Buffer where to store the bytes that are read.
460  * @param[in] count The number of bytes to read.
461  * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
462  *
463  * @retval SR_ERR_ARG Invalid argument.
464  * @retval SR_ERR Other error.
465  * @retval other The number of bytes read. If this is less than the number
466  * requested, the timeout was reached.
467  *
468  * @private
469  */
serial_read_blocking(struct sr_serial_dev_inst * serial,void * buf,size_t count,unsigned int timeout_ms)470 SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial,
471 	void *buf, size_t count, unsigned int timeout_ms)
472 {
473 	return _serial_read(serial, buf, count, 0, timeout_ms);
474 }
475 
476 /**
477  * Try to read up to @a count bytes from the specified serial port, return
478  * immediately with what's available.
479  *
480  * @param serial Previously initialized serial port structure.
481  * @param buf Buffer where to store the bytes that are read.
482  * @param[in] count The number of bytes to read.
483  *
484  * @retval SR_ERR_ARG Invalid argument.
485  * @retval SR_ERR Other error.
486  * @retval other The number of bytes read.
487  *
488  * @private
489  */
serial_read_nonblocking(struct sr_serial_dev_inst * serial,void * buf,size_t count)490 SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial,
491 	void *buf, size_t count)
492 {
493 	return _serial_read(serial, buf, count, 1, 0);
494 }
495 
496 /**
497  * Set serial parameters for the specified serial port.
498  *
499  * @param serial Previously initialized serial port structure.
500  * @param[in] baudrate The baudrate to set.
501  * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
502  * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
503  * @param[in] stopbits The number of stop bits to use (1 or 2).
504  * @param[in] flowcontrol The flow control settings to use (0 = none,
505  *                        1 = RTS/CTS, 2 = XON/XOFF).
506  * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
507  * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
508  *
509  * @retval SR_OK Success.
510  * @retval SR_ERR Failure.
511  *
512  * @private
513  */
serial_set_params(struct sr_serial_dev_inst * serial,int baudrate,int bits,int parity,int stopbits,int flowcontrol,int rts,int dtr)514 SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial,
515 	int baudrate, int bits, int parity, int stopbits,
516 	int flowcontrol, int rts, int dtr)
517 {
518 	int ret;
519 
520 	if (!serial) {
521 		sr_dbg("Invalid serial port.");
522 		return SR_ERR;
523 	}
524 
525 	sr_spew("Setting serial parameters on port %s.", serial->port);
526 
527 	if (!serial->lib_funcs || !serial->lib_funcs->set_params)
528 		return SR_ERR_NA;
529 	ret = serial->lib_funcs->set_params(serial,
530 		baudrate, bits, parity, stopbits,
531 		flowcontrol, rts, dtr);
532 	if (ret == SR_OK) {
533 		serial->comm_params.bit_rate = baudrate;
534 		serial->comm_params.data_bits = bits;
535 		serial->comm_params.parity_bits = parity ? 1 : 0;
536 		serial->comm_params.stop_bits = stopbits;
537 		sr_dbg("DBG: %s() rate %d, %d%s%d", __func__,
538 				baudrate, bits,
539 				(parity == 0) ? "n" : "x",
540 				stopbits);
541 	}
542 
543 	return ret;
544 }
545 
546 /**
547  * Set serial parameters for the specified serial port from parameter string.
548  *
549  * @param serial Previously initialized serial port structure.
550  * @param[in] paramstr A serial communication parameters string of the form
551  * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
552  * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
553  * \<baudrate\>=integer Baud rate.\n
554  * \<bits\>=5|6|7|8 Number of data bits.\n
555  * \<parity\>=n|e|o None, even, odd.\n
556  * \<stopbits\>=1|2 One or two stop bits.\n
557  * Options:\n
558  * dtr=0|1 Set DTR off resp. on.\n
559  * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
560  * rts=0|1 Set RTS off resp. on.\n
561  * Please note that values and combinations of these parameters must be
562  * supported by the concrete serial interface hardware and the drivers for it.
563  *
564  * @retval SR_OK Success.
565  * @retval SR_ERR Failure.
566  *
567  * @private
568  */
serial_set_paramstr(struct sr_serial_dev_inst * serial,const char * paramstr)569 SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
570 	const char *paramstr)
571 {
572 /** @cond PRIVATE */
573 #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
574 /** @endcond */
575 
576 	GRegex *reg;
577 	GMatchInfo *match;
578 	int speed, databits, parity, stopbits, flow, rts, dtr, i;
579 	char *mstr, **opts, **kv;
580 
581 	speed = databits = parity = stopbits = flow = 0;
582 	rts = dtr = -1;
583 	sr_spew("Parsing parameters from \"%s\".", paramstr);
584 	reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
585 	if (g_regex_match(reg, paramstr, 0, &match)) {
586 		if ((mstr = g_match_info_fetch(match, 1)))
587 			speed = strtoul(mstr, NULL, 10);
588 		g_free(mstr);
589 		if ((mstr = g_match_info_fetch(match, 2)))
590 			databits = strtoul(mstr, NULL, 10);
591 		g_free(mstr);
592 		if ((mstr = g_match_info_fetch(match, 3))) {
593 			switch (mstr[0]) {
594 			case 'n':
595 				parity = SP_PARITY_NONE;
596 				break;
597 			case 'e':
598 				parity = SP_PARITY_EVEN;
599 				break;
600 			case 'o':
601 				parity = SP_PARITY_ODD;
602 				break;
603 			}
604 		}
605 		g_free(mstr);
606 		if ((mstr = g_match_info_fetch(match, 4)))
607 			stopbits = strtoul(mstr, NULL, 10);
608 		g_free(mstr);
609 		if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
610 			if (mstr[0] != '/') {
611 				sr_dbg("missing separator before extra options");
612 				speed = 0;
613 			} else {
614 				/* A set of "key=value" options separated by / */
615 				opts = g_strsplit(mstr + 1, "/", 0);
616 				for (i = 0; opts[i]; i++) {
617 					kv = g_strsplit(opts[i], "=", 2);
618 					if (!strncmp(kv[0], "rts", 3)) {
619 						if (kv[1][0] == '1')
620 							rts = 1;
621 						else if (kv[1][0] == '0')
622 							rts = 0;
623 						else {
624 							sr_dbg("invalid value for rts: %c", kv[1][0]);
625 							speed = 0;
626 						}
627 					} else if (!strncmp(kv[0], "dtr", 3)) {
628 						if (kv[1][0] == '1')
629 							dtr = 1;
630 						else if (kv[1][0] == '0')
631 							dtr = 0;
632 						else {
633 							sr_dbg("invalid value for dtr: %c", kv[1][0]);
634 							speed = 0;
635 						}
636 					} else if (!strncmp(kv[0], "flow", 4)) {
637 						if (kv[1][0] == '0')
638 							flow = 0;
639 						else if (kv[1][0] == '1')
640 							flow = 1;
641 						else if (kv[1][0] == '2')
642 							flow = 2;
643 						else {
644 							sr_dbg("invalid value for flow: %c", kv[1][0]);
645 							speed = 0;
646 						}
647 					}
648 					g_strfreev(kv);
649 				}
650 				g_strfreev(opts);
651 			}
652 		}
653 		g_free(mstr);
654 	}
655 	g_match_info_unref(match);
656 	g_regex_unref(reg);
657 
658 	if (speed) {
659 		return serial_set_params(serial, speed, databits, parity,
660 					 stopbits, flow, rts, dtr);
661 	} else {
662 		sr_dbg("Could not infer speed from parameter string.");
663 		return SR_ERR_ARG;
664 	}
665 }
666 
667 /**
668  * Read a line from the specified serial port.
669  *
670  * @param[in] serial Previously initialized serial port structure.
671  * @param[out] buf Buffer where to store the bytes that are read.
672  * @param[in] buflen Size of the buffer.
673  * @param[in] timeout_ms How long to wait for a line to come in.
674  *
675  * Reading stops when CR or LF is found, which is stripped from the buffer.
676  *
677  * @retval SR_OK Success.
678  * @retval SR_ERR Failure.
679  *
680  * @private
681  */
serial_readline(struct sr_serial_dev_inst * serial,char ** buf,int * buflen,gint64 timeout_ms)682 SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial,
683 	char **buf, int *buflen, gint64 timeout_ms)
684 {
685 	gint64 start, remaining;
686 	int maxlen, len;
687 
688 	if (!serial) {
689 		sr_dbg("Invalid serial port.");
690 		return SR_ERR;
691 	}
692 
693 	if (!dev_is_supported(serial)) {
694 		sr_dbg("Cannot use unopened serial port %s.", serial->port);
695 		return -1;
696 	}
697 
698 	start = g_get_monotonic_time();
699 	remaining = timeout_ms;
700 
701 	maxlen = *buflen;
702 	*buflen = len = 0;
703 	while (1) {
704 		len = maxlen - *buflen - 1;
705 		if (len < 1)
706 			break;
707 		len = serial_read_blocking(serial, *buf + *buflen, 1, remaining);
708 		if (len > 0) {
709 			*buflen += len;
710 			*(*buf + *buflen) = '\0';
711 			if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
712 					|| *(*buf + *buflen - 1) == '\n')) {
713 				/* Strip CR/LF and terminate. */
714 				*(*buf + --*buflen) = '\0';
715 				break;
716 			}
717 		}
718 		/* Reduce timeout by time elapsed. */
719 		remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
720 		if (remaining <= 0)
721 			/* Timeout */
722 			break;
723 		if (len < 1)
724 			g_usleep(2000);
725 	}
726 	if (*buflen)
727 		sr_dbg("Received %d: '%s'.", *buflen, *buf);
728 
729 	return SR_OK;
730 }
731 
732 /**
733  * Try to find a valid packet in a serial data stream.
734  *
735  * @param serial Previously initialized serial port structure.
736  * @param buf Buffer containing the bytes to write.
737  * @param buflen Size of the buffer.
738  * @param[in] packet_size Size, in bytes, of a valid packet.
739  * @param is_valid Callback that assesses whether the packet is valid or not.
740  * @param[in] timeout_ms The timeout after which, if no packet is detected, to
741  *                       abort scanning.
742  *
743  * @retval SR_OK Valid packet was found within the given timeout.
744  * @retval SR_ERR Failure.
745  *
746  * @private
747  */
serial_stream_detect(struct sr_serial_dev_inst * serial,uint8_t * buf,size_t * buflen,size_t packet_size,packet_valid_callback is_valid,uint64_t timeout_ms)748 SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
749 	uint8_t *buf, size_t *buflen,
750 	size_t packet_size,
751 	packet_valid_callback is_valid,
752 	uint64_t timeout_ms)
753 {
754 	uint64_t start, time, byte_delay_us;
755 	size_t ibuf, i, maxlen;
756 	ssize_t len;
757 
758 	maxlen = *buflen;
759 
760 	sr_dbg("Detecting packets on %s (timeout = %" PRIu64 "ms).",
761 		serial->port, timeout_ms);
762 
763 	if (maxlen < (packet_size * 2) ) {
764 		sr_err("Buffer size must be at least twice the packet size.");
765 		return SR_ERR;
766 	}
767 
768 	/* Assume 8n1 transmission. That is 10 bits for every byte. */
769 	byte_delay_us = serial_timeout(serial, 1) * 1000;
770 	start = g_get_monotonic_time();
771 
772 	i = ibuf = len = 0;
773 	while (ibuf < maxlen) {
774 		len = serial_read_nonblocking(serial, &buf[ibuf], 1);
775 		if (len > 0) {
776 			ibuf += len;
777 		} else if (len == 0) {
778 			/* No logging, already done in serial_read(). */
779 		} else {
780 			/* Error reading byte, but continuing anyway. */
781 		}
782 
783 		time = g_get_monotonic_time() - start;
784 		time /= 1000;
785 
786 		if ((ibuf - i) >= packet_size) {
787 			GString *text;
788 			/* We have at least a packet's worth of data. */
789 			text = sr_hexdump_new(&buf[i], packet_size);
790 			sr_spew("Trying packet: %s", text->str);
791 			sr_hexdump_free(text);
792 			if (is_valid(&buf[i])) {
793 				sr_spew("Found valid %zu-byte packet after "
794 					"%" PRIu64 "ms.", (ibuf - i), time);
795 				*buflen = ibuf;
796 				return SR_OK;
797 			} else {
798 				sr_spew("Got %zu bytes, but not a valid "
799 					"packet.", (ibuf - i));
800 			}
801 			/* Not a valid packet. Continue searching. */
802 			i++;
803 		}
804 		if (time >= timeout_ms) {
805 			/* Timeout */
806 			sr_dbg("Detection timed out after %" PRIu64 "ms.", time);
807 			break;
808 		}
809 		if (len < 1)
810 			g_usleep(byte_delay_us);
811 	}
812 
813 	*buflen = ibuf;
814 
815 	sr_err("Didn't find a valid packet (read %zu bytes).", *buflen);
816 
817 	return SR_ERR;
818 }
819 
820 /**
821  * Extract the serial device and options from the options linked list.
822  *
823  * @param options List of options passed from the command line.
824  * @param serial_device Pointer where to store the extracted serial device.
825  * @param serial_options Pointer where to store the optional extracted serial
826  * options.
827  *
828  * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
829  * returned string should not be freed by the caller.
830  *
831  * @private
832  */
sr_serial_extract_options(GSList * options,const char ** serial_device,const char ** serial_options)833 SR_PRIV int sr_serial_extract_options(GSList *options,
834 	const char **serial_device, const char **serial_options)
835 {
836 	GSList *l;
837 	struct sr_config *src;
838 
839 	*serial_device = NULL;
840 
841 	for (l = options; l; l = l->next) {
842 		src = l->data;
843 		switch (src->key) {
844 		case SR_CONF_CONN:
845 			*serial_device = g_variant_get_string(src->data, NULL);
846 			sr_dbg("Parsed serial device: %s.", *serial_device);
847 			break;
848 		case SR_CONF_SERIALCOMM:
849 			*serial_options = g_variant_get_string(src->data, NULL);
850 			sr_dbg("Parsed serial options: %s.", *serial_options);
851 			break;
852 		}
853 	}
854 
855 	if (!*serial_device) {
856 		sr_dbg("No serial device specified.");
857 		return SR_ERR;
858 	}
859 
860 	return SR_OK;
861 }
862 
863 /** @private */
serial_source_add(struct sr_session * session,struct sr_serial_dev_inst * serial,int events,int timeout,sr_receive_data_callback cb,void * cb_data)864 SR_PRIV int serial_source_add(struct sr_session *session,
865 	struct sr_serial_dev_inst *serial, int events, int timeout,
866 	sr_receive_data_callback cb, void *cb_data)
867 {
868 	if ((events & (G_IO_IN | G_IO_ERR)) && (events & G_IO_OUT)) {
869 		sr_err("Cannot poll input/error and output simultaneously.");
870 		return SR_ERR_ARG;
871 	}
872 
873 	if (!dev_is_supported(serial)) {
874 		sr_err("Invalid serial port.");
875 		return SR_ERR_ARG;
876 	}
877 
878 	if (!serial->lib_funcs || !serial->lib_funcs->setup_source_add)
879 		return SR_ERR_NA;
880 
881 	return serial->lib_funcs->setup_source_add(session, serial,
882 		events, timeout, cb, cb_data);
883 }
884 
885 /** @private */
serial_source_remove(struct sr_session * session,struct sr_serial_dev_inst * serial)886 SR_PRIV int serial_source_remove(struct sr_session *session,
887 	struct sr_serial_dev_inst *serial)
888 {
889 	if (!dev_is_supported(serial)) {
890 		sr_err("Invalid serial port.");
891 		return SR_ERR_ARG;
892 	}
893 
894 	if (!serial->lib_funcs || !serial->lib_funcs->setup_source_remove)
895 		return SR_ERR_NA;
896 
897 	return serial->lib_funcs->setup_source_remove(session, serial);
898 }
899 
900 /**
901  * Create/allocate a new sr_serial_port structure.
902  *
903  * @param name The OS dependent name of the serial port. Must not be NULL.
904  * @param description An end user friendly description for the serial port.
905  *                    Can be NULL (in that case the empty string is used
906  *                    as description).
907  *
908  * @return The newly allocated sr_serial_port struct.
909  */
sr_serial_new(const char * name,const char * description)910 static struct sr_serial_port *sr_serial_new(const char *name,
911 	const char *description)
912 {
913 	struct sr_serial_port *serial;
914 
915 	if (!name)
916 		return NULL;
917 
918 	serial = g_malloc0(sizeof(*serial));
919 	serial->name = g_strdup(name);
920 	serial->description = g_strdup(description ? description : "");
921 
922 	return serial;
923 }
924 
925 /**
926  * Free a previously allocated sr_serial_port structure.
927  *
928  * @param serial The sr_serial_port struct to free. Must not be NULL.
929  */
sr_serial_free(struct sr_serial_port * serial)930 SR_API void sr_serial_free(struct sr_serial_port *serial)
931 {
932 	if (!serial)
933 		return;
934 	g_free(serial->name);
935 	g_free(serial->description);
936 	g_free(serial);
937 }
938 
append_port_list(GSList * devs,const char * name,const char * desc)939 static GSList *append_port_list(GSList *devs, const char *name, const char *desc)
940 {
941 	return g_slist_append(devs, sr_serial_new(name, desc));
942 }
943 
944 /**
945  * List available serial devices.
946  *
947  * @return A GSList of strings containing the path of the serial devices or
948  *         NULL if no serial device is found. The returned list must be freed
949  *         by the caller.
950  */
sr_serial_list(const struct sr_dev_driver * driver)951 SR_API GSList *sr_serial_list(const struct sr_dev_driver *driver)
952 {
953 	GSList *tty_devs;
954 	GSList *(*list_func)(GSList *list, sr_ser_list_append_t append);
955 
956 	/* Currently unused, but will be used by some drivers later on. */
957 	(void)driver;
958 
959 	tty_devs = NULL;
960 	if (ser_lib_funcs_libsp && ser_lib_funcs_libsp->list) {
961 		list_func = ser_lib_funcs_libsp->list;
962 		tty_devs = list_func(tty_devs, append_port_list);
963 	}
964 	if (ser_lib_funcs_hid && ser_lib_funcs_hid->list) {
965 		list_func = ser_lib_funcs_hid->list;
966 		tty_devs = list_func(tty_devs, append_port_list);
967 	}
968 	if (ser_lib_funcs_bt && ser_lib_funcs_bt->list) {
969 		list_func = ser_lib_funcs_bt->list;
970 		tty_devs = list_func(tty_devs, append_port_list);
971 	}
972 
973 	return tty_devs;
974 }
975 
append_port_find(GSList * devs,const char * name)976 static GSList *append_port_find(GSList *devs, const char *name)
977 {
978 	if (!name || !*name)
979 		return devs;
980 
981 	return g_slist_append(devs, g_strdup(name));
982 }
983 
984 /**
985  * Find USB serial devices via the USB vendor ID and product ID.
986  *
987  * @param[in] vendor_id Vendor ID of the USB device.
988  * @param[in] product_id Product ID of the USB device.
989  *
990  * @return A GSList of strings containing the path of the serial device or
991  *         NULL if no serial device is found. The returned list must be freed
992  *         by the caller.
993  *
994  * @private
995  */
sr_serial_find_usb(uint16_t vendor_id,uint16_t product_id)996 SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
997 {
998 	GSList *tty_devs;
999 	GSList *(*find_func)(GSList *list, sr_ser_find_append_t append,
1000 			uint16_t vid, uint16_t pid);
1001 
1002 	tty_devs = NULL;
1003 	if (ser_lib_funcs_libsp && ser_lib_funcs_libsp->find_usb) {
1004 		find_func = ser_lib_funcs_libsp->find_usb;
1005 		tty_devs = find_func(tty_devs, append_port_find,
1006 			vendor_id, product_id);
1007 	}
1008 	if (ser_lib_funcs_hid && ser_lib_funcs_hid->find_usb) {
1009 		find_func = ser_lib_funcs_hid->find_usb;
1010 		tty_devs = find_func(tty_devs, append_port_find,
1011 			vendor_id, product_id);
1012 	}
1013 
1014 	return tty_devs;
1015 }
1016 
1017 /** @private */
serial_timeout(struct sr_serial_dev_inst * port,int num_bytes)1018 SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
1019 {
1020 	int bits, baud, ret, timeout_ms;
1021 
1022 	/* Get the bitrate and frame length. */
1023 	bits = baud = 0;
1024 	if (port->lib_funcs && port->lib_funcs->get_frame_format) {
1025 		ret = port->lib_funcs->get_frame_format(port, &baud, &bits);
1026 		if (ret != SR_OK)
1027 			bits = baud = 0;
1028 	} else {
1029 		baud = port->comm_params.bit_rate;
1030 		bits = 1 + port->comm_params.data_bits +
1031 			port->comm_params.parity_bits +
1032 			port->comm_params.stop_bits;
1033 	}
1034 
1035 	/* Derive the timeout. Default to 1s. */
1036 	timeout_ms = 1000;
1037 	if (bits && baud) {
1038 		/* Throw in 10ms for misc OS overhead. */
1039 		timeout_ms = 10;
1040 		timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
1041 	}
1042 
1043 	return timeout_ms;
1044 }
1045 
1046 #else
1047 
1048 /* TODO Put fallback.c content here? */
1049 
1050 #endif
1051 
1052 /** @} */
1053