Skip to content

Close BLE interface off the event loop when the device disconnects - #1027

Open
gchai wants to merge 2 commits into
meshtastic:masterfrom
gchai:fix/ble-close-on-disconnect-thread
Open

gchai wants to merge 2 commits into
meshtastic:masterfrom
gchai:fix/ble-close-on-disconnect-thread

Conversation

@gchai

@gchai gchai commented Nov 26, 2026 •

Copy link
Copy Markdown

Follow-up to #976. That PR fixed close() re-entering itself when we start the disconnect. This PR covers the case where the device drops the link, e.g. when it reboots.

Cause

bleak runs disconnected_callback on BLEClient's event loop thread, and the callback called self.close() inline. If the device disconnects first, that callback's close() is the first one, so the _closing guard doesn't stop it. It then waits on operations that run on that same loop: MeshInterface.close() writes the disconnect message, then client.disconnect(). The loop is blocked waiting on itself and deadlocks:

  • meshtastic.connection.lost is never published;
  • iface.client is never cleared;
  • the BLEClient event loop thread sits in write_gatt_char → async_await → future.result() forever.

Fix

  • connect() passes _on_disconnected as the callback, and it runs close() on its own daemon thread. When close() started the disconnect itself, the callback's thread hits the _closing guard and returns, as before.
  • Now that this path runs to completion, three things on it are fixed too:
    • _exit_handler defaults to None at class level. The annotation alone created no attribute, so a close() while __init__ was still running (the device dropping the link during the config download) raised AttributeError and left the client half-closed.
    • The reader treats a BleakError as a disconnect once bleak reports the link down. CoreBluetooth's errors don't say "Not connected", so a read in flight at the drop used to surface as an uncaught READ_ERROR in BLEReceive.
    • When the link is already down, close() logs the unsendable disconnect message at debug. Before, every reboot logged ERROR Error closing mesh interface: Error writing BLE (are you in the 'bluetooth' user group? did you enter the pairing PIN on your computer?).

Testing

  • New unit tests:

    • the callback closes off the calling thread;
    • connect() registers _on_disconnected;
    • the reader stops quietly on a dropped link;
    • close() works before the atexit handler is registered.

    The last two fail before this change.

  • Hardware: Heltec MeshPocket on firmware 2.7.26, connecting from macOS with bleak 1.1.1 on Python 3.14. A script connects, has the node reboot itself (local reboot_seconds=2, no LoRa), waits 25 s and checks the state:

  • pytest: 574 passed, 2 skipped. pylint and mypy report only import errors for the optional riden, ppk2_api, parse and pyarrow packages, which this env doesn't install.

Linux is untested: on the one Linux machine available, master can't complete a BLE connection to the test node (the first FROMRADIO read never returns), so the reboot path can't be reached there.

This PR doesn't depend on #1026, the GATT-operation lock that fixes the related hang at connect. Either can merge first; the second needs a small rebase because both append tests to test_ble_interface.py.

Summary by CodeRabbit

  • Bug Fixes
    • Improved Bluetooth connection handling when a device disconnects, helping the app shut down the connection cleanly.
    • Reads now stop without an error when the Bluetooth link is already disconnected; other read errors continue to be reported.
    • Improved cleanup when closing a connection early, before its shutdown handler is ready.

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 meshtastic#976 still
covers the case where close() started the disconnect.
- _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
@coderabbitai

coderabbitai Bot commented Nov 26, 2026

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

BLE disconnect cleanup now runs on a daemon thread. Read and close handling recognize disconnected-link states, and the exit handler has a default value. Tests cover callback registration, thread usage, disconnected reads, and cleanup before exit-handler registration.

Changes: BLE disconnect handling

Layer / File(s) Summary
Disconnect detection and cleanup
meshtastic/ble_interface.py, meshtastic/tests/test_ble_interface.py
The disconnect callback starts close() on a daemon thread. Read and close handling check the link state, and _exit_handler defaults to None. Tests cover the callback, disconnected reads, thread usage, and early cleanup.

Estimated code review effort: 2 (Simple) | ~12 minutes

Change: Bug fix

Possibly related PRs

  • meshtastic/python#976: Both PRs address the close() re-entrancy path and the exit-handler behavior during BLE cleanup.
  • meshtastic/python#1012: Both PRs address close() when the exit handler has not been assigned during connection setup.

Suggested reviewers: ianmcorvidae, geeksville, shukari

Merge Risk: Minimal · up to f344d

BLE disconnect cleanup now runs on a separate thread to avoid a deadlock when the device drops the link first. No concrete merge-blocking risk was found. Linux behavior has not been verified by the author.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Close BLE interface off the event loop when the device disconnects" matches the main change. The raw summary says BLE disconnections now run close() on a separate daemon thread instead of B…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "Close BLE interface off the event loop when the device disconnects" matches the main change. The raw summary says BLE disconnections now run close() on a separate daemon thread instead of Bleak's event-loop thread, and the PR objectives describe the same fix for the deadlock. The title is short, specific, and states the primary change. The supporting changes (_exit_handler default, BleakError handling, logging level) are not in the title, which is expected.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 795a0f0 and f344d17.

Files selected for processing: 2

  • meshtastic/ble_interface.py
  • meshtastic/tests/test_ble_interface.py

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant