Repository navigation
Android: one state field per GATT client, one pending-operation registry, one submit path - #397
Merged
Merged
Conversation
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
force-pushed
the
fix/394-platform-disconnect-parity
branch
from
November 23, 2026 10:44
18d9312 to
e045212
Compare
#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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Refactor follow-up to #395 / #396, now rebased onto
mainafter 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
mainonce (7ea32f3) and re-applies that follow-up's semantics on top of the refactored structure:readRssianddiscoverServicesregister under the live-link gate before issuing the request.requestMturefuses a linkless client before serving a cached MTU or registering.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:
GattFixture,pluginWithInlineLooper/pluginWithRecordedLooper+drainPosts,mockGatt/mockCharacteristic, typed pending-list accessors inPluginTestSupport. Ten test classes had their own copy of the gatt/handler plumbing and their own reflection keys.GattClientwithCONNECTING / CONNECTED / AWAITING_RECONNECT / CLOSING / CLOSEDand itsautoConnectflag, held inGattRegistry. ReplacesconnectedGatts,closingGatts,awaitingReconnectGattsandautoConnectDevices; 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, andfinishCloseis a compare-and-set soSTATE_DISCONNECTEDand the fallback timer cannot close the same client twice.PendingOperation(gatt,deviceId,fail), andPendingOperations<T>owns the list withadd,addIfLinkedUp,remove,takeOldest,drainMatching,failMatching,any. The eight-block disconnect sweep is eight one-line sweeps; the withdraw helpers areremovecalls; the MTU cache shares the MTU collection's lock.submitGattRequest()owns registration, submission and withdrawal for read/write/descriptor read/descriptor write. Callers pass their stack call and their refusal mapping, sodeviceNotFound,characteristicNotFound, the write-support codes andinvalidAttributeLengthkeep 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).setNotifiablesplit —writeCccdDescriptor()and its status mapping extracted; the function has one reply path instead of two nested withdraws.Behavior fixes that fell out
setNotifiablewhose 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.submitGattRequestwithdraws 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 onmain+ 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).hil/on a real peripheral before merging is worth it.