From b45d7ac0d3bf5edbbae83181fc5df4e5dcaf11eb Mon Sep 17 00:00:00 2001 From: gchai Date: Wed, 25 Nov 2026 20:03:26 -0800 Subject: [PATCH 1/2] Close BLE interface off the event loop when the device disconnects bleak runs disconnected_callback on BLEClient's event loop thread, and the callback called close() inline. close() waits on operations that run on that same loop (writing the disconnect message, bleak's disconnect), so when the device drops the link itself, e.g. on a reboot, the loop deadlocks: connection.lost is never published and the client is never cleaned up. Run close() on its own thread instead. The re-entrancy guard from #976 still covers the case where close() started the disconnect. --- meshtastic/ble_interface.py | 10 +++++++++- meshtastic/tests/test_ble_interface.py | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/meshtastic/ble_interface.py b/meshtastic/ble_interface.py index 3b462ca30..7a714e0b0 100644 --- a/meshtastic/ble_interface.py +++ b/meshtastic/ble_interface.py @@ -194,11 +194,19 @@ 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) -> 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 _receiveFromRadioImpl(self) -> None: while self._want_receive: if self.should_read: diff --git a/meshtastic/tests/test_ble_interface.py b/meshtastic/tests/test_ble_interface.py index 281779f23..5ba20e440 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,23 @@ 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(): + 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" From f344d174259e010676d907e8b239452cac10d968 Mon Sep 17 00:00:00 2001 From: gchai Date: Thu, 26 Nov 2026 02:10:20 -0500 Subject: [PATCH 2/2] Address review: clean shutdown when the device drops the link - _exit_handler defaults to None at class level: the annotation alone created no attribute, so a close() mid-__init__ (device dropping the link, now reachable) raised AttributeError and left the client half-closed - the reader treats any BleakError as a disconnect once bleak reports the link down (CoreBluetooth's errors don't say "Not connected"), and stops via continue rather than falling through to a possibly unbound read buffer - close() logs the unsendable disconnect message at debug, not as an ERROR pointing at bluetooth groups and pairing PINs, when the device already dropped the link - tests: connect() registers _on_disconnected; the reader stops quietly on a dropped link; close() works before the atexit handler is registered - type hints on the callback and test helper --- meshtastic/ble_interface.py | 35 +++++++++++++------- meshtastic/tests/test_ble_interface.py | 45 +++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 13 deletions(-) diff --git a/meshtastic/ble_interface.py b/meshtastic/ble_interface.py index 7a714e0b0..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.""" @@ -199,7 +199,7 @@ def connect(self, address: Optional[str] = None) -> "BLEClient": client.discover() return client - def _on_disconnected(self, _client) -> None: + 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 @@ -207,6 +207,11 @@ def _on_disconnected(self, _client) -> None: 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: @@ -223,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) @@ -271,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 5ba20e440..f0963c272 100644 --- a/meshtastic/tests/test_ble_interface.py +++ b/meshtastic/tests/test_ble_interface.py @@ -154,7 +154,7 @@ def test_ble_disconnected_callback_closes_off_the_event_loop() -> None: closed_on = [] done = threading.Event() - def fake_close(): + def fake_close() -> None: closed_on.append(threading.current_thread()) done.set() @@ -163,3 +163,46 @@ def fake_close(): 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()