Repository navigation
feat: native-owned BLE connection pipeline - #6085
Conversation
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()
Greptile SummaryThis 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 Confidence Score: 3/5Two 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
Sequence DiagramsequenceDiagram
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
|
| 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
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 // ← guardAdditionally, bondCompletionCallback is a single slot, so two concurrent requestBond() calls will corrupt each other's callbacks (the second overwrites the first).
| // Limitless requires an encrypted link — bond before accessing characteristics | ||
| await transport.requestBond(); |
There was a problem hiding this comment.
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.
|
@greptile-apps re-review |
## 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)
Summary
discoverServices; native handles connect → discover → MTU → notify DartonPeripheralConnectedevents —connectPeripheral/reconnectKnownPeripheralreturn silently when already connected (matching Fieldy's pattern)requestBond()— new Pigeon method for devices that need encrypted links (Limitless)Problem
The old pipeline had Dart driving intermediate
discoverServicescalls and aggressive bonding on every connection, causing:createBond()on every reconnection caused authentication failures and "could not pair" popupsonPeripheralConnectedevents — CompanionService re-notifications replaced_servicesCompletermid-flight, causing 15s timeoutsensureConnection(force=true)tore down transports while native auto-reconnect was in progressCloses #6082
Test plan
🤖 Generated with Claude Code