Skip to content

feat: native BLE module replacing flutter_blue_plus (iOS + Android) - #5796

Merged
mdmohsin7 merged 55 commits into
mainfrom
feat/native-ble-module
Mar 21, 2026
Merged

mdmohsin7 merged 55 commits into
mainfrom
feat/native-ble-module

Conversation

@mdmohsin7

@mdmohsin7 mdmohsin7 commented Mar 18, 2026 •

Copy link
Copy Markdown
Member

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

  • Connect Omi device on Android, verify audio streaming works
  • Connect Omi device on iOS, verify audio streaming works
  • Minimize app, lock screen for 5+ min, unlock and use another app — verify no disconnect
  • Turn off device, turn back on — verify app shows connected on both platforms
  • Unpair device from app, re-pair same device — verify it connects (no stuck loading)
  • Swipe away app — verify foreground service stops and no "Reconnecting" notification
  • Open app again after swipe-away — verify device reconnects
  • Verify location foreground task only starts when location permission is granted
  • iOS: kill app, relaunch — state restoration reconnects without scan
  • Android: CompanionDeviceManager chooser appears during onboarding
  • Android: notification shows correct state (listening/reconnecting/failed)

🤖 Generated with Claude Code

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.
@mdmohsin7
mdmohsin7 marked this pull request as ready for review March 20, 2026 17:24
@greptile-apps

greptile-apps Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR replaces the flutter_blue_plus Dart BLE stack with a full native implementation (CoreBluetooth on iOS, BluetoothGatt + CompanionDeviceManager on Android) bridged to Flutter via Pigeon. The motivation is solid — chipset-level reconnection, proper state restoration, and OS-level device presence monitoring are real improvements that cannot be achieved from Dart. The architecture (Pigeon contract, BleBridge singleton, NativeBleTransport drop-in, serialized GATT queue) is well-structured, and the iOS implementation is clean. However there is one critical correctness defect on Android and two notable API-level issues:

  • Critical — OmiBleManager.kt BLE callbacks silent on Android 12: onCharacteristicChanged and onCharacteristicRead only override the API-33+ 3/4-argument signatures. On Android 12 (API 31–32), which is still widely deployed, the OS dispatches the older 2/3-argument overloads; neither is overridden here, so all BLE notifications (audio frames) and characteristic reads are silently dropped. Audio streaming is entirely non-functional on Android 12 for this PR.
  • OmiCompanionManager.onActivityResult uses untyped deprecated getParcelableExtra: On Android 13+ the result type can differ, making the cast unsafe and potentially causing companion association to fail silently.
  • OmiCompanionManager.disassociateAll uses deprecated associations/disassociate(String) APIs: The rest of the class already uses the newer myAssociations (API 33+). Inconsistent use risks stale associations accumulating past the system limit.
  • NativeBluetoothDiscoverer duplicates device type detection: The _isBee/_isOmi/etc. helpers re-implement the logic from the existing discoverer; new device types must be added in both places.
  • devices.dart contains raw print() calls that replaced structured Logger.debug calls — these log unconditionally in production.

Confidence Score: 1/5

  • Not safe to merge — audio streaming is entirely broken on Android 12 (API 31–32) due to missing deprecated GATT callback overrides.
  • The critical P0 defect in OmiBleManager.kt means that on Android 12 (API 31–32) — a very commonly used Android version — all BLE characteristic notifications and reads silently no-op. This causes complete audio streaming failure. The two OmiCompanionManager API-level issues are secondary but also affect correctness on Android 13+. The iOS implementation and Dart transport layer are well-constructed. The score would be 4+ after fixing the GATT callback issue and companion manager APIs.
  • app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt (missing deprecated GATT callback overrides) and app/android/app/src/main/kotlin/com/friend/ios/OmiCompanionManager.kt (deprecated CompanionDeviceManager APIs).

Important Files Changed

