Skip to content

Linux/Web/Windows/Apple: name a disconnected device in GATT request failures (#394) - #396

Merged
fotiDim merged 5 commits into
mainfrom
fix/394-platform-disconnect-parity
Nov 23, 2026
Merged

fotiDim merged 5 commits into
mainfrom
fix/394-platform-disconnect-parity

Conversation

@fotiDim

@fotiDim fotiDim commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #395, now rebased directly onto main, which contains #395. Completes the cross-platform part of #394.

Rebased onto 643ea0f after #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 deviceDisconnected on one platform and something unrelated on the next. Android now fails a read, write, descriptor read/write or subscription on a dead link with deviceDisconnected; this PR makes the others agree.

Platform Before After
Linux characteristicNotFound after a drop (BlueZ removes the GATT object tree with the link), or readFailed/writeFailed from NotConnected deviceDisconnected
Web unclassified NetworkError from the browser, or characteristicNotFound because the service cache is cleared on disconnection; unknown device also reported as a missing characteristic deviceDisconnected, and deviceNotFound for an unknown device
Windows failed — the request was issued before ConnectionStatusChanged removed the client and completed with Unreachable deviceDisconnected
Apple reads, descriptor reads/writes and subscriptions were handed to CoreBluetooth on a disconnected peripheral (writeValue and discoverServices were already guarded) deviceDisconnected, like writeValue since #378

The 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

  • Linux/Web — one resolve-and-check helper per platform. Linux funnels every GATT request through _getCharacteristic, so the check lives there; Web checks before the characteristic lookup because its cache is cleared on disconnection. Web reads the browser's own gatt.connected flag rather than the dependency's connected stream: the stream is seeded from that flag but only updates once the browser dispatches gattserverdisconnected, which happens in a task, so it still reports connected right after disconnect() or a drop detected in the same turn. The gatt getter is @visibleForTesting, so the read carries a scoped ignore. Both platforms throw the same Device Disconnected message as Android, Windows and Apple.
  • Windows — HasLiveLink(agent) sits next to GetConnectedDevice and is consulted by ReadValue, WriteValue, ReadDescriptorValue, WriteDescriptorValue and SetNotifiableAsync after the characteristic lookup, so characteristicNotFound keeps its precedence. A ConnectionStatus() read that throws counts as connected; the operation then reports the real error.
  • Apple — the same peripheral.state == .connected guard writeValue uses, placed the same way (lookup first, then state, then property/support checks).
  • Docs — CHANGELOG entries under the unreleased 3.4.1 section. The README no longer says the fail-fast is Android-only; it documents the behaviour under Error Handling, notes that it applies without autoConnect, and states that Linux/Web report deviceDisconnected before the characteristic lookup while Android/Windows/Apple still report characteristicNotFound first.

Verification

  • flutter analyze: clean. flutter test: 341 passed.
  • Apple: sources typecheck against FlutterMacOS.framework; the isolated Apple helpers (run_write_ownership_test.sh, run_discovery_progress_test.sh, run_central_restoration_owner_test.sh) pass.
  • Android (Android: refuse requests on a disconnected autoConnect client (#394) #395): ./gradlew :universal_ble:testDebugUnitTest, 119 passed.
  • Windows: not buildable on the machine this was written on; CI's windows job compiles it.
  • Linux/Web/Apple have no unit coverage for these paths (they need BlueZ/D-Bus, Web Bluetooth, and a connected CBPeripheral), so this is a code-inspection change.

Manual checks before the 3.4.1 release

  • Apple — read, descriptor read/write and subscribe on a connected peripheral, then repeat after a link loss. The guards are the one part where the platform's own callback behaviour can't be checked here.
  • Linux, connect then read immediately — await connect(), then readValue() on the same device with no call in between (no discoverServices, no wait for connectionStream). A live link must not be refused with deviceDisconnected: BlueZDevice.connected is a cached D-Bus property and connect() only awaits the Connect reply, 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.

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
fotiDim force-pushed the fix/394-platform-disconnect-parity branch from 18d9312 to e045212 Compare November 23, 2026 10:44
@fotiDim
fotiDim merged commit 8e13599 into main Nov 23, 2026
3 checks passed
@fotiDim
fotiDim deleted the fix/394-platform-disconnect-parity branch November 23, 2026 10:50
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.
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