diff --git a/meshtastic/ble_interface.py b/meshtastic/ble_interface.py index 3b462ca30..a0a03d833 100644 --- a/meshtastic/ble_interface.py +++ b/meshtastic/ble_interface.py @@ -30,9 +30,9 @@ class BLEInterface(MeshInterface): """MeshInterface using BLE to connect to devices.""" - # Declared at class level: close() may run during __init__ (connect-failure - # path) before the atexit handler is assigned further down in __init__. - _exit_handler: Optional[Any] + # Defaults at class level: close() may run during __init__ (connect-failure path, or the device dropping + # the link mid-__init__) before the atexit handler is assigned further down in __init__. + _exit_handler: Optional[Any] = None class BLEError(Exception): """An exception class for BLE errors.""" @@ -194,11 +194,24 @@ def connect(self, address: Optional[str] = None) -> "BLEClient": # Bleak docs recommend always doing a scan before connecting (even if we know addr) device = self.find_device(address) - client = BLEClient(device.address, disconnected_callback=lambda _: self.close()) + client = BLEClient(device.address, disconnected_callback=self._on_disconnected) client.connect() client.discover() return client + def _on_disconnected(self, _client: BleakClient) -> None: + """bleak's disconnected callback, which runs on BLEClient's event loop thread. + + close() blocks on operations that run on that same loop (writing the disconnect message, bleak's + disconnect), so calling it here deadlocks the loop whenever the device drops the link itself, e.g. + on a reboot: connection.lost is never published. Close from a separate thread instead.""" + Thread(target=self.close, name="BLEClose", daemon=True).start() + + def _link_down(self) -> bool: + """True once the device is gone: no client, or bleak reports it disconnected.""" + client = self.client + return client is None or not client.bleak_client.is_connected + def _receiveFromRadioImpl(self) -> None: while self._want_receive: if self.should_read: @@ -215,16 +228,18 @@ def _receiveFromRadioImpl(self) -> None: # Device disconnected probably, so end our read loop immediately logger.debug(f"Device disconnected, shutting down {e}") self._want_receive = False + continue except BleakError as e: - # We were definitely disconnected - if "Not connected" in str(e): + # CoreBluetooth fails a read in flight with errors that don't say "Not connected" when the + # device drops the link, so also ask bleak whether it's still connected. + if "Not connected" in str(e) or self._link_down(): logger.debug(f"Device disconnected, shutting down {e}") self._want_receive = False - else: - raise BLEInterface.BLEError( - "Error reading BLE", - BLEInterface.BLEError.READ_ERROR, - ) from e + continue + raise BLEInterface.BLEError( + "Error reading BLE", + BLEInterface.BLEError.READ_ERROR, + ) from e if not b: if retries < 5: time.sleep(0.1) @@ -263,7 +278,11 @@ def close(self) -> None: try: MeshInterface.close(self) except Exception as e: - logger.error(f"Error closing mesh interface: {e}") + if self._link_down(): + # The device already dropped the link (e.g. it rebooted), so the disconnect message can't go out. + logger.debug(f"Device already disconnected; not sent: {e}") + else: + logger.error(f"Error closing mesh interface: {e}") self._want_receive = False # Tell the thread we want it to stop if self._receiveThread: diff --git a/meshtastic/tests/test_ble_interface.py b/meshtastic/tests/test_ble_interface.py index 281779f23..f0963c272 100644 --- a/meshtastic/tests/test_ble_interface.py +++ b/meshtastic/tests/test_ble_interface.py @@ -1,5 +1,6 @@ """Meshtastic unit tests for ble_interface.py""" +import threading from unittest.mock import MagicMock, patch import pytest @@ -142,3 +143,66 @@ def test_ble_close_can_retry_after_cleanup_failure(failure) -> None: unregister.assert_called_once_with(iface._exit_handler) client.close.assert_called() notification.assert_called() + + +@pytest.mark.unit +def test_ble_disconnected_callback_closes_off_the_event_loop() -> None: + """bleak runs the disconnected callback on BLEClient's event loop; close() waits on that loop, + so the callback must hand close() to another thread instead of calling it inline.""" + iface = object.__new__(BLEInterface) + caller = threading.current_thread() + closed_on = [] + done = threading.Event() + + def fake_close() -> None: + closed_on.append(threading.current_thread()) + done.set() + + with patch.object(iface, "close", side_effect=fake_close): + iface._on_disconnected(MagicMock()) + assert done.wait(timeout=5), "close() was never called" + + assert closed_on[0] is not caller, "close() ran on the callback's (event loop) thread" + + +@pytest.mark.unit +def test_ble_connect_registers_disconnected_callback() -> None: + """connect() must hand bleak _on_disconnected, not a callback that closes inline on the event loop.""" + iface = object.__new__(BLEInterface) + device = MagicMock() + with patch.object(iface, "find_device", return_value=device), \ + patch("meshtastic.ble_interface.BLEClient") as client_cls: + iface.connect("node") + callback = client_cls.call_args.kwargs["disconnected_callback"] + assert callback.__func__ is BLEInterface._on_disconnected and callback.__self__ is iface + + +@pytest.mark.unit +def test_ble_receive_stops_quietly_when_device_dropped_link() -> None: + """A read in flight when the device drops the link (any BleakError wording) ends the reader, not raises.""" + iface = object.__new__(BLEInterface) + iface.should_read = True + iface._want_receive = True + iface.client = MagicMock() + iface.client.bleak_client.is_connected = False + iface.client.read_gatt_char.side_effect = BleakError("Peripheral disconnected") + iface._receiveFromRadioImpl() + assert iface._want_receive is False + + +@pytest.mark.unit +def test_ble_close_before_atexit_handler_registered() -> None: + """The device can drop the link mid-__init__, after self.client is set but before the atexit + handler is registered; close() must still clean up.""" + iface = object.__new__(BLEInterface) + iface._closing = False + iface._want_receive = False + iface._receiveThread = None + client = MagicMock() + iface.client = client + with patch("meshtastic.mesh_interface.MeshInterface.close"), \ + patch.object(iface, "_disconnected") as notification: + iface.close() + client.disconnect.assert_called_once() + assert iface.client is None + notification.assert_called_once()