Skip to content

fix: BLE reliability — reconnect races, CompanionService crash, characteristic guards - #6086

Merged
mdmohsin7 merged 5 commits into
mainfrom
fix/ble-reliability
Mar 28, 2026
Merged

mdmohsin7 merged 5 commits into
mainfrom
fix/ble-reliability

Conversation

@mdmohsin7

@mdmohsin7 mdmohsin7 commented Mar 27, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Stop Dart from racing native auto-reconnect — ensureConnection no longer disposes and recreates the transport for the same device. If a transport exists (even disconnected), native owns reconnection. Only creates a new transport on first connect or device switch.
  • Native connectPeripheral skips when pending reconnect exists — prevents a competing autoConnect=false from canceling native's autoConnect=true recovery (e.g. after status=5 stale bond removal)
  • _bleDisconnectDevice properly nulls _connection — uses DeviceService.disconnectDevice() so manual disconnect → reconnect works correctly
  • Prevent BleCompanionService crash when app process is dead — added isInitialized check before accessing OmiBleManager.instance
  • Guard characteristic operations against missing characteristics — check discovered services before calling native read/write/subscribe. Prevents noisy exceptions for device variants (e.g. image capture on Omi vs Omi Glass)

Root cause

After a transient BLE disconnect (e.g. status=5 stale bond), native schedules auto-reconnect with autoConnect=true. But Dart's ensureConnection(force=true) would dispose the transport, create a new one, and fire connectPeripheral with autoConnect=false — canceling native's patient reconnect with an impatient direct connection that fails.

Test plan

  • Fresh connect — works
  • Manual disconnect → reconnect — works
  • Device power cycle → auto-reconnect
  • Kill app completely, have paired device nearby — no crash
  • Connect Omi device — no Characteristic not found exceptions

🤖 Generated with Claude Code

CompanionDeviceService can be started by the OS even when the app is
fully dead. Accessing OmiBleManager.instance before initialization
caused a fatal IllegalStateException.

Add isInitialized check — if the app hasn't started, there's no
Flutter engine to handle connections, so skip reconnect.
Check discovered services before calling native read/write/subscribe.
Prevents noisy exceptions when a characteristic doesn't exist on a
device variant (e.g. image capture on Omi vs Omi Glass).
@greptile-apps

greptile-apps Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR addresses two BLE reliability problems on Android: a fatal IllegalStateException crash when the OS starts BleCompanionService while the app process is dead, and noisy native exceptions when optional characteristics (e.g. image capture on Omi vs. Omi Glass) are not present on a given device variant. It also refactors ensureConnection to clearly express three connection states and simplifies the manual-disconnect path.

Key changes:

  • OmiBleManager.isInitialized computed property added; BleCompanionService.handleDeviceAppeared and onCreate now guard against accessing the uninitialized singleton — correctly fixing the crash.
  • connectPeripheral reordered to skip if pendingReconnectRunnable != null, preventing a competing autoConnect=false GATT call from racing a native-managed autoConnect=true reconnect.
  • NativeBleTransport._hasCharacteristic guard added for getCharacteristicStream, readCharacteristic, and writeCharacteristic — prevents native-side exceptions when an optional characteristic is absent.
  • ensureConnection logic simplified to three explicit branches (connected → return; same-device-disconnected → null; different/no device, force only → connect).
  • _bleDisconnectDevice now delegates to DeviceService.disconnectDevice() instead of going through ensureConnection.

Issues found:

  • pendingReconnectRunnable in connectPeripheral is not address-scoped: if a pending reconnect exists for any device, a connection to a different device is silently blocked (P2).
  • disconnectDevice() nulls _connection without calling transport.dispose(), introducing a stream-controller leak on the DFU reconnect path (P2 regression).
  • readCharacteristic silently returns [] for absent characteristics while writeCharacteristic throws — inconsistency may suppress error handling (P2).

Confidence Score: 4/5

Safe to merge with minor follow-up: two resource-management edge cases should be addressed soon but don't block normal connection flows.