Filename Overview
app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt Core Android BLE manager with serialized GATT queue. Critical bug: onCharacteristicChanged and onCharacteristicRead only override the API-33+ 3/4-argument signatures; on Android 12 (API 31–32) the deprecated 2/3-arg overloads fire instead, silently dropping all BLE notifications and reads. Audio streaming is completely broken for Android 12 users.
app/android/app/src/main/kotlin/com/friend/ios/OmiCompanionManager.kt CompanionDeviceManager wrapper. Two issues: getParcelableExtra in onActivityResult uses the deprecated untyped form (risky on API 33+ where the result type may differ), and disassociateAll() uses the deprecated associations / disassociate(String) APIs — the rest of the class already uses the newer myAssociations API. Stale associations can accumulate, causing future pairings to fail.
app/android/app/src/main/kotlin/com/friend/ios/OmiBleForegroundService.kt Persistent BLE foreground service with dynamic notifications. Returns START_STICKY but has no handling for null intent on OS-triggered restarts (flagged in prior review). Uses applicationInfo.icon as notification small icon which may render incorrectly on some launchers. Otherwise solid structure.
app/android/app/src/main/kotlin/com/friend/ios/BleCompanionService.kt CompanionDeviceService for OS-level device presence events. Handles both the API 31–35 string-based and API 36+ DevicePresenceEvent callback paths. The appearCount guard is process-scoped so survives service restarts but resets on process kill, which could leave the counter at -1; mitigated by the reset-on-new-appear logic.
app/ios/Runner/OmiBleManager.swift iOS CoreBluetooth manager with state restoration and zero-CPU reconnection. UUID normalisation for 16/32-bit UUIDs is well-handled. CBCentralManager uses queue: nil (main thread), which is necessary for Pigeon compatibility but means all audio notifications fire on the main thread. Clean-up of read/write completions on disconnect is correct.
app/lib/services/devices/transports/native_ble_transport.dart Dart-side BLE transport over Pigeon. Re-subscription after auto-reconnect via _activeSubscriptionKeys is well-designed. Connection timeout of 30 s doesn't cancel the native connection, which can cause a late native connect callback to drive an unexpected _resubscribeAfterReconnect on a transport the caller considers disconnected. Several print calls should use the project logger.
app/lib/services/bridges/ble_bridge.dart Singleton Pigeon event dispatcher. Clean registration/unregistration pattern with UUID-keyed maps. Handles all BleFlutterApi callbacks correctly.
app/lib/services/devices/discovery/native_bluetooth_discoverer.dart Native BLE device scanner. Device type detection logic duplicates the existing discoverer's mapping; new device types added to the fleet won't be seen here unless this file is updated in parallel. Callback restore in the finally block is correct.
app/lib/providers/device_provider.dart Added fast-path in periodicConnect that calls ensureConnection before falling through to the polling timer. Indentation is inconsistent in the new block (flagged in prior review). Logic is sound.
app/lib/services/devices.dart Switches discoverer list to NativeBluetoothDiscoverer. Four Logger.debug calls were replaced with raw print() calls, which are not filtered in release builds and don't integrate with the structured logging system.
app/android/app/src/main/AndroidManifest.xml Correct manifest additions: CompanionDevice permissions, BleCompanionService with proper intent-filter and BIND_COMPANION_DEVICE_SERVICE permission, OmiBleForegroundService with connectedDevice foreground type, and flutter_foreground_task type changed from connectedDevice
app/lib/pigeon_interfaces.dart Well-defined Pigeon contract covering scan, connect/disconnect, GATT characteristic operations, and state events. Cross-platform parity between iOS and Android. No issues found.

Sequence Diagram

sequenceDiagram
    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)
Loading

Last reviewed commit: "fix: use CompanionDe..."

Comment on lines +445 to +459
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
}

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 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

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 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.

Suggested change
private val rssiKeepAliveInterval = 500L // ms
private val rssiKeepAliveInterval = 5000L // ms — prevents link supervision timeout; 5s is sufficient

Comment thread app/lib/providers/device_provider.dart Resolved
… deadlock

Android doesn't fire onCharacteristicWrite for WRITE_TYPE_NO_RESPONSE,
so the GATT queue would block forever after the first no-response write.
@mdmohsin7

Copy link
Copy Markdown
Member Author

@greptile-apps re-review

Comment on lines +573 to +578

if (!gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)) {
Log.w(TAG, "Failed to request high connection priority")
}

completeCommand()

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.

P0 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)
}

Comment on lines +97 to +104
* 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")

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 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
    ...
}

Comment on lines +119 to +131
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}")
}
}

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 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}")
            }
        }
    }
}

Comment thread app/lib/services/devices.dart Outdated
Comment on lines 133 to 152
@@ -146,7 +152,7 @@ class DeviceService implements IDeviceService {
if (_connection != 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.

P2 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:

Suggested change
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');

@mdmohsin7
mdmohsin7 merged commit 11105d6 into main Mar 21, 2026
1 of 2 checks passed
@mdmohsin7
mdmohsin7 deleted the feat/native-ble-module branch March 21, 2026 16:11
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…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)
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.

2 participants