Skip to content

Android: one state field per GATT client, one pending-operation registry, one submit path - #397

Merged
fotiDim merged 14 commits into
mainfrom
refactor/android-plugin-structure
Nov 23, 2026
Merged

fotiDim merged 14 commits into
mainfrom
refactor/android-plugin-structure

Conversation

@fotiDim

@fotiDim fotiDim commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Refactor follow-up to #395 / #396, now rebased onto main after both merged. Android only, no platform-channel or Dart API change.

It was originally cut before #395's follow-up landed, so this branch merges main once (7ea32f3) and re-applies that follow-up's semantics on top of the refactored structure:

  • readRssi and discoverServices register under the live-link gate before issuing the request.
  • requestMtu refuses a linkless client before serving a cached MTU or registering.
  • A subscription to a characteristic without a CCCD is refused, not reported as successful.
  • The reconnect backstop sweeps before the client is marked CONNECTED, so a request that passes the gate in that window is not failed after the stack accepted it.

#395's two device-less tests are ported to the fixture and the pending collections; the backstop-ordering test observes the client state from the failed future's inline callback instead of the removed test hook.

The five refactor commits, one per item:

  1. Test fixture — GattFixture, pluginWithInlineLooper / pluginWithRecordedLooper + drainPosts, mockGatt / mockCharacteristic, typed pending-list accessors in PluginTestSupport. Ten test classes had their own copy of the gatt/handler plumbing and their own reflection keys.
  2. Per-client connection state — GattClient with CONNECTING / CONNECTED / AWAITING_RECONNECT / CLOSING / CLOSED and its autoConnect flag, held in GattRegistry. Replaces connectedGatts, closingGatts, awaitingReconnectGatts and autoConnectDevices; the registry keeps the active client per address and separately tracks closing/replaced clients, so a replacement can be published while the previous client still owes its teardown. Reads that were set membership tests (isLinkUp, superseded, keep-open, close fallback) are state reads now, and finishClose is a compare-and-set so STATE_DISCONNECTED and the fallback timer cannot close the same client twice.
  3. Typed pending-operation registry — every future implements PendingOperation (gatt, deviceId, fail), and PendingOperations<T> owns the list with add, addIfLinkedUp, remove, takeOldest, drainMatching, failMatching, any. The eight-block disconnect sweep is eight one-line sweeps; the withdraw helpers are remove calls; the MTU cache shares the MTU collection's lock.
  4. One submit path — submitGattRequest() owns registration, submission and withdrawal for read/write/descriptor read/descriptor write. Callers pass their stack call and their refusal mapping, so deviceNotFound, characteristicNotFound, the write-support codes and invalidAttributeLength keep their order. The link check and registration remain under the same lock, and a refused or throwing call is withdrawn before the reply (the [Bug]: Android: an exception in writeValue leaves its pending future registered, so every later write completes one behind and times out #387 / [Bug]: Android ≤ 12: a write issued just after a link loss on an autoConnect client is never completed, so after the auto-reconnect every write lags by one and times out #394 invariants).
  5. setNotifiable split — writeCccdDescriptor() and its status mapping extracted; the function has one reply path instead of two nested withdraws.

Behavior fixes that fell out

  • A setNotifiable whose CCCD write throws used to be left pending: the inner handler withdrew the future and rethrew, then the outer handler withdrew again, found nothing, and sent no reply — the Dart call hung until its timeout. It now fails once, and a new test covers it.
  • A write refused by the stack while a disconnect sweep was claiming the reply could be answered twice. submitGattRequest withdraws only if no other path claimed the reply, and a new test covers it.

Nothing else changes on the wire: same error codes, same messages, same completion ordering (main looper), same sweep semantics.

Verification

  • ./gradlew :universal_ble:testDebugUnitTest: 127 tests, 0 failures (122 on main + 5 refactor/LinkLoss tests). The suite covers the connection lifecycle (DisconnectCloseTest, NotificationOwnershipTest, GattOwnershipTest, LinkLossOperationTest), the pending-operation matching (GattCallbackCompletionTest, WriteCompletionTest), MTU and the disconnect sweeps.
  • flutter analyze: clean (no Dart changes; only a CHANGELOG line).
  • Not covered: no device or HIL run from here. Since this rewrites connection teardown, a pass of hil/ on a real peripheral before merging is worth it.

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.
Neither platform supports autoConnect, so a dropped link removes the GATT
objects (BlueZ) or clears the service cache (Web) instead of leaving a client
open. A request submitted while disconnected therefore failed as
'characteristic not found' on Linux, and on Web as an unclassified browser
NetworkError or a missing characteristic, even though the device was still
known and simply not connected.

Resolve the device once and refuse the request with deviceDisconnected when
the link is down, for reads, writes, descriptor reads/writes and
subscriptions - the same set Android gates. A BlueZ device is checked
through the platform's Connected property; on Web the connection state comes
from the dependency's seeded connected stream, as getConnectionState already
reads it. Unknown devices now report deviceNotFound on Web too.
A Windows connection has no autoConnect, but the agent stays registered until
the ConnectionStatusChanged handler runs. A request submitted between the
drop and that callback was issued to WinRT anyway and completed with
Unreachable, which maps to failed rather than deviceDisconnected.

Check the link before issuing a read, write, descriptor read/write or
subscription, and refuse it with deviceDisconnected. A status read that
throws counts as connected so the operation still reports the real error.
Only writeValue and discoverServices guarded on peripheral.state, so a read,
descriptor read/write or subscription submitted while the peripheral was
disconnected was handed to CoreBluetooth, which cannot serve it. Guard them
the same way writeValue does since #378: characteristic/descriptor lookup
first, then deviceDisconnected.

No test: these paths need a connected CBPeripheral. The sources typecheck
against FlutterMacOS.framework and the isolated Apple test helpers still
pass.
Ten test classes rebuilt the same mock device, gatt, service, characteristic and
main-looper handler, and most of them repeated the reflection keys for the
pending-operation lists. A change to the plugin's internals, or to
PluginTestSupport's reflection helpers, had to be mirrored a dozen times.

Add GattFixture (one mock peripheral: gatt + service + characteristic +
descriptors, optional stack-accepting stubs), pluginWithInlineLooper /
pluginWithRecordedLooper with drainPosts, mockGatt / mockCharacteristic, and
typed pending-list accessors in PluginTestSupport. Migrate the test classes
onto them; no test logic changes.
The plugin kept one client's connection state in five places: the address
registry, connectedGatts, closingGatts, awaitingReconnectGatts and
autoConnectDevices. Every transition in connect() / disconnect() /
onConnectionStateChange() / cleanConnection() had to update several of them,
and the close fallback timer needed extra bookkeeping to notice that a set had
already been cleared.

Give each client a GattClient record holding its gatt, its State (CONNECTING,
CONNECTED, AWAITING_RECONNECT, CLOSING, CLOSED) and its autoConnect flag, and
keep those in GattRegistry. The registry maps an address to the client API
calls resolve, and separately tracks clients that are closing or were replaced,
so a replacement can be published while the previous client still owes its
teardown. Reads that were set membership tests are now state reads:
isLinkUp, the superseded check, the keep-open decision and the fallback timer.

finishClose() is a compare-and-set, so STATE_DISCONNECTED and the fallback
timer cannot close the same client twice. autoConnect moves from an address
set to the client: connect() copies the decision onto the client it replaces,
and disconnect() withdraws it from every client of the address.
Eight hand-written lists held near-identical future classes that differed only
in their completion type. Registering, matching the oldest entry, sweeping on a
disconnect and delivering the failure were copy-pasted per list: the disconnect
sweep alone was eight blocks, and each operation kind had its own lock.

Each future now implements PendingOperation (gatt, deviceId, fail), and
PendingOperations<T> owns the list under its own monitor with add,
addIfLinkedUp, remove, takeOldest, drainMatching, failMatching, any and size.
Completion still goes through the plugin's main-looper delivery, with the same
per-kind log label.

failPendingOperations is eight one-line sweeps, the withdraw helpers are plain
remove calls, and the MTU cache shares the MTU collection's lock. The
collection also owns the link check the submission paths used to repeat, so a
request is still either registered before the sweep or refused (#394).
readValue, writeValue, readDescriptorValue and writeDescriptorValue each
repeated the same sequence: resolve the characteristic or descriptor, validate
it, register a pending result with the link check, call the stack, withdraw
and fail when it refused, and withdraw again in the exception handler. The
validation ordering was a comment in three of them, and the refusal mapping
was easy to get subtly different.

submitGattRequest() now owns registration, submission and withdrawal. It keeps
the link check and the registration under the pending collection's lock, so
the disconnect sweep cannot strand a request that is accepted afterwards
(#394), and it withdraws a refused or throwing call so a completion cannot be
delivered to an orphaned entry (#387). Callers pass their stack call and the
error their operation reports for a refusal, which keeps deviceNotFound,
characteristicNotFound, the write-support codes and invalidAttributeLength in
their existing order.

The withdrawal now also reports whether another path already claimed the
reply. A disconnect that sweeps a read or write while its stack call is
running answers the Dart call once, instead of racing a second reply.
The function carried two local closures, a reassigned pending future, nested
try/catch around the deprecated and the API 33+ descriptor overloads, and a
switch to the characteristic notification. The reply bookkeeping was the
hardest part to follow, and it had a real bug: the inner handler withdrew the
pending result and rethrew, then the outer handler tried to withdraw again,
found nothing, and sent no reply at all. A throwing CCCD write (a descriptor
rebuilt by a concurrent discovery, a closed client) left the Dart call
awaiting until its timeout.

Extract writeCccdDescriptor() and its status mapping, and give the function a
single reply path: the pending future is withdrawn once, and the failure is
delivered by the same place that detected it. A CCCD callback or disconnect
that already owns the reply still wins, so nothing is answered twice.

Cover both directions: a throwing CCCD write answers exactly once, and a write
swept by a disconnect while the stack refuses it is not answered twice.
STATE_DISCONNECTED took the client's link down only after sweeping the pending
collections, so a request submitted while the sweep ran passed the link check,
registered in a list that had already been swept, and then reached a dead link
— the #394 hang the ordering was meant to prevent. Settle the client's state
(AWAITING_RECONNECT or CLOSING) before the sweep, as the old connected-set did,
and keep the client in the active slot until it is done so a replacement
published meanwhile is still told apart from it.

The disconnect report read `wasConnected` from the client's state, which
disconnect() has already moved to CLOSING, so a locally initiated teardown that
carries a non-zero status reported connectionFailed instead of the
status-specific code. GattClient now remembers that the link came up and hands
it out once per STATE_DISCONNECTED.

cleanConnection() no longer publishes an untracked client: a teardown racing the
fallback timer could evict a newer connection from the active slot. And
connect() now tears down the client it replaces — a client left waiting for
autoConnect to reconnect it was dropped from the registry but never closed, so
it kept an open GATT and an autoConnect attempt next to the new link.
beforeDrain ran inside the collection's lock on every drain and existed for one
test. Completions are already delivered while the sweep is still running, so
that test can publish the replacement from a completion instead and exercise
the same ordering without a hook in production code.
The seeded `connected` stream only learns about a drop once the browser
dispatches `gattserverdisconnected`, which happens in a task, so a request
issued right after `disconnect()` — or in the turn a drop is detected — still
saw the device as connected. It then reached the dependency's
discoverServices(), which throws "Cannot discover services if the device is
not connected", so the caller got an unclassified error instead of
deviceDisconnected.

Read the browser's own `gatt.connected` flag instead. The getter is
`@visibleForTesting`, so the read is scoped with an ignore.

Also align the Linux and Web message with the "Device Disconnected" text
Android, Windows and Apple emit, and document the behaviour under Error
Handling in the README, including that Linux and Web report deviceDisconnected
before the characteristic lookup.
@fotiDim
fotiDim force-pushed the fix/394-platform-disconnect-parity branch from 18d9312 to e045212 Compare November 23, 2026 10:44
Base automatically changed from fix/394-platform-disconnect-parity to main November 23, 2026 10:50
#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.
@fotiDim
fotiDim merged commit 5ce6bd6 into main Nov 23, 2026
3 checks passed
@fotiDim
fotiDim deleted the refactor/android-plugin-structure branch November 23, 2026 11:03
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.

1 participant