Repository navigation
Linux/Web/Windows/Apple: name a disconnected device in GATT request failures (#394) - #396
Merged
Merged
Conversation
This was referenced Nov 22, 2026
Merged
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.
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
fotiDim
added a commit
that referenced
this pull request
Nov 24, 2026
* Apple: manual HIL coverage for the #394 disconnect guard PR #396 left the Apple half of the fail-fast check untested: the guard needs a connected CBPeripheral, and there is no unit-level substitute. Add two manual integration tests to the example app, to be run on a Mac or an iOS device against a nearby peripheral that exposes a readable, a notifiable and a descriptor-bearing characteristic (the file documents the one used). apple_gatt_disconnect_test.dart Deterministic. Verifies the connected path (read, descriptor read, descriptor write through CCCD, subscribe/unsubscribe) and then both windows a link loss produces: requests raced against disconnect() while the peripheral is .disconnecting and still holds its attribute tree (all four report deviceDisconnected, the #396 guard), and requests after the disconnect completes (all four report characteristicNotFound, because CoreBluetooth has discarded CBPeripheral.services and the lookup runs before the guard). Both are refused locally, never handed to CoreBluetooth. apple_link_loss_test.dart The real link-loss case. Connects (optionally with autoConnect), waits for the peripheral to drop the link on its own, then immediately issues the same four requests and reports their codes. A drop has to be triggered on the peripheral side; the file explains how to set the wait and what NO_LINK_LOSS means. Neither test runs in CI. Observed on macOS 26.6.2 and iPadOS 26.6.1 with identical results. On iPadOS the Bluetooth prompt only surfaced once the example's NSAccessorySetupKitSupports keys were absent, so the test waits for poweredOn before scanning. * Apple: check the link before the GATT lookup The #394 guard #396 added checked `CBPeripheral.state` after the characteristic/descriptor lookup. CoreBluetooth discards a peripheral's attribute tree when the link drops, so by the time a request arrives after the drop the lookup fails first and the caller still got characteristicNotFound for a characteristic it had just used. The guard only fired in the .disconnecting window, where the tree is still cached. Move the state check ahead of the lookup in readValue, writeValue, setNotifiable, readDescriptorValue and writeDescriptorValue, matching Linux and Web. A request on a disconnected peripheral now reports deviceDisconnected whether or not CoreBluetooth still holds the tree; an unknown characteristic on a connected peripheral still reports characteristicNotFound. Android keeps the lookup-first order because an autoConnect client stays open with its services cached, which is what makes its link check reachable; a client it closes reports deviceNotFound instead. README and CHANGELOG now describe the platform split that way. Verified with example/integration_test/apple_gatt_disconnect_test.dart on macOS 26.6.2 and iPadOS 26.6.1 against a real peripheral: the connected path (read, descriptor read/write, subscribe) passes, and both the raced and the settled disconnect report deviceDisconnected for all four operations. * iOS example: build on Xcode 26 and get Bluetooth on a fresh install Two local fixes the iPad HIL run needed, kept in the repo: - Raise the example's iOS deployment target from 13.1 to 15.0 (Runner project and Podfile). Xcode 26 refuses to build 13.1; the plugin's own podspec keeps its 13.1 minimum for library consumers. - Drop the NSAccessorySetupKitSupports / NSAccessorySetupBluetoothServices / NSAccessorySetupBluetoothNames keys. With them, iPadOS 26.6.1 did not show the broad Bluetooth permission prompt on a fresh install: CBCentralManager stayed poweredOff and scanning found nothing for 90 s. Without them the prompt appears and the scan works. The example README explains that the AccessorySetupKit picker needs the keys added back, and that one build cannot do both on a first install. * Android/Windows/Apple: gate every request on the link before the lookup Steps 1 and 3 of the cross-platform alignment; step 2 (what a closed client reports) is a separate change. - Android: readValue, writeValue, setNotifiable, readDescriptorValue and writeDescriptorValue check isLinkUp(gatt) before the characteristic lookup. An autoConnect client keeps its cached tree across a link loss, so the lookup could still fail with characteristicNotFound for a characteristic the caller had used; the answer now depends on the connection, not the cache. submitGattRequest/addIfLinkedUp keep their lock-protected check as the authoritative one for the #394 race. - Windows: HasLiveLink now runs before FetchCharacteristicForOperation in ReadValue, WriteValue, ReadDescriptorValue, WriteDescriptorValue and SetNotifiableAsync, for the same reason. - Apple: requestMtu and readRssi refuse a disconnected peripheral with deviceDisconnected instead of reaching CoreBluetooth, and discoverServices uses the same "Device Disconnected" message, so the gated set and the error text match Android. Result: a known device whose link is down reports deviceDisconnected whether or not the cached attribute tree still holds the characteristic; characteristicNotFound now means the link was up. Clients the plugin has already forgotten still report deviceNotFound on Android and Windows (step 2). Verification: Android unit tests 129 passed (two new cases: an unknown characteristic on a dropped link reports disconnected, and on a live link it still reports not-found); Apple sources typecheck for macOS and iOS, the three isolated helpers pass, flutter analyze clean, flutter test 341 passed. The macOS HIL run against FS-7A25F8 now exercises six gated calls: MTU and RSSI succeed while connected and report deviceDisconnected in both the raced and the settled disconnect. Windows is compile-checked by CI. * Trim the link-check comments and drop the link-loss probe The precedence rule was repeated as a five-line comment at every call site (five times in the Android plugin, three plus two in the Swift one). State it once next to isLinkUp and leave a single line where the check is made. Delete example/integration_test/apple_link_loss_test.dart. It waits for a peripheral to drop the link on its own, which the test device never does without help, so it cannot run unattended; apple_gatt_disconnect_test.dart covers the raced and the settled disconnect deterministically. * Review follow-ups: doc accuracy, descriptor coverage, HIL cleanup - README: drop the claim that characteristicNotFound implies a live link. Android reports it for a read the stack refuses to start, which the parallel-queueId flow can produce on a live link. - requestMtu: document that a disconnected device fails with deviceDisconnected, including iOS/macOS where the value is local. - Retarget the Android value-length comments to the reordered checks: a wrong device, attribute or operation now outranks an oversized payload. - Add the descriptor precedence tests, dropped link and live link, as the characteristic paths already have. - Warn in the example's picker sheet that this build omits the AccessorySetupKit keys, so the picker cannot be shown. - HIL test: record unexpected error types instead of aborting the run, and disconnect in a teardown so a failed assertion leaves no link open.
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.
Follow-up to #395, now rebased directly onto
main, which contains #395. Completes the cross-platform part of #394.Rebased onto
643ea0fafter #395 squash-merged: the four platform bullets sit above the expanded Android bullet, and the README keeps #395's scope (MTU, service discovery, RSSI) plus its "needs the system to report the disconnection" caveat, both moved into the new Disconnected device section.What this fixes
#394 was Android-only in kind: only Android (and Apple) keep a client alive across a link loss and complete requests from a per-device pending list. The other platforms fail requests differently, so the same call answered
deviceDisconnectedon one platform and something unrelated on the next. Android now fails a read, write, descriptor read/write or subscription on a dead link withdeviceDisconnected; this PR makes the others agree.characteristicNotFoundafter a drop (BlueZ removes the GATT object tree with the link), orreadFailed/writeFailedfromNotConnecteddeviceDisconnectedNetworkErrorfrom the browser, orcharacteristicNotFoundbecause the service cache is cleared on disconnection; unknown device also reported as a missing characteristicdeviceDisconnected, anddeviceNotFoundfor an unknown devicefailed— the request was issued beforeConnectionStatusChangedremoved the client and completed withUnreachabledeviceDisconnectedwriteValueanddiscoverServiceswere already guarded)deviceDisconnected, likewriteValuesince #378The gated set is exactly the one Android gates: read, write, descriptor read/write, subscribe. MTU and service discovery keep their existing per-platform behaviour.
Commits
_getCharacteristic, so the check lives there; Web checks before the characteristic lookup because its cache is cleared on disconnection. Web reads the browser's owngatt.connectedflag rather than the dependency'sconnectedstream: the stream is seeded from that flag but only updates once the browser dispatchesgattserverdisconnected, which happens in a task, so it still reports connected right afterdisconnect()or a drop detected in the same turn. Thegattgetter is@visibleForTesting, so the read carries a scoped ignore. Both platforms throw the sameDevice Disconnectedmessage as Android, Windows and Apple.HasLiveLink(agent)sits next toGetConnectedDeviceand is consulted byReadValue,WriteValue,ReadDescriptorValue,WriteDescriptorValueandSetNotifiableAsyncafter the characteristic lookup, socharacteristicNotFoundkeeps its precedence. AConnectionStatus()read that throws counts as connected; the operation then reports the real error.peripheral.state == .connectedguardwriteValueuses, placed the same way (lookup first, then state, then property/support checks).autoConnect, and states that Linux/Web reportdeviceDisconnectedbefore the characteristic lookup while Android/Windows/Apple still reportcharacteristicNotFoundfirst.Verification
flutter analyze: clean.flutter test: 341 passed.FlutterMacOS.framework; the isolated Apple helpers (run_write_ownership_test.sh,run_discovery_progress_test.sh,run_central_restoration_owner_test.sh) pass../gradlew :universal_ble:testDebugUnitTest, 119 passed.windowsjob compiles it.CBPeripheral), so this is a code-inspection change.Manual checks before the 3.4.1 release
await connect(), thenreadValue()on the same device with no call in between (nodiscoverServices, no wait forconnectionStream). A live link must not be refused withdeviceDisconnected:BlueZDevice.connectedis a cached D-Bus property andconnect()only awaits theConnectreply, so this is what proves the plugin never reads it before BlueZ reports the connection.No version bump in this PR, so the two branches don't collide on
pubspec.yaml: 3.4.1 is still untagged and accumulates its entry here, as the repo has done for previous releases.