Skip to content

BLE and serial

Developer reference for LoRa BLE/serial transports, sidecar GATT reconnect, dual-radio wake stagger, or multi-protocol BLE coexistence. Repo-wide rules live in AGENTS.md.

Meshtastic, MeshCore, and MeshCom share LoRa BLE reconnect contracts on all platforms (linux, darwin, win32). Cold-start BLE auto-connect and the serial → BLE fallback are enabled on linux, darwin, and win32 via useProtocolRfAutoConnect; there is no platform guard. Reticulum stack autostart + awaitReticulumBleCoexistenceClear() still serialize Reticulum BLE ahead of LoRa GATT. The remaining Linux-specific reconnect branch is manual Restore in rfReconnectHelper (direct GATT connect without scan fallback). BLE transport is reticulum-sidecar btleplug GATT (/api/v1/gatt/*), proxied by Electron main gatt-sidecar-proxy.ts over gatt:* IPC. Renderer transport: transportSidecarGatt.ts (Meshtastic) / MeshCore framing / MeshCom NUS phone framing over the same GATT proxy. Electron session ids are meshtastic / meshcore / meshcom; MeshCom’s sidecar wire profile reuses MeshCore NUS (gattWireProfileFromSession). Serial: connection.ts, serialPortSignature.ts. Meshtastic BLE open: connection.ts / TransportManager. Reticulum BLE RNode / BLE Peer use the same sidecar process through rsReticulum and /api/v1/ble/*, with separate BLE centrals.

There is no Noble manager, no Web Bluetooth LoRa path, no Noble yield for Reticulum, and no 4-day Noble restart nudge.

Sidecar GATT (btleplug)

  • Owner: reticulum-sidecar gatt module (feature gatt-ble) owns the Meshtastic/MeshCore central. rsReticulum owns separate RNode/Peer centrals; on Apple, Peer uses its native CoreBluetooth implementation. Running in one process does not make these one adapter handle or scan owner.
  • BLE-light ensure: LoRa BLE does not require the user to Start Reticulum. ReticulumSidecarManager.ensureForBle() starts with --ble-only, leaving configured Reticulum interfaces, Nomad hosting, and rncp listeners stopped. Public Reticulum status is running: false, processRunning: true; GATT uses process liveness. Explicit Reticulum Start promotes that same process via POST /api/v1/stack/start, preserving LoRa sessions. Without an identity, Start opens the setup shell while RNS ready flags remain false. The hung-process watchdog preserves the current mode.
  • Shared process, not shared RNS session: Meshtastic/MeshCore GATT needs the sidecar process, not rns_ready / LXMF live. UI Restart stack soft-restarts live RNS in-process (POST /api/v1/stack/restart) so LoRa GATT sessions stay up. Explicit Stop / Quit still SIGTERM the process (drops GATT until the next ensureForBle). On process exit, GattSidecarProxy.invalidateAfterSidecarExit() clears the cached HTTP port so reconnect does not hammer a dead port.
  • Proxy: src/main/gatt-sidecar-proxy.ts — scan / connect / disconnect / to-radio / WS fromRadio + RSSI events; replaces former noble-ble-manager.ts.
  • IPC: gatt:start-scan, gatt:stop-scan, gatt:connect, gatt:disconnect, gatt:is-connected, gatt:to-radio, gatt:pair-state / gatt:pair / gatt:unpair (win32 only), plus push channels for discovered / connected / disconnected / fromRadio / linkRssi / issue.
  • Error taxonomy: stable snake_case codes (adapter_missing, scan_busy, mac_conflict, connect_timeout, pairing_required, …) — see reticulum-sidecar/src/gatt/error.rs; UI keys under connectionPanel.errors.ble.* via humanizeBleError / bleConnectErrors.
  • Linux in-app pairing: Electron main talks to host BlueZ over D-Bus (src/main/linux-bluez/ + ipc/linux-bluetooth-handlers.ts on the bluetooth-* IPC channels). Capability KeyboardOnly; PIN from ConnectionPanel answers RequestPasskey / RequestPinCode. Flatpak needs --allow=bluetooth and --system-talk-name=org.bluez (no bluetoothctl in the sandbox). Sidecar Linux LTK unbond may still shell out to bluetoothctl (separate path).
  • Windows in-app pairing: reticulum-sidecar/src/gatt/windows_pairing.rs pairs LoRa radios through WinRT custom pairing, as Chrome Web Bluetooth does (ProvidePin and ConfirmOnly are accepted; ConfirmPinMatch numeric comparison is rejected until the UI can show the code; retry at Encryption when EncryptionAndAuthentication cannot be met). Settings-only pairing fails on some radios (for example the L1 Pro MeshCore BLE companion) and leaves a half-paired device that wedges btleplug connect. The routes are GET /api/v1/gatt/pair-state and POST /api/v1/gatt/pair / unpair. Electron exposes them as win32-only gatt:pair-state / gatt:pair / gatt:unpair (src/main/ipc/gatt-pairing-handlers.ts, serialized through bleCoexistenceCoordinator.withScan('gatt', …); the PIN is never logged). Other platforms return unsupported. The WinRT calls block on IAsyncOperation::get() under spawn_blocking with timeouts, not on the IsolatedExecutor BLE runtime, so a wedged pairing call cannot set the stuck-scan latch. The sidecar refuses pair/unpair for an address held by a live session (mac_conflict). pair_state and the Windows connection-status probe (os_connected) take the same per-address permit as pair/unpair. Renderer flow (ConnectionPanel + lib/windowsBlePairing.ts): on select or Reconnect, check pair state; when unpaired, prompt for the PIN (MeshCore empty, Meshtastic prefilled 123456), pair, then connect. LoRa auto-reconnect (runLoraRfReconnectAttempt) checks the same pair state on Windows and skips the open when it is blocked or unpaired, which surfaces that existing panel state. A pair-state timeout or WinRT error does not connect and offers Remove & Re-pair Device. A pairing_required or "Bluetooth stack unresponsive" failure offers the same button (unpair, then pair). Pairing errors map Gatt error codes to locale keys; the sidecar's English stays in the log. Connect, discovery and subscribe errors that mention access denied or insufficient authentication/encryption map to pairing_required (classify_setup_error in btleplug_backend.rs).
  • Windows btleplug 0.13 split: on Windows the GATT backend uses btleplug 0.13 (the Cargo dependency is renamed to btleplug_win and aliased in btleplug_backend.rs). Other platforms stay on 0.11, because rsReticulum (rns-interface) pins 0.11 in the same process and both versions declare the BtlePlugCentralManagerDelegate Objective-C class, which cannot be registered twice on macOS. 0.13 provides WinRT add_peripheral. MeshCore companions stop advertising while any central holds the link, so find_peripheral_scanning can open an OS-connected radio by address after the cache check and unfiltered scan both miss its MAC. add_peripheral accepts any MAC, so the fallback is gated: the WinRT ConnectionStatus probe (windows_pairing::os_connected, same per-address permit as pair) starts in parallel with the 8s scan. A scan miss then waits at most OS_LINK_PROBE_GRACE (1s) for its answer, and falls back only when it is Some(true). An absent or unconnected radio, or an unknown link state, keeps the fast not found — scan first. Log lines: peripheral not advertising — connecting by address (windows) and … not OS-connected — skipping address fallback (windows), both with os_connected.
  • Connect budget: the backend CONNECT_DEADLINE (32s: lookup, connect, and GATT setup) plus SETUP_CLEANUP_TIMEOUT (5s) stays at least 3s under the isolated CONNECT_BUDGET (41s), as connect_deadline_and_cleanup_fit_inside_budget asserts. A radio that never answers reports connect timed out / GATT setup timed out. … timed out: Bluetooth stack unresponsive means a WinRT call really overran the budget; the isolated executor aborts that task (#1571) so the stuck latch clears in seconds for cancellable awaits (instead of waiting out a multi-minute hang), and refuses new connects only while the aborted join is still winding down.
  • Sidecar logs: the sidecar writes tracing without ANSI (with_ansi(false), plus NO_COLOR=1 from sidecarChildEnv). Main also strips ANSI before sanitizing (normalizeReticulumSidecarOutputLine). Without this, colored level tokens hide WARN, ERROR, and gatt INFO lines (gatt connect stage timings) from mesh-client.log.
  • Windows GattSession keep-alive: GattKeepAlive (MaintainConnection = true) is opened for both Meshtastic and MeshCore (wants_windows_keep_alive) immediately after peripheral.connect() and before discover_services, so Windows does not idle the link during discovery. The same session is held for the life of the open connection.
  • Windows post-pair discovery recovery (#1528 / #1571 / btleplug#325): After a fresh pair, WinRT uncached characteristic discovery can time out and fall back to an empty or hanging Cached attribute set (Uncached characteristic discovery timed out, falling back to cached mode → write characteristic missing, or a multi-minute hang that used to burn CONNECT_BUDGET before recovery ran). The sidecar does not fork btleplug; instead, on Windows LoRa profiles it (1) opens keep-alive early, (2) runs a pre-discover UUID-targeted WinRT probe (uuid_probe_pre stage via windows_gatt_uuid_probe.rs) and, on Found, disconnect/reconnect so btleplug clears empty ble_services before the first discover, (3) bounds that first discover_services to ~10s so a Cached hang fails fast enough for recovery, (4) on discover/missing-char failure runs one disconnect → settle → reconnect → rediscover cycle (rediscover; intentional DeviceDisconnected is ignored so setup is not cancelled as link_lost), and (5) if NUS/Meshtastic chars are still missing, runs the UUID probe again (uuid_probe) then reconnects for a final discover. Subscribe/writes still use btleplug handles. Renderer: isMeshcoreRetryableBleErrorMessage does not retry Bluetooth stack unresponsive / still stuck (avoids burning attempt 2 while the IsolatedExecutor is latched). Windows LoRa GATT uses btleplug 0.13.5 (btleplug_win); rsReticulum’s exact pin is raised via rsReticulum-btleplug-0.13.5.patch until upstream floats.
  • HTTP routes: documented in reticulum-sidecar-ipc.md (/api/v1/gatt/availability, /scan, /sessions, write/rssi/connected, session WS, registry register/unregister, Electron-main-only release-central / clear-bond-recovery). Registry register/unregister has no in-app caller; it is reserved for external owners such as rsReticulum RNode BLE, and Electron's coexistence coordinator covers configured Reticulum addresses instead.

LoRa BLE reconnect parity (Meshtastic + MeshCore)

  • rfReconnectController (lib/rfReconnectController.ts): single-owner link-lost / schedule / endAttempt for both runtimes (MeshCore TCP uses the same owner; conn side effects must not call handleConnectionLost for TCP).
  • Per-session connect lock in connection.ts (withGattConnectLock) plus connectGattWithScanBusyRetry when scan_busy — do not tear down an unrelated protocol’s GATT session for a scan.
  • Deferred disconnect while connect/reconnect open is in flight; flush in reconnect finally in useMeshtasticRuntime and useMeshcoreRuntime so edge-of-range drops keep retrying.
  • BLE exhaust latch (bleReconnectExhaustLatch.ts): after one full BLE attempt budget (RF_MAX_RECONNECT_ATTEMPTS_BLE), latches auto-reconnect off until user Connect / power resume / adapter poweredOn clears it — prevents late disconnect cleanup from restarting 1/N forever when the peripheral is gone.
  • Reconnect attempt budget (timeConstants.ts / bleReconnectHelper.ts raceWithDeadline): hard ceiling per BLE reconnect open+handshake attempt on all platforms.
  • Meshtastic BLE configure stall watchdog: MESHTASTIC_BLE_CONFIGURE_TIMEOUT_MS (120s) in meshtasticRuntimeWireEffects.ts; timer resets on NodeDB replay progress via touchMeshtasticConfigureProgress() from nodeStore.
  • MeshCore must not start the runtime reconnect loop on disconnect before the first successful configure — ConnectionPanel reconnectBleWithScan owns initial retries (meshcoreEverConfiguredRef). Manual disconnect (connectionStore.disconnectIntent) must not auto-reconnect — covered by useMeshcoreRuntime.reconnect.test.ts, useMeshtasticRuntime.reconnect-hardening.test.ts, and useReticulumRuntime.reconnect-hardening.test.ts.

Meshtastic USB serial vendor patches: @jsr/meshtastic__core and @jsr/meshtastic__transport-web-serial are patched via pnpm patchedDependencies so Web Serial streams abort cleanly on disconnect. Re-hash patches after JSR bumps; see docs/troubleshooting.md.

USB serial after sleep / zombie CDC: On onPowerResume with connectionType === 'serial', runtimes call beginSerialPostWakeUntrustedWindow() (serialDeliveryHealth / serialDeliveryProbe). Until a short companion probe succeeds (runSerialDeliveryProbe), silence uses SERIAL_POST_WAKE_DEAD_THRESHOLD_MS (~30s) instead of the normal 180s dead floor. MeshCom shares the same watchdog/loss/disconnect-router path as Meshtastic/MeshCore. Repeated delivery-ACK timeouts after transport loss raise connectionBanner.serialDeliveryUnhealthy. See docs/troubleshooting.md § USB serial after sleep.

GATT writes: Send each complete Meshtastic ToRadio protobuf or MeshCore command as one characteristic value. The sidecar rejects values above 512 bytes before writing, prefers WithResponse when the characteristic advertises WRITE, and otherwise uses WithoutResponse when supported. The OS handles ATT long writes; btleplug 0.11.8 does not expose negotiated MTU. Splitting an application frame into independent 20-byte writes corrupts both protocols. MeshCore BLE echo filtering: meshcoreCompanionTxEchoFilter.ts.

Meshtastic transport writes: meshtasticTransportLossDetection.ts wraps transport.toDevice with createSerializedWritableStream on serial, BLE, HTTP, and TCP. Meshtastic WiFi/TCP (fast) uses TransportTcpIpc with main-process meshtastic:tcp-* IPC (port 4403). After configure, getMetadata retries once after MESHTASTIC_GET_METADATA_AFTER_CONFIGURE_RETRY_MS when NodeDB traffic starves BLE. meshtasticSdkRoutingErrorConsoleHook.ts intercepts SDK routing failures and marks outbound chat rows failed.

Dual-radio BLE (Meshtastic + MeshCore)

Concurrent GATT sessions to different MACs are supported in the sidecar. Startup / wake still stagger auto-connect so two protocols do not slam the adapter at once:

Rule Detail
Init timing Dual-radio coordinator (meshcoreDualNobleBleInit.ts — name is historical) from App.tsx useLayoutEffect.
Primary order mesh-client:protocol localStorage (meshcore / meshtastic; Reticulum or missing → Meshtastic).
Secondary wait Secondary waits for primary GATT + handshake settle (or first attempt failure) — not full configure.
Wake usePowerRecovery: Meshtastic ~4s, MeshCore ~8s, optional settle wait up to ~30s when both use BLE.
Scans Main coordinator serializes app-requested scans and LoRa connection setup (scan_busy); existing links to other devices stay connected.
Tests meshcoreDualNobleBleInit.test.ts, ConnectionPanel auto-connect coverage.

Do not reintroduce Meshtastic-only startup gates or child-before-parent init — ProtocolAutoConnectCoordinator / useProtocolRfAutoConnect owns cold-start auto-connect for both protocols.

Multi-protocol BLE coexistence (incl. Reticulum)

  • Main-process ble-coexistence-coordinator.ts tracks pending/live LoRa connections and configured Reticulum BLE addresses (owners gatt:meshtastic / gatt:meshcore / gatt:meshcom / reticulum). Reserve before connection setup so another protocol cannot claim the same address while GATT opens. The sidecar GATT registry separately guards its own sessions; its external-registration API is not an automatic rsReticulum lifecycle bridge.
  • Reticulum BLE RNode/Peer and LoRa GATT run in the same process with separate centrals. The main coordinator serializes app-requested scans and LoRa connection setup without disconnecting links to other devices. Autonomous rsReticulum discovery/reconnect is not covered by that lease, and these checks do not establish hardware coexistence on every adapter.
  • Stale bonds / pairing timeouts still latch sidecar alerts (bleBondRemoved, blePairingTimedOut) — Forget/re-pair; Admin Start pairing shows PIN in-panel over USB (never Meshtastic 123456).
  • Meshtastic/MeshCore may see scan_busy while an app-requested Reticulum scan holds the lease; connectGattWithScanBusyRetry / startGattScanningWithRetry wait for release.

MeshCore picker scans are unfiltered on all three platforms, matching connect-by-id discovery: some companions advertise their name without the NUS service UUID. The picker may consequently show other nearby devices; connection still requires the expected NUS characteristics. Meshtastic and RNode keep their service filters. A generic service-discovery failure does not establish a pairing problem: the UI suggests closing another connected app, restarting/scanning the radio, and checking companion firmware. Authentication failures retain the explicit pairing flow.