2 * This file is part of the sigrok 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/>.
21 * Scan support for Bluetooth LE devices is modelled after the MIT licensed
22 * https://github.com/carsonmcdonald/bluez-experiments experiments/scantest.c
23 * example source code which is:
25 * The MIT License (MIT)
27 * Copyright (c) 2013 Carson McDonald
29 * Permission is hereby granted, free of charge, to any person obtaining a copy of
30 * this software and associated documentation files (the "Software"), to deal in
31 * the Software without restriction, including without limitation the rights to
32 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
33 * the Software, and to permit persons to whom the Software is furnished to do so,
34 * subject to the following conditions:
36 * The above copyright notice and this permission notice shall be included in all
37 * copies or substantial portions of the Software.
39 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
41 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
42 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
43 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
44 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
48 * This file implements an internal platform agnostic API of libsigrok
49 * for Bluetooth communication, as well as the first implementation on a
50 * specific platform which is based on the BlueZ library and got tested
54 * - Separate the "common" from the "bluez specific" parts. The current
55 * implementation uses the fact that HAVE_BLUETOOTH exclusively depends
56 * on HAVE_LIBBLUEZ, and thus both are identical.
57 * - Add missing features to the Linux platform support: Scan without
58 * root privileges, UUID to handle translation.
59 * - Add support for other platforms.
64 /* Unconditionally compile the source, optionally end up empty. */
68 #include <bluetooth/bluetooth.h>
69 #include <bluetooth/hci.h>
70 #include <bluetooth/hci_lib.h>
71 #include <bluetooth/l2cap.h>
72 #include <bluetooth/rfcomm.h>
84 #include <sys/socket.h>
88 #include <libsigrok/libsigrok.h>
89 #include "libsigrok-internal.h"
91 #define LOG_PREFIX "bt-bluez"
93 #define CONNECT_BLE_TIMEOUT 20 /* Connect timeout in seconds. */
94 #define STORE_MAC_REVERSE 1
95 #define ACCEPT_NONSEP_MAC 1
97 #define CONNECT_RFCOMM_TRIES 3
98 #define CONNECT_RFCOMM_RETRY_MS 100
100 /* Silence warning about (currently) unused routine. */
101 #define WITH_WRITE_TYPE_HANDLE 0
103 /* {{{ compat decls */
105 * The availability of conversion helpers in <bluetooth/bluetooth.h>
106 * appears to be version dependent. Let's provide the helper here if
107 * the header doesn't.
110 /* }}} compat decls */
111 /* {{{ Linux socket specific decls */
113 #define BLE_ATT_ERROR_RESP 0x01
114 #define BLE_ATT_EXCHANGE_MTU_REQ 0x02
115 #define BLE_ATT_EXCHANGE_MTU_RESP 0x03
116 #define BLE_ATT_FIND_INFORMATION_REQ 0x04
117 #define BLE_ATT_FIND_INFORMATION_RESP 0x05
118 #define BLE_ATT_FIND_BY_TYPE_REQ 0x06
119 #define BLE_ATT_FIND_BY_TYPE_RESP 0x07
120 #define BLE_ATT_READ_BY_TYPE_REQ 0x08
121 #define BLE_ATT_READ_BY_TYPE_RESP 0x09
122 #define BLE_ATT_READ_REQ 0x0a
123 #define BLE_ATT_READ_RESP 0x0b
124 #define BLE_ATT_READ_BLOB_REQ 0x0c
125 #define BLE_ATT_READ_BLOB_RESP 0x0d
126 #define BLE_ATT_READ_MULTIPLE_REQ 0x0e
127 #define BLE_ATT_READ_MULTIPLE_RESP 0x0f
128 #define BLE_ATT_READ_BY_GROUP_REQ 0x10
129 #define BLE_ATT_READ_BY_GROUP_RESP 0x11
130 #define BLE_ATT_WRITE_REQ 0x12
131 #define BLE_ATT_WRITE_RESP 0x13
132 #define BLE_ATT_WRITE_CMD 0x16
133 #define BLE_ATT_HANDLE_NOTIFICATION 0x1b
134 #define BLE_ATT_HANDLE_INDICATION 0x1d
135 #define BLE_ATT_HANDLE_CONFIRMATION 0x1e
136 #define BLE_ATT_SIGNED_WRITE_CMD 0x52
138 /* }}} Linux socket specific decls */
142 * Convert textual MAC presentation to array of bytes. In contrast to
143 * BlueZ conversion, accept colon or dash separated input as well as a
144 * dense format without separators (001122334455). We expect to use the
145 * library in an environment where colons are not always available as a
146 * separator in user provided specs, while users do want to use some
147 * separator for readability.
149 * TODO Instead of doing the actual conversion here (and dealing with
150 * BlueZ' internal byte order for device address bytes), we might as
151 * well just transform the input string to an output string, and always
152 * use the officially provided str2ba() conversion routine.
154 static int sr_bt_mac_text_to_bytes(const char *text, uint8_t *buf)
162 if (STORE_MAC_REVERSE)
165 while (len && endp && *endp) {
167 if (ACCEPT_NONSEP_MAC) {
169 numbuf[1] = endp[0] ? endp[1] : '\0';
173 v = strtol(ACCEPT_NONSEP_MAC ? numbuf : text, &endp, 16);
176 if (*endp != ':' && *endp != '-' && *endp != '\0')
178 if (v < 0 || v > 255)
180 if (STORE_MAC_REVERSE)
185 if (ACCEPT_NONSEP_MAC)
186 endp = (char *)text + (endp - numbuf);
187 if (*endp == ':' || *endp == '-')
192 sr_err("Failed to parse MAC, too few bytes in '%s'", text);
195 while (isspace(*endp))
198 sr_err("Failed to parse MAC, excess data in '%s'", text);
208 SR_PRIV const char *sr_bt_adapter_get_address(size_t idx)
211 struct hci_dev_info info;
214 rc = hci_devinfo(idx, &info);
215 sr_spew("DIAG: hci_devinfo(%zu) => rc %d", idx, rc);
219 rc = ba2str(&info.bdaddr, addr);
220 sr_spew("DIAG: ba2str() => rc %d", rc);
224 return g_strdup(addr);
231 /* User servicable options. */
232 sr_bt_scan_cb scan_cb;
234 sr_bt_data_cb data_cb;
237 char remote_addr[20];
238 size_t rfcomm_channel;
239 uint16_t read_handle;
240 uint16_t write_handle;
241 uint16_t cccd_handle;
243 /* Internal state. */
246 struct hci_filter orig_filter;
249 static int sr_bt_desc_open(struct sr_bt_desc *desc, int *id_ref);
250 static void sr_bt_desc_close(struct sr_bt_desc *desc);
251 static int sr_bt_check_socket_usable(struct sr_bt_desc *desc);
252 static ssize_t sr_bt_write_type(struct sr_bt_desc *desc, uint8_t type);
253 #if WITH_WRITE_TYPE_HANDLE
254 static ssize_t sr_bt_write_type_handle(struct sr_bt_desc *desc,
255 uint8_t type, uint16_t handle);
257 static ssize_t sr_bt_write_type_handle_bytes(struct sr_bt_desc *desc,
258 uint8_t type, uint16_t handle, const uint8_t *data, size_t len);
259 static ssize_t sr_bt_char_write_req(struct sr_bt_desc *desc,
260 uint16_t handle, const void *data, size_t len);
262 SR_PRIV struct sr_bt_desc *sr_bt_desc_new(void)
264 struct sr_bt_desc *desc;
266 desc = g_malloc0(sizeof(*desc));
276 SR_PRIV void sr_bt_desc_free(struct sr_bt_desc *desc)
281 sr_bt_desc_close(desc);
285 SR_PRIV int sr_bt_config_cb_scan(struct sr_bt_desc *desc,
286 sr_bt_scan_cb cb, void *cb_data)
292 desc->scan_cb_data = cb_data;
297 SR_PRIV int sr_bt_config_cb_data(struct sr_bt_desc *desc,
298 sr_bt_data_cb cb, void *cb_data)
304 desc->data_cb_data = cb_data;
309 SR_PRIV int sr_bt_config_addr_local(struct sr_bt_desc *desc, const char *addr)
317 if (!addr || !addr[0]) {
318 desc->local_addr[0] = '\0';
322 rc = sr_bt_mac_text_to_bytes(addr, &mac_bytes.b[0]);
326 rc = ba2str(&mac_bytes, desc->local_addr);
333 SR_PRIV int sr_bt_config_addr_remote(struct sr_bt_desc *desc, const char *addr)
341 if (!addr || !addr[0]) {
342 desc->remote_addr[0] = '\0';
346 rc = sr_bt_mac_text_to_bytes(addr, &mac_bytes.b[0]);
350 rc = ba2str(&mac_bytes, desc->remote_addr);
357 SR_PRIV int sr_bt_config_rfcomm(struct sr_bt_desc *desc, size_t channel)
362 desc->rfcomm_channel = channel;
367 SR_PRIV int sr_bt_config_notify(struct sr_bt_desc *desc,
368 uint16_t read_handle, uint16_t write_handle,
369 uint16_t cccd_handle, uint16_t cccd_value)
375 desc->read_handle = read_handle;
376 desc->write_handle = write_handle;
377 desc->cccd_handle = cccd_handle;
378 desc->cccd_value = cccd_value;
383 static int sr_bt_desc_open(struct sr_bt_desc *desc, int *id_ref)
392 if (desc->local_addr[0]) {
393 id = hci_devid(desc->local_addr);
394 } else if (desc->remote_addr[0]) {
395 str2ba(desc->remote_addr, &mac);
396 id = hci_get_route(&mac);
398 id = hci_get_route(NULL);
401 sr_err("devid failed");
408 sock = hci_open_dev(id);
410 perror("open HCI socket");
418 static void sr_bt_desc_close(struct sr_bt_desc *desc)
425 hci_close_dev(desc->fd);
434 #define EIR_NAME_COMPLETE 9
436 static int sr_bt_scan_prep(struct sr_bt_desc *desc)
439 uint8_t type, owntype, filter;
440 uint16_t ival, window;
444 struct hci_filter scan_filter;
449 /* TODO Replace magic values with symbolic identifiers. */
450 type = 0x01; /* LE public? */
451 ival = htobs(0x0010);
452 window = htobs(0x0010);
453 owntype = 0x00; /* any? */
456 rc = hci_le_set_scan_parameters(desc->fd,
457 type, ival, window, owntype, filter, timeout);
459 perror("set LE scan params");
466 rc = hci_le_set_scan_enable(desc->fd, enable, dup, timeout);
468 perror("set LE scan enable");
472 /* Save the current filter. For later restoration. */
473 slen = sizeof(desc->orig_filter);
474 rc = getsockopt(desc->fd, SOL_HCI, HCI_FILTER,
475 &desc->orig_filter, &slen);
477 perror("getsockopt(HCI_FILTER)");
481 hci_filter_clear(&scan_filter);
482 hci_filter_set_ptype(HCI_EVENT_PKT, &scan_filter);
483 hci_filter_set_event(EVT_LE_META_EVENT, &scan_filter);
484 rc = setsockopt(desc->fd, SOL_HCI, HCI_FILTER,
485 &scan_filter, sizeof(scan_filter));
487 perror("setsockopt(HCI_FILTER)");
494 static int sr_bt_scan_post(struct sr_bt_desc *desc)
503 /* Restore previous HCI filter. */
504 rc = setsockopt(desc->fd, SOL_HCI, HCI_FILTER,
505 &desc->orig_filter, sizeof(desc->orig_filter));
507 perror("setsockopt(HCI_FILTER)");
514 rc = hci_le_set_scan_enable(desc->fd, enable, dup, timeout);
521 static int sr_bt_scan_proc(struct sr_bt_desc *desc,
522 sr_bt_scan_cb scan_cb, void *cb_data,
523 uint8_t *data, size_t dlen, le_advertising_info *info)
532 if (type == EIR_NAME_COMPLETE) {
533 ba2str(&info->bdaddr, addr);
534 name = g_strndup((const char *)&data[1], dlen - 1);
536 scan_cb(cb_data, addr, name);
541 /* Unknown or unsupported type, ignore silently. */
545 SR_PRIV int sr_bt_scan_le(struct sr_bt_desc *desc, int duration)
549 uint8_t buf[HCI_MAX_EVENT_SIZE];
550 ssize_t rdlen, rdpos;
551 evt_le_meta_event *meta;
552 le_advertising_info *info;
558 sr_dbg("BLE scan (LE)");
560 rc = sr_bt_desc_open(desc, NULL);
564 rc = sr_bt_scan_prep(desc);
568 deadline = time(NULL);
569 deadline += duration;
570 while (time(NULL) <= deadline) {
572 if (sr_bt_check_socket_usable(desc) < 0)
574 rdlen = sr_bt_read(desc, buf, sizeof(buf));
581 if (rdlen < 1 + HCI_EVENT_HDR_SIZE)
583 meta = (void *)&buf[1 + HCI_EVENT_HDR_SIZE];
584 rdlen -= 1 + HCI_EVENT_HDR_SIZE;
585 if (meta->subevent != EVT_LE_ADVERTISING_REPORT)
587 info = (void *)&meta->data[1];
588 sr_spew("evt: type %d, len %d", info->evt_type, info->length);
593 while (rdpos < rdlen) {
594 datalen = info->data[rdpos];
595 dataptr = &info->data[1 + rdpos];
596 if (rdpos + 1 + datalen > info->length)
598 rdpos += 1 + datalen;
599 rc = sr_bt_scan_proc(desc,
600 desc->scan_cb, desc->scan_cb_data,
601 dataptr, datalen, info);
607 rc = sr_bt_scan_post(desc);
611 sr_bt_desc_close(desc);
616 SR_PRIV int sr_bt_scan_bt(struct sr_bt_desc *desc, int duration)
618 int dev_id, sock, rsp_max;
622 size_t rsp_count, idx;
628 sr_dbg("BLE scan (BT)");
630 sock = sr_bt_desc_open(desc, &dev_id);
635 info = g_malloc0(rsp_max * sizeof(*info));
636 flags = 0 /* | IREQ_CACHE_FLUSH */;
637 inq_rc = hci_inquiry(dev_id, duration, rsp_max, NULL, &info, flags);
639 perror("hci_inquiry");
642 for (idx = 0; idx < rsp_count; idx++) {
643 memset(addr, 0, sizeof(addr));
644 ba2str(&info[idx].bdaddr, addr);
645 memset(name, 0, sizeof(name));
646 if (hci_read_remote_name(sock, &info[idx].bdaddr, sizeof(name), name, 0) < 0)
647 snprintf(name, sizeof(name), "[unknown]");
649 desc->scan_cb(desc->scan_cb_data, addr, name);
653 sr_bt_desc_close(desc);
659 /* {{{ connect/disconnect */
661 SR_PRIV int sr_bt_connect_ble(struct sr_bt_desc *desc)
663 struct sockaddr_l2 sl2;
670 if (!desc->remote_addr[0])
672 sr_dbg("BLE connect, remote addr %s", desc->remote_addr);
674 s = socket(AF_BLUETOOTH, SOCK_SEQPACKET, 0);
676 perror("socket create");
681 memset(&sl2, 0, sizeof(sl2));
682 sl2.l2_family = AF_BLUETOOTH;
684 if (desc->local_addr[0])
685 str2ba(desc->local_addr, &mac);
688 memcpy(&sl2.l2_bdaddr, &mac, sizeof(sl2.l2_bdaddr));
689 sl2.l2_cid = L2CAP_FC_CONNLESS;
690 sl2.l2_bdaddr_type = BDADDR_LE_PUBLIC;
691 ret = bind(s, (void *)&sl2, sizeof(sl2));
698 struct bt_security buf = {
699 .level = BT_SECURITY_LOW,
702 ret = setsockopt(s, SOL_BLUETOOTH, BT_SECURITY, &buf, sizeof(buf));
704 perror("setsockopt");
709 deadline = g_get_monotonic_time();
710 deadline += CONNECT_BLE_TIMEOUT * 1000 * 1000;
711 str2ba(desc->remote_addr, &mac);
712 memcpy(&sl2.l2_bdaddr, &mac, sizeof(sl2.l2_bdaddr));
713 sl2.l2_bdaddr_type = BDADDR_LE_PUBLIC;
714 ret = connect(s, (void *)&sl2, sizeof(sl2));
716 * Cope with "in progress" condition. Keep polling the status
717 * until connect() completes, then get the error by means of
718 * getsockopt(). See the connect(2) manpage for details.
720 if (ret < 0 && errno == EINPROGRESS) {
721 struct pollfd fds[1];
726 * We seem to get here ("connect in progress") even when
727 * the specified peer is not around at all. Which results
728 * in extended periods of time where nothing happens, and
729 * an application timeout seems to be required.
731 sr_spew("in progress ...");
734 memset(fds, 0, sizeof(fds));
736 fds[0].events = POLLOUT;
737 ret = poll(fds, ARRAY_SIZE(fds), -1);
744 if (!(fds[0].revents & POLLOUT))
746 if (g_get_monotonic_time() >= deadline) {
747 sr_warn("Connect attempt timed out");
751 memset(fds, 0, sizeof(fds));
753 fds[0].events = POLLNVAL;
754 ret = poll(fds, 1, 0);
756 perror("poll(INVAL)");
760 /* socket fd is invalid(?) */
765 solen = sizeof(soerror);
766 ret = getsockopt(s, SOL_SOCKET, SO_ERROR, &soerror, &solen);
768 perror("getsockopt(SO_ERROR)");
772 /* connect(2) failed, SO_ERROR has the error code. */
774 perror("connect(PROGRESS)");
779 * TODO Get the receive MTU here?
780 * getsockopt(SOL_BLUETOOTH, BT_RCVMTU, u16);
791 SR_PRIV int sr_bt_connect_rfcomm(struct sr_bt_desc *desc)
793 struct sockaddr_rc addr;
798 if (!desc->remote_addr[0])
800 sr_dbg("RFCOMM connect, remote addr %s, channel %zu",
801 desc->remote_addr, desc->rfcomm_channel);
803 if (!desc->rfcomm_channel)
804 desc->rfcomm_channel = 1;
806 memset(&addr, 0, sizeof(addr));
807 addr.rc_family = AF_BLUETOOTH;
808 str2ba(desc->remote_addr, &addr.rc_bdaddr);
809 addr.rc_channel = desc->rfcomm_channel;
812 * There are cases where connect returns EBUSY if we are re-connecting
813 * to a device. Try multiple times to work around this issue.
815 for (i = 0; i < CONNECT_RFCOMM_TRIES; i++) {
816 fd = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
822 rc = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
824 sr_spew("connected");
827 } else if (rc < 0 && errno == EBUSY) {
829 g_usleep(CONNECT_RFCOMM_RETRY_MS * 1000);
837 sr_err("Connect failed, device busy.");
842 SR_PRIV void sr_bt_disconnect(struct sr_bt_desc *desc)
844 sr_dbg("BLE disconnect");
848 sr_bt_desc_close(desc);
851 static int sr_bt_check_socket_usable(struct sr_bt_desc *desc)
853 struct pollfd fds[1];
861 memset(fds, 0, sizeof(fds));
862 fds[0].fd = desc->fd;
863 fds[0].events = POLLERR | POLLHUP;
864 ret = poll(fds, ARRAY_SIZE(fds), 0);
869 if (fds[0].revents & POLLHUP)
871 if (fds[0].revents & POLLERR)
873 if (fds[0].revents & POLLNVAL)
879 /* }}} connect/disconnect */
880 /* {{{ indication/notification */
882 SR_PRIV int sr_bt_start_notify(struct sr_bt_desc *desc)
884 uint8_t buf[sizeof(desc->cccd_value)];
889 sr_dbg("BLE start notify");
891 if (sr_bt_check_socket_usable(desc) < 0)
894 write_u16le(buf, desc->cccd_value);
895 wrlen = sr_bt_char_write_req(desc, desc->cccd_handle, buf, sizeof(buf));
896 if (wrlen != sizeof(buf))
902 SR_PRIV int sr_bt_check_notify(struct sr_bt_desc *desc)
906 const uint8_t *bufptr;
909 uint16_t packet_handle;
910 uint8_t *packet_data;
912 const char *type_text;
918 if (sr_bt_check_socket_usable(desc) < 0)
922 * Get another message from the Bluetooth socket.
924 * TODO Can we assume that every "message" comes in a separate
925 * read(2) call, or can data combine at the caller's? Need we
926 * loop over the received content until all was consumed?
928 rdlen = sr_bt_read(desc, buf, sizeof(buf));
930 sr_dbg("check notifiy, read error, %zd", rdlen);
934 if (0) sr_spew("check notifiy, empty read");
938 buflen = (size_t)rdlen;
939 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
941 txt = sr_hexdump_new(bufptr, buflen);
942 sr_spew("check notifiy, read succes, length %zd, data: %s",
944 sr_hexdump_free(txt);
948 * Get header fields and references to the payload data. Notice
949 * that the first 16bit item after the packet type often is the
950 * handle, but need not always be. That is why the read position
951 * is kept, so that individual packet type handlers can either
952 * read _their_ layout strictly sequentially, or can conveniently
953 * access what a common preparation step has provided to them.
955 packet_handle = 0x0000;
958 packet_type = read_u8_inc_len(&bufptr, &buflen);
959 if (buflen >= sizeof(uint16_t)) {
960 packet_handle = read_u16le(bufptr);
961 packet_data = (void *)&bufptr[sizeof(uint16_t)];
962 packet_dlen = buflen - sizeof(uint16_t);
966 if (0) sr_spew("check notifiy, prep, hdl %" PRIu16 ", data %p len %zu",
967 packet_handle, packet_data, packet_dlen);
969 /* Dispatch according to the message type. */
970 switch (packet_type) {
971 case BLE_ATT_ERROR_RESP:
972 type_text = "error response";
974 sr_dbg("%s, no payload", type_text);
978 sr_dbg("%s, not handled here", type_text);
980 case BLE_ATT_WRITE_RESP:
981 type_text = "write response";
982 sr_dbg("%s, note taken", type_text);
984 case BLE_ATT_HANDLE_INDICATION:
985 type_text = "handle indication";
986 sr_dbg("%s, data len %zu", type_text, packet_dlen);
987 sr_bt_write_type(desc, BLE_ATT_HANDLE_CONFIRMATION);
988 sr_spew("%s, confirmation sent", type_text);
989 if (packet_handle != desc->read_handle)
993 ret = desc->data_cb(desc->data_cb_data,
994 packet_data, packet_dlen);
995 sr_spew("%s, data cb ret %d", type_text, ret);
997 case BLE_ATT_HANDLE_NOTIFICATION:
998 type_text = "handle notification";
999 sr_dbg("%s, data len %zu", type_text, packet_dlen);
1000 if (packet_handle != desc->read_handle)
1004 ret = desc->data_cb(desc->data_cb_data,
1005 packet_data, packet_dlen);
1006 sr_spew("%s, data cb ret %d", type_text, ret);
1009 sr_dbg("unhandled type 0x%02x, len %zu",
1010 packet_type, buflen);
1017 /* }}} indication/notification */
1018 /* {{{ read/write */
1020 SR_PRIV ssize_t sr_bt_write(struct sr_bt_desc *desc,
1021 const void *data, size_t len)
1028 if (sr_bt_check_socket_usable(desc) < 0)
1031 /* Send TX data to the writable characteristics for BLE UART services. */
1032 if (desc->write_handle)
1033 return sr_bt_char_write_req(desc, desc->write_handle, data, len);
1035 /* Send raw TX data to the RFCOMM socket for BT Classic channels. */
1036 return write(desc->fd, data, len);
1039 static ssize_t sr_bt_write_type(struct sr_bt_desc *desc, uint8_t type)
1048 if (sr_bt_check_socket_usable(desc) < 0)
1051 wrlen = write(desc->fd, &type, sizeof(type));
1054 if (wrlen < (ssize_t)sizeof(type))
1060 #if WITH_WRITE_TYPE_HANDLE
1061 static ssize_t sr_bt_write_type_handle(struct sr_bt_desc *desc,
1062 uint8_t type, uint16_t handle)
1064 return sr_bt_write_type_handle_bytes(desc, type, handle, NULL, 0);
1068 static ssize_t sr_bt_write_type_handle_bytes(struct sr_bt_desc *desc,
1069 uint8_t type, uint16_t handle, const uint8_t *data, size_t len)
1071 uint8_t header[sizeof(uint8_t) + sizeof(uint16_t)];
1072 struct iovec iov[2] = {
1073 { .iov_base = header, .iov_len = sizeof(header), },
1074 { .iov_base = (void *)data, .iov_len = len, },
1083 if (sr_bt_check_socket_usable(desc) < 0)
1087 write_u16le(&header[1], handle);
1090 wrlen = writev(desc->fd, iov, ARRAY_SIZE(iov));
1092 wrlen = write(desc->fd, header, sizeof(header));
1096 if (wrlen < (ssize_t)sizeof(header))
1098 wrlen -= sizeof(header);
1103 /* Returns negative upon error, or returns the number of _payload_ bytes written. */
1104 static ssize_t sr_bt_char_write_req(struct sr_bt_desc *desc,
1105 uint16_t handle, const void *data, size_t len)
1107 return sr_bt_write_type_handle_bytes(desc, BLE_ATT_WRITE_REQ,
1111 SR_PRIV ssize_t sr_bt_read(struct sr_bt_desc *desc, void *data, size_t len)
1113 struct pollfd fds[1];
1122 if (sr_bt_check_socket_usable(desc) < 0)
1125 memset(fds, 0, sizeof(fds));
1126 fds[0].fd = desc->fd;
1127 fds[0].events = POLLIN;
1128 ret = poll(fds, ARRAY_SIZE(fds), 0);
1133 if (!(fds[0].revents & POLLIN))
1136 rdlen = read(desc->fd, data, len);
1141 /* }}} indication/notification */