Repository navigation
refactor(android): BLE single-owner connection model - #6200
Conversation
Fixes two Crashlytics crashes: 1. SecurityException when startScan() is called before BLUETOOTH_SCAN permission is granted (Android 12+) 2. NullPointerException in ConcurrentHashMap.put when connectGatt() returns null (Bluetooth off/unavailable) — guarded at all 3 call sites and cleans up connectingAddresses to avoid permanently blocking future connection attempts
BLUETOOTH_SCAN only exists on Android 12+ (API 31). On older devices checkSelfPermission returns DENIED for the unknown permission, which would block scanning entirely.
disconnectAllPeripherals() was called when Bluetooth turned off, which set appClosed=true and manuallyDisconnected — wrong for a BT toggle. Dart was never notified, so the UI stayed "connected". New method handleBluetoothOff() cleans up GATT, notifies Dart of each disconnect, and preserves reconnect eligibility for when BT comes back on.
…/unmanageDevice/onDeviceReady Intent-based Pigeon API: Dart tells native to "manage" or "unmanage" a device. Native owns the full lifecycle (connect, retry, bond, MTU). Fires onDeviceReady once the device is fully ready for characteristic operations.
Remove all connection policy (retry, reconnect, manuallyDisconnected, appClosed). Add BleConnectionListener interface for the foreground service. Use getRemoteLeDevice(ADDRESS_TYPE_RANDOM) on API 34+ to fix autoConnect after BT toggle. Fresh callback per connection, peek()+poll() command queue.
Owns the entire BLE connection lifecycle: connect, bond, MTU, retry, BT state changes. Manages per-device state (ManagedDevice), stability timer, stale callback rejection via GATT hash, and companion rate limiting.
Check isFlutterAlive and user_disconnected prefs before starting service. Use ObservingDevicePresenceRequest on API 36+ for device presence events.
The deprecated string-based startObservingDevicePresence was silently dropping callbacks on API 36. Use ObservingDevicePresenceRequest.Builder with setAssociationId for both start and stop.
Wait for single onDeviceReady event instead of separate connect+services. Handle auto-reconnect via _resubscribeAfterReconnect.
Bonding is now handled natively via requiresBond=true.
…SharedPreferences
Greptile SummaryThis PR replaces the prior 4-actor BLE architecture (Dart DeviceProvider, Dart DeviceService, OmiBleManager, OmiBleForegroundService, BleCompanionService each holding partial ownership of the connection) with a clean single-owner model where Key findings:
Confidence Score: 4/5Generally safe to merge; the two P1 bugs in requestMtuThenNotifyReady affect a narrow timing window but can produce incorrect connected UI state during reconnect cycles. The architecture refactor is well-conceived and fixes multiple real Android BLE reliability problems. The two P1 issues are both confined to OmiBleForegroundService.requestMtuThenNotifyReady: the unconditional fireDeviceReady in the failure path and the leaking connectionListener on disconnect-during-MTU. Both are race-condition bugs that manifest in a narrow timing window but can cause the UI to show connected during an active retry cycle. app/android/app/src/main/kotlin/com/friend/ios/OmiBleForegroundService.kt — specifically the requestMtuThenNotifyReady method Important Files Changed
Sequence DiagramsequenceDiagram
participant Dart as Dart (NativeBleTransport)
participant FgSvc as OmiBleForegroundService
participant Mgr as OmiBleManager
participant BLE as Android BLE Stack
participant Comp as BleCompanionService
Dart->>FgSvc: manageDevice(addr, requiresBond)
FgSvc->>Mgr: connectGatt(addr, autoConnect=false)
Mgr->>BLE: device.connectGatt(...)
BLE-->>Mgr: onConnectionStateChange(CONNECTED)
Mgr->>FgSvc: connectionListener.onGattConnected(addr, gatt)
Mgr->>BLE: gatt.discoverServices()
BLE-->>Mgr: onServicesDiscovered(services)
Mgr->>FgSvc: connectionListener.onGattServicesDiscovered(addr, services)
FgSvc->>Mgr: enqueueCommand { gatt.requestMtu(512) }
BLE-->>Mgr: onMtuChanged(mtu)
Mgr->>FgSvc: connectionListener.onMtuChanged(addr, mtu)
FgSvc->>Dart: flutterApi.onDeviceReady(addr, services)
Note over BLE,Mgr: On disconnect
BLE-->>Mgr: onConnectionStateChange(DISCONNECTED, gattHash)
Mgr->>FgSvc: connectionListener.onGattDisconnected(addr, gattHash, status)
FgSvc->>Dart: flutterApi.onPeripheralDisconnected(addr, error)
FgSvc->>FgSvc: handleRetryLogic → postDelayed(3s)
FgSvc->>Mgr: connectGatt(addr, autoConnect=true)
Note over Comp,FgSvc: OS-triggered reconnect (device appeared)
Comp->>FgSvc: startService(addr) [rate-limited, isFlutterAlive guard]
Reviews (1): Last reviewed commit: "chore: regenerate Pigeon bindings" | Re-trigger Greptile |
| if (!gatt.requestMtu(MTU_SIZE)) { | ||
| Log.e(TAG, "requestMtu failed for $addr") | ||
| bleManager.completeCommand() | ||
| bleManager.connectionListener = originalListener | ||
| fireDeviceReady(addr, services) | ||
| } | ||
| } catch (e: Exception) { | ||
| Log.e(TAG, "requestMtu exception for $addr: ${e.message}") | ||
| bleManager.completeCommand() | ||
| bleManager.connectionListener = originalListener | ||
| fireDeviceReady(addr, services) | ||
| } |
There was a problem hiding this comment.
Spurious
onDeviceReady emitted when device disconnects during 100ms MTU delay
fireDeviceReady is called unconditionally in both the !gatt.requestMtu() and the catch branches, but these branches are entered whenever the GATT object is no longer valid — including when the device has just disconnected. Because the MTU command is posted with a 100ms delay (handler.postDelayed(..., MTU_REQUEST_DELAY_MS)), a device that disconnects within that window will already have delivered onPeripheralDisconnected to the Dart side before the delayed lambda runs. When requestMtu then throws/returns false on the stale GATT, fireDeviceReady is posted to the main handler.
On the Dart side, _handleConnectionState(false) has already cleared _deviceReadyCompleter to null. _handleDeviceReady therefore falls into the else branch and calls _resubscribeAfterReconnect(services), which emits DeviceTransportState.connected — even though the device is in the middle of a retry cycle. This can leave the UI showing "connected" during an active reconnect.
A minimal guard is to skip fireDeviceReady when the device is no longer connected:
if (!gatt.requestMtu(MTU_SIZE)) {
Log.e(TAG, "requestMtu failed for $addr")
bleManager.completeCommand()
bleManager.connectionListener = originalListener
if (bleManager.isPeripheralConnected(addr)) {
fireDeviceReady(addr, services)
}
}and the same check in the catch block.
| val originalListener = bleManager.connectionListener | ||
| bleManager.connectionListener = object : OmiBleManager.BleConnectionListener by connectionListener { | ||
| override fun onMtuChanged(address: String, mtu: Int, status: Int) { | ||
| bleManager.connectionListener = originalListener | ||
| Log.i(TAG, "MTU done for $addr (mtu=$mtu, status=$status)") | ||
| fireDeviceReady(addr, services) | ||
| } | ||
| } |
There was a problem hiding this comment.
Temporary
connectionListener leaks if the device disconnects while requestMtu is in-flight
bleManager.connectionListener is replaced with a temporary delegate object that restores itself only inside onMtuChanged. If the device disconnects after gatt.requestMtu() returns true but before the onMtuChanged callback fires, the restore never happens. bleManager.connectionListener is left pointing at the stale temporary object from this connection attempt.
On the next reconnect, requestMtuThenNotifyReady is called again and captures the stale temporary as originalListener:
val originalListener = bleManager.connectionListener // captures stale TempA, not the service's connectionListener
bleManager.connectionListener = TempB { ...; bleManager.connectionListener = originalListener /* = TempA */ }When TempB's onMtuChanged eventually fires, it restores TempA instead of the service's connectionListener. If TempA.onMtuChanged is then triggered on a third reconnect cycle, it fires fireDeviceReady with the first connection's service list — stale services.
Consider replacing the listener-swap approach with a flag on ManagedDevice (e.g., awaitingMtu: Boolean) so that connectionListener.onMtuChanged routes directly to fireDeviceReady for the right device without mutating the global listener reference.
| val addr = address.uppercase() | ||
| val managed = managedDevices[addr] ?: return | ||
|
|
||
| if (isDestroying || status == -1 || !isBluetoothEnabled) return |
There was a problem hiding this comment.
The status == -1 branch suppresses retries, but no code path in this refactor passes -1 to handleDisconnection / handleRetryLogic. Android GATT status codes are non-negative, and all callers of onGattDisconnected forward the real GATT status. This guard is vestigial from the old architecture and will never fire.
| if (isDestroying || status == -1 || !isBluetoothEnabled) return | |
| if (isDestroying || !isBluetoothEnabled) return |
) ## Summary Refactors the Android BLE connection architecture from 4+ competing actors (Dart DeviceProvider, Dart DeviceService, native OmiBleManager, native OmiBleForegroundService, and BleCompanionService) to a single-owner model where `OmiBleForegroundService` owns the entire connection lifecycle. ### Problems solved 1. **BT toggle reconnection failure**: After toggling Bluetooth off/on, `autoConnect=true` silently failed because Android clears the BLE device cache for unbonded devices and defaults to the wrong address type (PUBLIC instead of RANDOM). Fixed by using `getRemoteLeDevice(ADDRESS_TYPE_RANDOM)` on API 34+. 2. **API 36 CompanionDeviceManager callbacks silently dropped**: The deprecated `startObservingDevicePresence(String)` API doesn't fire callbacks on API 36. Fixed by using `ObservingDevicePresenceRequest.Builder().setAssociationId()`. 3. **Race conditions on reconnect**: Multiple actors calling `connectGatt` simultaneously caused zombie GATT objects and prevented reconnection. Fixed with pending GATT hash guards and pending retry checks in `manageDevice`. 4. **UI stale after unpair**: `BatteryInfoWidget` read directly from SharedPreferences instead of the provider, showing stale device info after unpair. 5. **Disconnect/unpair while device off**: Previous code required an active connection to unpair. Now `forgetDevice` tears down the transport regardless of connection state. ### Architecture ``` Dart (NativeBleTransport) │ manageDevice / unmanageDevice (Pigeon) ▼ BleHostApiImpl → OmiBleForegroundService (single connection owner) │ connectToDevice / handleDisconnection / handleRetryLogic │ BT state receiver (TURNING_OFF cleanup, STATE_ON reconnect) │ Bond state receiver ▼ OmiBleManager (pure GATT wrapper) │ connectGatt / disconnectGatt / closeGatt │ BleConnectionListener → back to ForegroundService ▼ Android BLE Stack BleCompanionService (OS-triggered) │ onDevicePresenceEvent (API 36+) / onDeviceAppeared (API 31-35) │ Guards: isFlutterAlive, user_disconnected, rate limiting ▼ OmiBleForegroundService.startService() ``` ### Key design decisions - **`autoConnect=false` for initial connect, `autoConnect=true` for retries**: Initial connection is nearby (from scan), retries need passive background scan that survives BT toggle. - **`getRemoteLeDevice(ADDRESS_TYPE_RANDOM)`**: Omi uses a static random BLE address. After BT toggle, Android loses the cached address type for unbonded devices and defaults to PUBLIC, causing silent connection failure. - **`START_NOT_STICKY`**: Omi streams audio via WebSocket which needs the Flutter app. No point keeping BLE alive without it (unlike devices with native audio pipelines). - **`isFlutterAlive` flag**: Prevents CompanionService from uselessly starting the foreground service when the app is dead. - **Stale callback rejection via GATT hashCode**: Each connection attempt gets a fresh `BluetoothGattCallback`. The `ManagedDevice.currentGattHash` ensures disconnect callbacks from old GATT objects are ignored. - **2-second delay on BT ON**: The BLE stack needs time to fully initialize after Bluetooth turns on before `connectGatt` can work reliably. ### Files changed | File | What changed | |------|-------------| | `pigeon_interfaces.dart` | New API: `manageDevice`/`unmanageDevice`/`onDeviceReady` replacing `connectPeripheral`/`reconnectKnownPeripheral`/`onPeripheralConnected`/`onServicesDiscovered` | | `PigeonCommunicator.g.*` | Regenerated bindings (Dart, Kotlin, Swift) | | `OmiBleManager.kt` | Pure GATT wrapper: removed all connection policy, added `BleConnectionListener`, `getRemoteLeDevice`, fresh callback per connection, peek()+poll() command queue | | `OmiBleForegroundService.kt` | Connection owner: `ManagedDevice` state, `manageDevice`/`unmanageDevice`, retry logic, BT state handling (TURNING_OFF cleanup + STATE_ON reconnect with 2s delay), bond pipeline, MTU negotiation, stability timer | | `BleCompanionService.kt` | `isFlutterAlive` guard, `user_disconnected` pref check, API 36 `DevicePresenceEvent` handling | | `OmiCompanionManager.kt` | `ObservingDevicePresenceRequest` on API 36+ for both start and stop | | `BleHostApiImpl.kt` | Routes `manageDevice`/`unmanageDevice` to foreground service | | `MainActivity.kt` | Sets `isFlutterAlive`, stops service on destroy | | `BleHostApiImpl.swift` | Maps `manageDevice`→`connectPeripheral`, `unmanageDevice`→`disconnectPeripheral` | | `OmiBleManager.swift` | Fires `onDeviceReady` instead of separate `onPeripheralConnected`+`onServicesDiscovered` | | `ble_bridge.dart` | `DeviceReadyCallback` replaces separate connection/services callbacks | | `native_ble_transport.dart` | Uses `manageDevice`, waits for `onDeviceReady`, handles auto-reconnect via `_resubscribeAfterReconnect` | | `device_connection.dart` | Passes `requiresBond` to transport, maps `connecting` state correctly | | `limitless_connection.dart` | Removes Dart-side `requestBond()` (bonding now native) | | `devices.dart` | Adds `forgetDevice()`, `connecting` state | | `device_provider.dart` | Handles `DeviceConnectionState.connecting` | | `device.dart` | Unpair calls `forgetDevice` + `unmanageDevice` | | `battery_info_widget.dart` | Uses provider's `pairedDevice` instead of SharedPreferences | | `device_settings.dart` | Same unpair fix as `device.dart` | ## Test plan - [x] Fresh connect (scan → select → connect) - [x] BT toggle (off → on) — reconnects automatically - [x] Device off → on — reconnects automatically - [x] Overnight (close app, device off → morning: open app, device on) - [ ] Unpair device while connected - [ ] Unpair device while disconnected (device off) - [ ] App kill (swipe away) + reopen - [ ] Rapid BT toggle cycling - [ ] iOS — connect, disconnect, reconnect 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Summary
Refactors the Android BLE connection architecture from 4+ competing actors (Dart DeviceProvider, Dart DeviceService, native OmiBleManager, native OmiBleForegroundService, and BleCompanionService) to a single-owner model where
OmiBleForegroundServiceowns the entire connection lifecycle.Problems solved
BT toggle reconnection failure: After toggling Bluetooth off/on,
autoConnect=truesilently failed because Android clears the BLE device cache for unbonded devices and defaults to the wrong address type (PUBLIC instead of RANDOM). Fixed by usinggetRemoteLeDevice(ADDRESS_TYPE_RANDOM)on API 34+.API 36 CompanionDeviceManager callbacks silently dropped: The deprecated
startObservingDevicePresence(String)API doesn't fire callbacks on API 36. Fixed by usingObservingDevicePresenceRequest.Builder().setAssociationId().Race conditions on reconnect: Multiple actors calling
connectGattsimultaneously caused zombie GATT objects and prevented reconnection. Fixed with pending GATT hash guards and pending retry checks inmanageDevice.UI stale after unpair:
BatteryInfoWidgetread directly from SharedPreferences instead of the provider, showing stale device info after unpair.Disconnect/unpair while device off: Previous code required an active connection to unpair. Now
forgetDevicetears down the transport regardless of connection state.Architecture
Key design decisions
autoConnect=falsefor initial connect,autoConnect=truefor retries: Initial connection is nearby (from scan), retries need passive background scan that survives BT toggle.getRemoteLeDevice(ADDRESS_TYPE_RANDOM): Omi uses a static random BLE address. After BT toggle, Android loses the cached address type for unbonded devices and defaults to PUBLIC, causing silent connection failure.START_NOT_STICKY: Omi streams audio via WebSocket which needs the Flutter app. No point keeping BLE alive without it (unlike devices with native audio pipelines).isFlutterAliveflag: Prevents CompanionService from uselessly starting the foreground service when the app is dead.BluetoothGattCallback. TheManagedDevice.currentGattHashensures disconnect callbacks from old GATT objects are ignored.connectGattcan work reliably.Files changed
pigeon_interfaces.dartmanageDevice/unmanageDevice/onDeviceReadyreplacingconnectPeripheral/reconnectKnownPeripheral/onPeripheralConnected/onServicesDiscoveredPigeonCommunicator.g.*OmiBleManager.ktBleConnectionListener,getRemoteLeDevice, fresh callback per connection, peek()+poll() command queueOmiBleForegroundService.ktManagedDevicestate,manageDevice/unmanageDevice, retry logic, BT state handling (TURNING_OFF cleanup + STATE_ON reconnect with 2s delay), bond pipeline, MTU negotiation, stability timerBleCompanionService.ktisFlutterAliveguard,user_disconnectedpref check, API 36DevicePresenceEventhandlingOmiCompanionManager.ktObservingDevicePresenceRequeston API 36+ for both start and stopBleHostApiImpl.ktmanageDevice/unmanageDeviceto foreground serviceMainActivity.ktisFlutterAlive, stops service on destroyBleHostApiImpl.swiftmanageDevice→connectPeripheral,unmanageDevice→disconnectPeripheralOmiBleManager.swiftonDeviceReadyinstead of separateonPeripheralConnected+onServicesDiscoveredble_bridge.dartDeviceReadyCallbackreplaces separate connection/services callbacksnative_ble_transport.dartmanageDevice, waits foronDeviceReady, handles auto-reconnect via_resubscribeAfterReconnectdevice_connection.dartrequiresBondto transport, mapsconnectingstate correctlylimitless_connection.dartrequestBond()(bonding now native)devices.dartforgetDevice(),connectingstatedevice_provider.dartDeviceConnectionState.connectingdevice.dartforgetDevice+unmanageDevicebattery_info_widget.dartpairedDeviceinstead of SharedPreferencesdevice_settings.dartdevice.dartTest plan
🤖 Generated with Claude Code