Debian Codegraph @

tests/test_manager.py

raw
1 """Tests for the manager."""
2
3 import asyncio
4 import logging
5 import time
6 from collections.abc import Callable, Iterable
7 from datetime import timedelta
8 from typing import Any
9 from unittest.mock import ANY, AsyncMock, Mock, PropertyMock, patch
10
11 import pytest
12 from bleak.backends.scanner import AdvertisementData, BLEDevice
13 from bleak_retry_connector import AllocationChange, Allocations, BleakSlotManager
14 from bluetooth_adapters import ADAPTER_ADDRESS, ADAPTER_PASSIVE_SCAN
15 from bluetooth_adapters.systems.linux import LinuxAdapters
16 from bluetooth_data_tools import monotonic_time_coarse
17 from freezegun import freeze_time
18
19 from habluetooth import (
20 FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
21 TRACKER_BUFFERING_WOBBLE_SECONDS,
22 UNAVAILABLE_TRACK_SECONDS,
23 BluetoothManager,
24 BluetoothReachabilityIntent,
25 BluetoothScanningMode,
26 BluetoothServiceInfoBleak,
27 HaBluetoothSlotAllocations,
28 HaScannerModeChange,
29 HaScannerRegistration,
30 HaScannerRegistrationEvent,
31 get_manager,
32 set_manager,
33 )
34 from habluetooth.central_manager import CentralBluetoothManager
35 from habluetooth.const import RESCUE_SCAN_ACCEPT_SECONDS
36
37 from . import (
38 HCI0_SOURCE_ADDRESS,
39 HCI1_SOURCE_ADDRESS,
40 NON_CONNECTABLE_REMOTE_SOURCE_ADDRESS,
41 InjectableRemoteScanner,
42 async_fire_time_changed,
43 generate_advertisement_data,
44 generate_ble_device,
45 inject_advertisement_with_source,
46 inject_advertisement_with_time_and_source,
47 inject_advertisement_with_time_and_source_connectable,
48 patch_bluetooth_time,
49 utcnow,
50 )
51 from .conftest import FakeBluetoothAdapters, FakeScanner
52
53 SOURCE_LOCAL = "local"
54
55
56 @pytest.mark.asyncio
57 @pytest.mark.skipif("platform.system() == 'Windows'")
58 async def test_async_recover_failed_adapters() -> None:
59 """Return the BluetoothManager instance."""
60 attempt = 0
61
62 class MockLinuxAdapters(LinuxAdapters):
63 @property
64 def adapters(self) -> dict[str, Any]:
65 nonlocal attempt
66 attempt += 1
67
68 if attempt == 1:
69 return {
70 "hci0": {
71 "address": "00:00:00:00:00:01",
72 "hw_version": "usb:v1D6Bp0246d053F",
73 "passive_scan": False,
74 "sw_version": "homeassistant",
75 "manufacturer": "ACME",
76 "product": "Bluetooth Adapter 5.0",
77 "product_id": "aa01",
78 "vendor_id": "cc01",
79 },
80 "hci1": {
81 "address": "00:00:00:00:00:00",
82 "hw_version": "usb:v1D6Bp0246d053F",
83 "passive_scan": False,
84 "sw_version": "homeassistant",
85 "manufacturer": "ACME",
86 "product": "Bluetooth Adapter 5.0",
87 "product_id": "aa01",
88 "vendor_id": "cc01",
89 },
90 "hci2": {
91 "address": "00:00:00:00:00:00",
92 "hw_version": "usb:v1D6Bp0246d053F",
93 "passive_scan": False,
94 "sw_version": "homeassistant",
95 "manufacturer": "ACME",
96 "product": "Bluetooth Adapter 5.0",
97 "product_id": "aa01",
98 "vendor_id": "cc01",
99 },
100 }
101
102 return {
103 "hci0": {
104 "address": "00:00:00:00:00:01",
105 "hw_version": "usb:v1D6Bp0246d053F",
106 "passive_scan": False,
107 "sw_version": "homeassistant",
108 "manufacturer": "ACME",
109 "product": "Bluetooth Adapter 5.0",
110 "product_id": "aa01",
111 "vendor_id": "cc01",
112 },
113 "hci1": {
114 "address": "00:00:00:00:00:02",
115 "hw_version": "usb:v1D6Bp0246d053F",
116 "passive_scan": False,
117 "sw_version": "homeassistant",
118 "manufacturer": "ACME",
119 "product": "Bluetooth Adapter 5.0",
120 "product_id": "aa01",
121 "vendor_id": "cc01",
122 },
123 "hci2": {
124 "address": "00:00:00:00:00:03",
125 "hw_version": "usb:v1D6Bp0246d053F",
126 "passive_scan": False,
127 "sw_version": "homeassistant",
128 "manufacturer": "ACME",
129 "product": "Bluetooth Adapter 5.0",
130 "product_id": "aa01",
131 "vendor_id": "cc01",
132 },
133 }
134
135 with (
136 patch("habluetooth.manager.async_reset_adapter") as mock_async_reset_adapter,
137 ):
138 adapters = MockLinuxAdapters()
139 slot_manager = BleakSlotManager()
140 manager = BluetoothManager(adapters, slot_manager)
141 await manager.async_setup()
142 set_manager(manager)
143 adapter = await manager.async_get_adapter_from_address_or_recover(
144 "00:00:00:00:00:03"
145 )
146 assert adapter == "hci2"
147 adapter = await manager.async_get_adapter_from_address_or_recover(
148 "00:00:00:00:00:02"
149 )
150 assert adapter == "hci1"
151 adapter = await manager.async_get_adapter_from_address_or_recover(
152 "00:00:00:00:00:01"
153 )
154 assert adapter == "hci0"
155
156 assert mock_async_reset_adapter.call_count == 2
157 assert mock_async_reset_adapter.call_args_list == [
158 (("hci1", "00:00:00:00:00:00", False),),
159 (("hci2", "00:00:00:00:00:00", False),),
160 ]
161
162
163 @pytest.mark.asyncio
164 async def test_create_manager() -> None:
165 """Return the BluetoothManager instance."""
166 adapters = FakeBluetoothAdapters()
167 slot_manager = BleakSlotManager()
168 manager = BluetoothManager(adapters, slot_manager)
169 set_manager(manager)
170 assert manager
171
172
173 @pytest.mark.asyncio
174 @pytest.mark.usefixtures("enable_bluetooth")
175 async def test_async_register_disappeared_callback(
176 register_hci0_scanner: None,
177 register_hci1_scanner: None,
178 ) -> None:
179 """Test bluetooth async_register_disappeared_callback handles failures."""
180 manager = get_manager()
181 assert manager._loop is not None
182
183 address = "44:44:33:11:23:12"
184
185 switchbot_device_signal_100 = generate_ble_device(
186 address, "wohand_signal_100", rssi=-100
187 )
188 switchbot_adv_signal_100 = generate_advertisement_data(
189 local_name="wohand_signal_100", service_uuids=[]
190 )
191 inject_advertisement_with_source(
192 switchbot_device_signal_100, switchbot_adv_signal_100, "hci0"
193 )
194
195 failed_disappeared: list[str] = []
196
197 def _failing_callback(_address: str) -> None:
198 """Failing callback."""
199 failed_disappeared.append(_address)
200 msg = "This is a test"
201 raise ValueError(msg)
202
203 ok_disappeared: list[str] = []
204
205 def _ok_callback(_address: str) -> None:
206 """Ok callback."""
207 ok_disappeared.append(_address)
208
209 cancel1 = manager.async_register_disappeared_callback(_failing_callback)
210 # Make sure the second callback still works if the first one fails and
211 # raises an exception
212 cancel2 = manager.async_register_disappeared_callback(_ok_callback)
213
214 switchbot_adv_signal_100 = generate_advertisement_data(
215 local_name="wohand_signal_100",
216 manufacturer_data={123: b"abc"},
217 service_uuids=[],
218 rssi=-80,
219 )
220 inject_advertisement_with_source(
221 switchbot_device_signal_100, switchbot_adv_signal_100, "hci1"
222 )
223
224 future_time = utcnow() + timedelta(seconds=3600)
225 future_monotonic_time = time.monotonic() + 3600
226 with (
227 freeze_time(future_time),
228 patch(
229 "habluetooth.manager.monotonic_time_coarse",
230 return_value=future_monotonic_time,
231 ),
232 ):
233 manager._async_check_unavailable()
234 async_fire_time_changed(future_time)
235
236 assert len(ok_disappeared) == 1
237 assert ok_disappeared[0] == address
238 assert len(failed_disappeared) == 1
239 assert failed_disappeared[0] == address
240
241 cancel1()
242 cancel2()
243
244
245 @pytest.mark.asyncio
246 @pytest.mark.usefixtures("enable_bluetooth")
247 async def test_check_unavailable_materializes_each_scanner_once() -> None:
248 """
249 _async_check_unavailable must hit each scanner's discovered_addresses once.
250
251 Regression for https://github.com/Bluetooth-Devices/habluetooth/issues/505:
252 the prior two-pass loop accessed every connectable scanner twice per
253 cycle, and ``HaScanner.discovered_addresses`` rebuilds bleak's
254 discovered-devices dict on every access.
255 """
256 manager = get_manager()
257 address = "44:44:33:11:23:12"
258
259 connectable_calls = 0
260 non_connectable_calls = 0
261
262 class CountingConnectable(FakeScanner):
263 @property
264 def discovered_addresses(self) -> Iterable[str]:
265 nonlocal connectable_calls
266 connectable_calls += 1
267 return (address,)
268
269 class CountingNonConnectable(FakeScanner):
270 @property
271 def discovered_addresses(self) -> Iterable[str]:
272 nonlocal non_connectable_calls
273 non_connectable_calls += 1
274 return (address,)
275
276 connectable = CountingConnectable("hci0", "hci0", connectable=True)
277 non_connectable = CountingNonConnectable("hci1", "hci1", connectable=False)
278 cancel_c = manager.async_register_scanner(connectable)
279 cancel_n = manager.async_register_scanner(non_connectable)
280
281 manager._async_check_unavailable()
282
283 assert connectable_calls == 1
284 assert non_connectable_calls == 1
285
286 cancel_c()
287 cancel_n()
288
289
290 @pytest.mark.asyncio
291 @pytest.mark.usefixtures("enable_bluetooth")
292 async def test_async_register_allocation_callback(
293 register_hci0_scanner: None,
294 register_hci1_scanner: None,
295 ) -> None:
296 """Test bluetooth async_register_allocation_callback handles failures."""
297 manager = get_manager()
298 assert manager._loop is not None
299
300 address = "44:44:33:11:23:12"
301
302 switchbot_device_signal_100 = generate_ble_device(
303 address, "wohand_signal_100", rssi=-100
304 )
305 switchbot_adv_signal_100 = generate_advertisement_data(
306 local_name="wohand_signal_100", service_uuids=[]
307 )
308 inject_advertisement_with_source(
309 switchbot_device_signal_100, switchbot_adv_signal_100, "hci0"
310 )
311
312 failed_allocations: list[HaBluetoothSlotAllocations] = []
313
314 def _failing_callback(allocations: HaBluetoothSlotAllocations) -> None:
315 """Failing callback."""
316 failed_allocations.append(allocations)
317 msg = "This is a test"
318 raise ValueError(msg)
319
320 ok_allocations: list[HaBluetoothSlotAllocations] = []
321
322 def _ok_callback(allocations: HaBluetoothSlotAllocations) -> None:
323 """Ok callback."""
324 ok_allocations.append(allocations)
325
326 cancel1 = manager.async_register_allocation_callback(_failing_callback)
327 # Make sure the second callback still works if the first one fails and
328 # raises an exception
329 cancel2 = manager.async_register_allocation_callback(_ok_callback)
330
331 switchbot_adv_signal_100 = generate_advertisement_data(
332 local_name="wohand_signal_100",
333 manufacturer_data={123: b"abc"},
334 service_uuids=[],
335 rssi=-80,
336 )
337 inject_advertisement_with_source(
338 switchbot_device_signal_100, switchbot_adv_signal_100, "hci1"
339 )
340
341 assert manager.async_current_allocations() == [
342 HaBluetoothSlotAllocations(
343 source="AA:BB:CC:DD:EE:00", slots=5, free=5, allocated=[]
344 ),
345 HaBluetoothSlotAllocations(
346 source="AA:BB:CC:DD:EE:11", slots=5, free=5, allocated=[]
347 ),
348 ]
349 manager.async_on_allocation_changed(
350 Allocations(
351 "AA:BB:CC:DD:EE:00",
352 5,
353 4,
354 ["44:44:33:11:23:12"],
355 )
356 )
357
358 assert len(ok_allocations) == 1
359 assert ok_allocations[0] == HaBluetoothSlotAllocations(
360 "AA:BB:CC:DD:EE:00",
361 5,
362 4,
363 ["44:44:33:11:23:12"],
364 )
365 assert len(failed_allocations) == 1
366 assert failed_allocations[0] == HaBluetoothSlotAllocations(
367 "AA:BB:CC:DD:EE:00",
368 5,
369 4,
370 ["44:44:33:11:23:12"],
371 )
372
373 with patch.object(
374 manager.slot_manager,
375 "get_allocations",
376 return_value=Allocations(
377 adapter="hci0",
378 slots=5,
379 free=4,
380 allocated=["44:44:33:11:23:12"],
381 ),
382 ):
383 manager.slot_manager._call_callbacks(
384 AllocationChange.ALLOCATED, "/org/bluez/hci0/dev_44_44_33_11_23_12"
385 )
386
387 assert len(ok_allocations) == 2
388
389 assert manager.async_current_allocations() == [
390 HaBluetoothSlotAllocations("AA:BB:CC:DD:EE:00", 5, 4, ["44:44:33:11:23:12"]),
391 HaBluetoothSlotAllocations(
392 source="AA:BB:CC:DD:EE:11", slots=5, free=5, allocated=[]
393 ),
394 ]
395 assert manager.async_current_allocations("AA:BB:CC:DD:EE:00") == [
396 HaBluetoothSlotAllocations("AA:BB:CC:DD:EE:00", 5, 4, ["44:44:33:11:23:12"]),
397 ]
398 cancel1()
399 cancel2()
400
401
402 @pytest.mark.asyncio
403 @pytest.mark.usefixtures("enable_bluetooth")
404 async def test_async_register_allocation_callback_non_connectable(
405 register_non_connectable_scanner: None,
406 ) -> None:
407 """Test async_current_allocations for a non-connectable scanner."""
408 manager = get_manager()
409 assert manager._loop is not None
410 assert manager.async_current_allocations() == [
411 HaBluetoothSlotAllocations(
412 source="AA:BB:CC:DD:EE:FF",
413 slots=0,
414 free=0,
415 allocated=[],
416 ),
417 ]
418
419
420 @pytest.mark.asyncio
421 @pytest.mark.usefixtures("enable_bluetooth")
422 async def test_async_register_scanner_registration_callback(
423 register_hci0_scanner: None,
424 register_hci1_scanner: None,
425 ) -> None:
426 """Test bluetooth async_register_scanner_registration_callback handles failures."""
427 manager = get_manager()
428 assert manager._loop is not None
429
430 scanners = manager.async_current_scanners()
431 assert len(scanners) == 2
432 sources = {scanner.source for scanner in scanners}
433 assert sources == {"AA:BB:CC:DD:EE:00", "AA:BB:CC:DD:EE:11"}
434
435 failed_scanner_callbacks: list[HaScannerRegistration] = []
436
437 def _failing_callback(scanner_registration: HaScannerRegistration) -> None:
438 """Failing callback."""
439 failed_scanner_callbacks.append(scanner_registration)
440 msg = "This is a test"
441 raise ValueError(msg)
442
443 ok_scanner_callbacks: list[HaScannerRegistration] = []
444
445 def _ok_callback(scanner_registration: HaScannerRegistration) -> None:
446 """Ok callback."""
447 ok_scanner_callbacks.append(scanner_registration)
448
449 cancel1 = manager.async_register_scanner_registration_callback(
450 _failing_callback, None
451 )
452 # Make sure the second callback still works if the first one fails and
453 # raises an exception
454 cancel2 = manager.async_register_scanner_registration_callback(_ok_callback, None)
455
456 hci3_scanner = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
457 hci3_scanner.connectable = True
458 manager = get_manager()
459 cancel = manager.async_register_scanner(hci3_scanner, connection_slots=5)
460
461 assert len(ok_scanner_callbacks) == 1
462 assert ok_scanner_callbacks[0] == HaScannerRegistration(
463 HaScannerRegistrationEvent.ADDED, hci3_scanner
464 )
465 assert len(failed_scanner_callbacks) == 1
466
467 cancel()
468
469 assert len(ok_scanner_callbacks) == 2
470 assert ok_scanner_callbacks[1] == HaScannerRegistration(
471 HaScannerRegistrationEvent.REMOVED, hci3_scanner
472 )
473 cancel1()
474 cancel2()
475
476
477 @pytest.mark.asyncio
478 @pytest.mark.usefixtures("enable_bluetooth")
479 async def test_async_register_scanner_mode_change_callback(
480 register_hci0_scanner: None,
481 register_hci1_scanner: None,
482 ) -> None:
483 """Test bluetooth async_register_scanner_mode_change_callback handles failures."""
484 manager = get_manager()
485 assert manager._loop is not None
486
487 scanners = manager.async_current_scanners()
488 assert len(scanners) == 2
489 scanner = scanners[0]
490
491 failed_mode_callbacks: list[HaScannerModeChange] = []
492
493 def _failing_callback(mode_change: HaScannerModeChange) -> None:
494 """Failing callback."""
495 failed_mode_callbacks.append(mode_change)
496 msg = "This is a test"
497 raise ValueError(msg)
498
499 ok_mode_callbacks: list[HaScannerModeChange] = []
500
501 def _ok_callback(mode_change: HaScannerModeChange) -> None:
502 """Ok callback."""
503 ok_mode_callbacks.append(mode_change)
504
505 cancel1 = manager.async_register_scanner_mode_change_callback(
506 _failing_callback, None
507 )
508 # Make sure the second callback still works if the first one fails and
509 # raises an exception
510 cancel2 = manager.async_register_scanner_mode_change_callback(_ok_callback, None)
511
512 # Test specific source callback
513 source_specific_callbacks: list[HaScannerModeChange] = []
514
515 def _source_specific_callback(mode_change: HaScannerModeChange) -> None:
516 """Source specific callback."""
517 source_specific_callbacks.append(mode_change)
518
519 cancel3 = manager.async_register_scanner_mode_change_callback(
520 _source_specific_callback, scanner.source
521 )
522
523 # Change requested mode
524
525 scanner.set_requested_mode(BluetoothScanningMode.ACTIVE)
526
527 assert len(ok_mode_callbacks) == 1
528 assert ok_mode_callbacks[0].scanner == scanner
529 assert ok_mode_callbacks[0].requested_mode == BluetoothScanningMode.ACTIVE
530 assert ok_mode_callbacks[0].current_mode == scanner.current_mode
531
532 assert len(failed_mode_callbacks) == 1
533 assert len(source_specific_callbacks) == 1
534
535 # Change current mode
536 scanner.set_current_mode(BluetoothScanningMode.ACTIVE)
537
538 assert len(ok_mode_callbacks) == 2
539 assert ok_mode_callbacks[1].scanner == scanner
540 assert ok_mode_callbacks[1].current_mode == BluetoothScanningMode.ACTIVE
541
542 assert len(failed_mode_callbacks) == 2
543 assert len(source_specific_callbacks) == 2
544
545 # No change when setting the same mode
546 scanner.set_current_mode(BluetoothScanningMode.ACTIVE)
547 assert len(ok_mode_callbacks) == 2
548
549 cancel1()
550 cancel2()
551 cancel3()
552
553
554 _PASSIVE_WARNING = "is in passive-only mode"
555
556
557 @pytest.mark.asyncio
558 async def test_active_scan_warns_about_existing_passive_scanner(
559 caplog: pytest.LogCaptureFixture,
560 ) -> None:
561 """Registering an active scan warns when a passive-only scanner exists."""
562 manager = get_manager()
563 passive = FakeScanner(
564 "AA:BB:CC:DD:EE:01", "hci1", requested_mode=BluetoothScanningMode.PASSIVE
565 )
566 cancel_scanner = manager.async_register_scanner(passive)
567 try:
568 with caplog.at_level(logging.WARNING):
569 cancel_scan = manager.async_register_active_scan("AA:BB:CC:DD:EE:99")
570 assert _PASSIVE_WARNING in caplog.text
571 assert passive.name in caplog.text
572 finally:
573 cancel_scan()
574 cancel_scanner()
575
576
577 @pytest.mark.asyncio
578 async def test_scanner_going_passive_after_active_scan_warns(
579 caplog: pytest.LogCaptureFixture,
580 ) -> None:
581 """A scanner becoming passive while active scans exist warns once."""
582 manager = get_manager()
583 cancel_scan = manager.async_register_active_scan("AA:BB:CC:DD:EE:99")
584 auto = FakeScanner(
585 "AA:BB:CC:DD:EE:02", "hci2", requested_mode=BluetoothScanningMode.AUTO
586 )
587 cancel_scanner = manager.async_register_scanner(auto)
588 try:
589 with caplog.at_level(logging.WARNING):
590 # Current-mode toggles on an AUTO scanner must not warn.
591 auto.set_current_mode(BluetoothScanningMode.ACTIVE)
592 assert _PASSIVE_WARNING not in caplog.text
593 # Flipping the requested mode to passive warns.
594 auto.set_requested_mode(BluetoothScanningMode.PASSIVE)
595 assert caplog.text.count(_PASSIVE_WARNING) == 1
596 assert auto.name in caplog.text
597 finally:
598 cancel_scanner()
599 cancel_scan()
600
601
602 @pytest.mark.asyncio
603 async def test_passive_scanner_warning_dedupes_per_source(
604 caplog: pytest.LogCaptureFixture,
605 ) -> None:
606 """One passive scanner warns once across many active-scan registrations."""
607 manager = get_manager()
608 passive = FakeScanner(
609 "AA:BB:CC:DD:EE:03", "hci3", requested_mode=BluetoothScanningMode.PASSIVE
610 )
611 cancel_scanner = manager.async_register_scanner(passive)
612 cancels: list[Callable[[], None]] = []
613 try:
614 with caplog.at_level(logging.WARNING):
615 cancels.extend(
616 manager.async_register_active_scan(addr)
617 for addr in ("AA:BB:CC:DD:EE:91", "AA:BB:CC:DD:EE:92")
618 )
619 assert caplog.text.count(_PASSIVE_WARNING) == 1
620 finally:
621 for cancel in cancels:
622 cancel()
623 cancel_scanner()
624
625
626 @pytest.mark.asyncio
627 async def test_active_scan_no_warning_for_auto_or_active_scanner(
628 caplog: pytest.LogCaptureFixture,
629 ) -> None:
630 """No warning when the only scanners are auto or active."""
631 manager = get_manager()
632 auto = FakeScanner(
633 "AA:BB:CC:DD:EE:04", "hci4", requested_mode=BluetoothScanningMode.AUTO
634 )
635 active = FakeScanner(
636 "AA:BB:CC:DD:EE:05", "hci5", requested_mode=BluetoothScanningMode.ACTIVE
637 )
638 cancel_auto = manager.async_register_scanner(auto)
639 cancel_active = manager.async_register_scanner(active)
640 try:
641 with caplog.at_level(logging.WARNING):
642 cancel_scan = manager.async_register_active_scan("AA:BB:CC:DD:EE:99")
643 assert _PASSIVE_WARNING not in caplog.text
644 finally:
645 cancel_scan()
646 cancel_auto()
647 cancel_active()
648
649
650 @pytest.mark.asyncio
651 async def test_passive_scanner_warning_resets_after_unregister(
652 caplog: pytest.LogCaptureFixture,
653 ) -> None:
654 """Re-registering a passive scanner warns again after it is unregistered."""
655 manager = get_manager()
656 cancel_scan = manager.async_register_active_scan("AA:BB:CC:DD:EE:99")
657 try:
658 with caplog.at_level(logging.WARNING):
659 cancel_scanner = manager.async_register_scanner(
660 FakeScanner(
661 "AA:BB:CC:DD:EE:06",
662 "hci6",
663 requested_mode=BluetoothScanningMode.PASSIVE,
664 )
665 )
666 assert caplog.text.count(_PASSIVE_WARNING) == 1
667 cancel_scanner()
668 caplog.clear()
669 with caplog.at_level(logging.WARNING):
670 cancel_scanner2 = manager.async_register_scanner(
671 FakeScanner(
672 "AA:BB:CC:DD:EE:06",
673 "hci6",
674 requested_mode=BluetoothScanningMode.PASSIVE,
675 )
676 )
677 assert caplog.text.count(_PASSIVE_WARNING) == 1
678 cancel_scanner2()
679 finally:
680 cancel_scan()
681
682
683 @pytest.mark.asyncio
684 async def test_async_register_scanner_with_connection_slots() -> None:
685 """Test registering a scanner with connection slots."""
686 manager = get_manager()
687 assert manager._loop is not None
688
689 scanners = manager.async_current_scanners()
690 assert len(scanners) == 0
691
692 hci3_scanner = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
693 hci3_scanner.connectable = True
694 manager = get_manager()
695 cancel = manager.async_register_scanner(hci3_scanner, connection_slots=5)
696 assert manager.async_current_allocations(hci3_scanner.source) == [
697 HaBluetoothSlotAllocations(hci3_scanner.source, 5, 5, [])
698 ]
699
700 cancel()
701
702
703 @pytest.mark.asyncio
704 async def test_async_register_connectable_scanner_seeds_allocations() -> None:
705 """Registering a connectable scanner seeds a zeroed allocations entry."""
706 manager = get_manager()
707 hci3_scanner = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
708 hci3_scanner.connectable = True
709 cancel = manager.async_register_scanner(hci3_scanner)
710 assert manager.async_current_allocations(hci3_scanner.source) == [
711 HaBluetoothSlotAllocations(hci3_scanner.source, 0, 0, [])
712 ]
713 cancel()
714
715
716 @pytest.mark.asyncio
717 async def test_async_register_scanner_preserves_pre_registration_allocations() -> None:
718 """An allocation push that arrives before registration is preserved."""
719 manager = get_manager()
720 hci3_scanner = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
721 hci3_scanner.connectable = True
722 manager.async_on_allocation_changed(
723 Allocations("AA:BB:CC:DD:EE:33", 3, 2, ["44:44:33:11:23:12"])
724 )
725 cancel = manager.async_register_scanner(hci3_scanner)
726 assert manager.async_current_allocations(hci3_scanner.source) == [
727 HaBluetoothSlotAllocations("AA:BB:CC:DD:EE:33", 3, 2, ["44:44:33:11:23:12"])
728 ]
729 cancel()
730
731
732 @pytest.mark.asyncio
733 async def test_async_reregister_scanner_reseeds_zeroed_allocations(
734 caplog: pytest.LogCaptureFixture,
735 ) -> None:
736 """A register, unregister, re-register round-trip clears stale allocations."""
737 manager = get_manager()
738 hci3_scanner = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
739 hci3_scanner.connectable = True
740 cancel = manager.async_register_scanner(hci3_scanner)
741 manager.async_on_allocation_changed(
742 Allocations("AA:BB:CC:DD:EE:33", 3, 2, ["44:44:33:11:23:12"])
743 )
744 cancel()
745 assert manager.async_current_allocations(hci3_scanner.source) == []
746 # A reconnecting proxy re-registers under the same source and must
747 # start from a clean slate rather than the previous session's list;
748 # since the previous registration was cancelled first this is not a
749 # duplicate and must not log the duplicate source error.
750 with caplog.at_level(logging.ERROR):
751 cancel = manager.async_register_scanner(hci3_scanner)
752 assert "already registered" not in caplog.text
753 assert manager.async_current_allocations(hci3_scanner.source) == [
754 HaBluetoothSlotAllocations(hci3_scanner.source, 0, 0, [])
755 ]
756 cancel()
757
758
759 @pytest.mark.asyncio
760 async def test_async_unregister_duplicate_source_completes_teardown(
761 caplog: pytest.LogCaptureFixture,
762 ) -> None:
763 """
764 Registering a duplicate source is a caller bug and is logged loudly.
765
766 Unregistering the second of two scanners sharing a source must still
767 not abort: the first unregister already cleared the shared allocations
768 entry, so the second must run the rest of the teardown, including the
769 REMOVED registration event, rather than raising midway.
770 """
771 manager = get_manager()
772 scanner_a = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
773 scanner_a.connectable = True
774 scanner_b = FakeScanner("AA:BB:CC:DD:EE:33", "hci4")
775 scanner_b.connectable = True
776 with caplog.at_level(logging.ERROR):
777 cancel_a = manager.async_register_scanner(scanner_a)
778 assert "already registered" not in caplog.text
779 cancel_b = manager.async_register_scanner(scanner_b)
780 assert "already registered by scanner hci3" in caplog.text
781 events: list[HaScannerRegistration] = []
782 cancel_callback = manager.async_register_scanner_registration_callback(
783 events.append, None
784 )
785 cancel_a()
786 cancel_b()
787 assert [event.event for event in events] == [
788 HaScannerRegistrationEvent.REMOVED,
789 HaScannerRegistrationEvent.REMOVED,
790 ]
791 assert manager.async_current_allocations(scanner_a.source) == []
792 cancel_callback()
793
794
795 @pytest.mark.asyncio
796 async def test_async_unregister_scanner_notifies_zeroed_allocations() -> None:
797 """Unregistering a scanner notifies subscribers with zeroed allocations."""
798 manager = get_manager()
799 hci3_scanner = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
800 hci3_scanner.connectable = True
801 cancel = manager.async_register_scanner(hci3_scanner)
802 manager.async_on_allocation_changed(
803 Allocations("AA:BB:CC:DD:EE:33", 3, 2, ["44:44:33:11:23:12"])
804 )
805 allocations: list[HaBluetoothSlotAllocations] = []
806 cancel_callback = manager.async_register_allocation_callback(
807 allocations.append, hci3_scanner.source
808 )
809 # Home Assistant's websocket subscribes globally (source=None) by
810 # default; it must receive the zeroed payload as well.
811 global_allocations: list[HaBluetoothSlotAllocations] = []
812 cancel_global_callback = manager.async_register_allocation_callback(
813 global_allocations.append
814 )
815 cancel()
816 zeroed = HaBluetoothSlotAllocations(hci3_scanner.source, 0, 0, [])
817 assert allocations == [zeroed]
818 assert global_allocations == [zeroed]
819 assert manager.async_current_allocations(hci3_scanner.source) == []
820 cancel_callback()
821 cancel_global_callback()
822
823
824 @pytest.mark.asyncio
825 async def test_async_unregister_scanner_is_idempotent(
826 caplog: pytest.LogCaptureFixture,
827 ) -> None:
828 """Double-invoking the cancel callback must not raise."""
829 manager = get_manager()
830 hci3_scanner = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
831 hci3_scanner.connectable = True
832 cancel = manager.async_register_scanner(hci3_scanner, connection_slots=5)
833
834 cancel()
835 assert hci3_scanner not in manager.async_current_scanners()
836
837 with caplog.at_level("DEBUG", logger="habluetooth.manager"):
838 cancel()
839
840 assert any("already unregistered" in record.message for record in caplog.records)
841
842
843 @pytest.mark.asyncio
844 @pytest.mark.usefixtures("enable_bluetooth")
845 async def test_diagnostics(register_hci0_scanner: None) -> None:
846 """Test bluetooth diagnostics."""
847 manager = get_manager()
848 assert manager._loop is not None
849 manager.async_on_allocation_changed(
850 Allocations(
851 "AA:BB:CC:DD:EE:00",
852 5,
853 4,
854 ["44:44:33:11:23:12"],
855 )
856 )
857 diagnostics = await manager.async_diagnostics()
858 assert diagnostics == {
859 "adapters": {},
860 "advertisement_tracker": ANY,
861 "all_history": ANY,
862 "allocations": {
863 "AA:BB:CC:DD:EE:00": {
864 "allocated": ["44:44:33:11:23:12"],
865 "free": 4,
866 "slots": 5,
867 "source": "AA:BB:CC:DD:EE:00",
868 }
869 },
870 "auto_scheduler": ANY,
871 "connectable_history": ANY,
872 "scanners": [
873 {
874 "connect_failures": {},
875 "connect_in_progress": {},
876 "connect_completed_total": 0,
877 "connect_failed_total": 0,
878 "last_connect_completed_time": 0.0,
879 "discovered_devices_and_advertisement_data": [],
880 "connectable": True,
881 "current_mode": None,
882 "requested_mode": None,
883 "last_detection": 0.0,
884 "monotonic_time": ANY,
885 "name": "hci0 (AA:BB:CC:DD:EE:00)",
886 "scanning": True,
887 "source": "AA:BB:CC:DD:EE:00",
888 "start_time": 0.0,
889 "type": "FakeScanner",
890 }
891 ],
892 "slot_manager": {
893 "adapter_slots": {"hci0": 5},
894 "allocations_by_adapter": {"hci0": []},
895 "manager": False,
896 },
897 }
898
899
900 @pytest.mark.usefixtures("enable_bluetooth")
901 @pytest.mark.asyncio
902 async def test_advertisements_do_not_switch_adapters_for_no_reason(
903 register_hci0_scanner: None,
904 register_hci1_scanner: None,
905 ) -> None:
906 """Test we only switch adapters when needed."""
907 address = "44:44:33:11:23:12"
908
909 switchbot_device_signal_100 = generate_ble_device(
910 address, "wohand_signal_100", rssi=-100
911 )
912 switchbot_adv_signal_100 = generate_advertisement_data(
913 local_name="wohand_signal_100", service_uuids=[]
914 )
915 inject_advertisement_with_source(
916 switchbot_device_signal_100, switchbot_adv_signal_100, HCI0_SOURCE_ADDRESS
917 )
918
919 assert (
920 get_manager().async_ble_device_from_address(address, True)
921 is switchbot_device_signal_100
922 )
923
924 switchbot_device_signal_99 = generate_ble_device(
925 address, "wohand_signal_99", rssi=-99
926 )
927 switchbot_adv_signal_99 = generate_advertisement_data(
928 local_name="wohand_signal_99", service_uuids=[]
929 )
930 inject_advertisement_with_source(
931 switchbot_device_signal_99, switchbot_adv_signal_99, HCI0_SOURCE_ADDRESS
932 )
933
934 assert (
935 get_manager().async_ble_device_from_address(address, True)
936 is switchbot_device_signal_99
937 )
938
939 switchbot_device_signal_98 = generate_ble_device(
940 address, "wohand_good_signal", rssi=-98
941 )
942 switchbot_adv_signal_98 = generate_advertisement_data(
943 local_name="wohand_good_signal", service_uuids=[]
944 )
945 inject_advertisement_with_source(
946 switchbot_device_signal_98, switchbot_adv_signal_98, HCI1_SOURCE_ADDRESS
947 )
948
949 # should not switch to hci1
950 assert (
951 get_manager().async_ble_device_from_address(address, True)
952 is switchbot_device_signal_99
953 )
954
955
956 @pytest.mark.usefixtures("enable_bluetooth")
957 @pytest.mark.asyncio
958 async def test_switching_adapters_based_on_rssi(
959 register_hci0_scanner: None,
960 register_hci1_scanner: None,
961 ) -> None:
962 """Test switching adapters based on rssi."""
963 address = "44:44:33:11:23:45"
964
965 switchbot_device_poor_signal = generate_ble_device(address, "wohand_poor_signal")
966 switchbot_adv_poor_signal = generate_advertisement_data(
967 local_name="wohand_poor_signal", service_uuids=[], rssi=-100
968 )
969 inject_advertisement_with_source(
970 switchbot_device_poor_signal,
971 switchbot_adv_poor_signal,
972 HCI0_SOURCE_ADDRESS,
973 )
974
975 assert (
976 get_manager().async_ble_device_from_address(address, True)
977 is switchbot_device_poor_signal
978 )
979
980 switchbot_device_good_signal = generate_ble_device(address, "wohand_good_signal")
981 switchbot_adv_good_signal = generate_advertisement_data(
982 local_name="wohand_good_signal", service_uuids=[], rssi=-60
983 )
984 inject_advertisement_with_source(
985 switchbot_device_good_signal,
986 switchbot_adv_good_signal,
987 HCI1_SOURCE_ADDRESS,
988 )
989
990 assert (
991 get_manager().async_ble_device_from_address(address, True)
992 is switchbot_device_good_signal
993 )
994
995 inject_advertisement_with_source(
996 switchbot_device_good_signal,
997 switchbot_adv_poor_signal,
998 HCI0_SOURCE_ADDRESS,
999 )
1000 assert (
1001 get_manager().async_ble_device_from_address(address, True)
1002 is switchbot_device_good_signal
1003 )
1004
1005 # We should not switch adapters unless the signal hits the threshold
1006 switchbot_device_similar_signal = generate_ble_device(
1007 address, "wohand_similar_signal"
1008 )
1009 switchbot_adv_similar_signal = generate_advertisement_data(
1010 local_name="wohand_similar_signal", service_uuids=[], rssi=-62
1011 )
1012
1013 inject_advertisement_with_source(
1014 switchbot_device_similar_signal,
1015 switchbot_adv_similar_signal,
1016 HCI0_SOURCE_ADDRESS,
1017 )
1018 assert (
1019 get_manager().async_ble_device_from_address(address, True)
1020 is switchbot_device_good_signal
1021 )
1022
1023
1024 @pytest.mark.usefixtures("enable_bluetooth")
1025 @pytest.mark.asyncio
1026 async def test_switching_adapters_based_on_zero_rssi(
1027 register_hci0_scanner: None,
1028 register_hci1_scanner: None,
1029 ) -> None:
1030 """Test switching adapters based on zero rssi."""
1031 address = "44:44:33:11:23:45"
1032
1033 switchbot_device_no_rssi = generate_ble_device(address, "wohand_poor_signal")
1034 switchbot_adv_no_rssi = generate_advertisement_data(
1035 local_name="wohand_no_rssi", service_uuids=[], rssi=0
1036 )
1037 inject_advertisement_with_source(
1038 switchbot_device_no_rssi, switchbot_adv_no_rssi, HCI0_SOURCE_ADDRESS
1039 )
1040
1041 assert (
1042 get_manager().async_ble_device_from_address(address, True)
1043 is switchbot_device_no_rssi
1044 )
1045
1046 switchbot_device_good_signal = generate_ble_device(address, "wohand_good_signal")
1047 switchbot_adv_good_signal = generate_advertisement_data(
1048 local_name="wohand_good_signal", service_uuids=[], rssi=-60
1049 )
1050 inject_advertisement_with_source(
1051 switchbot_device_good_signal,
1052 switchbot_adv_good_signal,
1053 HCI1_SOURCE_ADDRESS,
1054 )
1055
1056 assert (
1057 get_manager().async_ble_device_from_address(address, True)
1058 is switchbot_device_good_signal
1059 )
1060
1061 inject_advertisement_with_source(
1062 switchbot_device_good_signal, switchbot_adv_no_rssi, HCI0_SOURCE_ADDRESS
1063 )
1064 assert (
1065 get_manager().async_ble_device_from_address(address, True)
1066 is switchbot_device_good_signal
1067 )
1068
1069 # We should not switch adapters unless the signal hits the threshold
1070 switchbot_device_similar_signal = generate_ble_device(
1071 address, "wohand_similar_signal"
1072 )
1073 switchbot_adv_similar_signal = generate_advertisement_data(
1074 local_name="wohand_similar_signal", service_uuids=[], rssi=-62
1075 )
1076
1077 inject_advertisement_with_source(
1078 switchbot_device_similar_signal,
1079 switchbot_adv_similar_signal,
1080 HCI0_SOURCE_ADDRESS,
1081 )
1082 assert (
1083 get_manager().async_ble_device_from_address(address, True)
1084 is switchbot_device_good_signal
1085 )
1086
1087
1088 @pytest.mark.usefixtures("enable_bluetooth")
1089 @pytest.mark.asyncio
1090 async def test_switching_adapters_based_on_stale(
1091 register_hci0_scanner: None,
1092 register_hci1_scanner: None,
1093 ) -> None:
1094 """Test switching adapters based on the previous advertisement being stale."""
1095 address = "44:44:33:11:23:41"
1096 start_time_monotonic = 50.0
1097
1098 switchbot_device_poor_signal_hci0 = generate_ble_device(
1099 address, "wohand_poor_signal_hci0"
1100 )
1101 switchbot_adv_poor_signal_hci0 = generate_advertisement_data(
1102 local_name="wohand_poor_signal_hci0", service_uuids=[], rssi=-100
1103 )
1104 inject_advertisement_with_time_and_source(
1105 switchbot_device_poor_signal_hci0,
1106 switchbot_adv_poor_signal_hci0,
1107 start_time_monotonic,
1108 HCI0_SOURCE_ADDRESS,
1109 )
1110
1111 assert (
1112 get_manager().async_ble_device_from_address(address, True)
1113 is switchbot_device_poor_signal_hci0
1114 )
1115
1116 switchbot_device_poor_signal_hci1 = generate_ble_device(
1117 address, "wohand_poor_signal_hci1"
1118 )
1119 switchbot_adv_poor_signal_hci1 = generate_advertisement_data(
1120 local_name="wohand_poor_signal_hci1", service_uuids=[], rssi=-99
1121 )
1122 inject_advertisement_with_time_and_source(
1123 switchbot_device_poor_signal_hci1,
1124 switchbot_adv_poor_signal_hci1,
1125 start_time_monotonic,
1126 HCI1_SOURCE_ADDRESS,
1127 )
1128
1129 # Should not switch adapters until the advertisement is stale
1130 assert (
1131 get_manager().async_ble_device_from_address(address, True)
1132 is switchbot_device_poor_signal_hci0
1133 )
1134
1135 # Should switch to hci1 since the previous advertisement is stale
1136 # even though the signal is poor because the device is now
1137 # likely unreachable via hci0
1138 inject_advertisement_with_time_and_source(
1139 switchbot_device_poor_signal_hci1,
1140 switchbot_adv_poor_signal_hci1,
1141 start_time_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1,
1142 "hci1",
1143 )
1144
1145 assert (
1146 get_manager().async_ble_device_from_address(address, True)
1147 is switchbot_device_poor_signal_hci1
1148 )
1149
1150
1151 @pytest.mark.usefixtures("enable_bluetooth")
1152 @pytest.mark.asyncio
1153 async def test_switching_adapters_based_on_stale_with_discovered_interval(
1154 register_hci0_scanner: None,
1155 register_hci1_scanner: None,
1156 ) -> None:
1157 """Test switching with discovered interval."""
1158 address = "44:44:33:11:23:41"
1159 start_time_monotonic = 50.0
1160
1161 switchbot_device_poor_signal_hci0 = generate_ble_device(
1162 address, "wohand_poor_signal_hci0"
1163 )
1164 switchbot_adv_poor_signal_hci0 = generate_advertisement_data(
1165 local_name="wohand_poor_signal_hci0", service_uuids=[], rssi=-100
1166 )
1167 inject_advertisement_with_time_and_source(
1168 switchbot_device_poor_signal_hci0,
1169 switchbot_adv_poor_signal_hci0,
1170 start_time_monotonic,
1171 HCI0_SOURCE_ADDRESS,
1172 )
1173
1174 assert (
1175 get_manager().async_ble_device_from_address(address, True)
1176 is switchbot_device_poor_signal_hci0
1177 )
1178
1179 get_manager().async_set_fallback_availability_interval(address, 10)
1180
1181 switchbot_device_poor_signal_hci1 = generate_ble_device(
1182 address, "wohand_poor_signal_hci1"
1183 )
1184 switchbot_adv_poor_signal_hci1 = generate_advertisement_data(
1185 local_name="wohand_poor_signal_hci1", service_uuids=[], rssi=-99
1186 )
1187 inject_advertisement_with_time_and_source(
1188 switchbot_device_poor_signal_hci1,
1189 switchbot_adv_poor_signal_hci1,
1190 start_time_monotonic,
1191 HCI1_SOURCE_ADDRESS,
1192 )
1193
1194 # Should not switch adapters until the advertisement is stale
1195 assert (
1196 get_manager().async_ble_device_from_address(address, True)
1197 is switchbot_device_poor_signal_hci0
1198 )
1199
1200 inject_advertisement_with_time_and_source(
1201 switchbot_device_poor_signal_hci1,
1202 switchbot_adv_poor_signal_hci1,
1203 start_time_monotonic + 10 + 1,
1204 HCI1_SOURCE_ADDRESS,
1205 )
1206
1207 # Should not switch yet since we are not within the
1208 # wobble period
1209 assert (
1210 get_manager().async_ble_device_from_address(address, True)
1211 is switchbot_device_poor_signal_hci0
1212 )
1213
1214 inject_advertisement_with_time_and_source(
1215 switchbot_device_poor_signal_hci1,
1216 switchbot_adv_poor_signal_hci1,
1217 start_time_monotonic + 10 + TRACKER_BUFFERING_WOBBLE_SECONDS + 1,
1218 HCI1_SOURCE_ADDRESS,
1219 )
1220 # One missed interval is a per-scanner reception lottery: still hci0.
1221 assert (
1222 get_manager().async_ble_device_from_address(address, True)
1223 is switchbot_device_poor_signal_hci0
1224 )
1225 inject_advertisement_with_time_and_source(
1226 switchbot_device_poor_signal_hci1,
1227 switchbot_adv_poor_signal_hci1,
1228 start_time_monotonic + 23,
1229 HCI1_SOURCE_ADDRESS,
1230 )
1231 # Past the roam gate (1.5 stale windows): switch to hci1 since the
1232 # previous advertisement is stale even though the signal is poor
1233 # because the device is now likely unreachable via hci0
1234 assert (
1235 get_manager().async_ble_device_from_address(address, True)
1236 is switchbot_device_poor_signal_hci1
1237 )
1238
1239
1240 @pytest.mark.usefixtures("enable_bluetooth")
1241 @pytest.mark.asyncio
1242 async def test_stale_does_not_switch_to_much_weaker_scanner(
1243 register_hci0_scanner: None,
1244 register_hci1_scanner: None,
1245 ) -> None:
1246 """
1247 A far weaker scanner must not steal a strong owner on a single stale interval.
1248
1249 Regression for #568: scan-response-only sensors behind many active proxies
1250 oscillated because a weaker proxy holding a stale capture won the receive-time
1251 staleness check on a single missed interval. This device has a registered
1252 active-scan need, so the rescue flow governs; a materially weaker passive
1253 challenger instead waits for durably-gone (see
1254 test_stale_passive_weaker_scanner_waits_for_durably_gone).
1255 """
1256 address = "44:44:33:11:23:42"
1257 start = 50.0
1258 cancel_active = get_manager().async_register_active_scan(address)
1259 strong = generate_ble_device(address, "strong_hci0")
1260 strong_adv = generate_advertisement_data(
1261 local_name="strong_hci0", service_uuids=[], rssi=-46
1262 )
1263 inject_advertisement_with_time_and_source(
1264 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1265 )
1266 get_manager().async_set_fallback_availability_interval(address, 10) # stale=15
1267
1268 weak = generate_ble_device(address, "weak_hci1")
1269 weak_adv = generate_advertisement_data(
1270 local_name="weak_hci1", service_uuids=[], rssi=-90
1271 )
1272 # Just past the normal stale window: a 44 dB weaker scanner must NOT win.
1273 inject_advertisement_with_time_and_source(
1274 weak,
1275 weak_adv,
1276 start + 10 + TRACKER_BUFFERING_WOBBLE_SECONDS + 1,
1277 HCI1_SOURCE_ADDRESS,
1278 )
1279 assert get_manager().async_ble_device_from_address(address, True) is strong
1280 cancel_active()
1281
1282
1283 @pytest.mark.usefixtures("enable_bluetooth")
1284 @pytest.mark.asyncio
1285 async def test_stale_switches_to_weaker_scanner_once_durably_gone(
1286 register_hci0_scanner: None,
1287 register_hci1_scanner: None,
1288 ) -> None:
1289 """
1290 A device that moved into weak-only coverage still hands off after a longer wait.
1291
1292 The device needs active scans, so the weaker scanner is held off on a single
1293 stale interval but takes over once the owner has been silent for
1294 stale_seconds * DURABLY_GONE_STALE_FACTOR.
1295 """
1296 address = "44:44:33:11:23:43"
1297 start = 50.0
1298 cancel_active = get_manager().async_register_active_scan(address)
1299 strong = generate_ble_device(address, "strong_hci0")
1300 strong_adv = generate_advertisement_data(
1301 local_name="strong_hci0", service_uuids=[], rssi=-46
1302 )
1303 inject_advertisement_with_time_and_source(
1304 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1305 )
1306 # stale_seconds = 15, durably-gone = 15 * 2.5 = 37.5
1307 get_manager().async_set_fallback_availability_interval(address, 10)
1308
1309 weak = generate_ble_device(address, "weak_hci1")
1310 weak_adv = generate_advertisement_data(
1311 local_name="weak_hci1", service_uuids=[], rssi=-90
1312 )
1313 # Within the durably-gone window: still the strong owner.
1314 inject_advertisement_with_time_and_source(
1315 weak, weak_adv, start + 30, HCI1_SOURCE_ADDRESS
1316 )
1317 assert get_manager().async_ble_device_from_address(address, True) is strong
1318 # Past the durably-gone window: the weak scanner finally takes over.
1319 inject_advertisement_with_time_and_source(
1320 weak, weak_adv, start + 40, HCI1_SOURCE_ADDRESS
1321 )
1322 assert get_manager().async_ble_device_from_address(address, True) is weak
1323 cancel_active()
1324
1325
1326 @pytest.mark.usefixtures("enable_bluetooth")
1327 @pytest.mark.asyncio
1328 @pytest.mark.parametrize("debug", [True, False])
1329 async def test_stale_switches_to_comparable_scanner_at_normal_window(
1330 register_hci0_scanner: None,
1331 register_hci1_scanner: None,
1332 debug: bool,
1333 ) -> None:
1334 """
1335 A comparable scanner takes over a weak passive owner after the roam gate.
1336
1337 The owner is weak (below STRONG_OWNER_STALE_RSSI), so its silence is
1338 treated as the device possibly being gone, but a single missed
1339 interval is a per-scanner reception lottery; the comparable scanner
1340 may only take over once STALE_ROAM_FACTOR stale windows elapsed. A
1341 strong owner is protected regardless (see
1342 test_stale_keeps_strong_owner_against_comparable_scanner). Runs with
1343 debug logging both on and off to cover the log branches.
1344 """
1345 address = "44:44:33:11:23:44"
1346 start = 50.0
1347 get_manager()._debug = debug
1348 owner = generate_ble_device(address, "owner_hci0")
1349 owner_adv = generate_advertisement_data(
1350 local_name="owner_hci0", service_uuids=[], rssi=-90
1351 )
1352 inject_advertisement_with_time_and_source(
1353 owner, owner_adv, start, HCI0_SOURCE_ADDRESS
1354 )
1355 get_manager().async_set_fallback_availability_interval(address, 10)
1356
1357 # Weak owner, comparable challenger: kept on a single missed interval
1358 # (a per-scanner reception miss must not roam a stationary device).
1359 comparable = generate_ble_device(address, "comparable_hci1")
1360 comparable_adv = generate_advertisement_data(
1361 local_name="comparable_hci1", service_uuids=[], rssi=-95
1362 )
1363 inject_advertisement_with_time_and_source(
1364 comparable,
1365 comparable_adv,
1366 start + 10 + TRACKER_BUFFERING_WOBBLE_SECONDS + 1,
1367 HCI1_SOURCE_ADDRESS,
1368 )
1369 assert get_manager().async_ble_device_from_address(address, True) is owner
1370 # Past STALE_ROAM_FACTOR stale windows (1.5 * 15 = 22.5): the ordinary
1371 # roaming handoff proceeds.
1372 inject_advertisement_with_time_and_source(
1373 comparable, comparable_adv, start + 23, HCI1_SOURCE_ADDRESS
1374 )
1375 assert get_manager().async_ble_device_from_address(address, True) is comparable
1376
1377
1378 @pytest.mark.usefixtures("enable_bluetooth")
1379 @pytest.mark.asyncio
1380 async def test_stale_keeps_strong_owner_against_comparable_scanner(
1381 register_hci0_scanner: None,
1382 register_hci1_scanner: None,
1383 ) -> None:
1384 """
1385 A strong/close owner is not stolen by a comparable scanner on a stale interval.
1386
1387 Regression for the stationary-device flap: a strong owner (>=
1388 STRONG_OWNER_STALE_RSSI) that briefly goes quiet is almost certainly
1389 still there, so for a device that needs active scans a merely-comparable
1390 scanner must wait for durable absence (or a completed rescue window)
1391 rather than steal on one missed interval.
1392 """
1393 address = "44:44:33:11:23:47"
1394 start = 50.0
1395 cancel_active = get_manager().async_register_active_scan(address)
1396 strong = generate_ble_device(address, "strong_hci0")
1397 strong_adv = generate_advertisement_data(
1398 local_name="strong_hci0", service_uuids=[], rssi=-50
1399 )
1400 inject_advertisement_with_time_and_source(
1401 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1402 )
1403 get_manager().async_set_fallback_availability_interval(address, 10) # stale=15
1404
1405 comparable = generate_ble_device(address, "comparable_hci1")
1406 comparable_adv = generate_advertisement_data(
1407 local_name="comparable_hci1", service_uuids=[], rssi=-60
1408 )
1409 # Just past the normal stale window: a comparable scanner must NOT steal
1410 # the strong owner.
1411 inject_advertisement_with_time_and_source(
1412 comparable,
1413 comparable_adv,
1414 start + 10 + TRACKER_BUFFERING_WOBBLE_SECONDS + 1,
1415 HCI1_SOURCE_ADDRESS,
1416 )
1417 assert get_manager().async_ble_device_from_address(address, True) is strong
1418 cancel_active()
1419
1420
1421 @pytest.mark.usefixtures("enable_bluetooth")
1422 @pytest.mark.asyncio
1423 async def test_stale_strong_owner_yields_to_comparable_when_durably_gone(
1424 register_hci0_scanner: None,
1425 register_hci1_scanner: None,
1426 ) -> None:
1427 """A strong owner that is durably silent still hands off to a comparable scanner."""
1428 address = "44:44:33:11:23:48"
1429 start = 50.0
1430 cancel_active = get_manager().async_register_active_scan(address)
1431 strong = generate_ble_device(address, "strong_hci0")
1432 strong_adv = generate_advertisement_data(
1433 local_name="strong_hci0", service_uuids=[], rssi=-50
1434 )
1435 inject_advertisement_with_time_and_source(
1436 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1437 )
1438 # stale_seconds = 15, durably-gone = 15 * 2.5 = 37.5
1439 get_manager().async_set_fallback_availability_interval(address, 10)
1440
1441 comparable = generate_ble_device(address, "comparable_hci1")
1442 comparable_adv = generate_advertisement_data(
1443 local_name="comparable_hci1", service_uuids=[], rssi=-60
1444 )
1445 # Within the durably-gone window: strong owner kept.
1446 inject_advertisement_with_time_and_source(
1447 comparable, comparable_adv, start + 30, HCI1_SOURCE_ADDRESS
1448 )
1449 assert get_manager().async_ble_device_from_address(address, True) is strong
1450 # Past durably-gone: the comparable scanner finally takes over.
1451 inject_advertisement_with_time_and_source(
1452 comparable, comparable_adv, start + 40, HCI1_SOURCE_ADDRESS
1453 )
1454 assert get_manager().async_ble_device_from_address(address, True) is comparable
1455 cancel_active()
1456
1457
1458 @pytest.mark.usefixtures("enable_bluetooth")
1459 @pytest.mark.asyncio
1460 async def test_stale_strong_owner_yields_to_stronger_scanner(
1461 register_hci0_scanner: None,
1462 register_hci1_scanner: None,
1463 ) -> None:
1464 """A strong owner still yields immediately to a materially stronger scanner."""
1465 address = "44:44:33:11:23:49"
1466 start = 50.0
1467 strong = generate_ble_device(address, "strong_hci0")
1468 strong_adv = generate_advertisement_data(
1469 local_name="strong_hci0", service_uuids=[], rssi=-50
1470 )
1471 inject_advertisement_with_time_and_source(
1472 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1473 )
1474 get_manager().async_set_fallback_availability_interval(address, 10)
1475
1476 # >16 dB stronger: the RSSI path takes over immediately, strong owner or not.
1477 stronger = generate_ble_device(address, "stronger_hci1")
1478 stronger_adv = generate_advertisement_data(
1479 local_name="stronger_hci1", service_uuids=[], rssi=-20
1480 )
1481 inject_advertisement_with_time_and_source(
1482 stronger,
1483 stronger_adv,
1484 start + 10 + TRACKER_BUFFERING_WOBBLE_SECONDS + 1,
1485 HCI1_SOURCE_ADDRESS,
1486 )
1487 assert get_manager().async_ble_device_from_address(address, True) is stronger
1488
1489
1490 @pytest.mark.usefixtures("enable_bluetooth")
1491 @pytest.mark.asyncio
1492 async def test_stale_passive_weaker_scanner_waits_for_durably_gone(
1493 register_hci0_scanner: None,
1494 register_hci1_scanner: None,
1495 ) -> None:
1496 """
1497 A far weaker challenger cannot steal a passive device on one missed interval.
1498
1499 A hair-past-stale capture by a materially weaker scanner would flap
1500 ownership right back on the owner's next advertisement, so it waits
1501 for the durably-gone handoff instead.
1502 """
1503 address = "44:44:33:11:23:60"
1504 start = 50.0
1505 # Exercise the non-debug switch path; the sibling passive test runs
1506 # with the test-default debug logging on.
1507 get_manager()._debug = False
1508 strong = generate_ble_device(address, "strong_hci0")
1509 strong_adv = generate_advertisement_data(
1510 local_name="strong_hci0", service_uuids=[], rssi=-46
1511 )
1512 inject_advertisement_with_time_and_source(
1513 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1514 )
1515 # stale_seconds = 15, durably-gone = 37.5
1516 get_manager().async_set_fallback_availability_interval(address, 10)
1517
1518 weak = generate_ble_device(address, "weak_hci1")
1519 weak_adv = generate_advertisement_data(
1520 local_name="weak_hci1", service_uuids=[], rssi=-90
1521 )
1522 # Just past the normal stale window: the far weaker scanner must NOT
1523 # steal ownership on a single missed interval.
1524 inject_advertisement_with_time_and_source(
1525 weak,
1526 weak_adv,
1527 start + 10 + TRACKER_BUFFERING_WOBBLE_SECONDS + 1,
1528 HCI1_SOURCE_ADDRESS,
1529 )
1530 assert get_manager().async_ble_device_from_address(address, True) is strong
1531 # Past durably-gone: the weak scanner finally takes over.
1532 inject_advertisement_with_time_and_source(
1533 weak, weak_adv, start + 40, HCI1_SOURCE_ADDRESS
1534 )
1535 assert get_manager().async_ble_device_from_address(address, True) is weak
1536
1537
1538 @pytest.mark.usefixtures("enable_bluetooth")
1539 @pytest.mark.asyncio
1540 async def test_stale_passive_strong_owner_keeps_comparable_until_durably_gone(
1541 register_hci0_scanner: None,
1542 register_hci1_scanner: None,
1543 ) -> None:
1544 """
1545 A comparable challenger cannot steal a passive strong owner on one miss.
1546
1547 A comparable pair cannot reclaim on the RSSI path, so a stale steal
1548 would ping-pong on alternating missed intervals (issue #580); the
1549 challenger waits for the durably-gone handoff instead.
1550 """
1551 address = "44:44:33:11:23:61"
1552 start = 50.0
1553 strong = generate_ble_device(address, "strong_hci0")
1554 strong_adv = generate_advertisement_data(
1555 local_name="strong_hci0", service_uuids=[], rssi=-50
1556 )
1557 inject_advertisement_with_time_and_source(
1558 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1559 )
1560 # stale_seconds = 15, durably-gone = 37.5
1561 get_manager().async_set_fallback_availability_interval(address, 10)
1562
1563 comparable = generate_ble_device(address, "comparable_hci1")
1564 comparable_adv = generate_advertisement_data(
1565 local_name="comparable_hci1", service_uuids=[], rssi=-60
1566 )
1567 inject_advertisement_with_time_and_source(
1568 comparable,
1569 comparable_adv,
1570 start + 10 + TRACKER_BUFFERING_WOBBLE_SECONDS + 1,
1571 HCI1_SOURCE_ADDRESS,
1572 )
1573 assert get_manager().async_ble_device_from_address(address, True) is strong
1574 # Past durably-gone: the comparable scanner takes over.
1575 inject_advertisement_with_time_and_source(
1576 comparable, comparable_adv, start + 40, HCI1_SOURCE_ADDRESS
1577 )
1578 assert get_manager().async_ble_device_from_address(address, True) is comparable
1579
1580
1581 @pytest.mark.usefixtures("enable_bluetooth")
1582 @pytest.mark.asyncio
1583 @pytest.mark.parametrize("debug", [True, False])
1584 async def test_stale_active_need_defers_then_switches_after_rescue_window(
1585 register_hci0_scanner: None,
1586 register_hci1_scanner: None,
1587 debug: bool,
1588 ) -> None:
1589 """
1590 An active-need device defers the stale handoff until a rescue window ran.
1591
1592 The first challenger advertisement past the stale window starts a rescue
1593 episode (ownership kept); once the rescue's accept time is recorded and
1594 the owner stays silent, the next challenger advertisement that postdates
1595 it takes ownership. Runs with debug logging both on and off to cover
1596 both sides of the logging branches.
1597 """
1598 manager = get_manager()
1599 manager._debug = debug
1600 address = "44:44:33:11:23:62"
1601 start = 50.0
1602 cancel_active = manager.async_register_active_scan(address)
1603 strong = generate_ble_device(address, "strong_hci0")
1604 strong_adv = generate_advertisement_data(
1605 local_name="strong_hci0", service_uuids=[], rssi=-50
1606 )
1607 inject_advertisement_with_time_and_source(
1608 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1609 )
1610 # stale_seconds = 15, durably-gone = 37.5
1611 manager.async_set_fallback_availability_interval(address, 10)
1612
1613 comparable = generate_ble_device(address, "comparable_hci1")
1614 comparable_adv = generate_advertisement_data(
1615 local_name="comparable_hci1", service_uuids=[], rssi=-60
1616 )
1617 # Past the stale window: deferred, episode started, owner kept.
1618 inject_advertisement_with_time_and_source(
1619 comparable, comparable_adv, start + 16, HCI1_SOURCE_ADDRESS
1620 )
1621 assert manager.async_ble_device_from_address(address, True) is strong
1622 assert manager._rescue_triggered[address] == start + 16
1623 # A rescue window covering the address completed while the owner
1624 # stayed silent (the fake scanners cannot run real windows, so the
1625 # completion is recorded directly).
1626 manager._auto_scheduler._rescue_accept_after[address] = start + 20
1627 # Still before the completion: owner kept.
1628 inject_advertisement_with_time_and_source(
1629 comparable, comparable_adv, start + 19, HCI1_SOURCE_ADDRESS
1630 )
1631 assert manager.async_ble_device_from_address(address, True) is strong
1632 # Past the accept time but within one advertising interval of the
1633 # trigger: still deferred (the owner gets a full re-hear cycle).
1634 inject_advertisement_with_time_and_source(
1635 comparable, comparable_adv, start + 25, HCI1_SOURCE_ADDRESS
1636 )
1637 assert manager.async_ble_device_from_address(address, True) is strong
1638 # Past the accept time and one full interval past the trigger: hand off.
1639 inject_advertisement_with_time_and_source(
1640 comparable, comparable_adv, start + 27, HCI1_SOURCE_ADDRESS
1641 )
1642 assert manager.async_ble_device_from_address(address, True) is comparable
1643 assert address not in manager._rescue_triggered
1644 cancel_active()
1645
1646
1647 @pytest.mark.usefixtures("enable_bluetooth")
1648 @pytest.mark.asyncio
1649 async def test_stale_active_need_no_roaming_shortcut_for_weak_owner(
1650 register_hci0_scanner: None,
1651 register_hci1_scanner: None,
1652 ) -> None:
1653 """
1654 An active-need device never takes the roaming shortcut.
1655
1656 A comparable challenger of a weak owner switches instantly for a
1657 passive device, but for an active-need device the challenger may not
1658 have actively scanned recently, so the handoff defers through the
1659 rescue and lands only past the accept time.
1660 """
1661 manager = get_manager()
1662 address = "44:44:33:11:23:77"
1663 start = 50.0
1664 cancel_active = manager.async_register_active_scan(address)
1665 weak_owner = generate_ble_device(address, "weak_owner_hci0")
1666 weak_owner_adv = generate_advertisement_data(
1667 local_name="weak_owner_hci0", service_uuids=[], rssi=-90
1668 )
1669 inject_advertisement_with_time_and_source(
1670 weak_owner, weak_owner_adv, start, HCI0_SOURCE_ADDRESS
1671 )
1672 # stale_seconds = 15, durably-gone = 37.5
1673 manager.async_set_fallback_availability_interval(address, 10)
1674
1675 comparable = generate_ble_device(address, "comparable_hci1")
1676 comparable_adv = generate_advertisement_data(
1677 local_name="comparable_hci1", service_uuids=[], rssi=-95
1678 )
1679 # Comparable challenger of a weak owner just past stale: deferred,
1680 # episode started (no instant roaming handoff).
1681 inject_advertisement_with_time_and_source(
1682 comparable, comparable_adv, start + 16, HCI1_SOURCE_ADDRESS
1683 )
1684 assert manager.async_ble_device_from_address(address, True) is weak_owner
1685 assert manager._rescue_triggered[address] == start + 16
1686 # A rescue window covered the address; the handoff needs the accept
1687 # time passed and one full advertising interval since the trigger.
1688 manager._auto_scheduler._rescue_accept_after[address] = start + 21
1689 inject_advertisement_with_time_and_source(
1690 comparable, comparable_adv, start + 27, HCI1_SOURCE_ADDRESS
1691 )
1692 assert manager.async_ble_device_from_address(address, True) is comparable
1693 assert address not in manager._rescue_triggered
1694 cancel_active()
1695
1696
1697 @pytest.mark.usefixtures("enable_bluetooth")
1698 @pytest.mark.asyncio
1699 async def test_stale_active_need_owner_reheard_invalidates_episode(
1700 register_hci0_scanner: None,
1701 register_hci1_scanner: None,
1702 ) -> None:
1703 """
1704 The owner being heard again invalidates a rescue episode.
1705
1706 A completion recorded for an old episode must not authorize an instant
1707 switch in a later stale episode; the owner re-hearing the device resets
1708 the state so the next episode starts fresh.
1709 """
1710 manager = get_manager()
1711 address = "44:44:33:11:23:63"
1712 start = 50.0
1713 cancel_active = manager.async_register_active_scan(address)
1714 strong = generate_ble_device(address, "strong_hci0")
1715 strong_adv = generate_advertisement_data(
1716 local_name="strong_hci0", service_uuids=[], rssi=-50
1717 )
1718 inject_advertisement_with_time_and_source(
1719 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1720 )
1721 manager.async_set_fallback_availability_interval(address, 10)
1722
1723 comparable = generate_ble_device(address, "comparable_hci1")
1724 comparable_adv = generate_advertisement_data(
1725 local_name="comparable_hci1", service_uuids=[], rssi=-60
1726 )
1727 # Episode starts.
1728 inject_advertisement_with_time_and_source(
1729 comparable, comparable_adv, start + 16, HCI1_SOURCE_ADDRESS
1730 )
1731 assert manager._rescue_triggered[address] == start + 16
1732 manager._auto_scheduler._rescue_accept_after[address] = start + 17
1733 # The owner re-hears the device: the episode is now moot.
1734 inject_advertisement_with_time_and_source(
1735 strong, strong_adv, start + 18, HCI0_SOURCE_ADDRESS
1736 )
1737 assert manager.async_ble_device_from_address(address, True) is strong
1738 # Next stale episode: the old completion (start + 17) predates the
1739 # owner's last adv, so this must start a new episode, not switch.
1740 inject_advertisement_with_time_and_source(
1741 comparable, comparable_adv, start + 35, HCI1_SOURCE_ADDRESS
1742 )
1743 assert manager.async_ble_device_from_address(address, True) is strong
1744 assert manager._rescue_triggered[address] == start + 35
1745 cancel_active()
1746
1747
1748 @pytest.mark.usefixtures("enable_bluetooth")
1749 @pytest.mark.asyncio
1750 async def test_stale_active_need_retriggers_when_window_never_ran(
1751 register_hci0_scanner: None,
1752 register_hci1_scanner: None,
1753 ) -> None:
1754 """A rescue that never produced a window is re-triggered after the retry wait."""
1755 manager = get_manager()
1756 address = "44:44:33:11:23:64"
1757 start = 50.0
1758 strong = generate_ble_device(address, "strong_hci0")
1759 strong_adv = generate_advertisement_data(
1760 local_name="strong_hci0", service_uuids=[], rssi=-50
1761 )
1762 inject_advertisement_with_time_and_source(
1763 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
1764 )
1765 # stale_seconds = 65, durably-gone = 162.5: room for the 30s retry.
1766 manager.async_set_fallback_availability_interval(address, 60)
1767
1768 comparable = generate_ble_device(address, "comparable_hci1")
1769 comparable_adv = generate_advertisement_data(
1770 local_name="comparable_hci1", service_uuids=[], rssi=-60
1771 )
1772 # A cdef class method cannot be patched in the compiled build, so
1773 # observe the trigger calls by swapping in a mock scheduler through
1774 # the writable _auto_scheduler slot. Only rejected challenger advs
1775 # flow while it is installed, so the winning-adv path that needs the
1776 # real scheduler is never hit.
1777 real_scheduler = manager._auto_scheduler
1778 mock_scheduler = Mock()
1779 mock_scheduler._requests_by_address = {address: {Mock()}}
1780 mock_scheduler._rescue_accept_after = {}
1781 manager._auto_scheduler = mock_scheduler
1782 try:
1783 # Episode starts: first trigger.
1784 inject_advertisement_with_time_and_source(
1785 comparable, comparable_adv, start + 70, HCI1_SOURCE_ADDRESS
1786 )
1787 assert mock_scheduler.trigger_rescue.call_count == 1
1788 # Within the retry wait: no second trigger.
1789 inject_advertisement_with_time_and_source(
1790 comparable, comparable_adv, start + 90, HCI1_SOURCE_ADDRESS
1791 )
1792 assert mock_scheduler.trigger_rescue.call_count == 1
1793 # Past the retry wait with no completion recorded: re-trigger.
1794 inject_advertisement_with_time_and_source(
1795 comparable, comparable_adv, start + 105, HCI1_SOURCE_ADDRESS
1796 )
1797 assert mock_scheduler.trigger_rescue.call_count == 2
1798 # The retry restarted the episode, so the next adv within the
1799 # retry wait does not re-trigger again.
1800 inject_advertisement_with_time_and_source(
1801 comparable, comparable_adv, start + 120, HCI1_SOURCE_ADDRESS
1802 )
1803 assert mock_scheduler.trigger_rescue.call_count == 2
1804 # And another full retry wait later it does.
1805 inject_advertisement_with_time_and_source(
1806 comparable, comparable_adv, start + 140, HCI1_SOURCE_ADDRESS
1807 )
1808 assert mock_scheduler.trigger_rescue.call_count == 3
1809 finally:
1810 manager._auto_scheduler = real_scheduler
1811 assert manager.async_ble_device_from_address(address, True) is strong
1812
1813
1814 @pytest.mark.usefixtures("enable_bluetooth")
1815 @pytest.mark.asyncio
1816 @pytest.mark.parametrize("debug", [True, False])
1817 async def test_stale_active_need_comparable_active_challenger_defers(
1818 register_hci0_scanner: None,
1819 debug: bool,
1820 ) -> None:
1821 """
1822 A comparable ACTIVE challenger of a strong owner defers with grace.
1823
1824 Its side of the rescue is covered immediately but the accept time
1825 keeps the standard grace, so the owner gets one re-hear window; only
1826 a challenger advertisement past the accept time takes ownership.
1827 Runs with debug logging both on and off to cover the log branches.
1828 """
1829 manager = get_manager()
1830 manager._debug = debug
1831 address = "44:44:33:11:23:67"
1832 cancel_active = manager.async_register_active_scan(address)
1833 active_scanner = FakeScanner(
1834 "AA:BB:CC:DD:EE:22",
1835 "hci2",
1836 requested_mode=BluetoothScanningMode.ACTIVE,
1837 )
1838 active_scanner.connectable = True
1839 cancel_scanner = manager.async_register_scanner(active_scanner, connection_slots=5)
1840 now = monotonic_time_coarse()
1841 strong = generate_ble_device(address, "strong_hci0")
1842 strong_adv = generate_advertisement_data(
1843 local_name="strong_hci0", service_uuids=[], rssi=-50
1844 )
1845 inject_advertisement_with_time_and_source(
1846 strong, strong_adv, now - 16, HCI0_SOURCE_ADDRESS
1847 )
1848 # stale_seconds = 15, durably-gone = 37.5
1849 manager.async_set_fallback_availability_interval(address, 10)
1850
1851 comparable = generate_ble_device(address, "comparable_hci2")
1852 comparable_adv = generate_advertisement_data(
1853 local_name="comparable_hci2", service_uuids=[], rssi=-60
1854 )
1855 # Just past the stale window: deferred, the challenger's side of the
1856 # rescue is covered with the accept grace.
1857 inject_advertisement_with_time_and_source(
1858 comparable, comparable_adv, now, "AA:BB:CC:DD:EE:22"
1859 )
1860 assert manager.async_ble_device_from_address(address, True) is strong
1861 assert manager._rescue_triggered[address] == now
1862 accept = manager._auto_scheduler._rescue_accept_after[address]
1863 assert accept >= now + RESCUE_SCAN_ACCEPT_SECONDS - 1
1864 # Within the grace window: still the owner.
1865 inject_advertisement_with_time_and_source(
1866 comparable, comparable_adv, now + 2, "AA:BB:CC:DD:EE:22"
1867 )
1868 assert manager.async_ble_device_from_address(address, True) is strong
1869 # Past the accept but within one advertising interval: still deferred.
1870 inject_advertisement_with_time_and_source(
1871 comparable, comparable_adv, accept + 1, "AA:BB:CC:DD:EE:22"
1872 )
1873 assert manager.async_ble_device_from_address(address, True) is strong
1874 # Past the accept and one full interval past the trigger: hand off.
1875 inject_advertisement_with_time_and_source(
1876 comparable, comparable_adv, max(accept + 1, now + 11), "AA:BB:CC:DD:EE:22"
1877 )
1878 assert manager.async_ble_device_from_address(address, True) is comparable
1879 assert address not in manager._rescue_triggered
1880 cancel_active()
1881 cancel_scanner()
1882
1883
1884 @pytest.mark.usefixtures("enable_bluetooth")
1885 @pytest.mark.asyncio
1886 async def test_stale_active_need_weaker_active_challenger_defers() -> None:
1887 """
1888 A materially weaker ACTIVE challenger defers instead of stealing.
1889
1890 Its side of the rescue counts as covered immediately, so it wins on
1891 its next advertisement only if the owner stays silent; the owner being
1892 heard again keeps the device where it is.
1893 """
1894 manager = get_manager()
1895 address = "44:44:33:11:23:75"
1896 cancel_active = manager.async_register_active_scan(address)
1897 owner_scanner = FakeScanner("AA:BB:CC:DD:EE:99", "hci9")
1898 owner_scanner.connectable = True
1899 active_scanner = FakeScanner(
1900 "AA:BB:CC:DD:EE:AA",
1901 "hci10",
1902 requested_mode=BluetoothScanningMode.ACTIVE,
1903 )
1904 active_scanner.connectable = True
1905 cancel_owner = manager.async_register_scanner(owner_scanner, connection_slots=5)
1906 cancel_challenger = manager.async_register_scanner(
1907 active_scanner, connection_slots=5
1908 )
1909 now = monotonic_time_coarse()
1910 strong = generate_ble_device(address, "strong_hci9")
1911 strong_adv = generate_advertisement_data(
1912 local_name="strong_hci9", service_uuids=[], rssi=-50
1913 )
1914 inject_advertisement_with_time_and_source(
1915 strong, strong_adv, now - 16, "AA:BB:CC:DD:EE:99"
1916 )
1917 # stale_seconds = 15, durably-gone = 37.5
1918 manager.async_set_fallback_availability_interval(address, 10)
1919
1920 weak = generate_ble_device(address, "weak_hci10")
1921 weak_adv = generate_advertisement_data(
1922 local_name="weak_hci10", service_uuids=[], rssi=-90
1923 )
1924 # Far weaker ACTIVE challenger just past the stale window: deferred,
1925 # its rescue side counts as covered with the accept grace.
1926 inject_advertisement_with_time_and_source(weak, weak_adv, now, "AA:BB:CC:DD:EE:AA")
1927 assert manager.async_ble_device_from_address(address, True) is strong
1928 assert manager._rescue_triggered[address] == now
1929 accept = manager._auto_scheduler._rescue_accept_after[address]
1930 assert accept >= now + RESCUE_SCAN_ACCEPT_SECONDS - 1
1931 # Within the grace window: still the owner.
1932 inject_advertisement_with_time_and_source(
1933 weak, weak_adv, now + 2, "AA:BB:CC:DD:EE:AA"
1934 )
1935 assert manager.async_ble_device_from_address(address, True) is strong
1936 # Past the accept and one full interval past the trigger: hand off.
1937 inject_advertisement_with_time_and_source(
1938 weak, weak_adv, max(accept + 1, now + 11), "AA:BB:CC:DD:EE:AA"
1939 )
1940 assert manager.async_ble_device_from_address(address, True) is weak
1941 assert address not in manager._rescue_triggered
1942 cancel_active()
1943 cancel_owner()
1944 cancel_challenger()
1945
1946
1947 @pytest.mark.usefixtures("enable_bluetooth")
1948 @pytest.mark.asyncio
1949 async def test_owner_paused_for_connection_hands_off_immediately(
1950 register_hci1_scanner: None,
1951 ) -> None:
1952 """
1953 An owner that paused scanning for a connection is not kept in arbitration.
1954
1955 The #590 hold was reverted (issue #591): pinning ownership to a deaf
1956 scanner rejected fresh challenger data while recording nothing. A
1957 scanner that pauses scanning to connect hands its devices to any
1958 challenger immediately; the stale damping and the rescue flow only
1959 arbitrate between scanners that are still scanning.
1960 """
1961 manager = get_manager()
1962 address = "44:44:33:11:23:68"
1963 start = 50.0
1964 cancel_active = manager.async_register_active_scan(address)
1965 owner_scanner = FakeScanner("AA:BB:CC:DD:EE:33", "hci3")
1966 owner_scanner.connectable = True
1967 cancel_scanner = manager.async_register_scanner(owner_scanner, connection_slots=5)
1968 strong = generate_ble_device(address, "strong_hci3")
1969 strong_adv = generate_advertisement_data(
1970 local_name="strong_hci3", service_uuids=[], rssi=-50
1971 )
1972 inject_advertisement_with_time_and_source(
1973 strong, strong_adv, start, "AA:BB:CC:DD:EE:33"
1974 )
1975 manager.async_set_fallback_availability_interval(address, 10)
1976
1977 weak = generate_ble_device(address, "weak_hci1")
1978 weak_adv = generate_advertisement_data(
1979 local_name="weak_hci1", service_uuids=[], rssi=-90
1980 )
1981 with owner_scanner.connecting():
1982 assert owner_scanner.scanning is False
1983 # Not even stale (elapsed 1 < 15) and far weaker: hands off
1984 # immediately, and no rescue episode is started.
1985 inject_advertisement_with_time_and_source(
1986 weak, weak_adv, start + 1, HCI1_SOURCE_ADDRESS
1987 )
1988 assert manager.async_ble_device_from_address(address, True) is weak
1989 assert address not in manager._rescue_triggered
1990 cancel_active()
1991 cancel_scanner()
1992
1993
1994 @pytest.mark.usefixtures("enable_bluetooth")
1995 @pytest.mark.asyncio
1996 async def test_stale_active_need_retry_does_not_clobber_matured_accept(
1997 register_hci0_scanner: None,
1998 register_hci1_scanner: None,
1999 ) -> None:
2000 """
2001 The retry never restarts an episode whose window already ran.
2002
2003 Once an accept time is recorded, the episode is only waiting out the
2004 accept and interval gates; restarting it would push the trigger time
2005 forward and make the gates unreachable for slow advertisers.
2006 """
2007 manager = get_manager()
2008 address = "44:44:33:11:23:79"
2009 start = 50.0
2010 strong = generate_ble_device(address, "strong_hci0")
2011 strong_adv = generate_advertisement_data(
2012 local_name="strong_hci0", service_uuids=[], rssi=-50
2013 )
2014 inject_advertisement_with_time_and_source(
2015 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
2016 )
2017 # stale_seconds = 35, durably-gone = 87.5
2018 manager.async_set_fallback_availability_interval(address, 30)
2019
2020 comparable = generate_ble_device(address, "comparable_hci1")
2021 comparable_adv = generate_advertisement_data(
2022 local_name="comparable_hci1", service_uuids=[], rssi=-60
2023 )
2024 real_scheduler = manager._auto_scheduler
2025 mock_scheduler = Mock()
2026 mock_scheduler._requests_by_address = {address: {Mock()}}
2027 mock_scheduler._rescue_accept_after = {}
2028 manager._auto_scheduler = mock_scheduler
2029 try:
2030 # Episode starts.
2031 inject_advertisement_with_time_and_source(
2032 comparable, comparable_adv, start + 36, HCI1_SOURCE_ADDRESS
2033 )
2034 assert mock_scheduler.trigger_rescue.call_count == 1
2035 assert manager._rescue_triggered[address] == start + 36
2036 # A window ran; its accept time is still in the future.
2037 mock_scheduler._rescue_accept_after[address] = start + 80
2038 # Past the retry wait, but the accept exists: no restart, the
2039 # trigger time is preserved so the gates can mature.
2040 inject_advertisement_with_time_and_source(
2041 comparable, comparable_adv, start + 70, HCI1_SOURCE_ADDRESS
2042 )
2043 assert mock_scheduler.trigger_rescue.call_count == 1
2044 assert manager._rescue_triggered[address] == start + 36
2045 assert manager.async_ble_device_from_address(address, True) is strong
2046 finally:
2047 manager._auto_scheduler = real_scheduler
2048 manager._rescue_triggered.pop(address, None)
2049
2050
2051 @pytest.mark.usefixtures("enable_bluetooth")
2052 @pytest.mark.asyncio
2053 async def test_stale_active_need_durably_gone_ends_episode(
2054 register_hci0_scanner: None,
2055 register_hci1_scanner: None,
2056 ) -> None:
2057 """Durably-gone still hands off even when the rescue window never completed."""
2058 manager = get_manager()
2059 address = "44:44:33:11:23:65"
2060 start = 50.0
2061 cancel_active = manager.async_register_active_scan(address)
2062 strong = generate_ble_device(address, "strong_hci0")
2063 strong_adv = generate_advertisement_data(
2064 local_name="strong_hci0", service_uuids=[], rssi=-50
2065 )
2066 inject_advertisement_with_time_and_source(
2067 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
2068 )
2069 # stale_seconds = 15, durably-gone = 37.5
2070 manager.async_set_fallback_availability_interval(address, 10)
2071
2072 comparable = generate_ble_device(address, "comparable_hci1")
2073 comparable_adv = generate_advertisement_data(
2074 local_name="comparable_hci1", service_uuids=[], rssi=-60
2075 )
2076 inject_advertisement_with_time_and_source(
2077 comparable, comparable_adv, start + 16, HCI1_SOURCE_ADDRESS
2078 )
2079 assert manager.async_ble_device_from_address(address, True) is strong
2080 assert address in manager._rescue_triggered
2081 # Past durably-gone with no rescue completion: hand off anyway.
2082 inject_advertisement_with_time_and_source(
2083 comparable, comparable_adv, start + 40, HCI1_SOURCE_ADDRESS
2084 )
2085 assert manager.async_ble_device_from_address(address, True) is comparable
2086 assert address not in manager._rescue_triggered
2087 cancel_active()
2088
2089
2090 class _AutoWindowScanner(FakeScanner):
2091 """AUTO-capable fake scanner recording windows with discoverable data."""
2092
2093 def __init__(self, source: str, adapter: str, mode: BluetoothScanningMode) -> None:
2094 super().__init__(source, adapter, requested_mode=mode)
2095 self.connectable = True
2096 self.active_window_calls: list[float] = []
2097 self._discovered: dict[str, tuple[BLEDevice, AdvertisementData]] = {}
2098
2099 async def async_request_active_window(self, duration: float) -> bool:
2100 self.active_window_calls.append(duration)
2101 return True
2102
2103 @property
2104 def discovered_devices_and_advertisement_data(
2105 self,
2106 ) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
2107 return self._discovered
2108
2109
2110 @pytest.mark.usefixtures("enable_bluetooth")
2111 @pytest.mark.asyncio
2112 async def test_rescue_end_to_end_owner_mid_connect_fallback_window() -> None:
2113 """
2114 The full rescue chain resolves a mid-connect AUTO owner.
2115
2116 The AUTO owner still reports scanning while a connect attempt is in
2117 progress, so the challenger's stale advertisement is deferred and a
2118 rescue is triggered. The owner's worker tick cannot flip the owner's
2119 radio, delegates the window to a fallback scanner, and records the
2120 accept time; the first challenger advertisement past it takes
2121 ownership.
2122 """
2123 manager = get_manager()
2124 sched = manager._auto_scheduler
2125 address = "44:44:33:11:23:69"
2126 cancel_active = manager.async_register_active_scan(address)
2127 owner = _AutoWindowScanner("AA:BB:CC:DD:EE:55", "hci5", BluetoothScanningMode.AUTO)
2128 fallback = _AutoWindowScanner(
2129 "AA:BB:CC:DD:EE:66", "hci6", BluetoothScanningMode.AUTO
2130 )
2131 challenger = _AutoWindowScanner(
2132 "AA:BB:CC:DD:EE:77", "hci7", BluetoothScanningMode.PASSIVE
2133 )
2134 cancels = [
2135 manager.async_register_scanner(scanner, connection_slots=5)
2136 for scanner in (owner, fallback, challenger)
2137 ]
2138 now = monotonic_time_coarse()
2139 strong = generate_ble_device(address, "strong")
2140 strong_adv = generate_advertisement_data(
2141 local_name="strong", service_uuids=[], rssi=-50
2142 )
2143 inject_advertisement_with_time_and_source(
2144 strong, strong_adv, now - 16, owner.source
2145 )
2146 # stale_seconds = 15, durably-gone = 37.5
2147 manager.async_set_fallback_availability_interval(address, 10)
2148 fallback._discovered[address] = (
2149 generate_ble_device(address, "x"),
2150 generate_advertisement_data(local_name="x", rssi=-70),
2151 )
2152 owner._add_connecting(address)
2153 try:
2154 weak = generate_ble_device(address, "weak")
2155 weak_adv = generate_advertisement_data(
2156 local_name="weak", service_uuids=[], rssi=-60
2157 )
2158 # Past the stale window: deferred, rescue triggered.
2159 inject_advertisement_with_time_and_source(
2160 weak, weak_adv, now, challenger.source
2161 )
2162 assert manager.async_ble_device_from_address(address, True) is strong
2163 assert manager._rescue_triggered[address] == now
2164 # The owner's worker tick delegates the rescue window to the
2165 # fallback scanner because the owner is mid-connect.
2166 await sched._workers[owner.source]._tick()
2167 assert owner.active_window_calls == []
2168 assert fallback.active_window_calls
2169 accept = sched._rescue_accept_after[address]
2170 assert accept >= now
2171 # First challenger adv past the accept time and one advertising
2172 # interval past the trigger: hand off.
2173 inject_advertisement_with_time_and_source(
2174 weak, weak_adv, max(accept + 1, now + 11), challenger.source
2175 )
2176 assert manager.async_ble_device_from_address(address, True) is weak
2177 assert address not in manager._rescue_triggered
2178 finally:
2179 owner._finished_connecting(address, connected=False)
2180 cancel_active()
2181 for cancel in cancels:
2182 cancel()
2183
2184
2185 @pytest.mark.usefixtures("enable_bluetooth")
2186 @pytest.mark.asyncio
2187 async def test_rescue_episode_is_per_address_any_challenger_completes(
2188 register_hci0_scanner: None,
2189 register_hci1_scanner: None,
2190 ) -> None:
2191 """
2192 A rescue episode is keyed by address, not by the challenger.
2193
2194 Challenger A starts the episode; once the accept time passes, a
2195 different challenger's advertisement completes the handoff.
2196 """
2197 manager = get_manager()
2198 address = "44:44:33:11:23:70"
2199 start = 50.0
2200 cancel_active = manager.async_register_active_scan(address)
2201 other = FakeScanner("AA:BB:CC:DD:EE:88", "hci8")
2202 other.connectable = True
2203 cancel_other = manager.async_register_scanner(other, connection_slots=5)
2204 strong = generate_ble_device(address, "strong_hci0")
2205 strong_adv = generate_advertisement_data(
2206 local_name="strong_hci0", service_uuids=[], rssi=-50
2207 )
2208 inject_advertisement_with_time_and_source(
2209 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
2210 )
2211 manager.async_set_fallback_availability_interval(address, 10)
2212
2213 challenger_a = generate_ble_device(address, "challenger_hci1")
2214 challenger_a_adv = generate_advertisement_data(
2215 local_name="challenger_hci1", service_uuids=[], rssi=-60
2216 )
2217 inject_advertisement_with_time_and_source(
2218 challenger_a, challenger_a_adv, start + 16, HCI1_SOURCE_ADDRESS
2219 )
2220 assert manager._rescue_triggered[address] == start + 16
2221 manager._auto_scheduler._rescue_accept_after[address] = start + 20
2222 challenger_b = generate_ble_device(address, "challenger_hci8")
2223 challenger_b_adv = generate_advertisement_data(
2224 local_name="challenger_hci8", service_uuids=[], rssi=-62
2225 )
2226 inject_advertisement_with_time_and_source(
2227 challenger_b, challenger_b_adv, start + 27, "AA:BB:CC:DD:EE:88"
2228 )
2229 assert manager.async_ble_device_from_address(address, True) is challenger_b
2230 assert address not in manager._rescue_triggered
2231 cancel_active()
2232 cancel_other()
2233
2234
2235 @pytest.mark.usefixtures("enable_bluetooth")
2236 @pytest.mark.asyncio
2237 async def test_connectable_recheck_does_not_drive_rescue_episode(
2238 register_hci0_scanner: None,
2239 register_hci1_scanner: None,
2240 register_non_connectable_scanner: None,
2241 ) -> None:
2242 """
2243 The connectable re-check never starts a rescue episode.
2244
2245 All-history is owned by a fresh non-connectable source, so the
2246 all-history decision keeps without entering the stale branch; the
2247 connectable re-check then sees a stale connectable owner and denies
2248 the handoff, but with record_demotion=False it must not start an
2249 episode.
2250 """
2251 manager = get_manager()
2252 address = "44:44:33:11:23:71"
2253 start = 50.0
2254 cancel_active = manager.async_register_active_scan(address)
2255 connectable_owner = generate_ble_device(address, "conn_hci0")
2256 connectable_owner_adv = generate_advertisement_data(
2257 local_name="conn_hci0", service_uuids=[], rssi=-60
2258 )
2259 inject_advertisement_with_time_and_source(
2260 connectable_owner, connectable_owner_adv, start, HCI0_SOURCE_ADDRESS
2261 )
2262 manager.async_set_fallback_availability_interval(address, 10)
2263 # A much stronger non-connectable source takes all-history on the
2264 # RSSI path; the connectable history stays with hci0.
2265 nc_device = generate_ble_device(address, "nc")
2266 nc_adv = generate_advertisement_data(local_name="nc", service_uuids=[], rssi=-30)
2267 inject_advertisement_with_time_and_source_connectable(
2268 nc_device, nc_adv, start + 10, NON_CONNECTABLE_REMOTE_SOURCE_ADDRESS, False
2269 )
2270 assert manager.async_ble_device_from_address(address, False) is nc_device
2271 assert manager.async_ble_device_from_address(address, True) is connectable_owner
2272 # A weak connectable challenger: all-history keeps (fresh strong
2273 # owner); the connectable re-check hits the stale branch and denies,
2274 # and must not start an episode.
2275 challenger = generate_ble_device(address, "challenger_hci1")
2276 challenger_adv = generate_advertisement_data(
2277 local_name="challenger_hci1", service_uuids=[], rssi=-80
2278 )
2279 inject_advertisement_with_time_and_source(
2280 challenger, challenger_adv, start + 17, HCI1_SOURCE_ADDRESS
2281 )
2282 assert manager.async_ble_device_from_address(address, False) is nc_device
2283 assert manager.async_ble_device_from_address(address, True) is connectable_owner
2284 assert address not in manager._rescue_triggered
2285 cancel_active()
2286
2287
2288 @pytest.mark.usefixtures("enable_bluetooth")
2289 @pytest.mark.asyncio
2290 async def test_connectable_recheck_roams_active_need_device_at_stale(
2291 register_hci0_scanner: None,
2292 register_hci1_scanner: None,
2293 register_non_connectable_scanner: None,
2294 ) -> None:
2295 """
2296 The connectable re-check keeps the roaming rule for active-need devices.
2297
2298 Connection routing cares about liveness, not scan-response freshness:
2299 when the weak connectable owner goes silent, the connectable history
2300 must repoint to a comparable live challenger at the stale window
2301 instead of routing connect attempts at a dead radio until durably
2302 gone, and it must not drive rescue episode state.
2303 """
2304 manager = get_manager()
2305 address = "44:44:33:11:23:78"
2306 start = 50.0
2307 cancel_active = manager.async_register_active_scan(address)
2308 connectable_owner = generate_ble_device(address, "conn_hci0")
2309 connectable_owner_adv = generate_advertisement_data(
2310 local_name="conn_hci0", service_uuids=[], rssi=-80
2311 )
2312 inject_advertisement_with_time_and_source(
2313 connectable_owner, connectable_owner_adv, start, HCI0_SOURCE_ADDRESS
2314 )
2315 manager.async_set_fallback_availability_interval(address, 10)
2316 # A much stronger non-connectable source takes all-history on the
2317 # RSSI path; the connectable history stays with hci0.
2318 nc_device = generate_ble_device(address, "nc")
2319 nc_adv = generate_advertisement_data(local_name="nc", service_uuids=[], rssi=-30)
2320 inject_advertisement_with_time_and_source_connectable(
2321 nc_device, nc_adv, start + 10, NON_CONNECTABLE_REMOTE_SOURCE_ADDRESS, False
2322 )
2323 assert manager.async_ble_device_from_address(address, True) is connectable_owner
2324 # A comparable connectable challenger of the weak owner within the
2325 # roam gate: the connectable history is kept (single reception miss).
2326 challenger = generate_ble_device(address, "challenger_hci1")
2327 challenger_adv = generate_advertisement_data(
2328 local_name="challenger_hci1", service_uuids=[], rssi=-85
2329 )
2330 inject_advertisement_with_time_and_source(
2331 challenger, challenger_adv, start + 17, HCI1_SOURCE_ADDRESS
2332 )
2333 assert manager.async_ble_device_from_address(address, True) is connectable_owner
2334 # Past the roam gate (1.5 * 15 = 22.5 since the connectable owner's
2335 # last adv): all-history keeps (fresh strong NC owner), but the
2336 # connectable re-check roams to the live challenger.
2337 inject_advertisement_with_time_and_source(
2338 challenger, challenger_adv, start + 24, HCI1_SOURCE_ADDRESS
2339 )
2340 assert manager.async_ble_device_from_address(address, False) is nc_device
2341 assert manager.async_ble_device_from_address(address, True) is challenger
2342 assert address not in manager._rescue_triggered
2343 cancel_active()
2344
2345
2346 @pytest.mark.usefixtures("enable_bluetooth")
2347 @pytest.mark.asyncio
2348 async def test_rescue_registration_is_case_normalized(
2349 register_hci0_scanner: None,
2350 register_hci1_scanner: None,
2351 ) -> None:
2352 """A lowercase active-scan registration still drives the rescue flow."""
2353 manager = get_manager()
2354 address = "44:44:33:11:23:72"
2355 start = 50.0
2356 cancel_active = manager.async_register_active_scan(address.lower())
2357 strong = generate_ble_device(address, "strong_hci0")
2358 strong_adv = generate_advertisement_data(
2359 local_name="strong_hci0", service_uuids=[], rssi=-50
2360 )
2361 inject_advertisement_with_time_and_source(
2362 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
2363 )
2364 manager.async_set_fallback_availability_interval(address, 10)
2365
2366 comparable = generate_ble_device(address, "comparable_hci1")
2367 comparable_adv = generate_advertisement_data(
2368 local_name="comparable_hci1", service_uuids=[], rssi=-60
2369 )
2370 inject_advertisement_with_time_and_source(
2371 comparable, comparable_adv, start + 16, HCI1_SOURCE_ADDRESS
2372 )
2373 # Deferred (episode started), not handed off: the lowercase
2374 # registration matched the uppercase advertisement address.
2375 assert manager.async_ble_device_from_address(address, True) is strong
2376 assert manager._rescue_triggered[address] == start + 16
2377 cancel_active()
2378
2379
2380 @pytest.mark.usefixtures("enable_bluetooth")
2381 @pytest.mark.asyncio
2382 async def test_rescue_accept_time_boundaries(
2383 register_hci0_scanner: None,
2384 register_hci1_scanner: None,
2385 ) -> None:
2386 """
2387 The accept gates are accept_after >= pending and new.time > accept_after.
2388
2389 An advertisement at exactly the accept time stays deferred (strict
2390 greater-than); an accept time equal to the trigger time counts
2391 (greater-or-equal).
2392 """
2393 manager = get_manager()
2394 start = 50.0
2395 manager_sched = manager._auto_scheduler
2396
2397 # Part 1: adv at exactly the accept time stays deferred.
2398 address = "44:44:33:11:23:73"
2399 cancel_a = manager.async_register_active_scan(address)
2400 strong = generate_ble_device(address, "strong_hci0")
2401 strong_adv = generate_advertisement_data(
2402 local_name="strong_hci0", service_uuids=[], rssi=-50
2403 )
2404 inject_advertisement_with_time_and_source(
2405 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
2406 )
2407 manager.async_set_fallback_availability_interval(address, 10)
2408 comparable = generate_ble_device(address, "comparable_hci1")
2409 comparable_adv = generate_advertisement_data(
2410 local_name="comparable_hci1", service_uuids=[], rssi=-60
2411 )
2412 inject_advertisement_with_time_and_source(
2413 comparable, comparable_adv, start + 16, HCI1_SOURCE_ADDRESS
2414 )
2415 manager_sched._rescue_accept_after[address] = start + 20
2416 inject_advertisement_with_time_and_source(
2417 comparable, comparable_adv, start + 20, HCI1_SOURCE_ADDRESS
2418 )
2419 assert manager.async_ble_device_from_address(address, True) is strong
2420 # Past the accept but within one advertising interval of the trigger:
2421 # still deferred.
2422 inject_advertisement_with_time_and_source(
2423 comparable, comparable_adv, start + 24, HCI1_SOURCE_ADDRESS
2424 )
2425 assert manager.async_ble_device_from_address(address, True) is strong
2426 cancel_a()
2427
2428 # Part 2: an accept time equal to the trigger time counts.
2429 address = "44:44:33:11:23:74"
2430 cancel_b = manager.async_register_active_scan(address)
2431 strong2 = generate_ble_device(address, "strong2_hci0")
2432 strong2_adv = generate_advertisement_data(
2433 local_name="strong2_hci0", service_uuids=[], rssi=-50
2434 )
2435 inject_advertisement_with_time_and_source(
2436 strong2, strong2_adv, start, HCI0_SOURCE_ADDRESS
2437 )
2438 manager.async_set_fallback_availability_interval(address, 10)
2439 comparable2 = generate_ble_device(address, "comparable2_hci1")
2440 comparable2_adv = generate_advertisement_data(
2441 local_name="comparable2_hci1", service_uuids=[], rssi=-60
2442 )
2443 inject_advertisement_with_time_and_source(
2444 comparable2, comparable2_adv, start + 16, HCI1_SOURCE_ADDRESS
2445 )
2446 manager_sched._rescue_accept_after[address] = start + 16
2447 inject_advertisement_with_time_and_source(
2448 comparable2, comparable2_adv, start + 27, HCI1_SOURCE_ADDRESS
2449 )
2450 assert manager.async_ble_device_from_address(address, True) is comparable2
2451 cancel_b()
2452
2453
2454 @pytest.mark.usefixtures("enable_bluetooth")
2455 @pytest.mark.asyncio
2456 async def test_passive_stale_arbitration_clears_orphaned_episode(
2457 register_hci0_scanner: None,
2458 register_hci1_scanner: None,
2459 ) -> None:
2460 """
2461 A device that lost its active-scan need drops its episode on arbitration.
2462
2463 The orphaned entry must not linger; it would keep the scheduler's
2464 no-episode fast path off for every window dispatch.
2465 """
2466 manager = get_manager()
2467 address = "44:44:33:11:23:76"
2468 start = 50.0
2469 strong = generate_ble_device(address, "strong_hci0")
2470 strong_adv = generate_advertisement_data(
2471 local_name="strong_hci0", service_uuids=[], rssi=-50
2472 )
2473 inject_advertisement_with_time_and_source(
2474 strong, strong_adv, start, HCI0_SOURCE_ADDRESS
2475 )
2476 manager.async_set_fallback_availability_interval(address, 10)
2477 # Episode left behind by an active-scan need that was since unregistered.
2478 manager._rescue_triggered[address] = start
2479
2480 weak = generate_ble_device(address, "weak_hci1")
2481 weak_adv = generate_advertisement_data(
2482 local_name="weak_hci1", service_uuids=[], rssi=-90
2483 )
2484 # Weaker passive challenger past stale: kept, and the orphaned
2485 # episode is cleaned up.
2486 inject_advertisement_with_time_and_source(
2487 weak, weak_adv, start + 16, HCI1_SOURCE_ADDRESS
2488 )
2489 assert manager.async_ble_device_from_address(address, True) is strong
2490 assert address not in manager._rescue_triggered
2491
2492
2493 @pytest.mark.usefixtures("enable_bluetooth")
2494 @pytest.mark.asyncio
2495 async def test_clear_advertisement_history_clears_rescue_state(
2496 register_hci0_scanner: None,
2497 register_hci1_scanner: None,
2498 ) -> None:
2499 """async_clear_advertisement_history drops any in-flight rescue episode."""
2500 manager = get_manager()
2501 address = "44:44:33:11:23:66"
2502 manager._rescue_triggered[address] = 123.0
2503 manager.async_clear_advertisement_history(address)
2504 assert address not in manager._rescue_triggered
2505
2506
2507 def _rssi_adv(rssi: int) -> AdvertisementData:
2508 return generate_advertisement_data(
2509 local_name="smoothing", service_uuids=[], rssi=rssi
2510 )
2511
2512
2513 @pytest.mark.usefixtures("enable_bluetooth")
2514 @pytest.mark.asyncio
2515 async def test_rssi_smoothing_ignores_single_spike(
2516 register_hci0_scanner: None,
2517 register_hci1_scanner: None,
2518 ) -> None:
2519 """
2520 A one-off RSSI spike from a challenger does not flip a stationary owner.
2521
2522 Instantaneously the spike clears the 16 dB threshold, but the smoothed
2523 per-source RSSI does not, so ownership stays put.
2524 """
2525 manager = get_manager()
2526 address = "44:44:33:11:23:50"
2527 t = 50.0
2528 owner = generate_ble_device(address, "owner_hci0")
2529 challenger = generate_ble_device(address, "challenger_hci1")
2530
2531 inject_advertisement_with_time_and_source(
2532 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2533 )
2534 # Challenger first seen weaker (-60), so it enters the smoothing bucket.
2535 inject_advertisement_with_time_and_source(
2536 challenger, _rssi_adv(-60), t + 1, HCI1_SOURCE_ADDRESS
2537 )
2538 assert manager.async_ble_device_from_address(address, True) is owner
2539
2540 # Single spike to -30 (instantaneously 20 dB stronger than the owner):
2541 # smoothed hci1 = 0.3*-30 + 0.7*-60 = -51, still below -50 + threshold,
2542 # so it must NOT switch.
2543 inject_advertisement_with_time_and_source(
2544 challenger, _rssi_adv(-30), t + 2, HCI1_SOURCE_ADDRESS
2545 )
2546 assert manager.async_ble_device_from_address(address, True) is owner
2547
2548
2549 @pytest.mark.usefixtures("enable_bluetooth")
2550 @pytest.mark.asyncio
2551 async def test_rssi_smoothing_switches_on_sustained_stronger(
2552 register_hci0_scanner: None,
2553 register_hci1_scanner: None,
2554 ) -> None:
2555 """A sustained stronger challenger wins once its smoothed RSSI crosses."""
2556 manager = get_manager()
2557 address = "44:44:33:11:23:51"
2558 t = 50.0
2559 owner = generate_ble_device(address, "owner_hci0")
2560 challenger = generate_ble_device(address, "challenger_hci1")
2561
2562 inject_advertisement_with_time_and_source(
2563 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2564 )
2565 inject_advertisement_with_time_and_source(
2566 challenger, _rssi_adv(-55), t + 1, HCI1_SOURCE_ADDRESS
2567 )
2568 assert manager.async_ble_device_from_address(address, True) is owner
2569
2570 # Sustained -20 (30 dB stronger): the smoothed value climbs past the
2571 # threshold after a few samples and ownership flips.
2572 for i in range(8):
2573 inject_advertisement_with_time_and_source(
2574 challenger, _rssi_adv(-20), t + 2 + i, HCI1_SOURCE_ADDRESS
2575 )
2576 assert manager.async_ble_device_from_address(address, True) is challenger
2577
2578
2579 @pytest.mark.usefixtures("enable_bluetooth")
2580 @pytest.mark.asyncio
2581 async def test_rssi_smoothing_first_sighting_switches_immediately(
2582 register_hci0_scanner: None,
2583 register_hci1_scanner: None,
2584 ) -> None:
2585 """A first-seen challenger with a real margin switches at once (instantaneous)."""
2586 manager = get_manager()
2587 address = "44:44:33:11:23:52"
2588 t = 50.0
2589 owner = generate_ble_device(address, "owner_hci0")
2590 challenger = generate_ble_device(address, "challenger_hci1")
2591
2592 inject_advertisement_with_time_and_source(
2593 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2594 )
2595 # No prior smoothed history for the challenger: it seeds at its
2596 # instantaneous -20, which is a genuine 30 dB margin, so it wins now.
2597 inject_advertisement_with_time_and_source(
2598 challenger, _rssi_adv(-20), t + 1, HCI1_SOURCE_ADDRESS
2599 )
2600 assert manager.async_ble_device_from_address(address, True) is challenger
2601
2602
2603 @pytest.mark.usefixtures("enable_bluetooth")
2604 @pytest.mark.asyncio
2605 async def test_rssi_smoothing_bucket_evicted_with_history(
2606 register_hci0_scanner: None,
2607 register_hci1_scanner: None,
2608 ) -> None:
2609 """The smoothed-RSSI bucket is allocated cross-source and cleared with history."""
2610 manager = get_manager()
2611 address = "44:44:33:11:23:53"
2612 t = 50.0
2613 owner = generate_ble_device(address, "owner_hci0")
2614 challenger = generate_ble_device(address, "challenger_hci1")
2615
2616 inject_advertisement_with_time_and_source(
2617 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2618 )
2619 # Single source so far: no bucket allocated.
2620 assert address not in manager._smoothed_rssi
2621 inject_advertisement_with_time_and_source(
2622 challenger, _rssi_adv(-60), t + 1, HCI1_SOURCE_ADDRESS
2623 )
2624 # Cross-source seen: bucket now holds both sources.
2625 assert set(manager._smoothed_rssi[address]) == {
2626 HCI0_SOURCE_ADDRESS,
2627 HCI1_SOURCE_ADDRESS,
2628 }
2629
2630 manager.async_clear_advertisement_history(address)
2631 assert address not in manager._smoothed_rssi
2632
2633
2634 @pytest.mark.usefixtures("enable_bluetooth")
2635 @pytest.mark.asyncio
2636 async def test_rssi_smoothing_source_evicted_on_unregister(
2637 register_hci0_scanner: None,
2638 register_hci1_scanner: None,
2639 ) -> None:
2640 """Unregistering a scanner drops its source from every smoothed bucket."""
2641 manager = get_manager()
2642 address = "44:44:33:11:23:54"
2643 t = 50.0
2644 owner = generate_ble_device(address, "owner_hci0")
2645 challenger = generate_ble_device(address, "challenger_hci1")
2646
2647 inject_advertisement_with_time_and_source(
2648 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2649 )
2650 inject_advertisement_with_time_and_source(
2651 challenger, _rssi_adv(-60), t + 1, HCI1_SOURCE_ADDRESS
2652 )
2653 assert HCI1_SOURCE_ADDRESS in manager._smoothed_rssi[address]
2654
2655 def _unregister(source: str) -> None:
2656 for scanner in list(manager._sources.values()):
2657 if scanner.source == source:
2658 manager._async_unregister_scanner_internal(
2659 manager._connectable_scanners, scanner, None
2660 )
2661
2662 _unregister(HCI1_SOURCE_ADDRESS)
2663 # One source remains, so the bucket survives without the dropped source.
2664 assert HCI1_SOURCE_ADDRESS not in manager._smoothed_rssi[address]
2665 assert HCI0_SOURCE_ADDRESS in manager._smoothed_rssi[address]
2666
2667 # Dropping the last source empties the bucket; the address is removed so
2668 # the map can return to truly empty and re-enable the proxy-free fast path.
2669 _unregister(HCI0_SOURCE_ADDRESS)
2670 assert address not in manager._smoothed_rssi
2671 assert not manager._smoothed_rssi
2672
2673
2674 @pytest.mark.usefixtures("enable_bluetooth")
2675 @pytest.mark.asyncio
2676 async def test_rssi_smoothing_skips_unregistered_old_source(
2677 register_hci0_scanner: None,
2678 register_hci1_scanner: None,
2679 ) -> None:
2680 """
2681 A new bucket is not seeded against a source that has unregistered.
2682
2683 An old source lingers in _all_history after it unregisters (the
2684 unavailable sweep clears it later); seeding its stale RSSI would
2685 reintroduce the source the unregister cleanup just dropped.
2686 """
2687 manager = get_manager()
2688 address = "44:44:33:11:23:55"
2689 t = 50.0
2690 owner = generate_ble_device(address, "owner_hci0")
2691 challenger = generate_ble_device(address, "challenger_hci1")
2692
2693 # Seen from hci0 only, so no bucket exists yet.
2694 inject_advertisement_with_time_and_source(
2695 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2696 )
2697 assert address not in manager._smoothed_rssi
2698
2699 # hci0 unregisters, but its advertisement lingers in _all_history.
2700 for scanner in list(manager._sources.values()):
2701 if scanner.source == HCI0_SOURCE_ADDRESS:
2702 manager._async_unregister_scanner_internal(
2703 manager._connectable_scanners, scanner, None
2704 )
2705 assert manager._all_history[address].source == HCI0_SOURCE_ADDRESS
2706
2707 # hci1 now advertises; the dead hci0 source must not be seeded, so no
2708 # bucket is created for what is now effectively a single-source device.
2709 inject_advertisement_with_time_and_source(
2710 challenger, _rssi_adv(-60), t + 1, HCI1_SOURCE_ADDRESS
2711 )
2712 assert address not in manager._smoothed_rssi
2713
2714
2715 @pytest.mark.usefixtures("enable_bluetooth")
2716 @pytest.mark.asyncio
2717 async def test_rssi_smoothing_ignores_missing_rssi(
2718 register_hci0_scanner: None,
2719 register_hci1_scanner: None,
2720 ) -> None:
2721 """
2722 A dropped RSSI (0) is not folded into the smoothed average.
2723
2724 Proxies occasionally report no RSSI. Folding NO_RSSI_VALUE (-127) into the
2725 EWMA would poison the value and, because the average remembers it, drag it
2726 down for several adverts, manufacturing phantom weak readings. A no-RSSI
2727 advert must instead keep the last good smoothed value and write nothing.
2728 """
2729 manager = get_manager()
2730 address = "44:44:33:11:23:5A"
2731 t = 50.0
2732 owner = generate_ble_device(address, "owner_hci0")
2733 challenger = generate_ble_device(address, "challenger_hci1")
2734
2735 inject_advertisement_with_time_and_source(
2736 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2737 )
2738 # First cross-source sighting seeds the bucket at the real reading.
2739 inject_advertisement_with_time_and_source(
2740 challenger, _rssi_adv(-45), t + 1, HCI1_SOURCE_ADDRESS
2741 )
2742 assert manager._smoothed_rssi[address][HCI1_SOURCE_ADDRESS] == -45
2743
2744 # A burst of no-RSSI adverts must leave the smoothed value pinned, not walk
2745 # it toward -127.
2746 for i in range(3):
2747 inject_advertisement_with_time_and_source(
2748 challenger, _rssi_adv(0), t + 2 + i, HCI1_SOURCE_ADDRESS
2749 )
2750 assert manager._smoothed_rssi[address][HCI1_SOURCE_ADDRESS] == -45
2751 # The owner is unaffected by the dropped readings.
2752 assert manager.async_ble_device_from_address(address, True) is owner
2753
2754 # A new source whose very first advert has no RSSI is not seeded into the
2755 # existing bucket (it loses arbitration via NO_RSSI_VALUE instead).
2756 third = generate_ble_device(address, "third_hci2")
2757 inject_advertisement_with_time_and_source(third, _rssi_adv(0), t + 6, "hci2")
2758 assert "hci2" not in manager._smoothed_rssi[address]
2759 assert manager.async_ble_device_from_address(address, True) is owner
2760
2761
2762 @pytest.mark.usefixtures("enable_bluetooth")
2763 @pytest.mark.asyncio
2764 async def test_rssi_smoothing_no_bucket_seeded_from_missing_rssi(
2765 register_hci0_scanner: None,
2766 register_hci1_scanner: None,
2767 ) -> None:
2768 """
2769 A no-RSSI first cross-source sighting does not seed or steal ownership.
2770
2771 The bucket is seeded from the existing owner only; the no-RSSI source is
2772 left unseeded so it loses arbitration (NO_RSSI_VALUE) and the owner is kept,
2773 rather than priming the average with -127 or taking ownership with no
2774 signal. The source's next real advert seeds it cleanly.
2775 """
2776 manager = get_manager()
2777 address = "44:44:33:11:23:5B"
2778 t = 50.0
2779 owner = generate_ble_device(address, "owner_hci0")
2780 challenger = generate_ble_device(address, "challenger_hci1")
2781
2782 inject_advertisement_with_time_and_source(
2783 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2784 )
2785 # First cross-source advert has no RSSI: the challenger is not seeded and
2786 # does not take ownership.
2787 inject_advertisement_with_time_and_source(
2788 challenger, _rssi_adv(0), t + 1, HCI1_SOURCE_ADDRESS
2789 )
2790 assert manager._smoothed_rssi[address] == {HCI0_SOURCE_ADDRESS: -50}
2791 assert manager.async_ble_device_from_address(address, True) is owner
2792
2793 # A later real reading seeds the challenger cleanly.
2794 inject_advertisement_with_time_and_source(
2795 challenger, _rssi_adv(-45), t + 2, HCI1_SOURCE_ADDRESS
2796 )
2797 assert manager._smoothed_rssi[address] == {
2798 HCI0_SOURCE_ADDRESS: -50,
2799 HCI1_SOURCE_ADDRESS: -45,
2800 }
2801
2802
2803 @pytest.mark.usefixtures("enable_bluetooth")
2804 @pytest.mark.asyncio
2805 async def test_rssi_deadband_does_not_slow_one_way_move(
2806 register_hci0_scanner: None,
2807 register_hci1_scanner: None,
2808 ) -> None:
2809 """
2810 A fresh challenger still takes ownership at the plain threshold.
2811
2812 The deadband only applies to a source reclaiming ownership it was just
2813 demoted from; a challenger that has never owned the address pays only
2814 ADV_RSSI_SWITCH_THRESHOLD (16 dB), so a 17 dB one-way move is not slowed.
2815 The demoted owner is recorded for the asymmetric reclaim check.
2816 """
2817 manager = get_manager()
2818 address = "44:44:33:11:23:56"
2819 t = 50.0
2820 owner = generate_ble_device(address, "owner_hci0")
2821 challenger = generate_ble_device(address, "challenger_hci1")
2822
2823 inject_advertisement_with_time_and_source(
2824 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2825 )
2826 # 17 dB stronger and never previously the owner: switches on the plain
2827 # 16 dB threshold, no deadband.
2828 inject_advertisement_with_time_and_source(
2829 challenger, _rssi_adv(-33), t + 1, HCI1_SOURCE_ADDRESS
2830 )
2831 assert manager.async_ble_device_from_address(address, True) is challenger
2832 # hci0 was demoted, so a quick reclaim by it now faces the deadband.
2833 assert HCI0_SOURCE_ADDRESS in manager._demoted_sources[address]
2834
2835 # Per-address eviction clears the reclaim record.
2836 manager.async_clear_advertisement_history(address)
2837 assert address not in manager._demoted_sources
2838
2839
2840 @pytest.mark.usefixtures("enable_bluetooth")
2841 @pytest.mark.asyncio
2842 async def test_rssi_deadband_damps_reclaim(
2843 register_hci0_scanner: None,
2844 register_hci1_scanner: None,
2845 ) -> None:
2846 """
2847 A just-demoted source must clear THRESHOLD + DEADBAND to reclaim ownership.
2848
2849 hci0 owns, hci1 takes over (one-way, plain threshold), then hci0 tries to
2850 reclaim: a 20 dB margin sits inside the 16 + 6 deadband and must not switch
2851 back, while a sustained 24 dB margin clears it and reclaims. Without the
2852 asymmetric deadband the 20 dB reclaim would flip ownership immediately.
2853 """
2854 manager = get_manager()
2855 address = "44:44:33:11:23:57"
2856 t = 50.0
2857 owner = generate_ble_device(address, "owner_hci0")
2858 challenger = generate_ble_device(address, "challenger_hci1")
2859
2860 inject_advertisement_with_time_and_source(
2861 owner, _rssi_adv(-50), t, HCI0_SOURCE_ADDRESS
2862 )
2863 # hci1 takes over (fresh challenger, plain 16 dB threshold).
2864 inject_advertisement_with_time_and_source(
2865 challenger, _rssi_adv(-30), t + 1, HCI1_SOURCE_ADDRESS
2866 )
2867 assert manager.async_ble_device_from_address(address, True) is challenger
2868 assert HCI0_SOURCE_ADDRESS in manager._demoted_sources[address]
2869
2870 # hci0 reclaims at a sustained 20 dB margin (smoothed converges to -10 vs
2871 # hci1's -30): inside the 16 + 6 deadband, so ownership stays with hci1.
2872 for i in range(15):
2873 inject_advertisement_with_time_and_source(
2874 owner, _rssi_adv(-10), t + 2 + i, HCI0_SOURCE_ADDRESS
2875 )
2876 assert manager.async_ble_device_from_address(address, True) is challenger
2877
2878 # A sustained 24 dB margin (smoothed converges to -6) clears the deadband
2879 # and hci0 reclaims.
2880 for i in range(15):
2881 inject_advertisement_with_time_and_source(
2882 owner, _rssi_adv(-6), t + 20 + i, HCI0_SOURCE_ADDRESS
2883 )
2884 assert manager.async_ble_device_from_address(address, True) is owner
2885 # The reclaim demotes hci1 in turn.
2886 assert HCI1_SOURCE_ADDRESS in manager._demoted_sources[address]
2887
2888 # Per-source eviction on unregister drops the reclaim record for that source.
2889 for scanner in list(manager._sources.values()):
2890 if scanner.source == HCI1_SOURCE_ADDRESS:
2891 manager._async_unregister_scanner_internal(
2892 manager._connectable_scanners, scanner, None
2893 )
2894 assert address not in manager._demoted_sources
2895
2896
2897 def _assert_nway_reclaim_damped(address: str, sources: list[str]) -> None:
2898 """
2899 Drive ownership through every source in order, then reclaim from the first.
2900
2901 Each current owner is faded so the next fresh source takes over, which
2902 leaves every earlier owner in the demoted set. The first source then
2903 reclaims: a sustained 19 dB margin (inside 16 + 6) must not switch because
2904 it is still demoted, while a sustained 25 dB margin clears the deadband and
2905 wins. Single-slot hysteresis (only the most-recent loser) would let the
2906 first source back at the plain 16 dB, so this fails without the set.
2907 """
2908 manager = get_manager()
2909 devices = [generate_ble_device(address, f"dev_{source}") for source in sources]
2910 now = 50.0
2911 inject_advertisement_with_time_and_source(
2912 devices[0], _rssi_adv(-40), now, sources[0]
2913 )
2914 for k in range(1, len(sources)):
2915 for _ in range(12):
2916 now += 1
2917 inject_advertisement_with_time_and_source(
2918 devices[k - 1], _rssi_adv(-60), now, sources[k - 1]
2919 )
2920 now += 1
2921 inject_advertisement_with_time_and_source(
2922 devices[k], _rssi_adv(-40), now, sources[k]
2923 )
2924 assert manager.async_ble_device_from_address(address, True) is devices[-1]
2925 assert manager._demoted_sources[address] == set(sources[:-1])
2926
2927 # Reclaim inside the deadband: blocked because the first source is demoted.
2928 for _ in range(15):
2929 now += 1
2930 inject_advertisement_with_time_and_source(
2931 devices[0], _rssi_adv(-21), now, sources[0]
2932 )
2933 assert manager.async_ble_device_from_address(address, True) is devices[-1]
2934
2935 # Reclaim past the deadband: wins.
2936 for _ in range(15):
2937 now += 1
2938 inject_advertisement_with_time_and_source(
2939 devices[0], _rssi_adv(-15), now, sources[0]
2940 )
2941 assert manager.async_ble_device_from_address(address, True) is devices[0]
2942
2943
2944 def _register_connectable_source(source: str) -> Callable[[], None]:
2945 scanner = FakeScanner(source, source)
2946 scanner.connectable = True
2947 return get_manager().async_register_scanner(scanner, connection_slots=5)
2948
2949
2950 @pytest.mark.usefixtures("enable_bluetooth")
2951 @pytest.mark.asyncio
2952 async def test_rssi_deadband_damps_three_way_reclaim(
2953 register_hci0_scanner: None,
2954 register_hci1_scanner: None,
2955 ) -> None:
2956 """A reclaim after a 3-way bounce is still charged the deadband."""
2957 cancel = _register_connectable_source("hci2")
2958 try:
2959 _assert_nway_reclaim_damped(
2960 "44:44:33:11:23:5C",
2961 [HCI0_SOURCE_ADDRESS, HCI1_SOURCE_ADDRESS, "hci2"],
2962 )
2963 finally:
2964 cancel()
2965
2966
2967 @pytest.mark.usefixtures("enable_bluetooth")
2968 @pytest.mark.asyncio
2969 async def test_rssi_deadband_damps_four_way_reclaim(
2970 register_hci0_scanner: None,
2971 register_hci1_scanner: None,
2972 ) -> None:
2973 """A reclaim by the earliest owner after a 4-way bounce still pays the deadband."""
2974 cancels = [
2975 _register_connectable_source("hci2"),
2976 _register_connectable_source("hci3"),
2977 ]
2978 try:
2979 _assert_nway_reclaim_damped(
2980 "44:44:33:11:23:5D",
2981 [HCI0_SOURCE_ADDRESS, HCI1_SOURCE_ADDRESS, "hci2", "hci3"],
2982 )
2983 finally:
2984 for cancel in cancels:
2985 cancel()
2986
2987
2988 @pytest.mark.usefixtures("enable_bluetooth")
2989 @pytest.mark.asyncio
2990 async def test_rssi_deadband_not_charged_after_stale_handoff(
2991 register_hci0_scanner: None,
2992 register_hci1_scanner: None,
2993 ) -> None:
2994 """
2995 A stale-path handoff records no demotion, so the owner reclaims at THRESHOLD.
2996
2997 The deadband must only damp active RSSI ping-pong; a weak owner that goes
2998 silent and is taken over on the stale path must not then be charged the
2999 deadband to recover, which would leave the rightful owner stuck on a weaker
3000 proxy (the regression #570/#580 guard against). Only an active RSSI switch
3001 records a demotion.
3002 """
3003 manager = get_manager()
3004 address = "44:44:33:11:23:58"
3005 start = 50.0
3006 owner = generate_ble_device(address, "owner_hci0")
3007 owner_adv = generate_advertisement_data(
3008 local_name="owner_hci0", service_uuids=[], rssi=-90
3009 )
3010 inject_advertisement_with_time_and_source(
3011 owner, owner_adv, start, HCI0_SOURCE_ADDRESS
3012 )
3013 manager.async_set_fallback_availability_interval(address, 10)
3014
3015 # Weak owner goes silent; a comparable (weaker) scanner takes over on
3016 # the stale path once the roam gate elapsed, not the active RSSI path.
3017 comparable = generate_ble_device(address, "comparable_hci1")
3018 comparable_adv = generate_advertisement_data(
3019 local_name="comparable_hci1", service_uuids=[], rssi=-95
3020 )
3021 inject_advertisement_with_time_and_source(
3022 comparable, comparable_adv, start + 23, HCI1_SOURCE_ADDRESS
3023 )
3024 assert manager.async_ble_device_from_address(address, True) is comparable
3025 # The stale handoff is not an RSSI-path switch, so no reclaim penalty is set.
3026 assert address not in manager._demoted_sources
3027
3028
3029 @pytest.mark.usefixtures("enable_bluetooth")
3030 @pytest.mark.asyncio
3031 async def test_rssi_deadband_connectable_recheck_records_no_demotion(
3032 register_hci0_scanner: None,
3033 register_hci1_scanner: None,
3034 ) -> None:
3035 """
3036 A connectable re-check switch does not record an all-history demotion.
3037
3038 When the best (all-history) advertisement stays put but the connectable
3039 history switches sources on RSSI, that switch must not write to
3040 _demoted_sources; it is not an all-history ownership change, so a future
3041 challenger of the all-history owner is not wrongly treated as a reclaim.
3042 """
3043 manager = get_manager()
3044 address = "44:44:33:11:23:59"
3045 now = 50.0
3046 # hci1 owns the best (all-history) path with a strong non-connectable adv.
3047 best = generate_ble_device(address, "best_hci1")
3048 inject_advertisement_with_time_and_source_connectable(
3049 best, _rssi_adv(-30), now, HCI1_SOURCE_ADDRESS, False
3050 )
3051 # hci0 is the only connectable path, but weak.
3052 weak_conn = generate_ble_device(address, "weak_conn_hci0")
3053 inject_advertisement_with_time_and_source_connectable(
3054 weak_conn, _rssi_adv(-90), now + 1, HCI0_SOURCE_ADDRESS, True
3055 )
3056 assert manager.async_ble_device_from_address(address, True) is weak_conn
3057
3058 # A third source sends a much stronger connectable adv: it loses the
3059 # all-history compare to hci1 but wins the connectable re-check over hci0.
3060 strong_conn = generate_ble_device(address, "strong_conn_hci2")
3061 inject_advertisement_with_time_and_source_connectable(
3062 strong_conn, _rssi_adv(-50), now + 2, "hci2", True
3063 )
3064 # all-history owner unchanged; connectable history switched to the new path.
3065 assert manager.async_ble_device_from_address(address, False) is best
3066 assert manager.async_ble_device_from_address(address, True) is strong_conn
3067 # The connectable-only switch records no all-history demotion.
3068 assert address not in manager._demoted_sources
3069
3070
3071 @pytest.mark.usefixtures("enable_bluetooth")
3072 @pytest.mark.asyncio
3073 async def test_switching_adapters_based_on_rssi_connectable_to_non_connectable(
3074 register_hci0_scanner: None,
3075 register_hci1_scanner: None,
3076 ) -> None:
3077 """Test switching adapters based on rssi from connectable to non connectable."""
3078 address = "44:44:33:11:23:45"
3079 now = time.monotonic()
3080 switchbot_device_poor_signal = generate_ble_device(address, "wohand_poor_signal")
3081 switchbot_adv_poor_signal = generate_advertisement_data(
3082 local_name="wohand_poor_signal", service_uuids=[], rssi=-100
3083 )
3084 inject_advertisement_with_time_and_source_connectable(
3085 switchbot_device_poor_signal,
3086 switchbot_adv_poor_signal,
3087 now,
3088 HCI0_SOURCE_ADDRESS,
3089 True,
3090 )
3091
3092 assert (
3093 get_manager().async_ble_device_from_address(address, False)
3094 is switchbot_device_poor_signal
3095 )
3096 assert (
3097 get_manager().async_ble_device_from_address(address, True)
3098 is switchbot_device_poor_signal
3099 )
3100 switchbot_device_good_signal = generate_ble_device(address, "wohand_good_signal")
3101 switchbot_adv_good_signal = generate_advertisement_data(
3102 local_name="wohand_good_signal", service_uuids=[], rssi=-60
3103 )
3104 inject_advertisement_with_time_and_source_connectable(
3105 switchbot_device_good_signal,
3106 switchbot_adv_good_signal,
3107 now,
3108 "hci1",
3109 False,
3110 )
3111
3112 assert (
3113 get_manager().async_ble_device_from_address(address, False)
3114 is switchbot_device_good_signal
3115 )
3116 assert (
3117 get_manager().async_ble_device_from_address(address, True)
3118 is switchbot_device_poor_signal
3119 )
3120 inject_advertisement_with_time_and_source_connectable(
3121 switchbot_device_good_signal,
3122 switchbot_adv_poor_signal,
3123 now,
3124 "hci0",
3125 False,
3126 )
3127 assert (
3128 get_manager().async_ble_device_from_address(address, False)
3129 is switchbot_device_good_signal
3130 )
3131 assert (
3132 get_manager().async_ble_device_from_address(address, True)
3133 is switchbot_device_poor_signal
3134 )
3135 switchbot_device_excellent_signal = generate_ble_device(
3136 address, "wohand_excellent_signal"
3137 )
3138 switchbot_adv_excellent_signal = generate_advertisement_data(
3139 local_name="wohand_excellent_signal", service_uuids=[], rssi=-25
3140 )
3141
3142 inject_advertisement_with_time_and_source_connectable(
3143 switchbot_device_excellent_signal,
3144 switchbot_adv_excellent_signal,
3145 now,
3146 "hci2",
3147 False,
3148 )
3149 assert (
3150 get_manager().async_ble_device_from_address(address, False)
3151 is switchbot_device_excellent_signal
3152 )
3153 assert (
3154 get_manager().async_ble_device_from_address(address, True)
3155 is switchbot_device_poor_signal
3156 )
3157
3158
3159 @pytest.mark.usefixtures("enable_bluetooth")
3160 @pytest.mark.asyncio
3161 async def test_connectable_advertisement_can_be_retrieved_best_path_is_non_connectable(
3162 register_hci0_scanner: None,
3163 register_hci1_scanner: None,
3164 ) -> None:
3165 """
3166 Test we can still get a connectable BLEDevice when the best path is non-connectable.
3167
3168 In this case the device is closer to a non-connectable scanner, but the
3169 at least one connectable scanner has the device in range.
3170 """
3171 address = "44:44:33:11:23:45"
3172 now = time.monotonic()
3173 switchbot_device_good_signal = generate_ble_device(address, "wohand_good_signal")
3174 switchbot_adv_good_signal = generate_advertisement_data(
3175 local_name="wohand_good_signal", service_uuids=[], rssi=-60
3176 )
3177 inject_advertisement_with_time_and_source_connectable(
3178 switchbot_device_good_signal,
3179 switchbot_adv_good_signal,
3180 now,
3181 HCI1_SOURCE_ADDRESS,
3182 False,
3183 )
3184
3185 assert (
3186 get_manager().async_ble_device_from_address(address, False)
3187 is switchbot_device_good_signal
3188 )
3189 assert get_manager().async_ble_device_from_address(address, True) is None
3190
3191 switchbot_device_poor_signal = generate_ble_device(address, "wohand_poor_signal")
3192 switchbot_adv_poor_signal = generate_advertisement_data(
3193 local_name="wohand_poor_signal", service_uuids=[], rssi=-100
3194 )
3195 inject_advertisement_with_time_and_source_connectable(
3196 switchbot_device_poor_signal,
3197 switchbot_adv_poor_signal,
3198 now,
3199 HCI0_SOURCE_ADDRESS,
3200 True,
3201 )
3202
3203 assert (
3204 get_manager().async_ble_device_from_address(address, False)
3205 is switchbot_device_good_signal
3206 )
3207 assert (
3208 get_manager().async_ble_device_from_address(address, True)
3209 is switchbot_device_poor_signal
3210 )
3211
3212
3213 @pytest.mark.usefixtures("enable_bluetooth")
3214 @pytest.mark.asyncio
3215 async def test_switching_adapters_when_one_goes_away(
3216 register_hci0_scanner: None,
3217 ) -> None:
3218 """Test switching adapters when one goes away."""
3219 cancel_hci2 = get_manager().async_register_scanner(FakeScanner("hci2", "hci2"))
3220
3221 address = "44:44:33:11:23:45"
3222
3223 switchbot_device_good_signal = generate_ble_device(address, "wohand_good_signal")
3224 switchbot_adv_good_signal = generate_advertisement_data(
3225 local_name="wohand_good_signal", service_uuids=[], rssi=-60
3226 )
3227 inject_advertisement_with_source(
3228 switchbot_device_good_signal, switchbot_adv_good_signal, "hci2"
3229 )
3230
3231 assert (
3232 get_manager().async_ble_device_from_address(address, True)
3233 is switchbot_device_good_signal
3234 )
3235
3236 switchbot_device_poor_signal = generate_ble_device(address, "wohand_poor_signal")
3237 switchbot_adv_poor_signal = generate_advertisement_data(
3238 local_name="wohand_poor_signal", service_uuids=[], rssi=-100
3239 )
3240 inject_advertisement_with_source(
3241 switchbot_device_poor_signal,
3242 switchbot_adv_poor_signal,
3243 HCI0_SOURCE_ADDRESS,
3244 )
3245
3246 # We want to prefer the good signal when we have options
3247 assert (
3248 get_manager().async_ble_device_from_address(address, True)
3249 is switchbot_device_good_signal
3250 )
3251
3252 cancel_hci2()
3253
3254 inject_advertisement_with_source(
3255 switchbot_device_poor_signal,
3256 switchbot_adv_poor_signal,
3257 HCI0_SOURCE_ADDRESS,
3258 )
3259
3260 # Now that hci2 is gone, we should prefer the poor signal
3261 # since no poor signal is better than no signal
3262 assert (
3263 get_manager().async_ble_device_from_address(address, True)
3264 is switchbot_device_poor_signal
3265 )
3266
3267
3268 @pytest.mark.usefixtures("enable_bluetooth")
3269 @pytest.mark.asyncio
3270 async def test_switching_adapters_when_one_stop_scanning(
3271 register_hci0_scanner: None,
3272 ) -> None:
3273 """Test switching adapters when stops scanning."""
3274 hci2_scanner = FakeScanner("hci2", "hci2")
3275 cancel_hci2 = get_manager().async_register_scanner(hci2_scanner)
3276
3277 address = "44:44:33:11:23:45"
3278
3279 switchbot_device_good_signal = generate_ble_device(address, "wohand_good_signal")
3280 switchbot_adv_good_signal = generate_advertisement_data(
3281 local_name="wohand_good_signal", service_uuids=[], rssi=-60
3282 )
3283 inject_advertisement_with_source(
3284 switchbot_device_good_signal, switchbot_adv_good_signal, "hci2"
3285 )
3286
3287 assert (
3288 get_manager().async_ble_device_from_address(address, True)
3289 is switchbot_device_good_signal
3290 )
3291
3292 switchbot_device_poor_signal = generate_ble_device(address, "wohand_poor_signal")
3293 switchbot_adv_poor_signal = generate_advertisement_data(
3294 local_name="wohand_poor_signal", service_uuids=[], rssi=-100
3295 )
3296 inject_advertisement_with_source(
3297 switchbot_device_poor_signal,
3298 switchbot_adv_poor_signal,
3299 HCI0_SOURCE_ADDRESS,
3300 )
3301
3302 # We want to prefer the good signal when we have options
3303 assert (
3304 get_manager().async_ble_device_from_address(address, True)
3305 is switchbot_device_good_signal
3306 )
3307
3308 hci2_scanner.scanning = False
3309
3310 inject_advertisement_with_source(
3311 switchbot_device_poor_signal,
3312 switchbot_adv_poor_signal,
3313 HCI0_SOURCE_ADDRESS,
3314 )
3315
3316 # Now that hci2 has stopped scanning, we should prefer the poor signal
3317 # since poor signal is better than no signal
3318 assert (
3319 get_manager().async_ble_device_from_address(address, True)
3320 is switchbot_device_poor_signal
3321 )
3322
3323 cancel_hci2()
3324
3325
3326 @pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
3327 @pytest.mark.asyncio
3328 async def test_set_fallback_interval_small() -> None:
3329 """Test we can set the fallback advertisement interval."""
3330 assert (
3331 get_manager().async_get_fallback_availability_interval("44:44:33:11:23:12")
3332 is None
3333 )
3334
3335 get_manager().async_set_fallback_availability_interval("44:44:33:11:23:12", 2.0)
3336 assert (
3337 get_manager().async_get_fallback_availability_interval("44:44:33:11:23:12")
3338 == 2.0
3339 )
3340
3341 start_monotonic_time = time.monotonic()
3342 switchbot_device = generate_ble_device("44:44:33:11:23:12", "wohand")
3343 switchbot_adv = generate_advertisement_data(
3344 local_name="wohand", service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]
3345 )
3346 switchbot_device_went_unavailable = False
3347
3348 inject_advertisement_with_time_and_source(
3349 switchbot_device,
3350 switchbot_adv,
3351 start_monotonic_time,
3352 SOURCE_LOCAL,
3353 )
3354
3355 def _switchbot_device_unavailable_callback(
3356 _address: BluetoothServiceInfoBleak,
3357 ) -> None:
3358 """Switchbot device unavailable callback."""
3359 nonlocal switchbot_device_went_unavailable
3360 switchbot_device_went_unavailable = True
3361
3362 assert (
3363 get_manager().async_get_learned_advertising_interval("44:44:33:11:23:12")
3364 is None
3365 )
3366
3367 switchbot_device_unavailable_cancel = get_manager().async_track_unavailable(
3368 _switchbot_device_unavailable_callback,
3369 switchbot_device.address,
3370 connectable=False,
3371 )
3372
3373 monotonic_now = start_monotonic_time + 2
3374 with patch_bluetooth_time(
3375 monotonic_now + UNAVAILABLE_TRACK_SECONDS,
3376 ):
3377 async_fire_time_changed(utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS))
3378 await asyncio.sleep(0)
3379
3380 assert switchbot_device_went_unavailable is True
3381 switchbot_device_unavailable_cancel()
3382
3383 # We should forget fallback interval after it expires
3384 assert (
3385 get_manager().async_get_fallback_availability_interval("44:44:33:11:23:12")
3386 is None
3387 )
3388
3389
3390 @pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
3391 @pytest.mark.asyncio
3392 async def test_set_fallback_interval_big() -> None:
3393 """Test we can set the fallback advertisement interval."""
3394 assert (
3395 get_manager().async_get_fallback_availability_interval("44:44:33:11:23:12")
3396 is None
3397 )
3398
3399 # Force the interval to be really big and check it doesn't expire using
3400 # the default timeout of 900 seconds.
3401
3402 get_manager().async_set_fallback_availability_interval(
3403 "44:44:33:11:23:12", 604800.0
3404 )
3405 assert (
3406 get_manager().async_get_fallback_availability_interval("44:44:33:11:23:12")
3407 == 604800.0
3408 )
3409
3410 start_monotonic_time = time.monotonic()
3411 switchbot_device = generate_ble_device("44:44:33:11:23:12", "wohand")
3412 switchbot_adv = generate_advertisement_data(
3413 local_name="wohand", service_uuids=["cba20d00-224d-11e6-9fb8-0002a5d5c51b"]
3414 )
3415 switchbot_device_went_unavailable = False
3416
3417 inject_advertisement_with_time_and_source(
3418 switchbot_device,
3419 switchbot_adv,
3420 start_monotonic_time,
3421 SOURCE_LOCAL,
3422 )
3423
3424 def _switchbot_device_unavailable_callback(
3425 _address: BluetoothServiceInfoBleak,
3426 ) -> None:
3427 """Switchbot device unavailable callback."""
3428 nonlocal switchbot_device_went_unavailable
3429 switchbot_device_went_unavailable = True
3430
3431 assert (
3432 get_manager().async_get_learned_advertising_interval("44:44:33:11:23:12")
3433 is None
3434 )
3435
3436 switchbot_device_unavailable_cancel = get_manager().async_track_unavailable(
3437 _switchbot_device_unavailable_callback,
3438 switchbot_device.address,
3439 connectable=False,
3440 )
3441
3442 # Check that device hasn't expired after a day
3443
3444 monotonic_now = start_monotonic_time + 86400
3445 with patch_bluetooth_time(
3446 monotonic_now + UNAVAILABLE_TRACK_SECONDS,
3447 ):
3448 async_fire_time_changed(utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS))
3449 await asyncio.sleep(0)
3450
3451 assert switchbot_device_went_unavailable is False
3452
3453 # Try again after it has expired
3454
3455 monotonic_now = start_monotonic_time + 604800
3456 with patch_bluetooth_time(
3457 monotonic_now + UNAVAILABLE_TRACK_SECONDS,
3458 ):
3459 async_fire_time_changed(utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS))
3460 await asyncio.sleep(0)
3461
3462 assert switchbot_device_went_unavailable is True
3463
3464 switchbot_device_unavailable_cancel() # type: ignore[unreachable]
3465
3466 # We should forget fallback interval after it expires
3467 assert (
3468 get_manager().async_get_fallback_availability_interval("44:44:33:11:23:12")
3469 is None
3470 )
3471
3472
3473 @pytest.mark.asyncio
3474 async def test_subclassing_bluetooth_manager(caplog: pytest.LogCaptureFixture) -> None:
3475 """Test subclassing BluetoothManager."""
3476 slot_manager = BleakSlotManager()
3477 bluetooth_adapters = FakeBluetoothAdapters()
3478
3479 class TestBluetoothManager(BluetoothManager):
3480 """
3481 Test class for BluetoothManager.
3482
3483 This class implements _discover_service_info.
3484 """
3485
3486 def _discover_service_info(
3487 self, service_info: BluetoothServiceInfoBleak
3488 ) -> None:
3489 """
3490 Discover a new service info.
3491
3492 This method is intended to be overridden by subclasses.
3493 """
3494
3495 TestBluetoothManager(bluetooth_adapters, slot_manager)
3496 assert "does not implement _discover_service_info" not in caplog.text
3497
3498 class TestBluetoothManager2(BluetoothManager):
3499 """
3500 Test class for BluetoothManager.
3501
3502 This class does not implement _discover_service_info.
3503 """
3504
3505 TestBluetoothManager2(bluetooth_adapters, slot_manager)
3506 assert "does not implement _discover_service_info" in caplog.text
3507
3508
3509 @pytest.mark.asyncio
3510 async def test_is_operating_degraded_on_linux_with_mgmt() -> None:
3511 """Test is_operating_degraded returns False on Linux with mgmt control."""
3512 mock_bluetooth_adapters = FakeBluetoothAdapters()
3513 manager = BluetoothManager(
3514 mock_bluetooth_adapters,
3515 slot_manager=Mock(),
3516 )
3517
3518 with (
3519 patch("habluetooth.manager.IS_LINUX", True),
3520 patch.object(manager, "_mgmt_ctl", Mock()),
3521 ):
3522 # Mock mgmt_ctl being available
3523 assert manager.is_operating_degraded() is False
3524
3525
3526 @pytest.mark.asyncio
3527 async def test_is_operating_degraded_on_linux_without_mgmt() -> None:
3528 """Test is_operating_degraded returns True on Linux without mgmt control."""
3529 mock_bluetooth_adapters = FakeBluetoothAdapters()
3530 manager = BluetoothManager(
3531 mock_bluetooth_adapters,
3532 slot_manager=Mock(),
3533 )
3534
3535 with patch("habluetooth.manager.IS_LINUX", True):
3536 # mgmt_ctl is None by default
3537 assert manager._mgmt_ctl is None
3538 assert manager.is_operating_degraded() is True
3539
3540
3541 @pytest.mark.asyncio
3542 async def test_is_operating_degraded_on_non_linux() -> None:
3543 """Test is_operating_degraded returns False on non-Linux systems."""
3544 mock_bluetooth_adapters = FakeBluetoothAdapters()
3545 manager = BluetoothManager(
3546 mock_bluetooth_adapters,
3547 slot_manager=Mock(),
3548 )
3549
3550 with patch("habluetooth.manager.IS_LINUX", False):
3551 # Should return False regardless of mgmt_ctl state
3552 assert manager.is_operating_degraded() is False
3553
3554 # Even with mgmt_ctl set
3555 manager._mgmt_ctl = Mock()
3556 assert manager.is_operating_degraded() is False
3557
3558
3559 @pytest.mark.asyncio
3560 async def test_is_operating_degraded_after_permission_error() -> None:
3561 """Test is_operating_degraded after mgmt setup fails with permission error."""
3562 mock_bluetooth_adapters = FakeBluetoothAdapters()
3563 manager = BluetoothManager(
3564 mock_bluetooth_adapters,
3565 slot_manager=Mock(),
3566 )
3567
3568 with (
3569 patch("habluetooth.manager.IS_LINUX", True),
3570 patch("habluetooth.manager.MGMTBluetoothCtl") as mock_mgmt_class,
3571 ):
3572 # Make setup fail with permission error
3573 mock_mgmt_instance = Mock()
3574 mock_mgmt_instance.setup = AsyncMock(
3575 side_effect=PermissionError("No permission")
3576 )
3577 mock_mgmt_class.return_value = mock_mgmt_instance
3578
3579 # Setup should handle the error and set mgmt_ctl to None
3580 await manager.async_setup()
3581
3582 # Should be in degraded mode
3583 assert manager._mgmt_ctl is None
3584 assert manager.is_operating_degraded() is True
3585
3586
3587 @pytest.mark.asyncio
3588 @pytest.mark.usefixtures("enable_bluetooth")
3589 async def test_async_scanner_count_includes_non_connectable(
3590 register_hci0_scanner: None,
3591 register_non_connectable_scanner: None,
3592 ) -> None:
3593 """Connectable count excludes non-connectable; full count includes both."""
3594 manager = get_manager()
3595 assert manager.async_scanner_count(connectable=True) == 1
3596 assert manager.async_scanner_count(connectable=False) == 2
3597
3598
3599 @pytest.mark.asyncio
3600 @pytest.mark.usefixtures("enable_bluetooth")
3601 async def test_async_address_present_non_connectable_history(
3602 register_non_connectable_scanner: None,
3603 ) -> None:
3604 """async_address_present(connectable=False) reads the all-history map."""
3605 manager = get_manager()
3606 address = "44:44:33:11:23:99"
3607 device = generate_ble_device(address, "wohand")
3608 adv = generate_advertisement_data(local_name="wohand", service_uuids=[])
3609 inject_advertisement_with_time_and_source_connectable(
3610 device, adv, time.monotonic(), "AA:BB:CC:DD:EE:FF", False
3611 )
3612 assert manager.async_address_present(address, connectable=False) is True
3613 assert manager.async_address_present(address, connectable=True) is False
3614 missing = "00:00:00:00:00:00"
3615 assert manager.async_address_present(missing, connectable=False) is False
3616
3617
3618 @pytest.mark.asyncio
3619 async def test_async_track_unavailable_connectable_branch() -> None:
3620 """connectable=True routes the callback to the connectable callback map."""
3621 manager = get_manager()
3622
3623 def _cb(_info: BluetoothServiceInfoBleak) -> None:
3624 return
3625
3626 address = "11:22:33:44:55:66"
3627 cancel = manager.async_track_unavailable(_cb, address, connectable=True)
3628 try:
3629 assert _cb in manager._connectable_unavailable_callbacks[address]
3630 assert address not in manager._unavailable_callbacks
3631 finally:
3632 cancel()
3633 assert address not in manager._connectable_unavailable_callbacks
3634
3635
3636 @pytest.mark.asyncio
3637 async def test_async_current_allocations_unknown_source_returns_empty() -> None:
3638 """Querying an unknown source returns [] rather than None."""
3639 manager = get_manager()
3640 assert manager.async_current_allocations("not-a-real-source") == []
3641
3642
3643 @pytest.mark.asyncio
3644 async def test_async_recover_failed_adapters_skips_when_lock_held() -> None:
3645 """If recovery is already in flight, a concurrent call is a no-op."""
3646 manager = get_manager()
3647 with patch.object(
3648 manager, "async_get_bluetooth_adapters", new=AsyncMock()
3649 ) as mock_get:
3650 await manager._recovery_lock.acquire()
3651 try:
3652 await manager._async_recover_failed_adapters()
3653 finally:
3654 manager._recovery_lock.release()
3655 mock_get.assert_not_called()
3656
3657
3658 @pytest.mark.asyncio
3659 async def test_async_get_bluetooth_adapters_cached_false_triggers_refresh() -> None:
3660 """cached=False forces a refresh of the underlying adapter source."""
3661 manager = get_manager()
3662 assert manager._bluetooth_adapters is not None
3663 with patch.object(
3664 manager._bluetooth_adapters, "refresh", new=AsyncMock()
3665 ) as mock_refresh:
3666 await manager.async_get_bluetooth_adapters(cached=False)
3667 mock_refresh.assert_awaited_once()
3668
3669
3670 @pytest.mark.asyncio
3671 async def test_async_refresh_adapters_propagates_exception_to_waiters() -> None:
3672 """Concurrent callers must see the refresh exception, not silent success."""
3673 manager = get_manager()
3674 assert manager._bluetooth_adapters is not None
3675 refresh_started = asyncio.Event()
3676 release_refresh = asyncio.Event()
3677
3678 async def slow_failing_refresh() -> None:
3679 refresh_started.set()
3680 await release_refresh.wait()
3681 msg = "boom"
3682 raise RuntimeError(msg)
3683
3684 with patch.object(manager._bluetooth_adapters, "refresh", new=slow_failing_refresh):
3685 leader = asyncio.create_task(manager._async_refresh_adapters())
3686 await refresh_started.wait()
3687 waiter_a = asyncio.create_task(manager._async_refresh_adapters())
3688 waiter_b = asyncio.create_task(manager._async_refresh_adapters())
3689 # Yield so waiters register on the shared future.
3690 await asyncio.sleep(0)
3691 release_refresh.set()
3692 with pytest.raises(RuntimeError, match="boom"):
3693 await leader
3694 with pytest.raises(RuntimeError, match="boom"):
3695 await waiter_a
3696 with pytest.raises(RuntimeError, match="boom"):
3697 await waiter_b
3698 # Shared future must be cleared so the next call refreshes again.
3699 assert manager._adapter_refresh_future is None
3700
3701
3702 @pytest.mark.asyncio
3703 async def test_async_refresh_adapters_success_resolves_waiters() -> None:
3704 """Concurrent callers all see success and share the same refresh call."""
3705 manager = get_manager()
3706 assert manager._bluetooth_adapters is not None
3707 refresh_started = asyncio.Event()
3708 release_refresh = asyncio.Event()
3709 call_count = 0
3710
3711 async def slow_refresh() -> None:
3712 nonlocal call_count
3713 call_count += 1
3714 refresh_started.set()
3715 await release_refresh.wait()
3716
3717 with patch.object(manager._bluetooth_adapters, "refresh", new=slow_refresh):
3718 leader = asyncio.create_task(manager._async_refresh_adapters())
3719 await refresh_started.wait()
3720 waiter_a = asyncio.create_task(manager._async_refresh_adapters())
3721 waiter_b = asyncio.create_task(manager._async_refresh_adapters())
3722 await asyncio.sleep(0)
3723 release_refresh.set()
3724 await leader
3725 await waiter_a
3726 await waiter_b
3727 assert call_count == 1
3728 assert manager._adapter_refresh_future is None
3729
3730
3731 @pytest.mark.asyncio
3732 async def test_async_refresh_adapters_leader_cancellation_does_not_silently_succeed(
3733 caplog: pytest.LogCaptureFixture,
3734 ) -> None:
3735 """Leader cancellation must not let waiters proceed as if refresh succeeded."""
3736 manager = get_manager()
3737 assert manager._bluetooth_adapters is not None
3738 refresh_started = asyncio.Event()
3739
3740 async def hanging_refresh() -> None:
3741 refresh_started.set()
3742 await asyncio.Event().wait() # never resolves
3743
3744 with patch.object(manager._bluetooth_adapters, "refresh", new=hanging_refresh):
3745 leader = asyncio.create_task(manager._async_refresh_adapters())
3746 await refresh_started.wait()
3747 waiter = asyncio.create_task(manager._async_refresh_adapters())
3748 await asyncio.sleep(0)
3749 leader.cancel()
3750 with pytest.raises(asyncio.CancelledError):
3751 await leader
3752 # Waiter must observe a CancelledError, not silently complete.
3753 with pytest.raises(asyncio.CancelledError):
3754 await waiter
3755 assert manager._adapter_refresh_future is None
3756
3757
3758 @pytest.mark.asyncio
3759 async def test_async_refresh_adapters_waiter_cancellation_does_not_break_leader() -> (
3760 None
3761 ):
3762 """Cancelling one waiter must not strand the leader or other siblings."""
3763 manager = get_manager()
3764 assert manager._bluetooth_adapters is not None
3765 refresh_started = asyncio.Event()
3766 release_refresh = asyncio.Event()
3767
3768 async def slow_refresh() -> None:
3769 refresh_started.set()
3770 await release_refresh.wait()
3771
3772 with patch.object(manager._bluetooth_adapters, "refresh", new=slow_refresh):
3773 leader = asyncio.create_task(manager._async_refresh_adapters())
3774 await refresh_started.wait()
3775 waiter_a = asyncio.create_task(manager._async_refresh_adapters())
3776 waiter_b = asyncio.create_task(manager._async_refresh_adapters())
3777 await asyncio.sleep(0)
3778 waiter_a.cancel()
3779 with pytest.raises(asyncio.CancelledError):
3780 await waiter_a
3781 # Leader and surviving waiter must still complete normally.
3782 release_refresh.set()
3783 await leader
3784 await waiter_b
3785 assert manager._adapter_refresh_future is None
3786
3787
3788 @pytest.mark.asyncio
3789 async def test_async_refresh_adapters_adapters_property_failure_propagates() -> None:
3790 """Property access failure after refresh() must not strand waiters."""
3791 manager = get_manager()
3792 assert manager._bluetooth_adapters is not None
3793 refresh_started = asyncio.Event()
3794 release_refresh = asyncio.Event()
3795
3796 async def slow_refresh() -> None:
3797 refresh_started.set()
3798 await release_refresh.wait()
3799
3800 failing_adapters = PropertyMock(side_effect=RuntimeError("adapters boom"))
3801 with (
3802 patch.object(manager._bluetooth_adapters, "refresh", new=slow_refresh),
3803 patch.object(type(manager._bluetooth_adapters), "adapters", failing_adapters),
3804 ):
3805 leader = asyncio.create_task(manager._async_refresh_adapters())
3806 await refresh_started.wait()
3807 waiter = asyncio.create_task(manager._async_refresh_adapters())
3808 await asyncio.sleep(0)
3809 release_refresh.set()
3810 with pytest.raises(RuntimeError, match="adapters boom"):
3811 await leader
3812 with pytest.raises(RuntimeError, match="adapters boom"):
3813 await waiter
3814 assert manager._adapter_refresh_future is None
3815
3816
3817 @pytest.mark.asyncio
3818 async def test_async_refresh_adapters_recovers_after_prior_failure() -> None:
3819 """Sequential call after a failed refresh must start fresh and succeed."""
3820 manager = get_manager()
3821 assert manager._bluetooth_adapters is not None
3822 call_count = 0
3823
3824 async def flaky_refresh() -> None:
3825 nonlocal call_count
3826 call_count += 1
3827 if call_count == 1:
3828 msg = "first boom"
3829 raise RuntimeError(msg)
3830
3831 with patch.object(manager._bluetooth_adapters, "refresh", new=flaky_refresh):
3832 with pytest.raises(RuntimeError, match="first boom"):
3833 await manager._async_refresh_adapters()
3834 assert manager._adapter_refresh_future is None
3835 # Second call must start a fresh refresh, not reuse stale future state.
3836 await manager._async_refresh_adapters()
3837 assert call_count == 2
3838 assert manager._adapter_refresh_future is None
3839
3840
3841 @pytest.mark.asyncio
3842 async def test_address_reachability_diagnostics_connectable() -> None:
3843 """A connectable device in range reports its connectable scanner."""
3844 manager = get_manager()
3845 address = "44:44:33:11:23:45"
3846 scanner = InjectableRemoteScanner(
3847 "AA:BB:CC:DD:EE:FF", "Living Room Proxy", None, True
3848 )
3849 cancel = manager.async_register_scanner(scanner)
3850 device = generate_ble_device(address, "wohand")
3851 adv = generate_advertisement_data(local_name="wohand", rssi=-50)
3852 scanner.inject_advertisement(device, adv)
3853
3854 diag = manager.async_address_reachability_diagnostics(
3855 address, BluetoothReachabilityIntent.CONNECTION
3856 )
3857 # The address is intentionally not embedded; callers already have it.
3858 assert address not in diag
3859 assert "in connectable history" in diag
3860 assert "1 scanner(s) registered, 1 scanning, 1 connectable" in diag
3861 assert "Living Room Proxy (AA:BB:CC:DD:EE:FF) (connectable=True, rssi=-50" in diag
3862 # The "via" source resolves to the scanner name rather than a bare address.
3863 assert "last advertisement" in diag
3864 assert "via Living Room Proxy (AA:BB:CC:DD:EE:FF)" in diag
3865 cancel()
3866
3867
3868 @pytest.mark.asyncio
3869 async def test_address_reachability_diagnostics_non_connectable_only() -> None:
3870 """A device only seen by a non-connectable scanner has no connectable path."""
3871 manager = get_manager()
3872 address = "44:44:33:11:23:46"
3873 connectable = InjectableRemoteScanner("hci0", "hci0", None, True)
3874 cancel_c = manager.async_register_scanner(connectable)
3875 non_connectable = InjectableRemoteScanner("proxy", "proxy", None, False)
3876 cancel_n = manager.async_register_scanner(non_connectable)
3877 device = generate_ble_device(address, "wohand")
3878 adv = generate_advertisement_data(local_name="wohand", rssi=-70)
3879 non_connectable.inject_advertisement(device, adv)
3880
3881 diag = manager.async_address_reachability_diagnostics(
3882 address, BluetoothReachabilityIntent.CONNECTION
3883 )
3884 assert "only in non-connectable history (no connectable path)" in diag
3885 assert "seen by 1 scanner(s) but none with a connectable path" in diag
3886 assert "proxy (connectable=False, rssi=-70" in diag
3887 cancel_c()
3888 cancel_n()
3889
3890
3891 @pytest.mark.asyncio
3892 async def test_address_reachability_diagnostics_advertisement_intent() -> None:
3893 """An advertisement intent ignores connectable paths and slots."""
3894 manager = get_manager()
3895 address = "44:44:33:11:23:4a"
3896 non_connectable = InjectableRemoteScanner("proxy", "proxy", None, False)
3897 cancel = manager.async_register_scanner(non_connectable)
3898 device = generate_ble_device(address, "wohand")
3899 adv = generate_advertisement_data(local_name="wohand", rssi=-70)
3900 non_connectable.inject_advertisement(device, adv)
3901
3902 diag = manager.async_address_reachability_diagnostics(
3903 address, BluetoothReachabilityIntent.PASSIVE_ADVERTISEMENT
3904 )
3905 assert "advertising, seen by 1 scanner(s)" in diag
3906 assert "no connectable path" not in diag
3907 assert "slots" not in diag
3908 # ACTIVE_ADVERTISEMENT is treated the same as PASSIVE_ADVERTISEMENT for now.
3909 assert diag == manager.async_address_reachability_diagnostics(
3910 address, BluetoothReachabilityIntent.ACTIVE_ADVERTISEMENT
3911 )
3912 cancel()
3913
3914
3915 @pytest.mark.parametrize(
3916 "intent",
3917 [
3918 BluetoothReachabilityIntent.CONNECTION,
3919 BluetoothReachabilityIntent.PASSIVE_ADVERTISEMENT,
3920 BluetoothReachabilityIntent.ACTIVE_ADVERTISEMENT,
3921 ],
3922 )
3923 @pytest.mark.asyncio
3924 async def test_address_reachability_diagnostics_unknown(
3925 intent: BluetoothReachabilityIntent,
3926 ) -> None:
3927 """An address never seen reports as unknown for every intent."""
3928 manager = get_manager()
3929 diag = manager.async_address_reachability_diagnostics("44:44:33:11:23:47", intent)
3930 assert "unknown (never seen by any scanner)" in diag
3931
3932
3933 @pytest.mark.asyncio
3934 async def test_address_reachability_diagnostics_after_clearing_history() -> None:
3935 """A cleared address is reported as cleared, not as never seen."""
3936 manager = get_manager()
3937 address = "44:44:33:11:23:4b"
3938 scanner = InjectableRemoteScanner("proxy", "proxy", None, True)
3939 cancel = manager.async_register_scanner(scanner)
3940 device = generate_ble_device(address, "wohand")
3941 adv = generate_advertisement_data(local_name="wohand", rssi=-70)
3942 scanner.inject_advertisement(device, adv)
3943
3944 # Clearing empties the manager history but keeps the scanner record, so
3945 # the diagnostics must not claim no scanner has ever seen the address
3946 manager.async_clear_advertisement_history(address)
3947
3948 diag = manager.async_address_reachability_diagnostics(
3949 address, BluetoothReachabilityIntent.CONNECTION
3950 )
3951 assert "not in history (advertisement history was cleared)" in diag
3952 assert "never seen by any scanner" not in diag
3953 cancel()
3954
3955
3956 @pytest.mark.asyncio
3957 async def test_address_reachability_diagnostics_no_connectable_scanners() -> None:
3958 """With only a non-connectable scanner the connectable count is zero."""
3959 manager = get_manager()
3960 address = "44:44:33:11:23:48"
3961 non_connectable = InjectableRemoteScanner("proxy", "proxy", None, False)
3962 cancel = manager.async_register_scanner(non_connectable)
3963 device = generate_ble_device(address, "wohand")
3964 adv = generate_advertisement_data(local_name="wohand", rssi=-70)
3965 non_connectable.inject_advertisement(device, adv)
3966
3967 diag = manager.async_address_reachability_diagnostics(
3968 address, BluetoothReachabilityIntent.CONNECTION
3969 )
3970 assert "1 scanner(s) registered, 1 scanning, 0 connectable" in diag
3971 cancel()
3972
3973
3974 @pytest.mark.asyncio
3975 async def test_address_reachability_diagnostics_out_of_slots() -> None:
3976 """A connectable scanner with no free slots is reported as full."""
3977 manager = get_manager()
3978 address = "44:44:33:11:23:49"
3979 scanner = InjectableRemoteScanner("esphome_proxy", "esphome_proxy", None, True)
3980 cancel = manager.async_register_scanner(scanner)
3981 device = generate_ble_device(address, "wohand")
3982 adv = generate_advertisement_data(local_name="wohand", rssi=-50)
3983 scanner.inject_advertisement(device, adv)
3984
3985 with patch.object(
3986 scanner,
3987 "get_allocations",
3988 return_value=Allocations("esphome_proxy", 3, 0, []),
3989 ):
3990 diag = manager.async_address_reachability_diagnostics(
3991 address, BluetoothReachabilityIntent.CONNECTION
3992 )
3993 assert "connectable scanner(s) that report slot allocations are all full" in diag
3994 assert "slots=0/3" in diag
3995 cancel()
3996
3997
3998 @pytest.mark.asyncio
3999 async def test_address_reachability_diagnostics_in_history_no_scanner() -> None:
4000 """An address in history but cached by no scanner is not called advertising."""
4001 manager = get_manager()
4002 address = "44:44:33:11:23:4c"
4003 device = generate_ble_device(address, "wohand")
4004 adv = generate_advertisement_data(local_name="wohand", rssi=-70)
4005 # Injected from a source with no registered scanner; lands in history but
4006 # no scanner currently has it cached.
4007 inject_advertisement_with_source(device, adv, "ghost")
4008
4009 diag = manager.async_address_reachability_diagnostics(
4010 address, BluetoothReachabilityIntent.PASSIVE_ADVERTISEMENT
4011 )
4012 assert "previously seen but no scanner currently has it cached" in diag
4013 assert "advertising" not in diag
4014
4015
4016 @pytest.mark.asyncio
4017 async def test_address_reachability_diagnostics_connection_in_history_no_scanner() -> (
4018 None
4019 ):
4020 """A connect intent says the device is not in any discovered map."""
4021 manager = get_manager()
4022 address = "44:44:33:11:23:4d"
4023 device = generate_ble_device(address, "wohand")
4024 adv = generate_advertisement_data(local_name="wohand", rssi=-70)
4025 # In history but cached by no scanner: no connect path.
4026 inject_advertisement_with_source(device, adv, "ghost")
4027
4028 diag = manager.async_address_reachability_diagnostics(
4029 address, BluetoothReachabilityIntent.CONNECTION
4030 )
4031 assert "in connectable history" in diag
4032 assert "no scanner currently has it in its discovered devices" in diag
4033 assert "slot" not in diag
4034
4035
4036 @pytest.mark.asyncio
4037 async def test_address_reachability_diagnostics_all_scanners_connecting() -> None:
4038 """When every scanner is paused connecting, the device cannot be seen."""
4039 manager = get_manager()
4040 address = "44:44:33:11:23:4b"
4041 scanner = InjectableRemoteScanner("esphome_proxy", "esphome_proxy", None, True)
4042 cancel = manager.async_register_scanner(scanner)
4043
4044 with scanner.connecting():
4045 assert scanner.scanning is False
4046 diag = manager.async_address_reachability_diagnostics(
4047 address, BluetoothReachabilityIntent.CONNECTION
4048 )
4049 assert "1 scanner(s) registered, 0 scanning, 1 connectable" in diag
4050 assert "1 paused while connecting" in diag
4051 assert "no scanner is currently scanning" in diag
4052 assert "add more Bluetooth adapters or proxies" in diag
4053 cancel()
4054
4055
4056 @pytest.mark.asyncio
4057 async def test_address_reachability_diagnostics_scanner_stopped_not_connecting() -> (
4058 None
4059 ):
4060 """A stopped scanner (not connecting) reports no scanning without the advice."""
4061 manager = get_manager()
4062 scanner = InjectableRemoteScanner("esphome_proxy", "esphome_proxy", None, True)
4063 cancel = manager.async_register_scanner(scanner)
4064 scanner.scanning = False
4065
4066 diag = manager.async_address_reachability_diagnostics(
4067 "44:44:33:11:23:4d", BluetoothReachabilityIntent.CONNECTION
4068 )
4069 assert "1 scanner(s) registered, 0 scanning, 1 connectable" in diag
4070 assert "no scanner is currently scanning" in diag
4071 assert "paused while connecting" not in diag
4072 assert "add more Bluetooth adapters or proxies" not in diag
4073 cancel()
4074
4075
4076 @pytest.mark.asyncio
4077 @pytest.mark.usefixtures("enable_bluetooth")
4078 async def test_bleak_callback_exception_is_logged_and_isolated(
4079 register_hci0_scanner: None,
4080 caplog: pytest.LogCaptureFixture,
4081 ) -> None:
4082 """A raising bleak callback is caught and logged; siblings still fire."""
4083 manager = get_manager()
4084 address = "44:44:33:11:23:01"
4085 device = generate_ble_device(address, "wohand")
4086 adv = generate_advertisement_data(local_name="wohand", service_uuids=[], rssi=-40)
4087
4088 received: list[Any] = []
4089
4090 def _failing(_device: Any, _adv: Any) -> None:
4091 msg = "boom"
4092 raise ValueError(msg)
4093
4094 def _ok(_device: Any, _adv: Any) -> None:
4095 received.append(_device)
4096
4097 cancel_fail = manager.async_register_bleak_callback(_failing, {})
4098 cancel_ok = manager.async_register_bleak_callback(_ok, {})
4099 try:
4100 # A single advertisement dispatch fans out to both callbacks in one
4101 # loop; the failing one must not stop the ok one from firing.
4102 inject_advertisement_with_source(device, adv, "hci0")
4103 assert received # the ok callback fired despite the sibling raising
4104 assert "Error in callback" in caplog.text
4105 finally:
4106 cancel_fail()
4107 cancel_ok()
4108
4109
4110 @pytest.mark.asyncio
4111 async def test_supports_passive_scan_reflects_adapter_capability() -> None:
4112 """supports_passive_scan is True iff any adapter advertises passive scan."""
4113 manager = BluetoothManager(FakeBluetoothAdapters(), Mock())
4114 manager._adapters = {"hci0": {ADAPTER_PASSIVE_SCAN: False}}
4115 assert manager.supports_passive_scan is False
4116 manager._adapters = {
4117 "hci0": {ADAPTER_PASSIVE_SCAN: False},
4118 "hci1": {ADAPTER_PASSIVE_SCAN: True},
4119 }
4120 assert manager.supports_passive_scan is True
4121
4122
4123 @pytest.mark.asyncio
4124 async def test_supports_passive_scan_for_unknown_adapter_is_false() -> None:
4125 """supports_passive_scan_for fails closed for an adapter not in the cache."""
4126 manager = BluetoothManager(FakeBluetoothAdapters(), Mock())
4127 manager._adapters = {"hci0": {ADAPTER_PASSIVE_SCAN: True}}
4128 assert manager.supports_passive_scan_for("hci0") is True
4129 assert manager.supports_passive_scan_for("hci1") is False
4130
4131
4132 @pytest.mark.asyncio
4133 async def test_get_bluetooth_adapters_cached_with_empty_cache() -> None:
4134 """cached=True still populates when the adapter cache is empty (no refresh)."""
4135 adapters = FakeBluetoothAdapters()
4136 manager = BluetoothManager(adapters, Mock())
4137 with patch("habluetooth.manager.IS_LINUX", False):
4138 await manager.async_setup()
4139 try:
4140 manager._adapters = {}
4141 # cached=True with an empty cache repopulates straight from the backend
4142 # without taking the refresh path.
4143 with patch.object(adapters, "refresh", wraps=adapters.refresh) as spy:
4144 result = await manager.async_get_bluetooth_adapters(cached=True)
4145 spy.assert_not_called()
4146 assert result == adapters.adapters
4147 finally:
4148 manager.async_stop()
4149
4150
4151 @pytest.mark.asyncio
4152 async def test_get_adapter_from_address_refreshes_when_not_found() -> None:
4153 """A miss triggers a refresh, then a second lookup."""
4154 adapters = FakeBluetoothAdapters()
4155 manager = BluetoothManager(adapters, Mock())
4156 with patch("habluetooth.manager.IS_LINUX", False):
4157 await manager.async_setup()
4158 try:
4159 manager._adapters = {}
4160 # Unknown address: first lookup misses, a refresh runs, second lookup
4161 # still misses against the empty fake backend.
4162 with patch.object(adapters, "refresh", wraps=adapters.refresh) as spy:
4163 assert (
4164 await manager.async_get_adapter_from_address("00:00:00:00:00:09")
4165 is None
4166 )
4167 spy.assert_called_once() # the miss forced a refresh
4168
4169 # Known address resolves on the first lookup.
4170 manager._adapters = {"hci7": {ADAPTER_ADDRESS: "00:00:00:00:00:07"}}
4171 assert (
4172 await manager.async_get_adapter_from_address("00:00:00:00:00:07") == "hci7"
4173 )
4174 finally:
4175 manager.async_stop()
4176
4177
4178 @pytest.mark.asyncio
4179 async def test_async_setup_assigns_central_manager_when_unset() -> None:
4180 """async_setup claims the central singleton when it is unset."""
4181 original = CentralBluetoothManager.manager
4182 manager = BluetoothManager(FakeBluetoothAdapters(), Mock())
4183 try:
4184 CentralBluetoothManager.manager = None
4185 with patch("habluetooth.manager.IS_LINUX", False):
4186 await manager.async_setup()
4187 assert CentralBluetoothManager.manager is manager
4188 finally:
4189 CentralBluetoothManager.manager = original
4190 manager.async_stop()
4191
4192
4193 @pytest.mark.asyncio
4194 async def test_async_setup_returns_early_on_non_linux() -> None:
4195 """On non-Linux, setup skips mgmt control entirely."""
4196 manager = BluetoothManager(FakeBluetoothAdapters(), Mock())
4197 with patch("habluetooth.manager.IS_LINUX", False):
4198 await manager.async_setup()
4199 # Inside the non-Linux patch, setup returned before touching mgmt.
4200 assert manager._mgmt_ctl is None
4201 assert manager.is_operating_degraded() is False
4202 manager.async_stop()
4203
4204
4205 @pytest.mark.asyncio
4206 async def test_async_setup_handles_connection_error() -> None:
4207 """A CONNECTION_ERRORS failure during mgmt setup degrades gracefully."""
4208 manager = BluetoothManager(FakeBluetoothAdapters(), Mock())
4209 with (
4210 patch("habluetooth.manager.IS_LINUX", True),
4211 patch("habluetooth.manager.MGMTBluetoothCtl") as mock_mgmt_class,
4212 ):
4213 mock_instance = Mock()
4214 mock_instance.setup = AsyncMock(side_effect=OSError("no socket"))
4215 mock_mgmt_class.return_value = mock_instance
4216 await manager.async_setup()
4217 try:
4218 assert manager._mgmt_ctl is None
4219 assert manager.has_advertising_side_channel is False
4220 finally:
4221 manager.async_stop()
4222
4223
4224 @pytest.mark.asyncio
4225 async def test_async_stop_without_unavailable_tracking() -> None:
4226 """async_stop is a no-op for unavailable tracking when none is scheduled."""
4227 manager = BluetoothManager(FakeBluetoothAdapters(), Mock())
4228 with patch("habluetooth.manager.IS_LINUX", False):
4229 await manager.async_setup()
4230 manager._cancel_unavailable_tracking = None
4231 # Should not raise even though there is no tracking handle to cancel.
4232 manager.async_stop()
4233 assert manager.shutdown is True
4234
4235
4236 @pytest.mark.asyncio
4237 @pytest.mark.usefixtures("enable_bluetooth")
4238 async def test_unavailable_callback_exception_isolated(
4239 register_hci0_scanner: None,
4240 caplog: pytest.LogCaptureFixture,
4241 ) -> None:
4242 """A raising unavailable callback is logged; a sibling still fires."""
4243 manager = get_manager()
4244 address = "44:44:33:11:23:02"
4245 start = time.monotonic()
4246 device = generate_ble_device(address, "wohand")
4247 adv = generate_advertisement_data(local_name="wohand", service_uuids=[], rssi=-60)
4248 inject_advertisement_with_time_and_source_connectable(
4249 device, adv, start, HCI0_SOURCE_ADDRESS, False
4250 )
4251
4252 ok_calls: list[Any] = []
4253
4254 def _failing(_info: BluetoothServiceInfoBleak) -> None:
4255 msg = "boom"
4256 raise ValueError(msg)
4257
4258 def _ok(_info: BluetoothServiceInfoBleak) -> None:
4259 ok_calls.append(_info)
4260
4261 cancel_fail = manager.async_track_unavailable(_failing, address, connectable=False)
4262 cancel_ok = manager.async_track_unavailable(_ok, address, connectable=False)
4263 try:
4264 # Push the clock well past the fallback staleness window so the device
4265 # is considered unavailable.
4266 with patch_bluetooth_time(start + 100_000):
4267 manager._async_check_unavailable()
4268 assert len(ok_calls) == 1
4269 assert "Error in unavailable callback" in caplog.text
4270 finally:
4271 cancel_fail()
4272 cancel_ok()
4273
4274
4275 @pytest.mark.asyncio
4276 @pytest.mark.usefixtures("enable_bluetooth")
4277 async def test_remove_unavailable_callback_keeps_siblings(
4278 register_hci0_scanner: None,
4279 ) -> None:
4280 """Cancelling one unavailable callback leaves the address entry in place."""
4281 manager = get_manager()
4282 address = "44:44:33:11:23:03"
4283
4284 def _cb_a(_info: BluetoothServiceInfoBleak) -> None:
4285 return
4286
4287 def _cb_b(_info: BluetoothServiceInfoBleak) -> None:
4288 return
4289
4290 cancel_a = manager.async_track_unavailable(_cb_a, address, connectable=False)
4291 cancel_b = manager.async_track_unavailable(_cb_b, address, connectable=False)
4292 try:
4293 cancel_a()
4294 # One callback remains, so the address bucket is not deleted.
4295 assert address in manager._unavailable_callbacks
4296 assert _cb_b in manager._unavailable_callbacks[address]
4297 finally:
4298 cancel_b()
4299 assert address not in manager._unavailable_callbacks
4300
4301
4302 @pytest.mark.asyncio
4303 @pytest.mark.usefixtures("enable_bluetooth")
4304 async def test_unregister_source_callback_keeps_siblings(
4305 register_hci0_scanner: None,
4306 ) -> None:
4307 """Cancelling one source-keyed callback leaves the source bucket in place."""
4308 manager = get_manager()
4309
4310 def _cb_a(_change: HaScannerModeChange) -> None:
4311 return
4312
4313 def _cb_b(_change: HaScannerModeChange) -> None:
4314 return
4315
4316 cancel_a = manager.async_register_scanner_mode_change_callback(_cb_a, None)
4317 cancel_b = manager.async_register_scanner_mode_change_callback(_cb_b, None)
4318 try:
4319 cancel_a()
4320 # One callback remains under the None source, so it is not deleted.
4321 assert None in manager._scanner_mode_change_callbacks
4322 assert _cb_b in manager._scanner_mode_change_callbacks[None]
4323 finally:
4324 cancel_b()
4325 assert None not in manager._scanner_mode_change_callbacks
4326 # Cancelling again once the source bucket is gone is a no-op.
4327 cancel_b()
4328 assert None not in manager._scanner_mode_change_callbacks
4329
4330
4331 @pytest.mark.asyncio
4332 @pytest.mark.usefixtures("enable_bluetooth")
4333 async def test_should_keep_previous_adv_logs_when_debug_enabled(
4334 register_hci0_scanner: None,
4335 register_hci1_scanner: None,
4336 caplog: pytest.LogCaptureFixture,
4337 ) -> None:
4338 """With debug on, the keep-previous decision logs its switch reasons."""
4339 manager = get_manager()
4340 manager._debug = True
4341 address = "44:44:33:11:23:04"
4342 device = generate_ble_device(address, "wohand")
4343
4344 start = time.monotonic()
4345 weak = generate_advertisement_data(local_name="wohand", service_uuids=[], rssi=-40)
4346 inject_advertisement_with_time_and_source(device, weak, start, HCI0_SOURCE_ADDRESS)
4347
4348 with caplog.at_level(logging.DEBUG, logger="habluetooth.manager"):
4349 # A clearly stronger reading from a second still-scanning source wins
4350 # on RSSI (RSSI-switch debug branch).
4351 strong = generate_advertisement_data(
4352 local_name="wohand", service_uuids=[], rssi=-20
4353 )
4354 inject_advertisement_with_time_and_source(
4355 device, strong, start + 1, HCI1_SOURCE_ADDRESS
4356 )
4357 assert "new rssi" in caplog.text
4358
4359 caplog.clear()
4360 # A far-future reading makes the previous one stale, so any new
4361 # advertisement wins regardless of RSSI (stale-switch debug branch).
4362 inject_advertisement_with_time_and_source(
4363 device, weak, start + 100_000, HCI0_SOURCE_ADDRESS
4364 )
4365 assert "time elapsed" in caplog.text
4366
4367
4368 @pytest.mark.asyncio
4369 @pytest.mark.usefixtures("enable_bluetooth")
4370 async def test_non_connectable_advertisement_rejected_in_favour_of_previous(
4371 register_hci0_scanner: None,
4372 register_hci1_scanner: None,
4373 ) -> None:
4374 """A weaker non-connectable reading is rejected without re-adding history."""
4375 manager = get_manager()
4376 address = "44:44:33:11:23:05"
4377 device = generate_ble_device(address, "wohand")
4378 start = time.monotonic()
4379
4380 strong = generate_advertisement_data(
4381 local_name="wohand", service_uuids=[], rssi=-30
4382 )
4383 inject_advertisement_with_time_and_source_connectable(
4384 device, strong, start, HCI0_SOURCE_ADDRESS, False
4385 )
4386
4387 # A weaker, non-connectable reading from a second still-scanning source is
4388 # rejected; the stronger hci0 reading stays in history.
4389 weak = generate_advertisement_data(local_name="wohand", service_uuids=[], rssi=-95)
4390 inject_advertisement_with_time_and_source_connectable(
4391 device, weak, start + 1, HCI1_SOURCE_ADDRESS, False
4392 )
4393
4394 kept = manager.async_last_service_info(address, connectable=False)
4395 assert kept is not None
4396 assert kept.source == HCI0_SOURCE_ADDRESS
4397 assert kept.rssi == -30
4398
4399
4400 @pytest.mark.asyncio
4401 @pytest.mark.usefixtures("enable_bluetooth")
4402 async def test_should_keep_previous_adv_switches_without_debug_logging(
4403 register_hci0_scanner: None,
4404 register_hci1_scanner: None,
4405 caplog: pytest.LogCaptureFixture,
4406 ) -> None:
4407 """Switch decisions are silent when debug logging is disabled."""
4408 manager = get_manager()
4409 manager._debug = False
4410 address = "44:44:33:11:23:06"
4411 device = generate_ble_device(address, "wohand")
4412 start = time.monotonic()
4413
4414 weak = generate_advertisement_data(local_name="wohand", service_uuids=[], rssi=-40)
4415 inject_advertisement_with_time_and_source(device, weak, start, HCI0_SOURCE_ADDRESS)
4416
4417 with caplog.at_level(logging.DEBUG, logger="habluetooth.manager"):
4418 # RSSI switch: a stronger second source wins.
4419 strong = generate_advertisement_data(
4420 local_name="wohand", service_uuids=[], rssi=-20
4421 )
4422 inject_advertisement_with_time_and_source(
4423 device, strong, start + 1, HCI1_SOURCE_ADDRESS
4424 )
4425 # Stale switch: a far-future reading wins.
4426 inject_advertisement_with_time_and_source(
4427 device, weak, start + 100_000, HCI0_SOURCE_ADDRESS
4428 )
4429
4430 # The switch happened, but nothing was logged.
4431 latest = manager.async_last_service_info(address, connectable=True)
4432 assert latest is not None
4433 assert latest.source == HCI0_SOURCE_ADDRESS
4434 assert "Switching from" not in caplog.text
4435
4436
4437 @pytest.mark.asyncio
4438 @pytest.mark.usefixtures("enable_bluetooth")
4439 async def test_non_connectable_adv_promoted_when_connectable_path_registered(
4440 register_hci0_scanner: None,
4441 ) -> None:
4442 """
4443 A changed non-connectable adv is promoted when a connectable path is live.
4444
4445 Regression test for #534: a connectable scanner has a path to the device, but
4446 the current best advertisement arrives from a non-connectable source. The
4447 service_info must surface as connectable so connectable callbacks and discovery
4448 fire, otherwise Home Assistant believes there is no connectable path.
4449 """
4450 manager = get_manager()
4451 address = "44:44:33:11:23:45"
4452 now = time.monotonic()
4453
4454 discovered: list[BluetoothServiceInfoBleak] = []
4455 manager._subclass_discover_info = Mock(side_effect=discovered.append)
4456 bleak_devices: list[BLEDevice] = []
4457
4458 def _on_bleak(dev: BLEDevice, _adv: AdvertisementData) -> None:
4459 bleak_devices.append(dev)
4460
4461 # Register up front so the connectable_history replay on registration cannot
4462 # be mistaken for a promotion dispatch.
4463 cancel = manager.async_register_bleak_callback(_on_bleak, {})
4464 try:
4465 # Connectable adv from the registered hci0 scanner populates
4466 # connectable_history.
4467 device = generate_ble_device(address, "wohand")
4468 connectable_adv = generate_advertisement_data(
4469 local_name="wohand",
4470 service_uuids=[],
4471 manufacturer_data={1: b"\x01"},
4472 rssi=-60,
4473 )
4474 inject_advertisement_with_time_and_source_connectable(
4475 device, connectable_adv, now, HCI0_SOURCE_ADDRESS, True
4476 )
4477
4478 discovered.clear()
4479 bleak_devices.clear()
4480
4481 # A stronger non-connectable adv from another source wins the best-path
4482 # comparison and carries changed data so the identical-adv short-circuit
4483 # does not skip dispatch.
4484 non_connectable_adv = generate_advertisement_data(
4485 local_name="wohand",
4486 service_uuids=[],
4487 manufacturer_data={1: b"\x02"},
4488 rssi=-20,
4489 )
4490 inject_advertisement_with_time_and_source_connectable(
4491 device,
4492 non_connectable_adv,
4493 now,
4494 NON_CONNECTABLE_REMOTE_SOURCE_ADDRESS,
4495 False,
4496 )
4497 finally:
4498 cancel()
4499
4500 assert discovered
4501 assert discovered[-1].connectable is True
4502 assert bleak_devices
4503
4504
4505 @pytest.mark.asyncio
4506 @pytest.mark.usefixtures("enable_bluetooth")
4507 async def test_non_connectable_adv_not_promoted_after_connectable_scanner_unregisters() -> ( # noqa: E501
4508 None
4509 ):
4510 """
4511 A lingering connectable_history entry does not promote once its source is gone.
4512
4513 connectable_history is only pruned by the periodic unavailable check, so an
4514 unregistered connectable scanner can leave a stale entry behind. The promotion
4515 must verify the stored source is still registered before claiming a live path.
4516 """
4517 manager = get_manager()
4518 address = "44:44:33:11:23:46"
4519 now = time.monotonic()
4520
4521 discovered: list[BluetoothServiceInfoBleak] = []
4522 manager._subclass_discover_info = Mock(side_effect=discovered.append)
4523 bleak_devices: list[BLEDevice] = []
4524
4525 def _on_bleak(dev: BLEDevice, _adv: AdvertisementData) -> None:
4526 bleak_devices.append(dev)
4527
4528 # Register up front so the connectable_history replay on registration cannot
4529 # be mistaken for a promotion dispatch.
4530 cancel = manager.async_register_bleak_callback(_on_bleak, {})
4531 try:
4532 connectable_scanner = FakeScanner(HCI0_SOURCE_ADDRESS, "hci0")
4533 connectable_scanner.connectable = True
4534 cancel_scanner = manager.async_register_scanner(connectable_scanner)
4535
4536 device = generate_ble_device(address, "wohand")
4537 connectable_adv = generate_advertisement_data(
4538 local_name="wohand",
4539 service_uuids=[],
4540 manufacturer_data={1: b"\x01"},
4541 rssi=-60,
4542 )
4543 inject_advertisement_with_time_and_source_connectable(
4544 device, connectable_adv, now, HCI0_SOURCE_ADDRESS, True
4545 )
4546
4547 # Unregister the only connectable scanner; the connectable_history entry
4548 # intentionally lingers since unregister does not prune it.
4549 cancel_scanner()
4550 assert HCI0_SOURCE_ADDRESS not in manager._sources
4551 assert address in manager._connectable_history
4552
4553 discovered.clear()
4554 bleak_devices.clear()
4555
4556 non_connectable_adv = generate_advertisement_data(
4557 local_name="wohand",
4558 service_uuids=[],
4559 manufacturer_data={1: b"\x02"},
4560 rssi=-20,
4561 )
4562 inject_advertisement_with_time_and_source_connectable(
4563 device,
4564 non_connectable_adv,
4565 now,
4566 NON_CONNECTABLE_REMOTE_SOURCE_ADDRESS,
4567 False,
4568 )
4569 finally:
4570 cancel()
4571
4572 assert discovered
4573 assert discovered[-1].connectable is False
4574 assert not bleak_devices
4575
4576
4577 @pytest.mark.asyncio
4578 @pytest.mark.usefixtures("enable_bluetooth")
4579 async def test_connectable_adv_still_dispatches_to_bleak_callbacks(
4580 register_hci0_scanner: None,
4581 ) -> None:
4582 """A normal connectable adv still dispatches to bleak callbacks unchanged."""
4583 manager = get_manager()
4584 address = "44:44:33:11:23:47"
4585 device = generate_ble_device(address, "wohand")
4586 adv = generate_advertisement_data(local_name="wohand", service_uuids=[], rssi=-40)
4587
4588 bleak_devices: list[BLEDevice] = []
4589
4590 def _on_bleak(dev: BLEDevice, _adv: AdvertisementData) -> None:
4591 bleak_devices.append(dev)
4592
4593 cancel = manager.async_register_bleak_callback(_on_bleak, {})
4594 try:
4595 inject_advertisement_with_time_and_source_connectable(
4596 device, adv, time.monotonic(), HCI0_SOURCE_ADDRESS, True
4597 )
4598 finally:
4599 cancel()
4600
4601 assert bleak_devices == [device]
4602
4603
4604 @pytest.mark.asyncio
4605 @pytest.mark.usefixtures("enable_bluetooth")
4606 async def test_async_register_advertisement_callback(
4607 register_hci0_scanner: None,
4608 ) -> None:
4609 """Advertisement callbacks fire for every packet, even when unchanged."""
4610 manager = get_manager()
4611 address = "44:44:33:11:23:12"
4612 device = generate_ble_device(address, "wohand")
4613 adv = generate_advertisement_data(local_name="wohand", service_uuids=[])
4614 other_device = generate_ble_device("44:44:33:11:23:13", "other")
4615
4616 seen: list[BluetoothServiceInfoBleak] = []
4617
4618 def _failing_callback(_service_info: BluetoothServiceInfoBleak) -> None:
4619 msg = "This is a test"
4620 raise ValueError(msg)
4621
4622 cancel_failing = manager.async_register_advertisement_callback(
4623 _failing_callback, address
4624 )
4625 cancel = manager.async_register_advertisement_callback(seen.append, address)
4626
4627 inject_advertisement_with_source(device, adv, "hci0")
4628 inject_advertisement_with_source(device, adv, "hci0")
4629 inject_advertisement_with_source(other_device, adv, "hci0")
4630 assert [info.address for info in seen] == [address, address]
4631
4632 # Packets dropped by the Apple noise pre-filter are not delivered.
4633 apple_noise = generate_advertisement_data(
4634 manufacturer_data={76: b"\x01\x00"}, service_uuids=[]
4635 )
4636 inject_advertisement_with_source(device, apple_noise, "hci0")
4637 assert len(seen) == 2
4638
4639 cancel_failing()
4640 cancel()
4641 inject_advertisement_with_source(device, adv, "hci0")
4642 assert len(seen) == 2
4643 assert address not in manager._advertisement_callbacks