Debian Codegraph @

scripts/probe_adv_monitor.py

raw
1 """
2 Probe BlueZ AdvertisementMonitor1 or_patterns behaviour on a live adapter.
3
4 Standalone: needs only ``dbus_fast`` and a BlueZ >= 5.56 started with
5 ``--experimental`` on a kernel >= 5.10. Run it on the Bluetooth host:
6
7 python scripts/probe_adv_monitor.py --adapter hci0 --duration 20
8
9 It registers advertisement monitors the same way bleak does (RegisterMonitor
10 first, export the object second) and records which devices each monitor
11 reports through DeviceFound, then prints a table answering:
12
13 1. which FLAGS byte values the devices in range actually advertise;
14 2. whether two monitors of 16 patterns each cover everything
15 (HCI_MAX_ADV_MONITOR_NUM_PATTERNS is 16 on mainline);
16 3. with --test-overflow, what BlueZ does with a monitor of 32 patterns
17 (observed: never activated and released, so it is off by default);
18 4. how much the legacy three value list (0x02, 0x06, 0x1a) misses.
19
20 It only registers monitors; it never starts discovery or connects.
21 """
22
23 from __future__ import annotations
24
25 import argparse
26 import asyncio
27 import sys
28 import time
29 from typing import Any, no_type_check
30
31 from dbus_fast import BusType, Message, MessageType, PropertyAccess
32 from dbus_fast.aio import MessageBus
33 from dbus_fast.service import ServiceInterface, dbus_property, method
34
35 BLUEZ = "org.bluez"
36 MONITOR_IFACE = "org.bluez.AdvertisementMonitor1"
37 MANAGER_IFACE = "org.bluez.AdvertisementMonitorManager1"
38 DEVICE_IFACE = "org.bluez.Device1"
39 FLAGS_AD_TYPE = 0x01
40 ALL_FLAGS = list(range(0x20))
41 LEGACY_FLAGS = [0x02, 0x06, 0x1A]
42
43
44 def flags_pattern(value: int) -> list[Any]:
45 """Return an or_pattern matching a FLAGS AD structure equal to value."""
46 return [0, FLAGS_AD_TYPE, bytes([value])]
47
48
49 class Monitor(ServiceInterface):
50 """One org.bluez.AdvertisementMonitor1 object recording DeviceFound."""
51
52 def __init__(self, label: str, values: list[int]) -> None:
53 super().__init__(MONITOR_IFACE)
54 self.label = label
55 self.values = values
56 self.found: dict[str, float] = {}
57 self.lost: dict[str, float] = {}
58 self.activated = False
59 self.released = False
60
61 @method()
62 @no_type_check
63 def Release(self): # noqa: N802
64 self.released = True
65
66 @method()
67 @no_type_check
68 def Activate(self): # noqa: N802
69 self.activated = True
70
71 @method()
72 @no_type_check
73 def DeviceFound(self, device: o): # noqa: F821, N802
74 self.found.setdefault(device, time.monotonic())
75
76 @method()
77 @no_type_check
78 def DeviceLost(self, device: o): # noqa: F821, N802
79 self.lost[device] = time.monotonic()
80
81 @dbus_property(PropertyAccess.READ)
82 @no_type_check
83 def Type(self) -> s: # noqa: F821, N802
84 return "or_patterns"
85
86 @dbus_property(PropertyAccess.READ)
87 @no_type_check
88 def Patterns(self) -> a(yyay): # noqa: F821, N802
89 return [flags_pattern(v) for v in self.values]
90
91
92 class Probe:
93 """Register and tear down monitors on one adapter."""
94
95 def __init__(self, bus: MessageBus, adapter: str) -> None:
96 self.bus = bus
97 self.adapter_path = f"/org/bluez/{adapter}"
98 self._counter = 0
99
100 async def call(
101 self,
102 path: str,
103 iface: str,
104 member: str,
105 sig: str = "",
106 body: list[Any] | None = None,
107 ) -> Message:
108 reply = await self.bus.call(
109 Message(
110 destination=BLUEZ,
111 path=path,
112 interface=iface,
113 member=member,
114 signature=sig,
115 body=body or [],
116 )
117 )
118 if reply.message_type == MessageType.ERROR:
119 raise RuntimeError(
120 f"{member} on {path} failed: {reply.error_name}: {reply.body}"
121 )
122 return reply
123
124 async def manager_props(self) -> dict[str, Any]:
125 reply = await self.call(
126 self.adapter_path,
127 "org.freedesktop.DBus.Properties",
128 "GetAll",
129 "s",
130 [MANAGER_IFACE],
131 )
132 return {k: v.value for k, v in reply.body[0].items()}
133
134 async def register(self, monitors: list[Monitor]) -> list[str]:
135 paths: list[str] = []
136 for mon in monitors:
137 self._counter += 1
138 path = f"/org/habluetooth/probe/{self._counter}"
139 try:
140 await self.call(
141 self.adapter_path, MANAGER_IFACE, "RegisterMonitor", "o", [path]
142 )
143 except RuntimeError as err:
144 print(f" {mon.label}: RegisterMonitor failed: {err}", file=sys.stderr)
145 mon.released = True
146 continue
147 # bleak exports after registering; BlueZ ignores the monitor otherwise.
148 self.bus.export(path, mon)
149 paths.append(path)
150 return paths
151
152 async def unregister(self, monitors: list[Monitor], paths: list[str]) -> None:
153 registered = [mon for mon in monitors if not mon.released or mon.activated]
154 for mon, path in zip(registered, paths, strict=True):
155 self.bus.unexport(path, mon)
156 try:
157 await self.call(
158 self.adapter_path, MANAGER_IFACE, "UnregisterMonitor", "o", [path]
159 )
160 except RuntimeError as err:
161 print(f" warning: {err}", file=sys.stderr)
162
163 async def run_phase(
164 self, name: str, monitors: list[Monitor], duration: float
165 ) -> None:
166 print(f"\n== {name}: {len(monitors)} monitor(s), {duration:.0f}s")
167 paths = await self.register(monitors)
168 try:
169 await asyncio.sleep(duration)
170 finally:
171 await self.unregister(monitors, paths)
172 for mon in monitors:
173 state = "activated" if mon.activated else "NOT activated"
174 if mon.released:
175 state += ", released by BlueZ"
176 print(f" {mon.label}: {len(mon.found)} device(s), {state}")
177
178 async def device_names(self) -> dict[str, str]:
179 reply = await self.call(
180 "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"
181 )
182 names: dict[str, str] = {}
183 for path, ifaces in reply.body[0].items():
184 if (dev := ifaces.get(DEVICE_IFACE)) is None:
185 continue
186 addr = dev["Address"].value
187 name = dev["Name"].value if "Name" in dev else ""
188 names[path] = f"{addr} {name}".strip()
189 return names
190
191
192 def fmt_values(values: list[int]) -> str:
193 return ",".join(f"{v:#04x}" for v in values)
194
195
196 async def main() -> int:
197 parser = argparse.ArgumentParser(
198 description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
199 )
200 parser.add_argument("--adapter", default="hci0")
201 parser.add_argument(
202 "--duration", type=float, default=20.0, help="seconds per phase"
203 )
204 parser.add_argument(
205 "--skip-census",
206 action="store_true",
207 help="skip the per value census (4 phases)",
208 )
209 parser.add_argument(
210 "--test-overflow",
211 action="store_true",
212 help="also register one monitor with 32 patterns; BlueZ releases it and "
213 "may drop the bus connection, so this runs last and is off by default",
214 )
215 args = parser.parse_args()
216
217 try:
218 bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
219 except Exception as err:
220 print(f"cannot connect to the system bus: {err}", file=sys.stderr)
221 return 2
222 probe = Probe(bus, args.adapter)
223
224 try:
225 props = await probe.manager_props()
226 except RuntimeError as err:
227 print(
228 f"{MANAGER_IFACE} not available on {probe.adapter_path}: {err}\n"
229 "BlueZ >= 5.56 started with --experimental and kernel >= 5.10 are required",
230 file=sys.stderr,
231 )
232 return 2
233 print(f"adapter {probe.adapter_path}")
234 for key, value in props.items():
235 print(f" {key}: {value}")
236
237 census: dict[int, set[str]] = {v: set() for v in ALL_FLAGS}
238 if not args.skip_census:
239 for start in range(0, len(ALL_FLAGS), 8):
240 batch = ALL_FLAGS[start : start + 8]
241 monitors = [Monitor(f"flags {v:#04x}", [v]) for v in batch]
242 await probe.run_phase(
243 f"census {fmt_values(batch)}", monitors, args.duration
244 )
245 for mon in monitors:
246 census[mon.values[0]].update(mon.found)
247
248 legacy = Monitor("legacy 0x02,0x06,0x1a", LEGACY_FLAGS)
249 await probe.run_phase("legacy list", [legacy], args.duration)
250
251 # Put the common values last so a 16 pattern cap would drop them.
252 ordered = [v for v in ALL_FLAGS if v not in LEGACY_FLAGS] + LEGACY_FLAGS
253 pair = [
254 Monitor("monitor A (16 patterns)", ordered[:16]),
255 Monitor("monitor B (16 patterns)", ordered[16:]),
256 ]
257 await probe.run_phase("two monitor test", pair, args.duration)
258 two = set(pair[0].found) | set(pair[1].found)
259
260 names = await probe.device_names()
261 all_devices = set().union(*census.values()) | set(legacy.found) | two
262
263 print(
264 "\n== per FLAGS value (census: devices seen by a monitor with only that value)"
265 )
266 print(f"{'flags':>6} {'census':>6} {'legacy':>6} {'2x16':>6} devices")
267 for value in ALL_FLAGS:
268 devs = census[value]
269 if not devs and args.skip_census:
270 continue
271 in_legacy = len(devs & set(legacy.found))
272 in_two = len(devs & two)
273 listing = "; ".join(names.get(p, p) for p in sorted(devs))
274 print(f"{value:#06x} {len(devs):>6} {in_legacy:>6} {in_two:>6} {listing}")
275
276 print("\n== totals")
277 print(f" distinct devices in any phase: {len(all_devices)}")
278 print(f" legacy list: {len(legacy.found)}")
279 print(f" two monitors of 16: {len(two)}")
280 missed = all_devices - set(legacy.found)
281 if missed:
282 print(f" missed by the legacy list ({len(missed)}):")
283 for path in sorted(missed):
284 print(f" {names.get(path, path)}")
285
286 if args.test_overflow:
287 # Observed on BlueZ 5.7x: a monitor with more than 16 patterns is not
288 # truncated, it is never activated and released, and the bus
289 # connection dropped right after. Last, so the results above survive.
290 single = Monitor("32 patterns in one monitor", ordered)
291 await probe.run_phase("overflow test (32 patterns)", [single], args.duration)
292
293 bus.disconnect()
294 return 0
295
296
297 if __name__ == "__main__":
298 sys.exit(asyncio.run(main()))