Repository navigation
feat: native BLE module replacing flutter_blue_plus (iOS + Android) - #5796
Conversation
Combines Watch and BLE Pigeon contracts into a single file to avoid duplicate PigeonError declarations in generated Swift code.
Auto-generated from pigeon_interfaces.dart.
Auto-generated from pigeon_interfaces.dart.
Singleton managing CBCentralManager lifecycle, connection, service discovery, characteristic read/write/subscribe, and audio batching.
Bridges Pigeon API calls to OmiBleManager for scan, connect, read/write/subscribe operations.
Dispatches BLE events from native to registered NativeBleTransport instances by peripheral UUID.
Drop-in replacement for BleTransport on iOS using native CoreBluetooth via Pigeon instead of flutter_blue_plus.
Uses BleHostApi for scanning instead of flutter_blue_plus, with early termination when target device is found.
…tion API Adds kotlinOut/kotlinOptions for Android code generation. Adds async requestCompanionDeviceAssociation method for OS-level presence events.
iOS uses state restoration instead of CompanionDeviceManager.
Thread-safe GATT lifecycle, serialized command queue, auto-reconnect with retry limits, stale event validation, connection priority, and audio notification batching.
Receives device appeared/disappeared callbacks from Android OS without polling, enabling zero-CPU background reconnection.
Keeps process alive in background. Notification text updates based on connection state: connecting, listening, reconnecting, failed, BT off.
Handles pairing via system chooser dialog, presence observation start/stop, and device disassociation with MAC address filtering.
Delegates Pigeon calls to OmiBleManager and OmiCompanionManager. Handles async companion device association with Activity result.
Initializes OmiBleManager, sets up BleFlutterApi and BleHostApi, handles CompanionDeviceManager onActivityResult.
Adds companion_device_setup feature, companion background permissions, BleCompanionService and OmiBleForegroundService declarations.
Associates device before GATT connection so the system chooser finds the still-advertising device. Enables background presence events.
Don't call discoverServices on reconnect (native does it automatically). Add _isResubscribing guard. Clear services on disconnect for fresh discovery.
The intent-filter used incorrect action names, preventing Android's CompanionDeviceManager from binding to the service. Without binding, the app lost companion device power management exemptions.
- Bypass GATT queue for RSSI keepalive reads (HCI-level, no conflicts) - Add @synchronized to queue methods to prevent race conditions - Never self-terminate RSSI keepalive timer - Clear servicesDiscoveredFor on disconnect/reconnect - Add stability timer to reset retry count after 60s - Unlimited auto-reconnect retries with 3s delay - Request CONNECTION_PRIORITY_HIGH after service discovery - Clean up comments
…hing didConnect now calls discoverServices so Dart receives onServicesDiscovered after auto-reconnect, allowing re-subscription to characteristics.
Batching was never enabled — all audio frames go through onCharacteristicValueUpdated individually as the backend expects.
Add disconnectAllPeripherals to OmiBleManager and call it from applicationWillTerminate to prevent CoreBluetooth state restoration from keeping the connection alive after the user closes the app.
Greptile SummaryThis PR replaces the
Confidence Score: 1/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant Dart as Flutter/Dart
participant Bridge as BleBridge
participant Pigeon as Pigeon (BleHostApi)
participant Native as OmiBleManager (Native)
participant OS as BLE OS Layer
Note over Dart,OS: Initial Connection Flow
Dart->>Pigeon: startScan(timeout, serviceUuids)
Pigeon->>Native: startScan()
Native->>OS: startScan / CBCentralManager.scanForPeripherals
OS-->>Native: onScanResult / didDiscoverPeripheral
Native-->>Bridge: onPeripheralDiscovered(BlePeripheral)
Bridge-->>Dart: peripheralDiscoveredCallback(peripheral)
Dart->>Pigeon: connectPeripheral(uuid)
Pigeon->>Native: connectPeripheral()
Native->>OS: connectGatt(autoConnect=false) / CBCentralManager.connect()
OS-->>Native: onConnectionStateChange(CONNECTED) / didConnect
Native->>OS: discoverServices()
Native-->>Bridge: onPeripheralConnected(uuid)
Bridge-->>Dart: _connectCompleter.complete()
OS-->>Native: onServicesDiscovered / didDiscoverServices
Native-->>Bridge: onServicesDiscovered(uuid, services)
Bridge-->>Dart: _servicesCompleter.complete(services)
Note over Dart: Transport state → connected
Dart->>Pigeon: subscribeCharacteristic(uuid, svcUuid, charUuid)
Pigeon->>Native: enqueue subscribeCharacteristic
Native->>OS: setCharacteristicNotification + writeDescriptor(CCCD)
OS-->>Native: onDescriptorWrite (completeCommand)
OS-->>Native: onCharacteristicChanged(value) [continuous audio frames]
Native-->>Bridge: onCharacteristicValueUpdated(uuid, svc, char, value)
Bridge-->>Dart: _streamControllers[key].add(value)
Note over Dart,OS: Auto-Reconnect Flow (no polling)
OS-->>Native: onConnectionStateChange(DISCONNECTED) / didDisconnect
Native-->>Bridge: onPeripheralDisconnected(uuid, error)
Bridge-->>Dart: _handleConnectionState(false) → state = disconnected
Note over Native: Android: 3s delay → connectGatt(autoConnect=true)<br/>iOS: centralManager.connect() [chipset-level]
Native->>OS: reconnect (zero CPU/radio cost on iOS)
OS-->>Native: onConnectionStateChange(CONNECTED) / didConnect
Native-->>Bridge: onPeripheralConnected(uuid)
Bridge-->>Dart: _resubscribeAfterReconnect()
Dart->>Pigeon: subscribeCharacteristic (re-subscribe all)
Note over Dart: Transport state → connected (transparent to upper layers)
Last reviewed commit: "fix: use CompanionDe..." |
| private fun cleanupPeripheral(address: String) { | ||
| val addr = address.uppercase() | ||
| servicesDiscoveredFor.remove(addr) | ||
| stopRssiKeepAlive() | ||
|
|
||
| for (key in readCompletions.keys().toList().filter { it.startsWith(addr.lowercase()) }) { | ||
| readCompletions.remove(key)?.invoke(Result.failure(Exception("Peripheral disconnected"))) | ||
| } | ||
| for (key in writeCompletions.keys().toList().filter { it.startsWith(addr.lowercase()) }) { | ||
| writeCompletions.remove(key)?.invoke(Result.failure(Exception("Peripheral disconnected"))) | ||
| } | ||
|
|
||
| gattQueue.clear() | ||
| isProcessingCommand = false | ||
| } |
There was a problem hiding this comment.
Single-instance timers and GATT queue shared across all peripherals
gattQueue, isProcessingCommand, rssiKeepAliveRunnable, stabilityTimerRunnable, and pendingReconnectRunnable are all single fields on the manager (not keyed per peripheral). cleanupPeripheral clears the shared queue (gattQueue.clear()) and resets isProcessingCommand = false, which cancels pending GATT commands for all connected peripherals — not just the one being cleaned up.
Additionally, startRssiKeepAlive stops the global rssiKeepAliveRunnable before starting a new one (line 370), so connecting a second device destroys the keep-alive for the first.
For the Omi single-device use case this rarely bites, but it's a correctness hazard that will manifest whenever two peripherals are live simultaneously (e.g. during a handoff or a second connection attempt while the old GATT is closing). These maps/timers should be keyed by address, matching the pattern already used for connectedGatts and reconnectRetryCount.
| private var isProcessingCommand = false | ||
|
|
||
| private var rssiKeepAliveRunnable: Runnable? = null | ||
| private val rssiKeepAliveInterval = 500L // ms |
There was a problem hiding this comment.
RSSI keepalive interval of 500 ms is very aggressive
Reading RSSI every 500 ms keeps the BLE radio awake constantly and adds a steady stream of HCI events. The stated goal is to prevent the link-supervision timeout during Doze/background — a 5–10 second interval is more than sufficient to satisfy Android's link-supervision requirements while dramatically reducing radio duty cycle and CPU wake-ups.
| private val rssiKeepAliveInterval = 500L // ms | |
| private val rssiKeepAliveInterval = 5000L // ms — prevents link supervision timeout; 5s is sufficient |
… deadlock Android doesn't fire onCharacteristicWrite for WRITE_TYPE_NO_RESPONSE, so the GATT queue would block forever after the first no-response write.
|
@greptile-apps re-review |
|
|
||
| if (!gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)) { | ||
| Log.w(TAG, "Failed to request high connection priority") | ||
| } | ||
|
|
||
| completeCommand() |
There was a problem hiding this comment.
Missing deprecated
onCharacteristicChanged/onCharacteristicRead overrides — silent failure on Android < 13
The three-argument onCharacteristicChanged(gatt, characteristic, value: ByteArray) and four-argument onCharacteristicRead(gatt, characteristic, value: ByteArray, status: Int) overrides were introduced in API 33 (Android 13). On Android 12 (API 31–32) — which is still in wide use — the OS calls the old deprecated two/three-argument overloads, which are not overridden here. The default no-op implementations fire, so every characteristic notification (including all audio frames) is silently dropped and every read completion is never delivered, leaving readCompletions callbacks pending forever.
This means audio streaming is completely broken for any user running Android 12 or earlier.
Fix: add the deprecated overloads that delegate to the new signatures:
@Suppress("DEPRECATION")
override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic
) {
val value = characteristic.value ?: return
onCharacteristicChanged(gatt, characteristic, value)
}
@Suppress("DEPRECATION")
override fun onCharacteristicRead(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
status: Int
) {
val value = characteristic.value ?: byteArrayOf()
onCharacteristicRead(gatt, characteristic, value, status)
}| * Handle activity result from the chooser. | ||
| * Returns the selected device MAC address, or null. | ||
| */ | ||
| fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): String? { | ||
| if (requestCode != COMPANION_REQUEST_CODE) return null | ||
| if (resultCode != Activity.RESULT_OK) return null | ||
|
|
||
| @Suppress("deprecation") |
There was a problem hiding this comment.
Deprecated
getParcelableExtra without class token — incorrect type on Android 13+
getParcelableExtra<T>() without a Class argument is deprecated in Android 13 (API 33). While the @Suppress("deprecation") suppresses the compiler warning, the bigger problem is that on API 33+ with setSingleDevice(true), the intent extra for the association result may carry an AssociationInfo rather than a ScanResult, making the cast unsafe and potentially returning null (silently swallowed by ?: return null). The companion association would then appear to succeed but the device address is never returned.
Fix: use the parameterized form and check the SDK version:
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): String? {
if (requestCode != COMPANION_REQUEST_CODE) return null
if (resultCode != Activity.RESULT_OK) return null
val scanResult: android.bluetooth.le.ScanResult? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
data?.getParcelableExtra(
CompanionDeviceManager.EXTRA_DEVICE,
android.bluetooth.le.ScanResult::class.java
)
} else {
@Suppress("DEPRECATION")
data?.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE)
} ?: return null
val address = scanResult.device.address
...
}| return companionDeviceManager.myAssociations.mapNotNull { | ||
| it.deviceMacAddress?.toString() | ||
| } | ||
| } | ||
|
|
||
| fun disassociate(idOrAddress: String) { | ||
| try { | ||
| companionDeviceManager.disassociate(idOrAddress) | ||
| } catch (e: Exception) { | ||
| Log.w(TAG, "disassociate failed: ${e.message}") | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
disassociateAll() silently no-ops on Android 13+ — stale associations accumulate
getAssociations() uses companionDeviceManager.associations (deprecated in API 33, returns List<String> of association IDs as strings), and disassociate(idOrAddress) calls companionDeviceManager.disassociate(String) which is also deprecated in API 33 in favour of disassociate(Int). On Android 13+ both the deprecated property and method are still callable, but the inconsistency is risky: the try/catch in disassociate() swallows any exception silently.
More critically, disassociateAll() is called at the start of every associate() call. If disassociation silently fails, old associations accumulate. CompanionDeviceManager has a per-app limit, and exceeding it will cause future associate() calls to fail.
The rest of the class already uses myAssociations (API 33+) correctly. Update the cleanup path to be consistent:
fun disassociateAll() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S_V2) {
companionDeviceManager.myAssociations.forEach { info ->
try { companionDeviceManager.disassociate(info.id) } catch (e: Exception) {
Log.w(TAG, "disassociate(${info.id}) failed: ${e.message}")
}
}
} else {
@Suppress("DEPRECATION")
companionDeviceManager.associations.forEach { idStr ->
try { companionDeviceManager.disassociate(idStr) } catch (e: Exception) {
Log.w(TAG, "disassociate($idStr) failed: ${e.message}")
}
}
}
}| @@ -146,7 +152,7 @@ class DeviceService implements IDeviceService { | |||
| if (_connection != null) { | |||
There was a problem hiding this comment.
Debug
print statements replacing Logger.debug in production code
Several Logger.debug calls in ensureConnection were replaced with raw print() calls. These will appear in production stdout/logcat unconditionally (no release-mode stripping, no log-level control) and don't integrate with the existing structured logging infrastructure.
Replace all the print(...) calls with Logger.debug(...) to maintain consistency with the rest of the file:
| print('[DeviceService] device lookup result: ${device?.name ?? "NULL"} (locator: ${device?.locator?.kind})'); |
The same applies to:
print('[DeviceService] Device not in discovered list, checking stored device');print('[DeviceService] Using stored device: ${device.name}');print('[DeviceService] No stored device available for $id, returning');
Shows a one-time dialog when the device is connected but has no CompanionDeviceManager association, asking users to disconnect and re-pair to get improved connection stability.
On Android < 13 (API < 33), the OS calls the old 2/3-argument overloads of onCharacteristicChanged and onCharacteristicRead. Without these, audio notifications and characteristic reads would silently fail.
…asedHardware#5796) ## Why The current BLE stack relies on `flutter_blue_plus`, a Dart-level wrapper where all BLE logic runs on the main Flutter thread. This limits what we can do at the platform level and creates reliability issues: **Reconnection is fragile and slow.** When the device goes out of range or the connection drops, a 15-second polling timer does active BLE scans to recover. Users wait up to 15 seconds to reconnect even when the device is right next to them. Native APIs offer chipset-level reconnection that happens at the BLE controller with zero CPU cost — the OS handles it automatically. **Background persistence requires workarounds.** On Android, we've been using a location background service (foreground service type `connectedDevice`) as a hack to keep the app process alive. This is fragile — Android can still kill the process, and it doesn't integrate with the OS BLE lifecycle. CompanionDeviceManager provides proper OS-level device presence events that work even when the app is killed, but this requires native code to integrate. **No OS-level device lifecycle integration.** iOS has CoreBluetooth state restoration. Android has CompanionDeviceManager with device appeared/disappeared callbacks. Both provide zero-polling reconnection that survives app termination. These APIs can't be accessed through a Dart BLE library — they need native implementation. **All BLE logic runs on the main Flutter thread.** Connection management, reconnection decisions, scan lifecycle, and notification subscriptions are all Dart-side. Moving this to native gives us direct access to platform APIs, proper background execution, and the foundation for future optimizations. ## What changed ### Cross-platform Pigeon bridge - `pigeon_interfaces.dart` defines `BleHostApi` (Dart → Native) and `BleFlutterApi` (Native → Dart) - Single contract for scan, connect, disconnect, read/write/subscribe, and companion device association - Generated code for Swift, Kotlin, and Dart — type-safe, no manual method channel wiring ### iOS native module - `OmiBleManager.swift` — CBCentralManager singleton with state restoration (`willRestoreState`) - Chipset-level reconnection via `centralManager.connect()` — zero CPU/radio while waiting - Service discovery triggered automatically on reconnect so Dart receives fresh services and re-subscribes ### Android native module - `OmiBleManager.kt` — BluetoothGatt with serialized command queue (Android only allows one pending GATT operation at a time) - Thread-safe state via `ConcurrentHashMap` and `@Synchronized` queue methods — GATT callbacks run on binder thread, Pigeon calls on main thread - Stale GATT event validation — ignores callbacks from old connection instances - Unlimited auto-reconnect with 3s delay, 60s stability timer resets retry count after stable connection - `autoConnect=true` + `requestConnectionPriority(HIGH)` — connection survives backgrounding and screen-off - RSSI keepalive reads bypass the GATT queue (HCI-level, no conflicts with queued operations) — prevents link supervision timeout during Doze/background - RSSI keepalive timer always reschedules unconditionally (never self-terminates) - `OmiBleForegroundService` — dedicated BLE foreground service with dynamic notification (listening/reconnecting/failed/BT off) - `BleCompanionService` — extends `CompanionDeviceService` with correct intent-filter for system binding, receives OS-level device appeared/disappeared events without polling - `OmiCompanionManager` — CompanionDeviceManager pairing with MAC address filtering, integrated into onboarding - `appClosed` flag prevents CompanionDeviceService from restarting connection after user swipes away the app ### Dart transport layer - `NativeBleTransport` — drop-in replacement for `BleTransport`, platform-agnostic - `BleBridge` — singleton dispatching native callbacks to registered transport instances - `NativeBluetoothDiscoverer` — native scan replacing flutter_blue_plus scanner - Auto re-subscription to characteristics after reconnection - Guard against infinite reconnect loops (`_isResubscribing` flag) ### App lifecycle - Disconnect BLE and stop foreground service when user swipes away the app (Omi streams via WebSocket which requires the app running) - `flutter_foreground_task` service type changed from `connectedDevice|location` to `location` only — BLE keepalive is handled natively now - Foreground location task only starts when location permission is granted (was starting unconditionally) ### What stays unchanged - `flutter_blue_plus` is still in the project — not removed, available as fallback - All device-specific protocol logic (OmiDeviceConnection, BeeDeviceConnection, etc.) unchanged - WebSocket streaming, UI providers, WAL sync — all unchanged ## Test plan - [x] Connect Omi device on Android, verify audio streaming works - [x] Connect Omi device on iOS, verify audio streaming works - [x] Minimize app, lock screen for 5+ min, unlock and use another app — verify no disconnect - [x] Turn off device, turn back on — verify app shows connected on both platforms - [x] Unpair device from app, re-pair same device — verify it connects (no stuck loading) - [x] Swipe away app — verify foreground service stops and no "Reconnecting" notification - [x] Open app again after swipe-away — verify device reconnects - [x] Verify location foreground task only starts when location permission is granted - [x] iOS: kill app, relaunch — state restoration reconnects without scan - [x] Android: CompanionDeviceManager chooser appears during onboarding - [x] Android: notification shows correct state (listening/reconnecting/failed) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Why
The current BLE stack relies on
flutter_blue_plus, a Dart-level wrapper where all BLE logic runs on the main Flutter thread. This limits what we can do at the platform level and creates reliability issues:Reconnection is fragile and slow. When the device goes out of range or the connection drops, a 15-second polling timer does active BLE scans to recover. Users wait up to 15 seconds to reconnect even when the device is right next to them. Native APIs offer chipset-level reconnection that happens at the BLE controller with zero CPU cost — the OS handles it automatically.
Background persistence requires workarounds. On Android, we've been using a location background service (foreground service type
connectedDevice) as a hack to keep the app process alive. This is fragile — Android can still kill the process, and it doesn't integrate with the OS BLE lifecycle. CompanionDeviceManager provides proper OS-level device presence events that work even when the app is killed, but this requires native code to integrate.No OS-level device lifecycle integration. iOS has CoreBluetooth state restoration. Android has CompanionDeviceManager with device appeared/disappeared callbacks. Both provide zero-polling reconnection that survives app termination. These APIs can't be accessed through a Dart BLE library — they need native implementation.
All BLE logic runs on the main Flutter thread. Connection management, reconnection decisions, scan lifecycle, and notification subscriptions are all Dart-side. Moving this to native gives us direct access to platform APIs, proper background execution, and the foundation for future optimizations.
What changed
Cross-platform Pigeon bridge
pigeon_interfaces.dartdefinesBleHostApi(Dart → Native) andBleFlutterApi(Native → Dart)iOS native module
OmiBleManager.swift— CBCentralManager singleton with state restoration (willRestoreState)centralManager.connect()— zero CPU/radio while waitingAndroid native module
OmiBleManager.kt— BluetoothGatt with serialized command queue (Android only allows one pending GATT operation at a time)ConcurrentHashMapand@Synchronizedqueue methods — GATT callbacks run on binder thread, Pigeon calls on main threadautoConnect=true+requestConnectionPriority(HIGH)— connection survives backgrounding and screen-offOmiBleForegroundService— dedicated BLE foreground service with dynamic notification (listening/reconnecting/failed/BT off)BleCompanionService— extendsCompanionDeviceServicewith correct intent-filter for system binding, receives OS-level device appeared/disappeared events without pollingOmiCompanionManager— CompanionDeviceManager pairing with MAC address filtering, integrated into onboardingappClosedflag prevents CompanionDeviceService from restarting connection after user swipes away the appDart transport layer
NativeBleTransport— drop-in replacement forBleTransport, platform-agnosticBleBridge— singleton dispatching native callbacks to registered transport instancesNativeBluetoothDiscoverer— native scan replacing flutter_blue_plus scanner_isResubscribingflag)App lifecycle
flutter_foreground_taskservice type changed fromconnectedDevice|locationtolocationonly — BLE keepalive is handled natively nowWhat stays unchanged
flutter_blue_plusis still in the project — not removed, available as fallbackTest plan
🤖 Generated with Claude Code