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 */
58 * This builtin database of known devices (keyed by their names as
59 * provided during BT/BLE scans) can help improve the presentation of
60 * scan results. Ideally users could take the output and pass it to
61 * subsequent program invocations, not having to "come up with" the
62 * conn= spec, or only having to touch it up minimally. GUI dialogs
63 * could present scan results such that users just need to pick an
64 * item to open a connection.
66 * The current implementation guesses connection types from device
67 * names, and optionally amends them with additional parameters if
68 * experience shows that individual devices need these extra specs.
70 * This database may have to move to a separate source file should
71 * its size grow to amounts that are considered inappropriate here
72 * in the serial transport's BT dispatcher. For now the item count
76 static const struct scan_supported_item {
78 enum ser_bt_conn_t type;
79 const char *add_params;
80 } scan_supported_items[] = {
81 { "121GW", SER_BT_CONN_BLE122, NULL, },
82 { "Adafruit Bluefruit LE 8134", SER_BT_CONN_NRF51, NULL, },
83 { "HC-05", SER_BT_CONN_RFCOMM, NULL, },
84 { "UM25C", SER_BT_CONN_RFCOMM, NULL, },
85 { NULL, SER_BT_CONN_UNKNOWN, NULL, },
88 static const struct scan_supported_item *scan_is_supported(const char *name)
91 const struct scan_supported_item *item;
93 for (idx = 0; idx < ARRAY_SIZE(scan_supported_items); idx++) {
94 item = &scan_supported_items[idx];
97 if (strcmp(name, item->name) != 0)
105 static const char *ser_bt_conn_names[SER_BT_CONN_MAX] = {
106 [SER_BT_CONN_UNKNOWN] = "<type>",
107 [SER_BT_CONN_RFCOMM] = "rfcomm",
108 [SER_BT_CONN_BLE122] = "ble122",
109 [SER_BT_CONN_NRF51] = "nrf51",
110 [SER_BT_CONN_CC254x] = "cc254x",
113 static enum ser_bt_conn_t lookup_conn_name(const char *name)
119 return SER_BT_CONN_UNKNOWN;
120 idx = ARRAY_SIZE(ser_bt_conn_names);
122 item = ser_bt_conn_names[idx];
123 if (strcmp(item, name) == 0)
127 return SER_BT_CONN_UNKNOWN;
130 static const char *conn_name_text(enum ser_bt_conn_t type)
132 if (type >= ARRAY_SIZE(ser_bt_conn_names))
133 type = SER_BT_CONN_UNKNOWN;
135 return ser_bt_conn_names[type];
139 * Parse conn= specs for serial over Bluetooth communication.
141 * @param[in] serial The serial port that is about to get opened.
142 * @param[in] spec The caller provided conn= specification.
143 * @param[out] conn_type The type of BT comm (BT RFCOMM, BLE notify).
144 * @param[out] remote_addr The remote device address.
145 * @param[out] rfcomm_channel The RFCOMM channel (if applicable).
146 * @param[out] read_hdl The BLE notify read handle (if applicable).
147 * @param[out] write_hdl The BLE notify write handle (if applicable).
148 * @param[out] cccd_hdl The BLE notify CCCD handle (if applicable).
149 * @param[out] cccd_val The BLE notify CCCD value (if applicable).
151 * @return 0 upon success, non-zero upon failure.
153 * Summary of parsing rules as they are implemented:
154 * - Implementor's note: Automatic scan for available devices is not
155 * yet implemented. So strictly speaking some parts of the input
156 * spec are optional, but fallbacks may not take effect ATM.
157 * - Insist on the "bt" prefix. Accept "bt" alone without any other
159 * - The first field that follows is the connection type. Supported
160 * types are 'rfcomm', 'ble122', 'cc254x', and potentially others
161 * in a future implementation.
162 * - The next field is the remote device's address, either separated
163 * by colons or dashes or spaces, or not separated at all.
164 * - Other parameters (RFCOMM channel, notify handles and write values)
165 * get derived from the connection type.
166 * - More fields after the remote address are options which override
167 * builtin defaults (RFCOMM channels, BLE handles, etc).
169 * Supported formats resulting from these rules:
170 * bt/<conn>/<addr>[/<param>]...
173 * bt/rfcomm/11-22-33-44-55-66
174 * bt/rfcomm/11-22-33-44-55-66/channel=2
175 * bt/ble122/88:6b:12:34:56:78
176 * bt/cc254x/0123456789ab
178 * It's assumed that users easily can create those conn= specs from
179 * available information, or that scan routines will create such specs
180 * that copy'n'paste results (or GUI choices from previous scan results)
181 * can get processed here.
183 static int ser_bt_parse_conn_spec(
184 struct sr_serial_dev_inst *serial, const char *spec,
185 enum ser_bt_conn_t *conn_type, const char **remote_addr,
186 size_t *rfcomm_channel,
187 uint16_t *read_hdl, uint16_t *write_hdl,
188 uint16_t *cccd_hdl, uint16_t *cccd_val)
190 char **fields, *field;
191 enum ser_bt_conn_t type;
194 size_t fields_count, field_idx;
196 unsigned long parm_val;
199 *conn_type = SER_BT_CONN_UNKNOWN;
213 if (!serial || !spec || !spec[0])
216 /* Evaluate the mandatory first three fields. */
217 fields = g_strsplit_set(spec, "/", 0);
220 if (g_strv_length(fields) < 3) {
225 if (strcmp(field, SER_BT_CONN_PREFIX) != 0) {
230 type = lookup_conn_name(field);
238 if (!field || !*field) {
242 addr = g_strdup(field);
246 /* Derive default parameters that match the connection type. */
247 /* TODO Lookup defaults from a table? */
249 case SER_BT_CONN_RFCOMM:
253 case SER_BT_CONN_BLE122:
263 case SER_BT_CONN_NRF51:
265 * Are these values appropriate? Check the learn article at
266 * https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend?view=all
276 /* TODO 'random' type, sec-level=high */
278 case SER_BT_CONN_CC254x:
279 /* TODO Are these values appropriate? Just guessing here. */
294 * Preset a successful return value for the conn= parse call.
295 * Scan optional additional fields which specify more params.
296 * Update the defaults which were setup above. Pessimize the
297 * routine's return value in error paths.
300 fields_count = g_strv_length(fields);
301 for (field_idx = 3; field_idx < fields_count; field_idx++) {
302 field = fields[field_idx];
303 if (!field || !*field)
305 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_CHANNEL)) {
306 field += strlen(SER_BT_PARAM_PREFIX_CHANNEL);
308 ret = sr_atoul_base(field, &parm_val, &endp, 0);
309 if (ret != SR_OK || !endp || *endp != '\0') {
310 ret_parse = SR_ERR_ARG;
314 *rfcomm_channel = parm_val;
317 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_HDL_RX)) {
318 field += strlen(SER_BT_PARAM_PREFIX_HDL_RX);
320 ret = sr_atoul_base(field, &parm_val, &endp, 0);
321 if (ret != SR_OK || !endp || *endp != '\0') {
322 ret_parse = SR_ERR_ARG;
326 *read_hdl = parm_val;
329 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_HDL_TX)) {
330 field += strlen(SER_BT_PARAM_PREFIX_HDL_TX);
332 ret = sr_atoul_base(field, &parm_val, &endp, 0);
333 if (ret != SR_OK || !endp || *endp != '\0') {
334 ret_parse = SR_ERR_ARG;
338 *write_hdl = parm_val;
341 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_HDL_CCCD)) {
342 field += strlen(SER_BT_PARAM_PREFIX_HDL_CCCD);
344 ret = sr_atoul_base(field, &parm_val, &endp, 0);
345 if (ret != SR_OK || !endp || *endp != '\0') {
346 ret_parse = SR_ERR_ARG;
350 *cccd_hdl = parm_val;
353 if (g_str_has_prefix(field, SER_BT_PARAM_PREFIX_VAL_CCCD)) {
354 field += strlen(SER_BT_PARAM_PREFIX_VAL_CCCD);
356 ret = sr_atoul_base(field, &parm_val, &endp, 0);
357 if (ret != SR_OK || !endp || *endp != '\0') {
358 ret_parse = SR_ERR_ARG;
362 *cccd_val = parm_val;
372 static void ser_bt_mask_databits(struct sr_serial_dev_inst *serial,
373 uint8_t *data, size_t len)
379 if ((serial->comm_params.data_bits % 8) == 0)
382 mask32 = (1UL << serial->comm_params.data_bits) - 1;
383 mask = mask32 & 0xff;
384 for (idx = 0; idx < len; idx++)
388 static int ser_bt_data_cb(void *cb_data, uint8_t *data, size_t dlen)
390 struct sr_serial_dev_inst *serial;
396 ser_bt_mask_databits(serial, data, dlen);
397 sr_ser_queue_rx_data(serial, data, dlen);
403 /* {{{ wrap serial-over-BT operations in a common serial.c API */
405 /* See if a serial port's name refers to a BT type. */
406 SR_PRIV int ser_name_is_bt(struct sr_serial_dev_inst *serial)
413 if (!serial->port || !*serial->port)
416 /* Accept either "bt" alone, or "bt/" as a prefix. */
417 if (!g_str_has_prefix(serial->port, SER_BT_CONN_PREFIX))
419 off = strlen(SER_BT_CONN_PREFIX);
420 sep = serial->port[off];
421 if (sep != '\0' && sep != '/')
427 /* The open() wrapper for BT ports. */
428 static int ser_bt_open(struct sr_serial_dev_inst *serial, int flags)
430 enum ser_bt_conn_t conn_type;
431 const char *remote_addr;
432 size_t rfcomm_channel;
433 uint16_t read_hdl, write_hdl, cccd_hdl, cccd_val;
435 struct sr_bt_desc *desc;
439 /* Derive BT specific parameters from the port spec. */
440 rc = ser_bt_parse_conn_spec(serial, serial->port,
441 &conn_type, &remote_addr,
443 &read_hdl, &write_hdl,
444 &cccd_hdl, &cccd_val);
448 if (!conn_type || !remote_addr || !remote_addr[0]) {
449 /* TODO Auto-search for available connections? */
453 /* Create the connection. Only store params after successful use. */
454 desc = sr_bt_desc_new();
457 serial->bt_desc = desc;
458 rc = sr_bt_config_addr_remote(desc, remote_addr);
461 serial->bt_addr_remote = g_strdup(remote_addr);
463 case SER_BT_CONN_RFCOMM:
464 rc = sr_bt_config_rfcomm(desc, rfcomm_channel);
467 serial->bt_rfcomm_channel = rfcomm_channel;
469 case SER_BT_CONN_BLE122:
470 case SER_BT_CONN_NRF51:
471 case SER_BT_CONN_CC254x:
472 rc = sr_bt_config_notify(desc,
473 read_hdl, write_hdl, cccd_hdl, cccd_val);
476 serial->bt_notify_handle_read = read_hdl;
477 serial->bt_notify_handle_write = write_hdl;
478 serial->bt_notify_handle_cccd = cccd_hdl;
479 serial->bt_notify_value_cccd = cccd_val;
482 /* Unsupported type, or incomplete implementation. */
485 serial->bt_conn_type = conn_type;
487 /* Make sure the receive buffer can accept input data. */
488 if (!serial->rcv_buffer)
489 serial->rcv_buffer = g_string_sized_new(SER_BT_CHUNK_SIZE);
490 rc = sr_bt_config_cb_data(desc, ser_bt_data_cb, serial);
494 /* Open the connection. */
496 case SER_BT_CONN_RFCOMM:
497 rc = sr_bt_connect_rfcomm(desc);
501 case SER_BT_CONN_BLE122:
502 case SER_BT_CONN_NRF51:
503 case SER_BT_CONN_CC254x:
504 rc = sr_bt_connect_ble(desc);
507 rc = sr_bt_start_notify(desc);
518 static int ser_bt_close(struct sr_serial_dev_inst *serial)
523 if (!serial->bt_desc)
526 sr_bt_disconnect(serial->bt_desc);
527 sr_bt_desc_free(serial->bt_desc);
528 serial->bt_desc = NULL;
530 g_free(serial->bt_addr_local);
531 serial->bt_addr_local = NULL;
532 g_free(serial->bt_addr_remote);
533 serial->bt_addr_remote = NULL;
534 g_slist_free_full(serial->bt_source_args, g_free);
535 serial->bt_source_args = NULL;
540 /* Flush, discards pending RX data, empties buffers. */
541 static int ser_bt_flush(struct sr_serial_dev_inst *serial)
549 /* Drain, waits for completion of pending TX data. */
550 static int ser_bt_drain(struct sr_serial_dev_inst *serial)
553 /* EMPTY */ /* TODO? */
558 static int ser_bt_write(struct sr_serial_dev_inst *serial,
559 const void *buf, size_t count,
560 int nonblocking, unsigned int timeout_ms)
565 * TODO Support chunked transmission when callers' requests
566 * exceed the BT channel's capacity? See ser_hid_write().
569 switch (serial->bt_conn_type) {
570 case SER_BT_CONN_RFCOMM:
573 wrlen = sr_bt_write(serial->bt_desc, buf, count);
577 case SER_BT_CONN_BLE122:
578 case SER_BT_CONN_NRF51:
579 case SER_BT_CONN_CC254x:
581 * Assume that when applications call the serial layer's
582 * write routine, then the BLE chip/module does support
583 * a TX handle. Just call the serial-BT library's write
588 wrlen = sr_bt_write(serial->bt_desc, buf, count);
598 static int ser_bt_read(struct sr_serial_dev_inst *serial,
599 void *buf, size_t count,
600 int nonblocking, unsigned int timeout_ms)
602 gint64 deadline_us, now_us;
603 uint8_t buffer[SER_BT_CHUNK_SIZE];
609 * Immediately satisfy the caller's request from the RX buffer
610 * if the requested amount of data is available already.
612 if (sr_ser_has_queued_data(serial) >= count)
613 return sr_ser_unqueue_rx_data(serial, buf, count);
616 * When a timeout was specified, then determine the deadline
617 * where to stop reception.
621 now_us = g_get_monotonic_time();
622 deadline_us = now_us + timeout_ms * 1000;
626 * Keep receiving from the port until the caller's requested
627 * amount of data has become available, or the timeout has
628 * expired. In the absence of a timeout, stop reading when an
629 * attempt no longer yields receive data.
632 /* Run another attempt to receive data. */
633 switch (serial->bt_conn_type) {
634 case SER_BT_CONN_RFCOMM:
635 rdlen = sr_bt_read(serial->bt_desc, buffer, sizeof(buffer));
638 rc = ser_bt_data_cb(serial, buffer, rdlen);
642 case SER_BT_CONN_BLE122:
643 case SER_BT_CONN_NRF51:
644 case SER_BT_CONN_CC254x:
645 dlen = sr_ser_has_queued_data(serial);
646 rc = sr_bt_check_notify(serial->bt_desc);
649 else if (sr_ser_has_queued_data(serial) != dlen)
660 * Stop upon receive errors, or timeout expiration. Only
661 * stop upon empty reception in the absence of a timeout.
665 if (nonblocking && !rdlen)
668 now_us = g_get_monotonic_time();
669 if (now_us > deadline_us)
673 /* Also stop when sufficient data has become available. */
674 if (sr_ser_has_queued_data(serial) >= count)
679 * Satisfy the caller's demand for receive data from previously
680 * queued incoming data.
682 dlen = sr_ser_has_queued_data(serial);
688 return sr_ser_unqueue_rx_data(serial, buf, dlen);
691 struct bt_source_args_t {
692 /* The application callback. */
693 sr_receive_data_callback cb;
695 /* The serial device, to store RX data. */
696 struct sr_serial_dev_inst *serial;
700 * Gets periodically invoked by the glib main loop. "Drives" (checks)
701 * progress of BT communication, and invokes the application's callback
702 * which processes RX data (when some has become available), as well as
703 * handles application level timeouts.
705 static int bt_source_cb(int fd, int revents, void *cb_data)
707 struct bt_source_args_t *args;
708 struct sr_serial_dev_inst *serial;
709 uint8_t rx_buf[SER_BT_CHUNK_SIZE];
717 serial = args->serial;
720 if (!serial->bt_conn_type)
724 * Drain receive data which the channel might have pending.
725 * This is "a copy" of the "background part" of ser_bt_read(),
726 * without the timeout support code, and not knowing how much
727 * data the application is expecting.
730 switch (serial->bt_conn_type) {
731 case SER_BT_CONN_RFCOMM:
732 rdlen = sr_bt_read(serial->bt_desc, rx_buf, sizeof(rx_buf));
735 rc = ser_bt_data_cb(serial, rx_buf, rdlen);
739 case SER_BT_CONN_BLE122:
740 case SER_BT_CONN_NRF51:
741 case SER_BT_CONN_CC254x:
742 dlen = sr_ser_has_queued_data(serial);
743 rc = sr_bt_check_notify(serial->bt_desc);
746 else if (sr_ser_has_queued_data(serial) != dlen)
758 * When RX data became available (now or earlier), pass this
759 * condition to the application callback. Always periodically
760 * run the application callback, since it handles timeouts and
761 * might carry out other tasks as well like signalling progress.
763 if (sr_ser_has_queued_data(args->serial))
765 rc = args->cb(fd, revents, args->cb_data);
770 /* TODO Can we use the Bluetooth socket's file descriptor? Probably not portably. */
771 #define WITH_MAXIMUM_TIMEOUT_VALUE 0
772 static int ser_bt_setup_source_add(struct sr_session *session,
773 struct sr_serial_dev_inst *serial,
774 int events, int timeout,
775 sr_receive_data_callback cb, void *cb_data)
777 struct bt_source_args_t *args;
782 /* Optionally enforce a minimum poll period. */
783 if (WITH_MAXIMUM_TIMEOUT_VALUE && timeout > WITH_MAXIMUM_TIMEOUT_VALUE)
784 timeout = WITH_MAXIMUM_TIMEOUT_VALUE;
786 /* Allocate status container for background data reception. */
787 args = g_malloc0(sizeof(*args));
789 args->cb_data = cb_data;
790 args->serial = serial;
793 * Have a periodic timer installed. Register the allocated block
794 * with the serial device, since the GSource's finalizer won't
795 * free the memory, and we haven't bothered to create a custom
796 * BT specific GSource.
798 rc = sr_session_source_add(session, -1, events, timeout, bt_source_cb, args);
803 serial->bt_source_args = g_slist_append(serial->bt_source_args, args);
808 static int ser_bt_setup_source_remove(struct sr_session *session,
809 struct sr_serial_dev_inst *serial)
813 (void)sr_session_source_remove(session, -1);
814 /* Release callback args here already? */
819 struct bt_scan_args_t {
821 sr_ser_list_append_t append;
826 static void scan_cb(void *cb_args, const char *addr, const char *name)
828 struct bt_scan_args_t *scan_args;
831 const struct scan_supported_item *item;
832 enum ser_bt_conn_t type;
833 char *port_name, *port_desc;
839 sr_info("BT scan, found: %s - %s\n", addr, name);
841 /* Check whether the device was seen before. */
842 for (l = scan_args->addr_list; l; l = l->next) {
843 if (strcmp(addr, l->data) == 0)
847 /* Substitute colons in the address by dashes. */
850 snprintf(addr_text, sizeof(addr_text), "%s", addr);
851 g_strcanon(addr_text, "0123456789abcdefABCDEF", '-');
853 /* Create a port name, and a description. */
854 item = scan_is_supported(name);
855 type = item ? item->type : SER_BT_CONN_UNKNOWN;
856 port_name = g_strdup_printf("%s/%s/%s%s",
857 SER_BT_CONN_PREFIX, conn_name_text(type), addr_text,
858 (item && item->add_params) ? item->add_params : "");
859 port_desc = g_strdup_printf("%s (%s)", name, scan_args->bt_type);
861 scan_args->port_list = scan_args->append(scan_args->port_list, port_name, port_desc);
865 /* Keep track of the handled address. */
866 addr_copy = g_strdup(addr);
867 scan_args->addr_list = g_slist_append(scan_args->addr_list, addr_copy);
870 static GSList *ser_bt_list(GSList *list, sr_ser_list_append_t append)
872 static const int scan_duration = 3;
874 struct bt_scan_args_t scan_args;
875 struct sr_bt_desc *desc;
878 * Implementor's note: This "list" routine is best-effort. We
879 * assume that registering callbacks always succeeds. Silently
880 * ignore failure to scan for devices. Just return those which
884 desc = sr_bt_desc_new();
888 memset(&scan_args, 0, sizeof(scan_args));
889 scan_args.port_list = list;
890 scan_args.append = append;
892 scan_args.addr_list = NULL;
893 scan_args.bt_type = "BT";
894 (void)sr_bt_config_cb_scan(desc, scan_cb, &scan_args);
895 (void)sr_bt_scan_bt(desc, scan_duration);
896 g_slist_free_full(scan_args.addr_list, g_free);
898 scan_args.addr_list = NULL;
899 scan_args.bt_type = "BLE";
900 (void)sr_bt_config_cb_scan(desc, scan_cb, &scan_args);
901 (void)sr_bt_scan_le(desc, scan_duration);
902 g_slist_free_full(scan_args.addr_list, g_free);
904 sr_bt_desc_free(desc);
906 return scan_args.port_list;
909 static struct ser_lib_functions serlib_bt = {
911 .close = ser_bt_close,
912 .flush = ser_bt_flush,
913 .drain = ser_bt_drain,
914 .write = ser_bt_write,
917 * Bluetooth communication has no concept of bitrate, so ignore
918 * these arguments silently. Neither need we pass the frame format
919 * down to internal BT comm routines, nor need we keep the values
920 * here, since the caller will cache/register them already.
922 .set_params = std_dummy_set_params,
923 .set_handshake = std_dummy_set_handshake,
924 .setup_source_add = ser_bt_setup_source_add,
925 .setup_source_remove = ser_bt_setup_source_remove,
927 .get_frame_format = NULL,
929 SR_PRIV struct ser_lib_functions *ser_lib_funcs_bt = &serlib_bt;
934 SR_PRIV int ser_name_is_bt(struct sr_serial_dev_inst *serial)
941 SR_PRIV struct ser_lib_functions *ser_lib_funcs_bt = NULL;