2 * This file is part of the libsigrok project.
4 * Copyright (C) 2018-2019 Gerhard Sittig <gerhard.sittig@gmx.net>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include <libsigrok/libsigrok.h>
23 #include "libsigrok-internal.h"
27 #define LOG_PREFIX "serial-bt"
29 #ifdef HAVE_SERIAL_COMM
32 #define SER_BT_CONN_PREFIX "bt"
33 #define SER_BT_CHUNK_SIZE 1200
35 #define SER_BT_PARAM_PREFIX_CHANNEL "channel="
36 #define SER_BT_PARAM_PREFIX_HDL_RX "handle_rx="
37 #define SER_BT_PARAM_PREFIX_HDL_TX "handle_tx="
38 #define SER_BT_PARAM_PREFIX_HDL_CCCD "handle_cccd="
39 #define SER_BT_PARAM_PREFIX_VAL_CCCD "value_cccd="
44 * Serial port handling, wraps the external BT/BLE dependencies.
48 * @defgroup grp_serial_bt Serial port handling, BT/BLE group
50 * Make serial-over-BT communication appear like a regular serial port.
55 /* {{{ support for serial-over-BT channels */
57 static const struct scan_supported_item {
59 enum ser_bt_conn_t type;
60 const char *add_params;
61 } scan_supported_items[] = {
62 /* Guess connection types from device names (useful for scans). */
63 { "121GW", SER_BT_CONN_BLE122, NULL, },
64 { "Adafruit Bluefruit LE 8134", SER_BT_CONN_NRF51, NULL, },
65 { "HC-05", SER_BT_CONN_RFCOMM, NULL, },
66 { "UM25C", SER_BT_CONN_RFCOMM, NULL, },
67 { NULL, SER_BT_CONN_UNKNOWN, NULL, },
70 static const char *ser_bt_conn_names[SER_BT_CONN_MAX] = {
71 [SER_BT_CONN_UNKNOWN] = "<type>",
72 [SER_BT_CONN_RFCOMM] = "rfcomm",
73 [SER_BT_CONN_BLE122] = "ble122",
74 [SER_BT_CONN_NRF51] = "nrf51",
75 [SER_BT_CONN_CC254x] = "cc254x",
78 static enum ser_bt_conn_t lookup_conn_name(const char *name)
84 return SER_BT_CONN_UNKNOWN;
85 idx = ARRAY_SIZE(ser_bt_conn_names);
87 item = ser_bt_conn_names[idx];
88 if (strcmp(item, name) == 0)
92 return SER_BT_CONN_UNKNOWN;
95 static const char *conn_name_text(enum ser_bt_conn_t type)
97 if (type >= ARRAY_SIZE(ser_bt_conn_names))
98 type = SER_BT_CONN_UNKNOWN;
100 return ser_bt_conn_names[type];
104 * Parse conn= specs for serial over Bluetooth communication.
106 * @param[in] serial The serial port that is about to get opened.
107 * @param[in] spec The caller provided conn= specification.
108 * @param[out] conn_type The type of BT comm (BT RFCOMM, BLE notify).
109 * @param[out] remote_addr The remote device address.
110 * @param[out] rfcomm_channel The RFCOMM channel (if applicable).
111 * @param[out] read_hdl The BLE notify read handle (if applicable).
112 * @param[out] write_hdl The BLE notify write handle (if applicable).
113 * @param[out] cccd_hdl The BLE notify CCCD handle (if applicable).
114 * @param[out] cccd_val The BLE notify CCCD value (if applicable).
116 * @return 0 upon success, non-zero upon failure.
118 * Summary of parsing rules as they are implemented:
119 * - Implementor's note: Automatic scan for available devices is not
120 * yet implemented. So strictly speaking some parts of the input
121 * spec are optional, but fallbacks may not take effect ATM.
122 * - Insist on the "bt" prefix. Accept "bt" alone without any other
124 * - The first field that follows is the connection type. Supported
125 * types are 'rfcomm', 'ble122', 'cc254x', and potentially others
126 * in a future implementation.
127 * - The next field is the remote device's address, either separated
128 * by colons or dashes or spaces, or not separated at all.
129 * - Other parameters (RFCOMM channel, notify handles and write values)
130 * get derived from the connection type.
131 * - More fields after the remote address are options which override
132 * builtin defaults (RFCOMM channels, BLE handles, etc).
134 * Supported formats resulting from these rules:
135 * bt/<conn>/<addr>[/<param>]...
138 * bt/rfcomm/11-22-33-44-55-66
139 * bt/rfcomm/11-22-33-44-55-66/channel=2
140 * bt/ble122/88:6b:12:34:56:78
141 * bt/cc254x/0123456789ab
143 * It's assumed that users easily can create those conn= specs from
144 * available information, or that scan routines will create such specs
145 * that copy'n'paste results (or GUI choices from previous scan results)
146 * can get processed here.
148 static int ser_bt_parse_conn_spec(
149 struct sr_serial_dev_inst *serial, const char *spec,
150 enum ser_bt_conn_t *conn_type, const char **remote_addr,
151 size_t *rfcomm_channel,
152 uint16_t *read_hdl, uint16_t *write_hdl,
153 uint16_t *cccd_hdl, uint16_t *cccd_val)
155 char **fields, *field;
156 enum ser_bt_conn_t type;
159 size_t fields_count, field_idx;
161 unsigned long parm_val;
164 *conn_type = SER_BT_CONN_UNKNOWN;
178 if (!serial || !spec || !spec[0])
181 /* Evaluate the mandatory first three fields. */
182 fields = g_strsplit_set(spec, "/", 0);
185 if (g_strv_length(fields) < 3) {
190 if (strcmp(field, SER_BT_CONN_PREFIX) != 0) {
195 type = lookup_conn_name(field);
203 if (!field || !*field) {
207 addr = g_strdup(field);
211 /* Derive default parameters that match the connection type. */
212 /* TODO Lookup defaults from a table? */
214 case SER_BT_CONN_RFCOMM:
218 case SER_BT_CONN_BLE122:
228 case SER_BT_CONN_NRF51:
230 * Are these values appropriate? Check the learn article at
231 * https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend?view=all
241 /* TODO 'random' type, sec-level=high */
243 case SER_BT_CONN_CC254x:
244 /* TODO Are these values appropriate? Just guessing here. */
259 * Preset a successful return value for the conn= parse call.
260 * Scan optional additional fields which specify more params.
261 * Update the defaults which were setup above. Pessimize the
262 * routine's return value in error paths.
265 fields_count = g_strv_length(fields);
266 for (field_idx = 3; field_idx < fields_count; field_idx++) {
267 field = fields[field_idx];
268 if (!field || !*field)
270 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_CHANNEL)) {
271 field += strlen(SER_BT_PARAM_PREFIX_CHANNEL);
273 ret = sr_atoul_base(field, &parm_val, &endp, 0);
274 if (ret != SR_OK || !endp || *endp != '\0') {
275 ret_parse = SR_ERR_ARG;
279 *rfcomm_channel = parm_val;
282 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_HDL_RX)) {
283 field += strlen(SER_BT_PARAM_PREFIX_HDL_RX);
285 ret = sr_atoul_base(field, &parm_val, &endp, 0);
286 if (ret != SR_OK || !endp || *endp != '\0') {
287 ret_parse = SR_ERR_ARG;
291 *read_hdl = parm_val;
294 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_HDL_TX)) {
295 field += strlen(SER_BT_PARAM_PREFIX_HDL_TX);
297 ret = sr_atoul_base(field, &parm_val, &endp, 0);
298 if (ret != SR_OK || !endp || *endp != '\0') {
299 ret_parse = SR_ERR_ARG;
303 *write_hdl = parm_val;
306 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_HDL_CCCD)) {
307 field += strlen(SER_BT_PARAM_PREFIX_HDL_CCCD);
309 ret = sr_atoul_base(field, &parm_val, &endp, 0);
310 if (ret != SR_OK || !endp || *endp != '\0') {
311 ret_parse = SR_ERR_ARG;
315 *cccd_hdl = parm_val;
318 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_VAL_CCCD)) {
319 field += strlen(SER_BT_PARAM_PREFIX_VAL_CCCD);
321 ret = sr_atoul_base(field, &parm_val, &endp, 0);
322 if (ret != SR_OK || !endp || *endp != '\0') {
323 ret_parse = SR_ERR_ARG;
327 *cccd_val = parm_val;
337 static void ser_bt_mask_databits(struct sr_serial_dev_inst *serial,
338 uint8_t *data, size_t len)
344 if ((serial->comm_params.data_bits % 8) == 0)
347 mask32 = (1UL << serial->comm_params.data_bits) - 1;
348 mask = mask32 & 0xff;
349 for (idx = 0; idx < len; idx++)
353 static int ser_bt_data_cb(void *cb_data, uint8_t *data, size_t dlen)
355 struct sr_serial_dev_inst *serial;
361 ser_bt_mask_databits(serial, data, dlen);
362 sr_ser_queue_rx_data(serial, data, dlen);
368 /* {{{ wrap serial-over-BT operations in a common serial.c API */
370 /* See if a serial port's name refers to a BT type. */
371 SR_PRIV int ser_name_is_bt(struct sr_serial_dev_inst *serial)
378 if (!serial->port || !*serial->port)
381 /* Accept either "bt" alone, or "bt/" as a prefix. */
382 if (!g_str_has_prefix(serial->port, SER_BT_CONN_PREFIX))
384 off = strlen(SER_BT_CONN_PREFIX);
385 sep = serial->port[off];
386 if (sep != '\0' && sep != '/')
392 /* The open() wrapper for BT ports. */
393 static int ser_bt_open(struct sr_serial_dev_inst *serial, int flags)
395 enum ser_bt_conn_t conn_type;
396 const char *remote_addr;
397 size_t rfcomm_channel;
398 uint16_t read_hdl, write_hdl, cccd_hdl, cccd_val;
400 struct sr_bt_desc *desc;
404 /* Derive BT specific parameters from the port spec. */
405 rc = ser_bt_parse_conn_spec(serial, serial->port,
406 &conn_type, &remote_addr,
408 &read_hdl, &write_hdl,
409 &cccd_hdl, &cccd_val);
413 if (!conn_type || !remote_addr || !remote_addr[0]) {
414 /* TODO Auto-search for available connections? */
418 /* Create the connection. Only store params after successful use. */
419 desc = sr_bt_desc_new();
422 serial->bt_desc = desc;
423 rc = sr_bt_config_addr_remote(desc, remote_addr);
426 serial->bt_addr_remote = g_strdup(remote_addr);
428 case SER_BT_CONN_RFCOMM:
429 rc = sr_bt_config_rfcomm(desc, rfcomm_channel);
432 serial->bt_rfcomm_channel = rfcomm_channel;
434 case SER_BT_CONN_BLE122:
435 case SER_BT_CONN_NRF51:
436 case SER_BT_CONN_CC254x:
437 rc = sr_bt_config_notify(desc,
438 read_hdl, write_hdl, cccd_hdl, cccd_val);
441 serial->bt_notify_handle_read = read_hdl;
442 serial->bt_notify_handle_write = write_hdl;
443 serial->bt_notify_handle_cccd = cccd_hdl;
444 serial->bt_notify_value_cccd = cccd_val;
447 /* Unsupported type, or incomplete implementation. */
450 serial->bt_conn_type = conn_type;
452 /* Make sure the receive buffer can accept input data. */
453 if (!serial->rcv_buffer)
454 serial->rcv_buffer = g_string_sized_new(SER_BT_CHUNK_SIZE);
455 rc = sr_bt_config_cb_data(desc, ser_bt_data_cb, serial);
459 /* Open the connection. */
461 case SER_BT_CONN_RFCOMM:
462 rc = sr_bt_connect_rfcomm(desc);
466 case SER_BT_CONN_BLE122:
467 case SER_BT_CONN_NRF51:
468 case SER_BT_CONN_CC254x:
469 rc = sr_bt_connect_ble(desc);
472 rc = sr_bt_start_notify(desc);
483 static int ser_bt_close(struct sr_serial_dev_inst *serial)
488 if (!serial->bt_desc)
491 sr_bt_disconnect(serial->bt_desc);
492 sr_bt_desc_free(serial->bt_desc);
493 serial->bt_desc = NULL;
495 g_free(serial->bt_addr_local);
496 serial->bt_addr_local = NULL;
497 g_free(serial->bt_addr_remote);
498 serial->bt_addr_remote = NULL;
499 g_slist_free_full(serial->bt_source_args, g_free);
500 serial->bt_source_args = NULL;
505 /* Flush, discards pending RX data, empties buffers. */
506 static int ser_bt_flush(struct sr_serial_dev_inst *serial)
514 /* Drain, waits for completion of pending TX data. */
515 static int ser_bt_drain(struct sr_serial_dev_inst *serial)
518 /* EMPTY */ /* TODO? */
523 static int ser_bt_write(struct sr_serial_dev_inst *serial,
524 const void *buf, size_t count,
525 int nonblocking, unsigned int timeout_ms)
530 * TODO Support chunked transmission when callers' requests
531 * exceed the BT channel's capacity? See ser_hid_write().
534 switch (serial->bt_conn_type) {
535 case SER_BT_CONN_RFCOMM:
538 wrlen = sr_bt_write(serial->bt_desc, buf, count);
542 case SER_BT_CONN_BLE122:
543 case SER_BT_CONN_NRF51:
544 case SER_BT_CONN_CC254x:
546 * Assume that when applications call the serial layer's
547 * write routine, then the BLE chip/module does support
548 * a TX handle. Just call the serial-BT library's write
553 wrlen = sr_bt_write(serial->bt_desc, buf, count);
563 static int ser_bt_read(struct sr_serial_dev_inst *serial,
564 void *buf, size_t count,
565 int nonblocking, unsigned int timeout_ms)
567 gint64 deadline_us, now_us;
568 uint8_t buffer[SER_BT_CHUNK_SIZE];
574 * Immediately satisfy the caller's request from the RX buffer
575 * if the requested amount of data is available already.
577 if (sr_ser_has_queued_data(serial) >= count)
578 return sr_ser_unqueue_rx_data(serial, buf, count);
581 * When a timeout was specified, then determine the deadline
582 * where to stop reception.
586 now_us = g_get_monotonic_time();
587 deadline_us = now_us + timeout_ms * 1000;
591 * Keep receiving from the port until the caller's requested
592 * amount of data has become available, or the timeout has
593 * expired. In the absence of a timeout, stop reading when an
594 * attempt no longer yields receive data.
597 /* Run another attempt to receive data. */
598 switch (serial->bt_conn_type) {
599 case SER_BT_CONN_RFCOMM:
600 rdlen = sr_bt_read(serial->bt_desc, buffer, sizeof(buffer));
603 rc = ser_bt_data_cb(serial, buffer, rdlen);
607 case SER_BT_CONN_BLE122:
608 case SER_BT_CONN_NRF51:
609 case SER_BT_CONN_CC254x:
610 dlen = sr_ser_has_queued_data(serial);
611 rc = sr_bt_check_notify(serial->bt_desc);
614 else if (sr_ser_has_queued_data(serial) != dlen)
625 * Stop upon receive errors, or timeout expiration. Only
626 * stop upon empty reception in the absence of a timeout.
630 if (nonblocking && !rdlen)
633 now_us = g_get_monotonic_time();
634 if (now_us > deadline_us)
638 /* Also stop when sufficient data has become available. */
639 if (sr_ser_has_queued_data(serial) >= count)
644 * Satisfy the caller's demand for receive data from previously
645 * queued incoming data.
647 dlen = sr_ser_has_queued_data(serial);
653 return sr_ser_unqueue_rx_data(serial, buf, dlen);
656 struct bt_source_args_t {
657 /* The application callback. */
658 sr_receive_data_callback cb;
660 /* The serial device, to store RX data. */
661 struct sr_serial_dev_inst *serial;
665 * Gets periodically invoked by the glib main loop. "Drives" (checks)
666 * progress of BT communication, and invokes the application's callback
667 * which processes RX data (when some has become available), as well as
668 * handles application level timeouts.
670 static int bt_source_cb(int fd, int revents, void *cb_data)
672 struct bt_source_args_t *args;
673 struct sr_serial_dev_inst *serial;
674 uint8_t rx_buf[SER_BT_CHUNK_SIZE];
682 serial = args->serial;
685 if (!serial->bt_conn_type)
689 * Drain receive data which the channel might have pending.
690 * This is "a copy" of the "background part" of ser_bt_read(),
691 * without the timeout support code, and not knowing how much
692 * data the application is expecting.
695 switch (serial->bt_conn_type) {
696 case SER_BT_CONN_RFCOMM:
697 rdlen = sr_bt_read(serial->bt_desc, rx_buf, sizeof(rx_buf));
700 rc = ser_bt_data_cb(serial, rx_buf, rdlen);
704 case SER_BT_CONN_BLE122:
705 case SER_BT_CONN_NRF51:
706 case SER_BT_CONN_CC254x:
707 dlen = sr_ser_has_queued_data(serial);
708 rc = sr_bt_check_notify(serial->bt_desc);
711 else if (sr_ser_has_queued_data(serial) != dlen)
723 * When RX data became available (now or earlier), pass this
724 * condition to the application callback. Always periodically
725 * run the application callback, since it handles timeouts and
726 * might carry out other tasks as well like signalling progress.
728 if (sr_ser_has_queued_data(args->serial))
730 rc = args->cb(fd, revents, args->cb_data);
735 /* TODO Can we use the Bluetooth socket's file descriptor? Probably not portably. */
736 #define WITH_MAXIMUM_TIMEOUT_VALUE 0
737 static int ser_bt_setup_source_add(struct sr_session *session,
738 struct sr_serial_dev_inst *serial,
739 int events, int timeout,
740 sr_receive_data_callback cb, void *cb_data)
742 struct bt_source_args_t *args;
747 /* Optionally enforce a minimum poll period. */
748 if (WITH_MAXIMUM_TIMEOUT_VALUE && timeout > WITH_MAXIMUM_TIMEOUT_VALUE)
749 timeout = WITH_MAXIMUM_TIMEOUT_VALUE;
751 /* Allocate status container for background data reception. */
752 args = g_malloc0(sizeof(*args));
754 args->cb_data = cb_data;
755 args->serial = serial;
758 * Have a periodic timer installed. Register the allocated block
759 * with the serial device, since the GSource's finalizer won't
760 * free the memory, and we haven't bothered to create a custom
761 * BT specific GSource.
763 rc = sr_session_source_add(session, -1, events, timeout, bt_source_cb, args);
768 serial->bt_source_args = g_slist_append(serial->bt_source_args, args);
773 static int ser_bt_setup_source_remove(struct sr_session *session,
774 struct sr_serial_dev_inst *serial)
778 (void)sr_session_source_remove(session, -1);
779 /* Release callback args here already? */
784 static const struct scan_supported_item *scan_is_supported(const char *name)
787 const struct scan_supported_item *item;
789 for (idx = 0; idx < ARRAY_SIZE(scan_supported_items); idx++) {
790 item = &scan_supported_items[idx];
793 if (strcmp(name, item->name) != 0)
801 struct bt_scan_args_t {
803 sr_ser_list_append_t append;
808 static void scan_cb(void *cb_args, const char *addr, const char *name)
810 struct bt_scan_args_t *scan_args;
813 const struct scan_supported_item *item;
814 enum ser_bt_conn_t type;
815 char *port_name, *port_desc;
821 sr_info("BT scan, found: %s - %s\n", addr, name);
823 /* Check whether the device was seen before. */
824 for (l = scan_args->addr_list; l; l = l->next) {
825 if (strcmp(addr, l->data) == 0)
829 /* Substitute colons in the address by dashes. */
832 snprintf(addr_text, sizeof(addr_text), "%s", addr);
833 g_strcanon(addr_text, "0123456789abcdefABCDEF", '-');
835 /* Create a port name, and a description. */
836 item = scan_is_supported(name);
837 type = item ? item->type : SER_BT_CONN_UNKNOWN;
838 port_name = g_strdup_printf("%s/%s/%s%s",
839 SER_BT_CONN_PREFIX, conn_name_text(type), addr_text,
840 (item && item->add_params) ? item->add_params : "");
841 port_desc = g_strdup_printf("%s (%s)", name, scan_args->bt_type);
843 scan_args->port_list = scan_args->append(scan_args->port_list, port_name, port_desc);
847 /* Keep track of the handled address. */
848 addr_copy = g_strdup(addr);
849 scan_args->addr_list = g_slist_append(scan_args->addr_list, addr_copy);
852 static GSList *ser_bt_list(GSList *list, sr_ser_list_append_t append)
854 static const int scan_duration = 3;
856 struct bt_scan_args_t scan_args;
857 struct sr_bt_desc *desc;
860 * Implementor's note: This "list" routine is best-effort. We
861 * assume that registering callbacks always succeeds. Silently
862 * ignore failure to scan for devices. Just return those which
866 desc = sr_bt_desc_new();
870 memset(&scan_args, 0, sizeof(scan_args));
871 scan_args.port_list = list;
872 scan_args.append = append;
874 scan_args.addr_list = NULL;
875 scan_args.bt_type = "BT";
876 (void)sr_bt_config_cb_scan(desc, scan_cb, &scan_args);
877 (void)sr_bt_scan_bt(desc, scan_duration);
878 g_slist_free_full(scan_args.addr_list, g_free);
880 scan_args.addr_list = NULL;
881 scan_args.bt_type = "BLE";
882 (void)sr_bt_config_cb_scan(desc, scan_cb, &scan_args);
883 (void)sr_bt_scan_le(desc, scan_duration);
884 g_slist_free_full(scan_args.addr_list, g_free);
886 sr_bt_desc_free(desc);
888 return scan_args.port_list;
891 static struct ser_lib_functions serlib_bt = {
893 .close = ser_bt_close,
894 .flush = ser_bt_flush,
895 .drain = ser_bt_drain,
896 .write = ser_bt_write,
899 * Bluetooth communication has no concept of bitrate, so ignore
900 * these arguments silently. Neither need we pass the frame format
901 * down to internal BT comm routines, nor need we keep the values
902 * here, since the caller will cache/register them already.
904 .set_params = std_dummy_set_params,
905 .set_handshake = std_dummy_set_handshake,
906 .setup_source_add = ser_bt_setup_source_add,
907 .setup_source_remove = ser_bt_setup_source_remove,
909 .get_frame_format = NULL,
911 SR_PRIV struct ser_lib_functions *ser_lib_funcs_bt = &serlib_bt;
916 SR_PRIV int ser_name_is_bt(struct sr_serial_dev_inst *serial)
923 SR_PRIV struct ser_lib_functions *ser_lib_funcs_bt = NULL;