Skip to content

Android: refuse requests on a disconnected autoConnect client (#394) - #395

Merged
fotiDim merged 2 commits into
mainfrom
fix/394-autoconnect-link-loss
Nov 23, 2026
Merged

fotiDim merged 2 commits into
mainfrom
fix/394-autoconnect-link-loss

Conversation

@fotiDim

@fotiDim fotiDim commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Fixes #394.

Problem

With connect(autoConnect: true), the BluetoothGatt client stays open after a link loss. A request submitted in the gap before Android reconnects it still finds the client in the registry and the characteristic in the cached service tree. Below API 33 the stack accepts the request (e.g. writeCharacteristic returns true) and then drops it without a callback:

E/BtGatt.GattService: writeCharacteristic() - No connection for …

The pending entry outlived the disconnect: cleanup had already run, and STATE_CONNECTED swept nothing. After the reconnect the stack reused the same client, so onCharacteristicWrite completed that stale entry (oldest match) — every later write was completed by the next one's callback and the Dart call timed out after 10 s. With the per-device queue the peripheral got about one write per timeout. The same mechanism applies to reads, descriptor reads/writes and CCCD subscriptions.

Fix

  • Refuse requests without a live link. A request is now registered only while its client's link is up, checked inside the same list lock the disconnect cleanup takes (MutableList.addIfLinkedUp). Either the check sees the link gone and fails with deviceDisconnected, or the entry is registered in time for cleanup to sweep it. Applied to writeValue, readValue, writeDescriptorValue, readDescriptorValue and the CCCD write in setNotifiable, after the existing lookups so deviceNotFound, characteristicNotFound and the write-support errors keep their precedence.
  • Backstop on reconnect. A client kept open by autoConnect after STATE_DISCONNECTED is tracked until it reports STATE_CONNECTED again; at that point anything still pending for that client is failed with deviceDisconnected. Only that client's operations are touched, and a duplicate STATE_CONNECTED without an intervening link loss sweeps nothing. The existing cleanup sweep was extracted into failPendingOperations for this.
  • readDescriptorValue now registers its pending result before issuing the read, as readValue already does, so an early response cannot be lost.
  • The fallback close timer clears connectedGatts when no STATE_DISCONNECTED ever arrives.

This matches Apple, which fails a write with deviceDisconnected when its peripheral is not connected (#378).

Tests

  • New LinkLossOperationTest: a write after link loss fails immediately with deviceDisconnected and never reaches the stack; a write after the auto-reconnect completes on its own callback; a request left from the previous link is failed on reconnect; the backstop touches only the reconnecting client; a duplicate STATE_CONNECTED does not fail in-flight requests; reads/descriptor operations/subscriptions are refused the same way.
  • PluginTestSupport gains attachConnectedGatt; existing read/write/subscription tests now simulate STATE_CONNECTED so they keep exercising the stack-refusal path rather than the new gate.

./gradlew :universal_ble:testDebugUnitTest: 119 tests, 0 failures. flutter analyze: clean.

Also documents the behaviour in README.md (auto-connect) and bumps to 3.4.1 with a CHANGELOG entry.

An autoConnect client stays open after a link loss, so writeValue could
still find the cached characteristic and the stack could accept the write
and drop it without ever calling onCharacteristicWrite. The orphaned pending
entry was then completed by the first callback of the reconnected link, so
every later write lagged by one and timed out after 10 s - about one write
per timeout with the per-device queue.

Register a request only while its client's link is up, under the same lock
the disconnect cleanup sweeps, so a concurrent submit is either swept or
refused with deviceDisconnected. Apply that to reads, writes, descriptor
reads/writes and CCCD subscriptions. As a backstop, a client kept open by
autoConnect that reports STATE_CONNECTED again fails anything still pending
from its previous link. readDescriptorValue now registers its pending result
before issuing the read, as readValue already does.
…ct (#394)

Follow-up to the autoConnect link-loss fix.

- requestMtu, discoverServices and readRssi registered their pending result
  without the link check, so the same accept-and-drop gap could strand an
  entry for them. They now register under the disconnect cleanup's lock only
  while the link is up, and before issuing the request, as readValue does.
- A subscription to a characteristic without a CCCD was never gated: there is
  no CCCD write to refuse, but setCharacteristicNotification() succeeds
  locally on a linkless client and reported a subscription the stack cannot
  deliver. It is now refused like any other request.
- On STATE_CONNECTED the backstop now sweeps before connectedGatts marks the
  link up. Otherwise a request that passed the submission gate in that window
  was failed with deviceDisconnected after the stack had accepted it.
- LinkLossOperationTest: theBackstopTouchesOnlyTheReconnectingClient registered
  its write before the disconnect sweep, which cleanUpConnection already
  failed, so the test passed with the backstop removed. Register it after the
  sweep, and add coverage for the sweep ordering, the CCCD-less subscription
  and the MTU/discovery/RSSI refusal.
- MtuCompletionTest attaches its clients as connected, matching the new gate.
- README/CHANGELOG: document the wider scope and the dependency on the
  platform reporting the disconnection.

122 Android unit tests, 0 failures. flutter analyze clean.
@vienvudev

Copy link
Copy Markdown

Tested the PR head (2d9d342) on the device from #394: Samsung SC-02M, Android 11 (API 30), Magic Motion Flamingo T. My app-side workaround (close + fresh connect on link loss) was removed for this test, so the plugin's in-place autoConnect reconnect is what's being exercised.

Setup: connect(autoConnect: true), write-without-response every ~250 ms (vibration pattern), toy powered off for ~5 s and back on, 4 times (3 of them mid-pattern).

Results:

07:06:29.229 D/UniversalBle: onConnectionStateChange-> Status: 19 Remote User Terminated Connection, NewState: 0
07:06:29.236 D/UniversalBle: WRITE -> XX:XX:XX:XX:87:96 <svc> <chr> len=12 property=WITHOUT_RESPONSE   <-- 7 ms after link loss
07:06:29.241 I/flutter: UniversalBleException: Code: UniversalBleErrorCode.deviceDisconnected ...      <-- failed in 5 ms
07:06:42.249 D/BtGatt.GattService: onConnected() - clientIf=11, connId=11, status=0                    <-- same client
...
D/UniversalBle: WRITE -> ...
D/BtGatt.GattService: onWriteCharacteristic() - address=..., status=0                                 <-- 1-7 ms, Dart future completes

Not tested: API 33+, iOS, and the read / descriptor / subscription / MTU / RSSI paths beyond initial setup.

Looks good from my side. Thanks for the quick fix!

@fotiDim

fotiDim commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for running this with the workaround removed — that is the setup that actually exercises the plugin's in-place autoConnect reconnect, and the numbers match what the fix is supposed to do: a 6–29 ms submission now fails in 3–28 ms with deviceDisconnected and never reaches GattService, and 418 writes with a stable clientIf and zero timeouts confirm no orphaned entry is left to steal the next completion.

For the record on what this does not cover: MTU and RSSI are unchanged by this PR — a reconnect only sweeps anything still pending for the old link — so the device paths without evidence here are reads, descriptor reads/writes and CCCD subscriptions. They register under the same lock as the write and are covered by unit tests, but that is not the same as your four-cycle result. API 33+ is also unverified; there the write returns a status, so the link gate is a second line of defence rather than the only one.

Much appreciated.

@fotiDim
fotiDim merged commit 643ea0f into main Nov 23, 2026
3 checks passed
@fotiDim
fotiDim deleted the fix/394-autoconnect-link-loss branch November 23, 2026 10:41
fotiDim added a commit that referenced this pull request Nov 23, 2026
#395's follow-up (the wider live-link gate) landed after this branch was cut,
so its semantics are re-applied on top of the refactored structure: readRssi
and discoverServices register under the gate before issuing, requestMtu
refuses a linkless client before serving or registering, a subscription
without a CCCD is refused, and the reconnect backstop sweeps before the link
is marked up.

The two device-less tests #395 added are ported to the fixture and the pending
collections, and the backstop-ordering test observes the client state from the
failed future's inline callback instead of the removed test hook.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants