From 1d8330194f38c0419904ff875119bdc0de03d31b Mon Sep 17 00:00:00 2001 From: Jeff Whitlatch Date: Sun, 23 Aug 2026 22:17:56 -0700 Subject: [PATCH 1/4] Fix BLE close() deadlock from re-entrant disconnect callback When close() disconnects the BLE device, Bleak fires the disconnected_callback which calls close() again. The second close() tries to disconnect while the first is still in progress, causing a deadlock. Add a _closing guard flag to prevent the re-entrant call. Co-authored-by: Cursor --- meshtastic/ble_interface.py | 5 +++++ meshtastic/tests/test_ble_interface.py | 29 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/meshtastic/ble_interface.py b/meshtastic/ble_interface.py index 2101dc363..c936bc631 100644 --- a/meshtastic/ble_interface.py +++ b/meshtastic/ble_interface.py @@ -60,6 +60,7 @@ def __init__( # pylint: disable=R0917 ) self.should_read = False + self._closing = False logger.debug("Threads starting") self._want_receive = True @@ -254,6 +255,10 @@ def _sendToRadioImpl(self, toRadio) -> None: self.should_read = True def close(self) -> None: + if self._closing: + return + self._closing = True + try: MeshInterface.close(self) except Exception as e: diff --git a/meshtastic/tests/test_ble_interface.py b/meshtastic/tests/test_ble_interface.py index 0b725e65c..f0569cd0f 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 atexit from unittest.mock import MagicMock, patch import pytest @@ -67,3 +68,31 @@ def test_ble_receive_wraps_unexpected_bleak_error_with_kind(): with pytest.raises(BLEInterface.BLEError) as excinfo: iface._receiveFromRadioImpl() assert excinfo.value.kind == BLEInterface.BLEError.READ_ERROR + + +@pytest.mark.unit +def test_ble_close_reentrant_does_not_deadlock() -> None: + """close() must not deadlock when disconnect callback re-enters close().""" + iface = object.__new__(BLEInterface) + iface._closing = False + iface._want_receive = False + iface._receiveThread = None + + disconnect_count = 0 + + def fake_disconnect(): + nonlocal disconnect_count + disconnect_count += 1 + iface.close() # re-entrant call — should return immediately + + mock_client = MagicMock() + mock_client.disconnect.side_effect = fake_disconnect + iface.client = mock_client + iface._exit_handler = lambda: None + + with patch("meshtastic.mesh_interface.MeshInterface.close"), \ + patch.object(iface, "_disconnected"): + iface.close() + + assert disconnect_count == 1, "disconnect() should be called exactly once" + assert iface.client is None, "client should be cleaned up" From 209d10ad41461cb488e6c5b8c5982412c5252207 Mon Sep 17 00:00:00 2001 From: Jeff Whitlatch Date: Fri, 20 Nov 2026 11:35:56 -0700 Subject: [PATCH 2/4] Allow BLE close cleanup to retry after exceptions --- meshtastic/ble_interface.py | 26 ++++++++------ meshtastic/tests/test_ble_interface.py | 47 ++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 11 deletions(-) diff --git a/meshtastic/ble_interface.py b/meshtastic/ble_interface.py index c936bc631..3b462ca30 100644 --- a/meshtastic/ble_interface.py +++ b/meshtastic/ble_interface.py @@ -260,11 +260,11 @@ def close(self) -> None: self._closing = True try: - MeshInterface.close(self) - except Exception as e: - logger.error(f"Error closing mesh interface: {e}") + try: + MeshInterface.close(self) + except Exception as e: + logger.error(f"Error closing mesh interface: {e}") - if self._want_receive: self._want_receive = False # Tell the thread we want it to stop if self._receiveThread: self._receiveThread.join( @@ -272,13 +272,17 @@ def close(self) -> None: ) # If bleak is hung, don't wait for the thread to exit (it is critical we disconnect) self._receiveThread = None - if self.client: - if self._exit_handler is not None: - atexit.unregister(self._exit_handler) - self.client.disconnect() - self.client.close() - self.client = None - self._disconnected() # send the disconnected indicator up to clients + if self.client: + self.client.disconnect() + self.client.close() + if self._exit_handler is not None: + atexit.unregister(self._exit_handler) + self.client = None + self._disconnected() + except BaseException: + # Keep successful closes idempotent, but allow failed cleanup to retry. + self._closing = False + raise class BLEClient: diff --git a/meshtastic/tests/test_ble_interface.py b/meshtastic/tests/test_ble_interface.py index f0569cd0f..9fd7e1d09 100644 --- a/meshtastic/tests/test_ble_interface.py +++ b/meshtastic/tests/test_ble_interface.py @@ -93,6 +93,53 @@ def fake_disconnect(): with patch("meshtastic.mesh_interface.MeshInterface.close"), \ patch.object(iface, "_disconnected"): iface.close() + iface.close() # A completed close must also remain idempotent. assert disconnect_count == 1, "disconnect() should be called exactly once" assert iface.client is None, "client should be cleaned up" + + +@pytest.mark.unit +@pytest.mark.parametrize("failure", ["join", "disconnect", "close", "notification"]) +def test_ble_close_can_retry_after_cleanup_failure(failure) -> None: + """A failed cleanup must not permanently disable close().""" + iface = object.__new__(BLEInterface) + iface._closing = False + iface._want_receive = True + receive_thread = MagicMock() + iface._receiveThread = receive_thread + client = MagicMock() + iface.client = client + iface._exit_handler = lambda: None + notification = MagicMock() + iface._disconnected = notification + failing_step = { + "join": receive_thread.join, + "disconnect": client.disconnect, + "close": client.close, + "notification": notification, + }[failure] + failing_step.side_effect = RuntimeError("cleanup failed") + + with patch("meshtastic.mesh_interface.MeshInterface.close"), \ + patch("meshtastic.ble_interface.atexit.unregister") as unregister: + with pytest.raises(RuntimeError, match="cleanup failed"): + iface.close() + + assert iface._closing is False + if failure != "notification": + assert iface.client is client + unregister.assert_not_called() + + failing_step.side_effect = None + iface.close() + iface.close() + + assert iface._closing is True + assert iface.client is None + assert iface._receiveThread is None + assert iface._want_receive is False + assert failing_step.call_count == 2 + unregister.assert_called_once_with(iface._exit_handler) + client.close.assert_called() + notification.assert_called() From 92f71cd8659daa17f083dc27085c03609faa674a Mon Sep 17 00:00:00 2001 From: Ian McEwen Date: Fri, 20 Nov 2026 11:45:41 -0700 Subject: [PATCH 3/4] Fix pylint annoyance --- meshtastic/tests/test_ble_interface.py | 1 - 1 file changed, 1 deletion(-) diff --git a/meshtastic/tests/test_ble_interface.py b/meshtastic/tests/test_ble_interface.py index 9fd7e1d09..e82cdc910 100644 --- a/meshtastic/tests/test_ble_interface.py +++ b/meshtastic/tests/test_ble_interface.py @@ -1,6 +1,5 @@ """Meshtastic unit tests for ble_interface.py""" -import atexit from unittest.mock import MagicMock, patch import pytest From c0568a00a1b86bfc441dda6c3ab79130b131248c Mon Sep 17 00:00:00 2001 From: Ian McEwen Date: Fri, 20 Nov 2026 12:22:23 -0700 Subject: [PATCH 4/4] Another CI complaint --- meshtastic/tests/test_ble_interface.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/meshtastic/tests/test_ble_interface.py b/meshtastic/tests/test_ble_interface.py index e82cdc910..281779f23 100644 --- a/meshtastic/tests/test_ble_interface.py +++ b/meshtastic/tests/test_ble_interface.py @@ -111,7 +111,7 @@ def test_ble_close_can_retry_after_cleanup_failure(failure) -> None: iface.client = client iface._exit_handler = lambda: None notification = MagicMock() - iface._disconnected = notification + iface._disconnected = notification # type: ignore[method-assign] failing_step = { "join": receive_thread.join, "disconnect": client.disconnect,