All three P2 findings are non-blocking in normal operation. The transport-leak occurs only on the DFU path after manual disconnect, the reconnect-guard issue is limited to the single-device architecture, and the read/write inconsistency is cosmetic for current callers. Score 4 rather than 5 because the transport disposal regression is a real resource leak introduced by this PR.

app/lib/services/devices.dart (disconnectDevice disposal gap) and app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt (pendingReconnectRunnable address scoping).

Important Files Changed

Filename Overview
app/android/app/src/main/kotlin/com/friend/ios/BleCompanionService.kt Adds OmiBleManager.isInitialized guard before accessing the singleton, correctly preventing a crash when the OS starts the service while the app process is dead.
app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt Adds isInitialized flag; reorders connectPeripheral to skip early if a pending native reconnect exists — guard is correct for single-device use but uses a non-address-scoped pendingReconnectRunnable.
app/lib/services/devices/transports/native_ble_transport.dart Adds _hasCharacteristic guard for read/write/subscribe to prevent native exceptions; write throws on absence while read silently returns [] — minor inconsistency.
app/lib/services/devices.dart Refactors ensureConnection to three clear cases; disconnectDevice() nulls _connection without calling transport.dispose(), introducing a stream-controller leak on the DFU reconnect path.
app/lib/providers/device_provider.dart Simplifies _bleDisconnectDevice to use disconnectDevice() directly; btDevice parameter is unused in the new body but harmless.

Reviews (2): Last reviewed commit: "fix: _bleDisconnectDevice uses disconnec..." | Re-trigger Greptile

Prevents Dart from canceling native's autoConnect=true reconnect
(e.g. after status=5 bond removal) with a competing autoConnect=false
connection that fails.
…vice

If a transport exists for the device (even if disconnected), native
owns reconnection. Only create a new transport on first connect or
device switch. Dart stops racing native's auto-reconnect.
Previously called connection.disconnect() directly, leaving _connection
set. This prevented ensureConnection from creating a new transport on
manual reconnect.
@mdmohsin7

Copy link
Copy Markdown
Member Author

@greptile-apps re-review

@mdmohsin7 mdmohsin7 changed the title fix: BLE reliability — CompanionService crash & characteristic guards fix: BLE reliability — reconnect races, CompanionService crash, characteristic guards Mar 28, 2026
@mdmohsin7
mdmohsin7 merged commit cb0bc8a into main Mar 28, 2026
3 checks passed
@mdmohsin7
mdmohsin7 deleted the fix/ble-reliability branch March 28, 2026 12:44
@beastoin

Copy link
Copy Markdown
Collaborator

test?

@mdmohsin7

Copy link
Copy Markdown
Member Author

test?

tested locally

Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…cteristic guards (BasedHardware#6086)

## Summary

- **Stop Dart from racing native auto-reconnect** — `ensureConnection`
no longer disposes and recreates the transport for the same device. If a
transport exists (even disconnected), native owns reconnection. Only
creates a new transport on first connect or device switch.
- **Native `connectPeripheral` skips when pending reconnect exists** —
prevents a competing `autoConnect=false` from canceling native's
`autoConnect=true` recovery (e.g. after status=5 stale bond removal)
- **`_bleDisconnectDevice` properly nulls `_connection`** — uses
`DeviceService.disconnectDevice()` so manual disconnect → reconnect
works correctly
- **Prevent BleCompanionService crash when app process is dead** — added
`isInitialized` check before accessing `OmiBleManager.instance`
- **Guard characteristic operations against missing characteristics** —
check discovered services before calling native read/write/subscribe.
Prevents noisy exceptions for device variants (e.g. image capture on Omi
vs Omi Glass)

## Root cause

After a transient BLE disconnect (e.g. status=5 stale bond), native
schedules auto-reconnect with `autoConnect=true`. But Dart's
`ensureConnection(force=true)` would dispose the transport, create a new
one, and fire `connectPeripheral` with `autoConnect=false` — canceling
native's patient reconnect with an impatient direct connection that
fails.

## Test plan

- [x] Fresh connect — works
- [x] Manual disconnect → reconnect — works
- [x] Device power cycle → auto-reconnect
- [x] Kill app completely, have paired device nearby — no crash
- [x] Connect Omi device — no `Characteristic not found` exceptions

🤖 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