Debian Codegraph @

src/bluetooth_adapters/systems/linux_hci.py

raw
1 from __future__ import annotations
2
3 import ctypes
4
5 try:
6 import fcntl
7 except ImportError:
8 # fcntl is not available on Windows
9 fcntl = None # type: ignore
10 import logging
11 import socket
12 from typing import Any
13
14 _LOGGER = logging.getLogger(__name__)
15
16 AF_BLUETOOTH = 31
17 PF_BLUETOOTH = AF_BLUETOOTH
18 BTPROTO_HCI = 1
19 HCI_MAX_DEV = 16
20 HCIGETDEVLIST = 0x800448D2 # _IOR('H', 210, int)
21 HCIGETDEVINFO = 0x800448D3 # _IOR('H', 211, int)
22
23 HCI_UP = 0 # HCI device flag
24 LMP_LE = 0x40 # LMP capabilities
25
26
27 class hci_dev_req(ctypes.Structure):
28 _fields_ = [("dev_id", ctypes.c_uint16), ("dev_opt", ctypes.c_uint32)]
29
30
31 class hci_dev_list_req(ctypes.Structure):
32 _fields_ = [("dev_num", ctypes.c_uint16), ("dev_req", hci_dev_req * HCI_MAX_DEV)]
33
34
35 class bdaddr_t(ctypes.Structure):
36 _fields_ = [("b", ctypes.c_uint8 * 6)]
37
38 def __str__(self) -> str:
39 return ":".join(["%02X" % x for x in reversed(self.b)])
40
41
42 class hci_dev_stats(ctypes.Structure):
43 _fields_ = [
44 ("err_rx", ctypes.c_uint32),
45 ("err_tx", ctypes.c_uint32),
46 ("cmd_tx", ctypes.c_uint32),
47 ("evt_rx", ctypes.c_uint32),
48 ("acl_tx", ctypes.c_uint32),
49 ("acl_rx", ctypes.c_uint32),
50 ("sco_tx", ctypes.c_uint32),
51 ("sco_rx", ctypes.c_uint32),
52 ("byte_rx", ctypes.c_uint32),
53 ("byte_tx", ctypes.c_uint32),
54 ]
55
56
57 class hci_dev_info(ctypes.Structure):
58 _fields_ = [
59 ("dev_id", ctypes.c_uint16),
60 ("name", ctypes.c_char * 8),
61 ("bdaddr", bdaddr_t),
62 ("flags", ctypes.c_uint32),
63 ("type", ctypes.c_uint8),
64 ("features", ctypes.c_uint8 * 8),
65 ("pkt_type", ctypes.c_uint32),
66 ("link_policy", ctypes.c_uint32),
67 ("link_mode", ctypes.c_uint32),
68 ("acl_mtu", ctypes.c_uint16),
69 ("acl_pkts", ctypes.c_uint16),
70 ("sco_mtu", ctypes.c_uint16),
71 ("sco_pkts", ctypes.c_uint16),
72 ("stat", hci_dev_stats),
73 ]
74
75
76 hci_dev_info_p = ctypes.POINTER(hci_dev_info)
77
78
79 def get_adapters_from_hci() -> dict[int, dict[str, Any]]:
80 """Get bluetooth adapters from HCI."""
81 if not fcntl:
82 raise RuntimeError("fcntl is not available")
83 out: dict[int, dict[str, Any]] = {}
84 sock: socket.socket | None = None
85 try:
86 sock = socket.socket(AF_BLUETOOTH, socket.SOCK_RAW, BTPROTO_HCI)
87 buf = hci_dev_list_req()
88 buf.dev_num = HCI_MAX_DEV
89 ret = fcntl.ioctl(sock.fileno(), HCIGETDEVLIST, buf)
90 if ret < 0:
91 raise OSError(f"HCIGETDEVLIST failed: {ret}")
92 for i in range(buf.dev_num):
93 dev_req = buf.dev_req[i]
94 dev = hci_dev_info()
95 dev.dev_id = dev_req.dev_id
96 ret = fcntl.ioctl(sock.fileno(), HCIGETDEVINFO, dev)
97 info = {str(k): getattr(dev, k) for k, *v_ in dev._fields_}
98 info["bdaddr"] = str(info["bdaddr"])
99 info["name"] = info["name"].decode()
100 info["powered"] = bool(info["flags"] & (1 << HCI_UP))
101 info["advertise"] = bool(
102 info["features"][4] & LMP_LE
103 ) # assume advertising supported if device supports LE
104 out[int(dev.dev_id)] = info
105 except OSError as error:
106 _LOGGER.debug("Error while getting HCI devices: %s", error)
107 return out
108 except Exception as error: # pylint: disable=broad-except
109 _LOGGER.exception("Unexpected error while getting HCI devices: %s", error)
110 return out
111 finally:
112 if sock:
113 sock.close()
114 return out