Skip to content

feat: native-owned BLE connection pipeline - #6085

Merged
mdmohsin7 merged 17 commits into
mainfrom
feat/native-ble-pipeline
Mar 27, 2026
Merged

mdmohsin7 merged 17 commits into
mainfrom
feat/native-ble-pipeline

Conversation

@mdmohsin7

@mdmohsin7 mdmohsin7 commented Mar 27, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Native owns the full BLE connection pipeline — Dart no longer calls discoverServices; native handles connect → discover → MTU → notify Dart
  • No duplicate onPeripheralConnected events — connectPeripheral/reconnectKnownPeripheral return silently when already connected (matching Fieldy's pattern)
  • Discover-first, no aggressive bonding — services are discovered immediately after GATT connect regardless of bond state; bonding removed from the connection pipeline since Omi doesn't require it
  • Per-device bonding via requestBond() — new Pigeon method for devices that need encrypted links (Limitless)
  • iOS RSSI keep-alive — 1s polling added to prevent connection supervision timeout
  • Status 22 and 147 added to retryable GATT codes

Problem

The old pipeline had Dart driving intermediate discoverServices calls and aggressive bonding on every connection, causing:

  1. Status=5 stale bond loops — after device power cycle, createBond() on every reconnection caused authentication failures and "could not pair" popups
  2. Duplicate onPeripheralConnected events — CompanionService re-notifications replaced _servicesCompleter mid-flight, causing 15s timeouts
  3. Dart/native reconnection races — ensureConnection(force=true) tore down transports while native auto-reconnect was in progress

Closes #6082

Test plan

  • Android Omi: fresh connect → audio streaming works
  • Android Omi: disconnect → reconnect works
  • Android Omi: device power cycle → auto-reconnect without re-pairing
  • Android Limitless: connect → bond → encrypted data streams
  • Android Limitless: disconnect → reconnect works
  • iOS: fresh connect
  • iOS: disconnect → reconnect
  • iOS: state restoration after app kill

🤖 Generated with Claude Code

Native side now owns the full connection pipeline — Dart no longer
drives intermediate service discovery steps.
Remove Dart-initiated discoverServices call. connect() now fires
connectPeripheral and waits for native to complete the full pipeline
(connect → discover → MTU) before receiving onServicesDiscovered.
- Always discover services immediately after connection (bond-independent)
- Bond initiated 1s after discovery with 15s timeout to prevent hangs
- bondStateReceiver simplified: no longer triggers discovery, just logs
- Status 22 added to retryable codes for paired-to-another-phone recovery
- Remove public discoverServices() method (no longer called from Dart)
- Clean up bondTimeoutRunnable on disconnect

Fixes overnight reconnect scenario where createBond() with no timeout
would hang forever, blocking service discovery and causing "failed to
pair" errors that required manual re-pairing.
Method removed from Pigeon interface — native pipeline handles
service discovery internally.
…evice bonding

- Always discover services immediately after GATT connect (bond-independent)
- Remove aggressive bond-after-discovery that caused stale bond loops
- Return silently when already connected (no duplicate onPeripheralConnected)
- Add requestBond() for devices needing encrypted links (e.g. Limitless)
- Add status 22 and 147 to retryable GATT codes
- didConnect already calls discoverServices natively
- Add 1s RSSI polling as connection keep-alive
- Add didReadRSSI delegate callback
iOS handles bonding automatically at the OS level.
Native owns service discovery pipeline. requestBond added for
devices requiring encrypted links.
Default no-op implementation — only overridden by NativeBleTransport.
connect() now awaits native-owned pipeline. requestBond() delegates
to native for devices needing encrypted links.
Limitless requires encrypted link for data streaming. Bond is
requested after connect, before subscribing to characteristics.
- Cancel pending bondTimeoutRunnable and fail bondCompletionCallback
  on peripheral disconnect to prevent stale callbacks
- Fix comment that said bonding happens after onServicesDiscovered
- Add missing @OverRide on NativeBleTransport.requestBond()
@mdmohsin7
mdmohsin7 marked this pull request as ready for review March 27, 2026 18:42
@greptile-apps

greptile-apps Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR moves the full BLE connection pipeline (connect → discover services → MTU → notify Dart) into native code on both iOS and Android, removing Dart's intermediate discoverServices call. It also decouples bonding from the connection pipeline entirely — bonding is now an explicit on-demand step via a new requestBond() Pigeon method used only by the Limitless device. iOS gains a 1 s RSSI keep-alive to prevent connection supervision timeouts, and Android adds GATT status codes 22 and 147 to the retryable set.\n\nKey findings:\n- cleanupPeripheral on Android unconditionally clears in-progress bond state regardless of which device triggered the cleanup, breaking Limitless bonding if any other device disconnects at the same moment.\n- Both iOS and Android now return silently from connectPeripheral/reconnectKnownPeripheral when the device is already connected; this prevents duplicate events but also means Dart's _connectCompleter can never be completed (30 s timeout) when Dart calls connect() and native already holds an active GATT connection — most likely in the state-restoration path (noted as unchecked in the test plan).\n- The Limitless connect() flow logs a warning when bonding fails but proceeds to subscribe encrypted characteristics anyway, which will likely result in silent GATT errors downstream rather than a clear failure surface.

Confidence Score: 3/5

Two P1 defects remain: unscoped bond cancellation in cleanupPeripheral and the _connectCompleter timeout regression on the already-connected path.

The core Android/iOS happy-path improvements are well-designed and the test matrix covers the primary scenarios, but the two identified defects affect real device configurations (multi-device and state restoration) and represent behavioral regressions from the previous implementation.

app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt (cleanupPeripheral bond scope) and app/lib/services/devices/transports/native_ble_transport.dart (_connectCompleter timeout regression)

Important Files Changed

Filename Overview
app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt Core Android BLE manager refactored to drop bonding from the connection pipeline and add on-demand requestBond(). cleanupPeripheral has a scope bug: it unconditionally cancels any in-progress bond regardless of which device disconnected.
app/lib/services/devices/transports/native_ble_transport.dart Dart transport simplified to trust native for the full connect→discover pipeline; adds requestBond(). _connectCompleter can hang indefinitely (30s timeout) when native returns silently for already-connected devices.
app/ios/Runner/OmiBleManager.swift iOS BLE manager gains RSSI keep-alive polling (1 s) to prevent supervision timeout; discoverServices removed from public API; connectPeripheral now returns silently if already connected (state restoration edge case is unvalidated).
app/lib/services/devices/limitless_connection.dart Calls requestBond() before subscribing characteristics; bond failure is logged but does not throw — encrypted characteristic subscription may still be attempted and will silently fail.
app/lib/services/devices/transports/device_transport.dart Adds requestBond() as a default no-op (=> true) on the base transport — clean addition with correct semantics.
app/ios/Runner/BleHostApiImpl.swift Replaces discoverServices with requestBond; iOS always returns success immediately since the OS handles bonding automatically — correct.
app/android/app/src/main/kotlin/com/friend/ios/BleHostApiImpl.kt Thin delegation change: swaps discoverServices for requestBond — straightforward and correct.
app/lib/pigeon_interfaces.dart Pigeon interface updated from discoverServices to async requestBond — correctly annotated with @async.
app/lib/gen/pigeon_communicator.g.dart Auto-generated Pigeon glue code updated for requestBond — no manual changes required here.
app/android/app/src/main/kotlin/com/friend/ios/PigeonCommunicator.g.kt Generated Kotlin Pigeon glue updated for requestBond — async reply pattern implemented correctly.
app/ios/Runner/PigeonCommunicator.g.swift Generated Swift Pigeon glue updated for requestBond — async result pattern implemented correctly.

Sequence Diagram

sequenceDiagram
    participant D as Dart (NativeBleTransport)
    participant P as Pigeon
    participant N as Native (iOS/Android)
    participant BLE as BLE Chipset

    Note over D,BLE: Fresh Connection
    D->>P: connectPeripheral(uuid)
    P->>N: connectPeripheral
    N->>BLE: connectGatt / centralManager.connect
    BLE-->>N: onConnectionStateChange(CONNECTED)
    N->>P: onPeripheralConnected(uuid)
    P-->>D: _connectCompleter.complete()
    N->>BLE: discoverServices()
    BLE-->>N: onServicesDiscovered(services)
    N->>P: onServicesDiscovered(uuid, services)
    P-->>D: _servicesCompleter.complete(services)
    D->>D: _state = connected

    Note over D,BLE: Limitless Bond (on-demand)
    D->>P: requestBond(uuid)
    P->>N: requestBond
    N->>BLE: device.createBond()
    BLE-->>N: ACTION_BOND_STATE_CHANGED (BONDED)
    N-->>P: Result(true)
    P-->>D: bonded = true
    D->>D: subscribe encrypted characteristics

    Note over D,BLE: Already-Connected Path (regression)
    D->>P: connectPeripheral(uuid)
    P->>N: connectPeripheral
    N->>N: peripheral.state==connected, silent return
    Note over D: _connectCompleter never completes, 30s timeout
Loading

Comments Outside Diff (2)

  1. app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt, line 519-527 (link)

    P1 Bond state teardown is not scoped to the disconnecting device

    cleanupPeripheral(address) receives a specific device address, but the bond state fields (bondingAddress, bondTimeoutRunnable, bondCompletionCallback) are cleared unconditionally on lines 523–527. In a two-device scenario — e.g. Omi and Limitless both connected — a disconnect event for Omi (or any other device) will cancel an in-progress Limitless bond and invoke the callback with false, even though addr != bondingAddress.

    The read/write completions and servicesDiscoveredFor correctly filter by addr.lowercase(); the bond state should do the same:

    if (bondingAddress == addr) {
        bondingAddress = null
        bondTimeoutRunnable?.let { mainHandler.removeCallbacks(it) }
        bondTimeoutRunnable = null
        bondCompletionCallback?.invoke(false)
        bondCompletionCallback = null
    }
  2. app/lib/services/devices/transports/native_ble_transport.dart, line 56-67 (link)

    P1 _connectCompleter hangs when native returns silently for an already-connected device

    Both iOS (connectPeripheral) and Android (connectPeripheral/reconnectKnownPeripheral) now return silently when the peripheral is already connected. In those paths, neither didConnect (iOS) nor onConnectionStateChange(CONNECTED) (Android) fire, so onPeripheralConnected is never sent to Dart. That means _connectCompleter is never completed and connect() will always time out after 30 seconds.

    This regression is most visible in two real-world scenarios:

    1. iOS state restoration after app kill — willRestoreState populates peripherals with .connected peripherals but skips calling centralManager.connect() for them. When Dart then calls connectPeripheral, the iOS guard (if peripheral.state == .connected { return }) fires, no didConnect callback is delivered, and the completer stalls. This is confirmed by the unchecked test plan item "iOS: state restoration after app kill".

    2. Android: Dart state reset while GATT stays connected — If _handleConnectionState(false) resets _state to disconnected but the GATT layer remains physically connected, the next connect() call sends connectPeripheral to Android. Android detects it is still connected and returns silently; _connectCompleter never completes.

    The old code specifically re-sent onPeripheralConnected (and onServicesDiscovered) to cover exactly these cases. A minimal fix is to poll on the Dart side after calling connectPeripheral:

    _hostApi.connectPeripheral(_peripheralUuid);
    
    final alreadyConnected = await _hostApi.isPeripheralConnected(_peripheralUuid);
    if (alreadyConnected && !_connectCompleter!.isCompleted) {
      _connectCompleter!.complete();
    }

    Or native should send onPeripheralConnected even in the already-connected branch (the approach the old code used for exactly this purpose).

Reviews (2): Last reviewed commit: "fix: iOS connectPeripheral silent return..." | Re-trigger Greptile

Comment on lines 97 to 112
when (bondState) {
BluetoothDevice.BOND_BONDED -> {
Log.i(TAG, "Bonding complete for $address, discovering services")
servicesDiscoveredFor.remove(address)
enqueueCommand {
if (!gatt.discoverServices()) {
Log.e(TAG, "discoverServices returned false after bonding")
completeCommand()
}
}
Log.i(TAG, "Bonding complete for $address")
bondTimeoutRunnable?.let { mainHandler.removeCallbacks(it) }
bondTimeoutRunnable = null
bondCompletionCallback?.invoke(true)
bondCompletionCallback = null
}
BluetoothDevice.BOND_NONE -> {
Log.w(TAG, "Bonding failed for $address, attempting service discovery anyway")
servicesDiscoveredFor.remove(address)
enqueueCommand {
if (!gatt.discoverServices()) {
Log.e(TAG, "discoverServices returned false after bond failure")
completeCommand()
}
}
Log.w(TAG, "Bonding failed/removed for $address")
bondTimeoutRunnable?.let { mainHandler.removeCallbacks(it) }
bondTimeoutRunnable = null
bondCompletionCallback?.invoke(false)
bondCompletionCallback = null
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Bond receiver fires for any device, not just the one being bonded

bondStateReceiver no longer validates that the address of the bond state change matches the device that was passed to requestBond(). Any bond state change broadcast from any device (including system-initiated events or a different peripheral) will invoke bondCompletionCallback and null it out.

For example, if Bluetooth re-evaluates a previously-bonded unrelated device at the same moment Limitless is pairing, BOND_BONDED from the wrong device resolves (or BOND_NONE fails) the Limitless bond future prematurely.

The old code guarded with val gatt = connectedGatts[address] ?: return to scope events to known connected devices. The new code dropped that guard. A minimal fix is to track the address being bonded and check it:

// Add to class:
private var bondingAddress: String? = null

// In requestBond():
bondingAddress = addr

// In bondStateReceiver:
val address = device.address.uppercase()
if (address != bondingAddress) return   // ← guard

Additionally, bondCompletionCallback is a single slot, so two concurrent requestBond() calls will corrupt each other's callbacks (the second overwrites the first).

Comment on lines +46 to +47
// Limitless requires an encrypted link — bond before accessing characteristics
await transport.requestBond();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Bond failure is silently ignored, connection proceeds to subscribe characteristics

requestBond() returns false on timeout or failure, but the return value is discarded here. For Limitless, a failed bond means characteristic access will fail with an "Insufficient Authentication" GATT error later. It would be clearer to surface the failure early:

final bonded = await transport.requestBond();
if (!bonded) {
  throw Exception('Limitless: bonding failed — cannot access encrypted characteristics');
}

This prevents confusing downstream failures (e.g., getCharacteristicStream silently producing no data) from obscuring the real cause.

- Add bondingAddress guard to bondStateReceiver so bond events from
  unrelated peripherals don't resolve the callback prematurely
- Clear bondingAddress on bond complete, failure, timeout, and cleanup
- Log warning when Limitless bond fails instead of silently proceeding
Match Android behavior — don't re-fire onPeripheralConnected when
the peripheral is already connected. Prevents duplicate event issues.
@mdmohsin7

Copy link
Copy Markdown
Member Author

@greptile-apps re-review

@mdmohsin7
mdmohsin7 merged commit 7645da3 into main Mar 27, 2026
2 checks passed
@mdmohsin7
mdmohsin7 deleted the feat/native-ble-pipeline branch March 27, 2026 19:56
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
## Summary

- **Native owns the full BLE connection pipeline** — Dart no longer
calls `discoverServices`; native handles connect → discover → MTU →
notify Dart
- **No duplicate `onPeripheralConnected` events** —
`connectPeripheral`/`reconnectKnownPeripheral` return silently when
already connected (matching Fieldy's pattern)
- **Discover-first, no aggressive bonding** — services are discovered
immediately after GATT connect regardless of bond state; bonding removed
from the connection pipeline since Omi doesn't require it
- **Per-device bonding via `requestBond()`** — new Pigeon method for
devices that need encrypted links (Limitless)
- **iOS RSSI keep-alive** — 1s polling added to prevent connection
supervision timeout
- **Status 22 and 147 added to retryable GATT codes**

## Problem

The old pipeline had Dart driving intermediate `discoverServices` calls
and aggressive bonding on every connection, causing:
1. **Status=5 stale bond loops** — after device power cycle,
`createBond()` on every reconnection caused authentication failures and
"could not pair" popups
2. **Duplicate `onPeripheralConnected` events** — CompanionService
re-notifications replaced `_servicesCompleter` mid-flight, causing 15s
timeouts
3. **Dart/native reconnection races** — `ensureConnection(force=true)`
tore down transports while native auto-reconnect was in progress

## Closes BasedHardware#6082

## Test plan

- [x] Android Omi: fresh connect → audio streaming works
- [x] Android Omi: disconnect → reconnect works
- [x] Android Omi: device power cycle → auto-reconnect without
re-pairing
- [x] Android Limitless: connect → bond → encrypted data streams
- [x] Android Limitless: disconnect → reconnect works
- [x] iOS: fresh connect
- [x] iOS: disconnect → reconnect
- [x] iOS: state restoration after app kill

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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.

Move BLE connection to a fully native-owned pipeline

1 participant