From 05b3f9c5add31d8333cdaa9f3ac74da395bf303a Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Mon, 23 Nov 2026 22:37:39 +0100 Subject: [PATCH 1/6] 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_gatt_disconnect_test.dart | 333 ++++++++++++++++++ .../apple_link_loss_test.dart | 222 ++++++++++++ 2 files changed, 555 insertions(+) create mode 100644 example/integration_test/apple_gatt_disconnect_test.dart create mode 100644 example/integration_test/apple_link_loss_test.dart diff --git a/example/integration_test/apple_gatt_disconnect_test.dart b/example/integration_test/apple_gatt_disconnect_test.dart new file mode 100644 index 00000000..cb0ef0f9 --- /dev/null +++ b/example/integration_test/apple_gatt_disconnect_test.dart @@ -0,0 +1,333 @@ +// Manual Apple HIL check for the #394 disconnect guard (PR #396). +// +// Runs the real plugin on macOS against a real peripheral. It is not part of +// CI: it needs a radio and a nearby connectable device whose GATT database has +// a readable, a notifiable and a descriptor-bearing characteristic. +// +// cd example +// flutter test integration_test/apple_gatt_disconnect_test.dart -d macos \ +// --dart-define=APPLE_BLE_TEST_DEVICE='FS-7A25F8' +// +// The device used here (FS-7A25F8) exposes: +// 180A 2A51 [read] +// FFF0 FFF1 [notify] with 2902, FFF2 [writeNoResp] +// +// It checks two windows, both of which a link loss produces: +// +// RACE_DISCONNECT The requests are issued while the peripheral is +// .disconnecting and still holds its attribute tree. +// #396's state guard settles all four with +// deviceDisconnected. +// AFTER_DISCONNECT The disconnect has completed. CoreBluetooth has +// discarded CBPeripheral.services, so the characteristic +// lookup fails before the state guard runs and the caller +// gets characteristicNotFound. The requests are still +// refused locally, never handed to CoreBluetooth. +// +// Observed on macOS 26.6.2 and iPadOS 26.6.1, 2026-11-23. +// +// On iPadOS 26.6.1 the Bluetooth permission prompt did not appear while the +// example declared NSAccessorySetupKitSupports (used by the ASK picker), and +// CBManagerState stayed poweredOff, so the scan was a no-op. Removing those +// keys surfaced the prompt; the test waits for poweredOn so it works either +// way once Bluetooth has been granted. +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:universal_ble/universal_ble.dart'; + +const String targetName = String.fromEnvironment( + 'APPLE_BLE_TEST_DEVICE', + defaultValue: 'FS-7A25F8', +); + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('Apple GATT requests: connected works, disconnected is refused', ( + tester, + ) async { + final scanned = {}; + UniversalBle.onScanResult = (device) { + scanned[device.deviceId] = device; + if (device.name == targetName) { + UniversalBle.stopScan().ignore(); + } + }; + + // On a fresh install iOS shows the Bluetooth permission prompt on first + // use and reports CBManagerState.poweredOff until it is answered. Wait for + // poweredOn before scanning, otherwise the scan is a no-op. + var availability = await UniversalBle.getBluetoothAvailabilityState(); + // ignore: avoid_print + print('WAITING_FOR_POWER $availability'); + final powerDeadline = DateTime.now().add(const Duration(seconds: 90)); + var lastSeen = availability; + while (availability != AvailabilityState.poweredOn && + DateTime.now().isBefore(powerDeadline)) { + await Future.delayed(const Duration(milliseconds: 500)); + availability = await UniversalBle.getBluetoothAvailabilityState(); + if (availability != lastSeen) { + // ignore: avoid_print + print('WAITING_FOR_POWER $availability'); + lastSeen = availability; + } + } + // ignore: avoid_print + print('AVAILABILITY $availability'); + expect( + availability, + AvailabilityState.poweredOn, + reason: 'accept the Bluetooth prompt on the device', + ); + await UniversalBle.startScan(); + final deadline = DateTime.now().add(const Duration(seconds: 60)); + BleDevice? target; + while (DateTime.now().isBefore(deadline)) { + for (final d in scanned.values) { + if (d.name == targetName) target = d; + } + if (target != null) break; + await tester.pump(const Duration(milliseconds: 250)); + await Future.delayed(const Duration(milliseconds: 250)); + } + UniversalBle.onScanResult = null; + await UniversalBle.stopScan(); + expect(target, isNotNull, reason: '$targetName was not advertising'); + final deviceId = target!.deviceId; + // ignore: avoid_print + print('DEVICE $deviceId ${target.name}'); + + await UniversalBle.connect(deviceId); + // ignore: avoid_print + print('CONNECTED ${await UniversalBle.getConnectionState(deviceId)}'); + + final services = await UniversalBle.discoverServices( + deviceId, + withDescriptors: true, + timeout: const Duration(seconds: 60), + ); + for (final s in services) { + for (final c in s.characteristics) { + // ignore: avoid_print + print( + 'GATT ${s.uuid} ${c.uuid} ${c.properties.map((p) => p.name).join(",")} ' + 'descriptors=${c.descriptors.map((d) => d.uuid).join(",")}', + ); + } + } + + final readPair = _findReadable(services); + final notifyPair0 = _findNotifiableWithCccd(services); + expect(readPair, isNotNull, reason: 'no readable characteristic'); + expect(notifyPair0, isNotNull, reason: 'no notifiable characteristic'); + + final (:service, :characteristic) = readPair!; + final readService = service; + final readCharacteristic = characteristic; + final notifyPair = notifyPair0!; + final notifyService = notifyPair.service; + final notifyCharacteristic = notifyPair.characteristic; + final cccd = notifyPair.cccd; + + // --- Connected: every request the guard now covers must succeed. --- + final value = await UniversalBle.read( + deviceId, + readService, + readCharacteristic, + ); + // ignore: avoid_print + print('READ_OK $readCharacteristic ${value.length} bytes'); + + final descriptorValue = await UniversalBle.readDescriptor( + deviceId, + notifyService, + notifyCharacteristic, + cccd, + ); + // ignore: avoid_print + print('DESCRIPTOR_READ_OK $cccd $descriptorValue'); + + await UniversalBle.writeDescriptor( + deviceId, + notifyService, + notifyCharacteristic, + cccd, + Uint8List.fromList([0x01, 0x00]), + ); + // ignore: avoid_print + print('DESCRIPTOR_WRITE_OK $cccd enable'); + + await UniversalBle.subscribeNotifications( + deviceId, + notifyService, + notifyCharacteristic, + ); + // ignore: avoid_print + print('SUBSCRIBE_OK $notifyCharacteristic'); + + await UniversalBle.unsubscribe( + deviceId, + notifyService, + notifyCharacteristic, + ); + // ignore: avoid_print + print('UNSUBSCRIBE_OK $notifyCharacteristic'); + + // --- Race the same requests against disconnect(): the peripheral is in + // .disconnecting and still holds its attribute tree, the window #396's + // state guard exists for. --- + final disconnectFuture = UniversalBle.disconnect(deviceId); + final raced = []; + Future race(String label, Future Function() action) async { + try { + await action(); + raced.add('$label=SUCCESS'); + } on UniversalBleException catch (e) { + raced.add('$label=${e.code}'); + } on TimeoutException catch (_) { + raced.add('$label=TIMEOUT'); + } + } + + await Future.wait([ + race( + 'read', + () => UniversalBle.read(deviceId, readService, readCharacteristic), + ), + race( + 'readDescriptor', + () => UniversalBle.readDescriptor( + deviceId, + notifyService, + notifyCharacteristic, + cccd, + ), + ), + race( + 'writeDescriptor', + () => UniversalBle.writeDescriptor( + deviceId, + notifyService, + notifyCharacteristic, + cccd, + Uint8List.fromList([0x00, 0x00]), + ), + ), + race( + 'subscribe', + () => UniversalBle.subscribeNotifications( + deviceId, + notifyService, + notifyCharacteristic, + ), + ), + ]); + await disconnectFuture; + // ignore: avoid_print + print('RACE_DISCONNECT ${raced.join(" ")}'); + + for (var i = 0; i < 40; i++) { + final state = await UniversalBle.getConnectionState(deviceId); + if (state == BleConnectionState.disconnected) break; + await Future.delayed(const Duration(milliseconds: 100)); + } + // ignore: avoid_print + print('DISCONNECTED ${await UniversalBle.getConnectionState(deviceId)}'); + + // --- Disconnected: the plugin must refuse these itself, not hand them to + // CoreBluetooth and wait for the timeout. Which code that is depends on + // whether CoreBluetooth has invalidated the attribute tree yet: the guard + // reports deviceDisconnected while it is cached, and the lookup reports + // characteristicNotFound once it is gone. --- + final afterDrop = []; + Future refused(String label, Future Function() action) async { + try { + await action(); + // ignore: avoid_print + print('$label: NO ERROR (unexpected)'); + fail('$label on a disconnected peripheral completed instead of failing'); + } on UniversalBleException catch (e) { + // ignore: avoid_print + print('$label: ${e.code} "${e.message}"'); + expect( + e.code, + anyOf( + UniversalBleErrorCode.deviceDisconnected, + UniversalBleErrorCode.characteristicNotFound, + ), + reason: '$label must be refused by the plugin, got ${e.code}', + ); + afterDrop.add('$label=${e.code}'); + } on TimeoutException catch (_) { + fail('$label reached CoreBluetooth and never completed'); + } + } + + await refused( + 'read', + () => UniversalBle.read(deviceId, readService, readCharacteristic), + ); + await refused( + 'readDescriptor', + () => UniversalBle.readDescriptor( + deviceId, + notifyService, + notifyCharacteristic, + cccd, + ), + ); + await refused( + 'writeDescriptor', + () => UniversalBle.writeDescriptor( + deviceId, + notifyService, + notifyCharacteristic, + cccd, + Uint8List.fromList([0x00, 0x00]), + ), + ); + await refused( + 'subscribeNotifications', + () => UniversalBle.subscribeNotifications( + deviceId, + notifyService, + notifyCharacteristic, + ), + ); + // ignore: avoid_print + print('AFTER_DISCONNECT ${afterDrop.join(" ")}'); + }); +} + +({String service, String characteristic})? _findReadable( + List services, +) { + for (final s in services) { + for (final c in s.characteristics) { + if (c.properties.contains(CharacteristicProperty.read)) { + return (service: s.uuid, characteristic: c.uuid); + } + } + } + return null; +} + +({String service, String characteristic, String cccd})? +_findNotifiableWithCccd(List services) { + for (final s in services) { + for (final c in s.characteristics) { + if (!c.properties.contains(CharacteristicProperty.notify)) continue; + for (final d in c.descriptors) { + final uuid = d.uuid.toUpperCase(); + if (uuid.endsWith('2902') || + uuid.endsWith('2902-0000-1000-8000-00805F9B34FB')) { + return (service: s.uuid, characteristic: c.uuid, cccd: d.uuid); + } + } + } + } + return null; +} diff --git a/example/integration_test/apple_link_loss_test.dart b/example/integration_test/apple_link_loss_test.dart new file mode 100644 index 00000000..2cb6cb29 --- /dev/null +++ b/example/integration_test/apple_link_loss_test.dart @@ -0,0 +1,222 @@ +// Manual Apple HIL probe: a real peripheral-side link loss. +// +// Connects to a nearby device, discovers its GATT database, then waits for the +// peripheral to drop the link on its own. On the drop it immediately issues the +// requests PR #396 guards, and reports the error code of each. This is the +// check the PR left open: a request submitted while the link is down must not +// reach CoreBluetooth. +// +// cd example +// flutter test integration_test/apple_link_loss_test.dart -d macos \ +// --dart-define=APPLE_BLE_TEST_DEVICE='FS-7A25F8' \ +// --dart-define=APPLE_BLE_AUTOCONNECT=true +// +// You have to trigger the drop yourself (power the peripheral off, walk it out +// of range); a device that only drops when it is idle rarely does so while a +// central is connected. Without a drop the test reports NO_LINK_LOSS and stops. +// `APPLE_BLE_LINK_LOSS_WAIT` sets the wait in seconds (default 180). +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:universal_ble/universal_ble.dart'; + +const String targetName = String.fromEnvironment( + 'APPLE_BLE_TEST_DEVICE', + defaultValue: 'FS-7A25F8', +); +const int waitSeconds = int.fromEnvironment( + 'APPLE_BLE_LINK_LOSS_WAIT', + defaultValue: 180, +); +const bool autoConnect = bool.fromEnvironment('APPLE_BLE_AUTOCONNECT'); + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('Apple GATT requests after a real link loss', (tester) async { + final scanned = {}; + final seenNames = {}; + UniversalBle.onScanResult = (device) { + scanned[device.deviceId] = device; + final name = device.name ?? ''; + if (name.isNotEmpty && seenNames.add(name)) { + // ignore: avoid_print + print('SEEN $name ${device.services.length} services'); + } + if (device.name == targetName) { + UniversalBle.stopScan().ignore(); + } + }; + await UniversalBle.startScan(); + final deadline = DateTime.now().add(const Duration(seconds: 60)); + BleDevice? target; + while (DateTime.now().isBefore(deadline)) { + for (final d in scanned.values) { + if (d.name == targetName) target = d; + } + if (target != null) break; + await Future.delayed(const Duration(milliseconds: 250)); + } + UniversalBle.onScanResult = null; + await UniversalBle.stopScan(); + expect(target, isNotNull, reason: '$targetName was not advertising'); + final deviceId = target!.deviceId; + // ignore: avoid_print + print('FOUND $deviceId'); + + await UniversalBle.connect(deviceId, autoConnect: autoConnect); + // ignore: avoid_print + print('MODE autoConnect=$autoConnect'); + final dropped = Completer(); + final connectedAt = DateTime.now(); + final subscription = UniversalBle.connectionChangeStream(deviceId).listen( + (change) { + // ignore: avoid_print + print( + 'EVENT t=${DateTime.now().difference(connectedAt).inMilliseconds}ms ' + 'connected=${change.isConnected} code=${change.errorCode}', + ); + if (!change.isConnected && !dropped.isCompleted) { + dropped.complete(change); + } + }, + ); + final services = await UniversalBle.discoverServices( + deviceId, + withDescriptors: true, + timeout: const Duration(seconds: 60), + ); + final readPair = _findReadable(services); + final notifyPair = _findNotifiableWithCccd(services); + expect(readPair, isNotNull); + expect(notifyPair, isNotNull); + // ignore: avoid_print + print( + 'CONNECTED read=${readPair!.characteristic} ' + 'notify=${notifyPair!.characteristic}', + ); + + // Wait for the peripheral to leave on its own. Do not poll it: the point is + // an idle link that the device tears down. + final drop = await Future.any([ + dropped.future, + Future.delayed( + Duration(seconds: waitSeconds), + () => null, + ), + ]); + if (drop == null) { + // ignore: avoid_print + print('NO_LINK_LOSS within ${waitSeconds}s; device kept the link'); + await UniversalBle.disconnect(deviceId); + await subscription.cancel(); + return; + } + // ignore: avoid_print + print( + 'LINK_LOSS error=${drop.error} code=${drop.errorCode} ' + 'native=${drop.nativeErrorCode}', + ); + + // Fire the guarded requests immediately, while the drop is fresh: this is + // the window in which a periodic timer would submit them. + final results = []; + Future probe(String label, Future Function() action) async { + try { + final value = await action(); + results.add('$label=SUCCESS(${value is List ? value.length : value})'); + } on UniversalBleException catch (e) { + results.add('$label=${e.code}'); + } on TimeoutException catch (_) { + results.add('$label=TIMEOUT'); + } + } + + await Future.wait([ + probe( + 'read', + () => UniversalBle.read( + deviceId, + readPair.service, + readPair.characteristic, + ), + ), + probe( + 'readDescriptor', + () => UniversalBle.readDescriptor( + deviceId, + notifyPair.service, + notifyPair.characteristic, + notifyPair.cccd, + ), + ), + probe( + 'writeDescriptor', + () => UniversalBle.writeDescriptor( + deviceId, + notifyPair.service, + notifyPair.characteristic, + notifyPair.cccd, + Uint8List.fromList([0x00, 0x00]), + ), + ), + probe( + 'subscribe', + () => UniversalBle.subscribeNotifications( + deviceId, + notifyPair.service, + notifyPair.characteristic, + ), + ), + ]); + // ignore: avoid_print + print('AFTER_LINK_LOSS ${results.join(" ")}'); + + // The steady state a second later, once CoreBluetooth has had time to drop + // the object's attribute tree. + await Future.delayed(const Duration(seconds: 1)); + await probe( + 'readLater', + () => UniversalBle.read( + deviceId, + readPair.service, + readPair.characteristic, + ), + ); + // ignore: avoid_print + print('LATER ${results.last}'); + + await UniversalBle.disconnect(deviceId); + await subscription.cancel(); + }, timeout: const Timeout(Duration(minutes: 12))); +} + +({String service, String characteristic})? _findReadable( + List services, +) { + for (final s in services) { + for (final c in s.characteristics) { + if (c.properties.contains(CharacteristicProperty.read)) { + return (service: s.uuid, characteristic: c.uuid); + } + } + } + return null; +} + +({String service, String characteristic, String cccd})? +_findNotifiableWithCccd(List services) { + for (final s in services) { + for (final c in s.characteristics) { + if (!c.properties.contains(CharacteristicProperty.notify)) continue; + for (final d in c.descriptors) { + if (d.uuid.toUpperCase().startsWith('00002902')) { + return (service: s.uuid, characteristic: c.uuid, cccd: d.uuid); + } + } + } + } + return null; +} From dfffddbbc1ec21e68dbae89bd63c7321d790b5bf Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Mon, 23 Nov 2026 23:15:55 +0100 Subject: [PATCH 2/6] 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. --- CHANGELOG.md | 2 +- README.md | 2 +- .../universal_ble/UniversalBlePlugin.swift | 56 ++++++++++++------- .../apple_gatt_disconnect_test.dart | 22 +++----- 4 files changed, 47 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72e00570..394d6a0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ * Linux: a read, write, descriptor read/write or subscription submitted while the device is disconnected now fails with `deviceDisconnected` instead of `characteristicNotFound` or a generic `readFailed`/`writeFailed`. BlueZ drops the GATT object tree together with the link, so the lookup used to report the characteristic as unknown — as if the device had changed its services — and a request that reached D-Bus failed with `NotConnected` under a generic code (#394). * Web: the same requests now fail with `deviceDisconnected` instead of surfacing the browser's `NetworkError` as an unclassified error, and an unknown device reports `deviceNotFound` instead of a missing characteristic. The service cache is cleared on disconnection, so the lookup previously failed before the browser could say the link was gone (#394). * Windows: the same requests now fail with `deviceDisconnected` when the link is down but the connection-status callback has not removed the client yet. The operation used to be submitted anyway and completed with `Unreachable`, which surfaced as `failed` (#394). -* Apple: reads, descriptor reads and writes, and subscriptions now refuse a disconnected peripheral with `deviceDisconnected`, as `writeValue` already did since #378, instead of submitting a request the peripheral cannot serve (#394). +* Apple: reads, writes, descriptor reads and writes, and subscriptions now check `CBPeripheral.state` before the characteristic or descriptor lookup, so a request on a disconnected peripheral fails with `deviceDisconnected`. CoreBluetooth discards a peripheral's attribute tree when the link drops, so with the previous lookup-first order the caller got `characteristicNotFound` for a characteristic it had just used. The check now runs first, as it already did on Linux and Web; an unknown characteristic on a connected peripheral still reports `characteristicNotFound` (#394). * Android: a read, write, descriptor read/write, notification subscription, MTU request, service discovery or RSSI read submitted to an `autoConnect` client after its link dropped now fails right away with `deviceDisconnected` instead of reaching the stack. The client stays open and keeps its cached services after the link loss, and below API 33 the stack accepts such a request and then drops it without a callback, leaving a pending entry that the first callback of the reconnected link completes — so every later write lagged by one and timed out after 10 s, giving about one write per timeout. The link check shares the lock with the disconnect cleanup, so a request submitted concurrently is either registered in time to be swept or refused; as a backstop, a client whose link comes back fails anything still pending from the previous link before the new link starts accepting requests. `readDescriptorValue`, `readRssi` and `discoverServices` register their pending result before issuing the operation, as `readValue` already did. A subscription to a characteristic without a CCCD is refused the same way. All of this needs the system to report the disconnection, which the plugin cannot infer on its own (#394). ## 3.4.0 diff --git a/README.md b/README.md index 8097cc97..d279aa1e 100644 --- a/README.md +++ b/README.md @@ -1000,7 +1000,7 @@ When a peripheral refuses a characteristic or descriptor read/write, or a subscr A read, write, descriptor access or subscription to a device whose link is down fails right away with `UniversalBleErrorCode.deviceDisconnected`, instead of waiting for the request timeout or reaching the stack. On Android the same applies to MTU requests, service discovery and RSSI reads. This holds whether or not the connection was made with `autoConnect`, and it relies on the system reporting the disconnection: if it never does, the plugin cannot tell the link is down. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. -On Linux and Web the disconnect check runs before the characteristic lookup, because BlueZ drops a device's GATT object tree with the link and Web clears its service cache on disconnection. Those two platforms therefore report `deviceDisconnected` for a request on a disconnected device even when the characteristic no longer exists, while Android, Windows and Apple still report `characteristicNotFound` for an unknown characteristic. Do not rely on `characteristicNotFound` alone as a "services changed, re-discover" signal on Linux or Web. +On Linux, Web and Apple the disconnect check runs before the characteristic lookup, because BlueZ and CoreBluetooth discard a device's GATT object tree with the link and Web clears its service cache on disconnection. Those platforms therefore report `deviceDisconnected` for a request on a disconnected device even when the characteristic no longer exists. Android and Windows still report `characteristicNotFound` for an unknown characteristic on a known device, and an Android client that `autoConnect` does not keep open is closed on disconnect, so a later request reports `deviceNotFound`. Do not rely on `characteristicNotFound` alone as a "services changed, re-discover" signal on Linux, Web or Apple. ## Peripheral Mode diff --git a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift index 1c5ffdfd..84c8be48 100644 --- a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift +++ b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift @@ -545,14 +545,18 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral return } - guard let gattCharacteristic = peripheral.getCharacteristic(characteristic, of: service) else { - completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) - return - } + // Check the link before the characteristic lookup: a settled disconnection + // discards the peripheral's attribute tree, so the lookup would otherwise + // report characteristicNotFound for a device that is known and simply + // disconnected. Linux and Web check first for the same reason. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return } + guard let gattCharacteristic = peripheral.getCharacteristic(characteristic, of: service) else { + completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) + return + } if bleInputProperty == .notification && !gattCharacteristic.properties.contains(.notify) { completion(Result.failure(createFlutterError(code: .characteristicDoesNotSupportNotify, message: "Characteristic does not support notify"))) @@ -575,14 +579,18 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(self)"))) return } - guard let gattCharacteristic = peripheral.getCharacteristic(characteristic, of: service) else { - completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) - return - } + // Check the link before the characteristic lookup: a settled disconnection + // discards the peripheral's attribute tree, so the lookup would otherwise + // report characteristicNotFound for a device that is known and simply + // disconnected. Linux and Web check first for the same reason. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return } + guard let gattCharacteristic = peripheral.getCharacteristic(characteristic, of: service) else { + completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) + return + } if !gattCharacteristic.properties.contains(.read) { completion(Result.failure(createFlutterError(code: .characteristicDoesNotSupportRead, message: "Characteristic does not support read"))) return @@ -597,14 +605,18 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(self)"))) return } - guard let gattCharacteristic = peripheral.getCharacteristic(characteristic, of: service) else { - completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) - return - } + // Check the link before the characteristic lookup: a settled disconnection + // discards the peripheral's attribute tree, so the lookup would otherwise + // report characteristicNotFound for a device that is known and simply + // disconnected. Linux and Web check first for the same reason. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return } + guard let gattCharacteristic = peripheral.getCharacteristic(characteristic, of: service) else { + completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) + return + } // Reject unsupported operations before retiring any previous owner's work. let supportsWrite = bleOutputProperty == .withResponse @@ -661,14 +673,16 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(deviceId)"))) return } - guard let gattDescriptor = peripheral.getDescriptor(descriptor, for: characteristic, of: service) else { - completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Descriptor not found:\(descriptor)"))) - return - } + // Check the link before the descriptor lookup, for the same reason the + // characteristic paths do. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return } + guard let gattDescriptor = peripheral.getDescriptor(descriptor, for: characteristic, of: service) else { + completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Descriptor not found:\(descriptor)"))) + return + } peripheral.readValue(for: gattDescriptor) descriptorReadFutures.append(DescriptorReadFuture( deviceId: deviceId, @@ -685,14 +699,16 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(deviceId)"))) return } - guard let gattDescriptor = peripheral.getDescriptor(descriptor, for: characteristic, of: service) else { - completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Descriptor not found:\(descriptor)"))) - return - } + // Check the link before the descriptor lookup, for the same reason the + // characteristic paths do. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return } + guard let gattDescriptor = peripheral.getDescriptor(descriptor, for: characteristic, of: service) else { + completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Descriptor not found:\(descriptor)"))) + return + } // CoreBluetooth throws NSInternalInconsistencyException if writeValue:forDescriptor: is called on CCCD (0x2902). // CoreBluetooth requires using setNotifyValue:forCharacteristic: for CCCD. diff --git a/example/integration_test/apple_gatt_disconnect_test.dart b/example/integration_test/apple_gatt_disconnect_test.dart index cb0ef0f9..b1ce4f08 100644 --- a/example/integration_test/apple_gatt_disconnect_test.dart +++ b/example/integration_test/apple_gatt_disconnect_test.dart @@ -19,10 +19,9 @@ // #396's state guard settles all four with // deviceDisconnected. // AFTER_DISCONNECT The disconnect has completed. CoreBluetooth has -// discarded CBPeripheral.services, so the characteristic -// lookup fails before the state guard runs and the caller -// gets characteristicNotFound. The requests are still -// refused locally, never handed to CoreBluetooth. +// discarded CBPeripheral.services, but the state check +// runs before the lookup, so all four are refused with +// deviceDisconnected instead of characteristicNotFound. // // Observed on macOS 26.6.2 and iPadOS 26.6.1, 2026-11-23. // @@ -238,10 +237,9 @@ void main() { print('DISCONNECTED ${await UniversalBle.getConnectionState(deviceId)}'); // --- Disconnected: the plugin must refuse these itself, not hand them to - // CoreBluetooth and wait for the timeout. Which code that is depends on - // whether CoreBluetooth has invalidated the attribute tree yet: the guard - // reports deviceDisconnected while it is cached, and the lookup reports - // characteristicNotFound once it is gone. --- + // CoreBluetooth and wait for the timeout. The state check runs before the + // lookup, so they report deviceDisconnected even though CoreBluetooth has + // already discarded the attribute tree. --- final afterDrop = []; Future refused(String label, Future Function() action) async { try { @@ -254,12 +252,10 @@ void main() { print('$label: ${e.code} "${e.message}"'); expect( e.code, - anyOf( - UniversalBleErrorCode.deviceDisconnected, - UniversalBleErrorCode.characteristicNotFound, - ), - reason: '$label must be refused by the plugin, got ${e.code}', + UniversalBleErrorCode.deviceDisconnected, + reason: '$label must report deviceDisconnected, got ${e.code}', ); + expect(e.message, contains('Disconnected')); afterDrop.add('$label=${e.code}'); } on TimeoutException catch (_) { fail('$label reached CoreBluetooth and never completed'); From d7322d23201662ff53ad8a5552c001fbaadd7663 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Mon, 23 Nov 2026 23:27:36 +0100 Subject: [PATCH 3/6] 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. --- example/README.md | 15 +++++++++++++ example/ios/Podfile | 2 +- example/ios/Podfile.lock | 2 +- example/ios/Runner.xcodeproj/project.pbxproj | 6 ++--- example/ios/Runner/Info.plist | 23 -------------------- 5 files changed, 20 insertions(+), 28 deletions(-) diff --git a/example/README.md b/example/README.md index d991adde..00d8989f 100644 --- a/example/README.md +++ b/example/README.md @@ -1,3 +1,18 @@ # universal_ble_example Demonstrates how to use the universal_ble plugin. + +## iOS: deployment target and Bluetooth permission + +The iOS app targets 15.0 because Xcode 26 no longer builds the 13.1 minimum +that the plugin itself supports. + +The app deliberately omits the `NSAccessorySetupKitSupports`, +`NSAccessorySetupBluetoothServices` and `NSAccessorySetupBluetoothNames` +keys. On a fresh install with those keys present, iPadOS 26.6.1 did not show +the broad Bluetooth permission prompt at all, so `CBCentralManager` stayed +`poweredOff` and scanning found nothing. Without them the prompt appears and +the scan works. To try the AccessorySetupKit picker instead, add the keys +described in the plugin README's picker section to this app's `Info.plist` +and run the app again; a build with them cannot also obtain the broad +permission on a first install. diff --git a/example/ios/Podfile b/example/ios/Podfile index 9d7ef08d..6649374d 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -# platform :ios, '15.0' +platform :ios, '15.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 29304b60..cdfeb606 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -11,6 +11,6 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Flutter: 71a624a5bc0c04062bf19101d501e466baf2fb47 -PODFILE CHECKSUM: 3ba3a73b1b12adcf321a227a745625fe0888cc82 +PODFILE CHECKSUM: 53a6aebc29ccee84c41f92f409fc20cd4ca011f1 COCOAPODS: 1.16.2 diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index 3aeacc61..1c4488b5 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -448,7 +448,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -576,7 +576,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -625,7 +625,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist index 99436b29..455bd291 100644 --- a/example/ios/Runner/Info.plist +++ b/example/ios/Runner/Info.plist @@ -30,29 +30,6 @@ Discover Bluetooth devices NSBluetoothPeripheralUsageDescription Discover Bluetooth devices - NSAccessorySetupKitSupports - - Bluetooth - - NSAccessorySetupBluetoothServices - - 180D - 180F - 180A - 1800 - FFE0 - FFF0 - 00000001-0000-1000-8000-00805F9B34FB - 12345678-1234-1234-1234-1234567890AB - - NSAccessorySetupBluetoothNames - - Test - BLE - Device - HIL - Polar - UIApplicationSceneManifest UIApplicationSupportsMultipleScenes From 2087fd8dee9fe795d9c211acbbce91cd7eeb0d3f Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Tue, 24 Nov 2026 07:21:51 +0100 Subject: [PATCH 4/6] 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. --- CHANGELOG.md | 2 + README.md | 4 +- .../universal_ble/UniversalBlePlugin.kt | 45 ++++++++++++++ .../universal_ble/LinkLossOperationTest.kt | 59 +++++++++++++++++++ .../universal_ble/UniversalBlePlugin.swift | 10 +++- .../apple_gatt_disconnect_test.dart | 11 ++++ windows/src/universal_ble_plugin.cpp | 50 ++++++++-------- 7 files changed, 155 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 394d6a0c..777bfbaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ * Web: the same requests now fail with `deviceDisconnected` instead of surfacing the browser's `NetworkError` as an unclassified error, and an unknown device reports `deviceNotFound` instead of a missing characteristic. The service cache is cleared on disconnection, so the lookup previously failed before the browser could say the link was gone (#394). * Windows: the same requests now fail with `deviceDisconnected` when the link is down but the connection-status callback has not removed the client yet. The operation used to be submitted anyway and completed with `Unreachable`, which surfaced as `failed` (#394). * Apple: reads, writes, descriptor reads and writes, and subscriptions now check `CBPeripheral.state` before the characteristic or descriptor lookup, so a request on a disconnected peripheral fails with `deviceDisconnected`. CoreBluetooth discards a peripheral's attribute tree when the link drops, so with the previous lookup-first order the caller got `characteristicNotFound` for a characteristic it had just used. The check now runs first, as it already did on Linux and Web; an unknown characteristic on a connected peripheral still reports `characteristicNotFound` (#394). +* Android and Windows: the link check now runs before the characteristic and descriptor lookup too, so a read, write, descriptor read/write or subscription on a known but disconnected device reports `deviceDisconnected` even when the cached attribute tree no longer holds the characteristic. Previously the lookup won and the answer depended on the platform. Android's submission gate keeps its lock-protected check as the authoritative one for the race described above (#394). +* Apple: MTU requests and RSSI reads now refuse a disconnected peripheral with `deviceDisconnected` instead of reaching CoreBluetooth, matching Android. Service discovery already refused one and now uses the same "Device Disconnected" message, so the set of gated calls is identical on both platforms (#394). * Android: a read, write, descriptor read/write, notification subscription, MTU request, service discovery or RSSI read submitted to an `autoConnect` client after its link dropped now fails right away with `deviceDisconnected` instead of reaching the stack. The client stays open and keeps its cached services after the link loss, and below API 33 the stack accepts such a request and then drops it without a callback, leaving a pending entry that the first callback of the reconnected link completes — so every later write lagged by one and timed out after 10 s, giving about one write per timeout. The link check shares the lock with the disconnect cleanup, so a request submitted concurrently is either registered in time to be swept or refused; as a backstop, a client whose link comes back fails anything still pending from the previous link before the new link starts accepting requests. `readDescriptorValue`, `readRssi` and `discoverServices` register their pending result before issuing the operation, as `readValue` already did. A subscription to a characteristic without a CCCD is refused the same way. All of this needs the system to report the disconnection, which the plugin cannot infer on its own (#394). ## 3.4.0 diff --git a/README.md b/README.md index d279aa1e..26527d17 100644 --- a/README.md +++ b/README.md @@ -998,9 +998,9 @@ When a peripheral refuses a characteristic or descriptor read/write, or a subscr ### Disconnected device -A read, write, descriptor access or subscription to a device whose link is down fails right away with `UniversalBleErrorCode.deviceDisconnected`, instead of waiting for the request timeout or reaching the stack. On Android the same applies to MTU requests, service discovery and RSSI reads. This holds whether or not the connection was made with `autoConnect`, and it relies on the system reporting the disconnection: if it never does, the plugin cannot tell the link is down. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. +A read, write, descriptor access or subscription to a device whose link is down fails right away with `UniversalBleErrorCode.deviceDisconnected`, instead of waiting for the request timeout or reaching the stack. On Android and Apple the same applies to MTU requests, service discovery and RSSI reads. This holds whether or not the connection was made with `autoConnect`, and it relies on the system reporting the disconnection: if it never does, the plugin cannot tell the link is down. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. -On Linux, Web and Apple the disconnect check runs before the characteristic lookup, because BlueZ and CoreBluetooth discard a device's GATT object tree with the link and Web clears its service cache on disconnection. Those platforms therefore report `deviceDisconnected` for a request on a disconnected device even when the characteristic no longer exists. Android and Windows still report `characteristicNotFound` for an unknown characteristic on a known device, and an Android client that `autoConnect` does not keep open is closed on disconnect, so a later request reports `deviceNotFound`. Do not rely on `characteristicNotFound` alone as a "services changed, re-discover" signal on Linux, Web or Apple. +Every platform runs this check before the characteristic or descriptor lookup, so a known device whose link is down reports `deviceDisconnected` even when its cached attribute tree no longer holds the characteristic. `characteristicNotFound` therefore means the link was up and the attribute is unknown. A device the plugin has already forgotten reports `deviceNotFound`: Android closes a client that `autoConnect` does not keep open, and Windows removes its device agent when the connection-status callback reports the drop. ## Peripheral Mode diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index 4bb568f4..4a309c81 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -629,6 +629,15 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("SET_NOTIFY -> $deviceId $service $characteristic input=$bleInputProperty") val gatt = gattRegistry.get(deviceId).gatt + // Refuse a request on a link that is already down before looking + // anything up: an autoConnect client keeps its cached services + // across a link loss, so the lookup would otherwise decide the + // answer for a device that is known and simply disconnected. The + // submission gate re-checks under its lock to close the race (#394). + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -782,6 +791,15 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("READ -> $deviceId $service $characteristic") val gatt = gattRegistry.get(deviceId).gatt + // Refuse a request on a link that is already down before looking + // anything up: an autoConnect client keeps its cached services + // across a link loss, so the lookup would otherwise decide the + // answer for a device that is known and simply disconnected. The + // submission gate re-checks under its lock to close the race (#394). + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -906,6 +924,15 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("WRITE -> $deviceId $service $characteristic len=${value.size} property=$bleOutputProperty") val gatt = gattRegistry.get(deviceId).gatt + // Refuse a request on a link that is already down before looking + // anything up: an autoConnect client keeps its cached services + // across a link loss, so the lookup would otherwise decide the + // answer for a device that is known and simply disconnected. The + // submission gate re-checks under its lock to close the race (#394). + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1126,6 +1153,15 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("READ_DESCRIPTOR -> $deviceId $service $characteristic $descriptor") val gatt = gattRegistry.get(deviceId).gatt + // Refuse a request on a link that is already down before looking + // anything up: an autoConnect client keeps its cached services + // across a link loss, so the lookup would otherwise decide the + // answer for a device that is known and simply disconnected. The + // submission gate re-checks under its lock to close the race (#394). + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1247,6 +1283,15 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("WRITE_DESCRIPTOR -> $deviceId $service $characteristic $descriptor len=${value.size}") val gatt = gattRegistry.get(deviceId).gatt + // Refuse a request on a link that is already down before looking + // anything up: an autoConnect client keeps its cached services + // across a link loss, so the lookup would otherwise decide the + // answer for a device that is known and simply disconnected. The + // submission gate re-checks under its lock to close the race (#394). + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( diff --git a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt index 1c3a5205..c9c3ecf2 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt @@ -372,4 +372,63 @@ internal class LinkLossOperationTest { Mockito.verify(gatt, Mockito.never()).readRemoteRssi() Mockito.verify(gatt, Mockito.never()).discoverServices() } + + @Test + fun anUnknownCharacteristicOnADroppedLinkStillReportsDisconnected() { + // The client keeps its cached tree across the link loss, but the tree + // need not still hold the requested characteristic. The link check runs + // before the lookup, so the answer describes the connection the caller + // can act on rather than the cache. + val plugin = connectedAutoConnectPlugin() + report(plugin, BluetoothGatt.STATE_DISCONNECTED) + + val unknown = UUID.randomUUID().toString() + val reads = mutableListOf>() + plugin.readValue(deviceAddress, serviceUuid.toString(), unknown) { reads.add(it) } + assertEquals(1, reads.size) + assertDeviceDisconnected(reads.single()) + + val writes = mutableListOf>() + plugin.writeValue( + deviceAddress, + serviceUuid.toString(), + unknown, + ByteArray(2), + BleOutputProperty.WITHOUT_RESPONSE, + ) { writes.add(it) } + assertEquals(1, writes.size) + assertDeviceDisconnected(writes.single()) + + val subscriptions = mutableListOf>() + plugin.setNotifiable( + deviceAddress, + serviceUuid.toString(), + unknown, + BleInputProperty.NOTIFICATION, + ) { subscriptions.add(it) } + assertEquals(1, subscriptions.size) + assertDeviceDisconnected(subscriptions.single()) + + Mockito.verify(gatt, Mockito.never()) + .readCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) + } + + @Test + fun anUnknownCharacteristicOnALiveLinkStillReportsNotFound() { + val plugin = connectedAutoConnectPlugin() + + val reads = mutableListOf>() + plugin.readValue( + deviceAddress, + serviceUuid.toString(), + UUID.randomUUID().toString(), + ) { reads.add(it) } + + assertEquals(1, reads.size) + assertEquals( + UniversalBleErrorCode.CHARACTERISTIC_NOT_FOUND.raw.toString(), + errorCode(reads.single()), + "a live link keeps reporting a missing characteristic as such", + ) + } } diff --git a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift index 84c8be48..c76914ac 100644 --- a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift +++ b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift @@ -499,7 +499,7 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral guard peripheral.state == .connected else { completion( - Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device is not connected")) + Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected")) ) return } @@ -746,6 +746,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(self)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } let mtu = peripheral.maximumWriteValueLength(for: CBCharacteristicWriteType.withoutResponse) let GATT_HEADER_LENGTH = 3 let mtuResult = Int64(mtu + GATT_HEADER_LENGTH) @@ -766,6 +770,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(deviceId)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } peripheral.readRSSI() rssiReadFutures.append(RssiReadFuture(deviceId: deviceId, result: completion)) } diff --git a/example/integration_test/apple_gatt_disconnect_test.dart b/example/integration_test/apple_gatt_disconnect_test.dart index b1ce4f08..9e65e286 100644 --- a/example/integration_test/apple_gatt_disconnect_test.dart +++ b/example/integration_test/apple_gatt_disconnect_test.dart @@ -175,6 +175,13 @@ void main() { // ignore: avoid_print print('UNSUBSCRIBE_OK $notifyCharacteristic'); + final mtu = await UniversalBle.requestMtu(deviceId, 185); + // ignore: avoid_print + print('MTU_OK $mtu'); + final rssi = await UniversalBle.readRssi(deviceId); + // ignore: avoid_print + print('RSSI_OK $rssi'); + // --- Race the same requests against disconnect(): the peripheral is in // .disconnecting and still holds its attribute tree, the window #396's // state guard exists for. --- @@ -223,6 +230,8 @@ void main() { notifyCharacteristic, ), ), + race('requestMtu', () => UniversalBle.requestMtu(deviceId, 185)), + race('readRssi', () => UniversalBle.readRssi(deviceId)), ]); await disconnectFuture; // ignore: avoid_print @@ -293,6 +302,8 @@ void main() { notifyCharacteristic, ), ); + await refused('requestMtu', () => UniversalBle.requestMtu(deviceId, 185)); + await refused('readRssi', () => UniversalBle.readRssi(deviceId)); // ignore: avoid_print print('AFTER_DISCONNECT ${afterDrop.join(" ")}'); }); diff --git a/windows/src/universal_ble_plugin.cpp b/windows/src/universal_ble_plugin.cpp index 6acef467..3d07b95a 100644 --- a/windows/src/universal_ble_plugin.cpp +++ b/windows/src/universal_ble_plugin.cpp @@ -581,17 +581,18 @@ void UniversalBlePlugin::ReadValue( return; } - const auto gatt_characteristic_lease = - bluetooth_agent->FetchCharacteristicForOperation(service, - characteristic); - const GattCharacteristic gatt_characteristic = - gatt_characteristic_lease.characteristic.obj; if (!HasLiveLink(bluetooth_agent)) { result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, "Device Disconnected")); return; } + const auto gatt_characteristic_lease = + bluetooth_agent->FetchCharacteristicForOperation(service, + characteristic); + const GattCharacteristic gatt_characteristic = + gatt_characteristic_lease.characteristic.obj; + const auto properties = gatt_characteristic.CharacteristicProperties(); if ((properties & GattCharacteristicProperties::Read) == GattCharacteristicProperties::None) { @@ -679,16 +680,17 @@ void UniversalBlePlugin::WriteValue( "Unknown devicesId:" + device_id)); return; } - const auto gatt_characteristic_lease = - bluetooth_agent->FetchCharacteristicForOperation(service, - characteristic); - const GattCharacteristic gatt_characteristic = - gatt_characteristic_lease.characteristic.obj; if (!HasLiveLink(bluetooth_agent)) { result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, "Device Disconnected")); return; } + + const auto gatt_characteristic_lease = + bluetooth_agent->FetchCharacteristicForOperation(service, + characteristic); + const GattCharacteristic gatt_characteristic = + gatt_characteristic_lease.characteristic.obj; const auto properties = gatt_characteristic.CharacteristicProperties(); auto write_option = GattWriteOption::WriteWithResponse; @@ -790,17 +792,18 @@ void UniversalBlePlugin::ReadDescriptorValue( return; } - const auto gatt_characteristic_lease = - bluetooth_agent->FetchCharacteristicForOperation(service, - characteristic); - const GattCharacteristic gatt_characteristic = - gatt_characteristic_lease.characteristic.obj; if (!HasLiveLink(bluetooth_agent)) { result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, "Device Disconnected")); return; } + const auto gatt_characteristic_lease = + bluetooth_agent->FetchCharacteristicForOperation(service, + characteristic); + const GattCharacteristic gatt_characteristic = + gatt_characteristic_lease.characteristic.obj; + gatt_characteristic .GetDescriptorsForUuidAsync(uuid_to_guid(descriptor), BluetoothCacheMode::Uncached) @@ -930,17 +933,18 @@ void UniversalBlePlugin::WriteDescriptorValue( "Unknown devicesId:" + device_id)); return; } - const auto gatt_characteristic_lease = - bluetooth_agent->FetchCharacteristicForOperation(service, - characteristic); - const GattCharacteristic gatt_characteristic = - gatt_characteristic_lease.characteristic.obj; if (!HasLiveLink(bluetooth_agent)) { result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, "Device Disconnected")); return; } + const auto gatt_characteristic_lease = + bluetooth_agent->FetchCharacteristicForOperation(service, + characteristic); + const GattCharacteristic gatt_characteristic = + gatt_characteristic_lease.characteristic.obj; + gatt_characteristic .GetDescriptorsForUuidAsync(uuid_to_guid(descriptor), BluetoothCacheMode::Uncached) @@ -3105,9 +3109,6 @@ fire_and_forget UniversalBlePlugin::SetNotifiableAsync( co_return; } - stage = "lookup-characteristic"; - auto gatt_char = device_agent->FetchCharacteristic(service, characteristic); - stage = "check-link"; if (!HasLiveLink(device_agent)) { reply(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, @@ -3115,6 +3116,9 @@ fire_and_forget UniversalBlePlugin::SetNotifiableAsync( co_return; } + stage = "lookup-characteristic"; + auto gatt_char = device_agent->FetchCharacteristic(service, characteristic); + const auto properties = gatt_char.obj.CharacteristicProperties(); auto descriptor_value = GattClientCharacteristicConfigurationDescriptorValue::None; From 7b55fd23047028d1d43f40e29f0776d05278f4ac Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Tue, 24 Nov 2026 11:05:13 +0100 Subject: [PATCH 5/6] 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. --- .../universal_ble/UniversalBlePlugin.kt | 35 +-- .../universal_ble/UniversalBlePlugin.swift | 21 +- .../apple_link_loss_test.dart | 222 ------------------ 3 files changed, 15 insertions(+), 263 deletions(-) delete mode 100644 example/integration_test/apple_link_loss_test.dart diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index 4a309c81..f7e99c04 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -629,11 +629,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("SET_NOTIFY -> $deviceId $service $characteristic input=$bleInputProperty") val gatt = gattRegistry.get(deviceId).gatt - // Refuse a request on a link that is already down before looking - // anything up: an autoConnect client keeps its cached services - // across a link loss, so the lookup would otherwise decide the - // answer for a device that is known and simply disconnected. The - // submission gate re-checks under its lock to close the race (#394). + // A disconnected device reports that, whatever the cache holds. if (!isLinkUp(gatt)) { callback(Result.failure(deviceDisconnectedError())) return @@ -791,11 +787,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("READ -> $deviceId $service $characteristic") val gatt = gattRegistry.get(deviceId).gatt - // Refuse a request on a link that is already down before looking - // anything up: an autoConnect client keeps its cached services - // across a link loss, so the lookup would otherwise decide the - // answer for a device that is known and simply disconnected. The - // submission gate re-checks under its lock to close the race (#394). + // A disconnected device reports that, whatever the cache holds. if (!isLinkUp(gatt)) { callback(Result.failure(deviceDisconnectedError())) return @@ -924,11 +916,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("WRITE -> $deviceId $service $characteristic len=${value.size} property=$bleOutputProperty") val gatt = gattRegistry.get(deviceId).gatt - // Refuse a request on a link that is already down before looking - // anything up: an autoConnect client keeps its cached services - // across a link loss, so the lookup would otherwise decide the - // answer for a device that is known and simply disconnected. The - // submission gate re-checks under its lock to close the race (#394). + // A disconnected device reports that, whatever the cache holds. if (!isLinkUp(gatt)) { callback(Result.failure(deviceDisconnectedError())) return @@ -1153,11 +1141,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("READ_DESCRIPTOR -> $deviceId $service $characteristic $descriptor") val gatt = gattRegistry.get(deviceId).gatt - // Refuse a request on a link that is already down before looking - // anything up: an autoConnect client keeps its cached services - // across a link loss, so the lookup would otherwise decide the - // answer for a device that is known and simply disconnected. The - // submission gate re-checks under its lock to close the race (#394). + // A disconnected device reports that, whatever the cache holds. if (!isLinkUp(gatt)) { callback(Result.failure(deviceDisconnectedError())) return @@ -1283,11 +1267,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("WRITE_DESCRIPTOR -> $deviceId $service $characteristic $descriptor len=${value.size}") val gatt = gattRegistry.get(deviceId).gatt - // Refuse a request on a link that is already down before looking - // anything up: an autoConnect client keeps its cached services - // across a link loss, so the lookup would otherwise decide the - // answer for a device that is known and simply disconnected. The - // submission gate re-checks under its lock to close the race (#394). + // A disconnected device reports that, whatever the cache holds. if (!isLinkUp(gatt)) { callback(Result.failure(deviceDisconnectedError())) return @@ -1556,6 +1536,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), * outside that lock leaves a window where the check passes, cleanup sweeps, * and the result is added afterwards — stranded until a later callback * completes it one behind (#394). + * + * Requests check it before the characteristic lookup: an autoConnect client + * keeps its cached services across a link loss, so a lookup-first order + * would report a missing characteristic for a device that is known and + * simply disconnected. The submission gate still re-checks under its lock. */ private fun isLinkUp(gatt: BluetoothGatt): Boolean = gattRegistry.find(gatt)?.isLinkUp == true diff --git a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift index c76914ac..40e981cf 100644 --- a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift +++ b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift @@ -545,10 +545,7 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral return } - // Check the link before the characteristic lookup: a settled disconnection - // discards the peripheral's attribute tree, so the lookup would otherwise - // report characteristicNotFound for a device that is known and simply - // disconnected. Linux and Web check first for the same reason. + // A settled disconnection discards the attribute tree: check the link first. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return @@ -579,10 +576,7 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(self)"))) return } - // Check the link before the characteristic lookup: a settled disconnection - // discards the peripheral's attribute tree, so the lookup would otherwise - // report characteristicNotFound for a device that is known and simply - // disconnected. Linux and Web check first for the same reason. + // A settled disconnection discards the attribute tree: check the link first. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return @@ -605,10 +599,7 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(self)"))) return } - // Check the link before the characteristic lookup: a settled disconnection - // discards the peripheral's attribute tree, so the lookup would otherwise - // report characteristicNotFound for a device that is known and simply - // disconnected. Linux and Web check first for the same reason. + // A settled disconnection discards the attribute tree: check the link first. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return @@ -673,8 +664,7 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(deviceId)"))) return } - // Check the link before the descriptor lookup, for the same reason the - // characteristic paths do. + // Same precedence as the characteristic paths. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return @@ -699,8 +689,7 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .deviceNotFound, message: "Unknown deviceId:\(deviceId)"))) return } - // Check the link before the descriptor lookup, for the same reason the - // characteristic paths do. + // Same precedence as the characteristic paths. guard peripheral.state == .connected else { completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) return diff --git a/example/integration_test/apple_link_loss_test.dart b/example/integration_test/apple_link_loss_test.dart deleted file mode 100644 index 2cb6cb29..00000000 --- a/example/integration_test/apple_link_loss_test.dart +++ /dev/null @@ -1,222 +0,0 @@ -// Manual Apple HIL probe: a real peripheral-side link loss. -// -// Connects to a nearby device, discovers its GATT database, then waits for the -// peripheral to drop the link on its own. On the drop it immediately issues the -// requests PR #396 guards, and reports the error code of each. This is the -// check the PR left open: a request submitted while the link is down must not -// reach CoreBluetooth. -// -// cd example -// flutter test integration_test/apple_link_loss_test.dart -d macos \ -// --dart-define=APPLE_BLE_TEST_DEVICE='FS-7A25F8' \ -// --dart-define=APPLE_BLE_AUTOCONNECT=true -// -// You have to trigger the drop yourself (power the peripheral off, walk it out -// of range); a device that only drops when it is idle rarely does so while a -// central is connected. Without a drop the test reports NO_LINK_LOSS and stops. -// `APPLE_BLE_LINK_LOSS_WAIT` sets the wait in seconds (default 180). -import 'dart:async'; -import 'dart:typed_data'; - -import 'package:flutter_test/flutter_test.dart'; -import 'package:integration_test/integration_test.dart'; -import 'package:universal_ble/universal_ble.dart'; - -const String targetName = String.fromEnvironment( - 'APPLE_BLE_TEST_DEVICE', - defaultValue: 'FS-7A25F8', -); -const int waitSeconds = int.fromEnvironment( - 'APPLE_BLE_LINK_LOSS_WAIT', - defaultValue: 180, -); -const bool autoConnect = bool.fromEnvironment('APPLE_BLE_AUTOCONNECT'); - -void main() { - IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - - testWidgets('Apple GATT requests after a real link loss', (tester) async { - final scanned = {}; - final seenNames = {}; - UniversalBle.onScanResult = (device) { - scanned[device.deviceId] = device; - final name = device.name ?? ''; - if (name.isNotEmpty && seenNames.add(name)) { - // ignore: avoid_print - print('SEEN $name ${device.services.length} services'); - } - if (device.name == targetName) { - UniversalBle.stopScan().ignore(); - } - }; - await UniversalBle.startScan(); - final deadline = DateTime.now().add(const Duration(seconds: 60)); - BleDevice? target; - while (DateTime.now().isBefore(deadline)) { - for (final d in scanned.values) { - if (d.name == targetName) target = d; - } - if (target != null) break; - await Future.delayed(const Duration(milliseconds: 250)); - } - UniversalBle.onScanResult = null; - await UniversalBle.stopScan(); - expect(target, isNotNull, reason: '$targetName was not advertising'); - final deviceId = target!.deviceId; - // ignore: avoid_print - print('FOUND $deviceId'); - - await UniversalBle.connect(deviceId, autoConnect: autoConnect); - // ignore: avoid_print - print('MODE autoConnect=$autoConnect'); - final dropped = Completer(); - final connectedAt = DateTime.now(); - final subscription = UniversalBle.connectionChangeStream(deviceId).listen( - (change) { - // ignore: avoid_print - print( - 'EVENT t=${DateTime.now().difference(connectedAt).inMilliseconds}ms ' - 'connected=${change.isConnected} code=${change.errorCode}', - ); - if (!change.isConnected && !dropped.isCompleted) { - dropped.complete(change); - } - }, - ); - final services = await UniversalBle.discoverServices( - deviceId, - withDescriptors: true, - timeout: const Duration(seconds: 60), - ); - final readPair = _findReadable(services); - final notifyPair = _findNotifiableWithCccd(services); - expect(readPair, isNotNull); - expect(notifyPair, isNotNull); - // ignore: avoid_print - print( - 'CONNECTED read=${readPair!.characteristic} ' - 'notify=${notifyPair!.characteristic}', - ); - - // Wait for the peripheral to leave on its own. Do not poll it: the point is - // an idle link that the device tears down. - final drop = await Future.any([ - dropped.future, - Future.delayed( - Duration(seconds: waitSeconds), - () => null, - ), - ]); - if (drop == null) { - // ignore: avoid_print - print('NO_LINK_LOSS within ${waitSeconds}s; device kept the link'); - await UniversalBle.disconnect(deviceId); - await subscription.cancel(); - return; - } - // ignore: avoid_print - print( - 'LINK_LOSS error=${drop.error} code=${drop.errorCode} ' - 'native=${drop.nativeErrorCode}', - ); - - // Fire the guarded requests immediately, while the drop is fresh: this is - // the window in which a periodic timer would submit them. - final results = []; - Future probe(String label, Future Function() action) async { - try { - final value = await action(); - results.add('$label=SUCCESS(${value is List ? value.length : value})'); - } on UniversalBleException catch (e) { - results.add('$label=${e.code}'); - } on TimeoutException catch (_) { - results.add('$label=TIMEOUT'); - } - } - - await Future.wait([ - probe( - 'read', - () => UniversalBle.read( - deviceId, - readPair.service, - readPair.characteristic, - ), - ), - probe( - 'readDescriptor', - () => UniversalBle.readDescriptor( - deviceId, - notifyPair.service, - notifyPair.characteristic, - notifyPair.cccd, - ), - ), - probe( - 'writeDescriptor', - () => UniversalBle.writeDescriptor( - deviceId, - notifyPair.service, - notifyPair.characteristic, - notifyPair.cccd, - Uint8List.fromList([0x00, 0x00]), - ), - ), - probe( - 'subscribe', - () => UniversalBle.subscribeNotifications( - deviceId, - notifyPair.service, - notifyPair.characteristic, - ), - ), - ]); - // ignore: avoid_print - print('AFTER_LINK_LOSS ${results.join(" ")}'); - - // The steady state a second later, once CoreBluetooth has had time to drop - // the object's attribute tree. - await Future.delayed(const Duration(seconds: 1)); - await probe( - 'readLater', - () => UniversalBle.read( - deviceId, - readPair.service, - readPair.characteristic, - ), - ); - // ignore: avoid_print - print('LATER ${results.last}'); - - await UniversalBle.disconnect(deviceId); - await subscription.cancel(); - }, timeout: const Timeout(Duration(minutes: 12))); -} - -({String service, String characteristic})? _findReadable( - List services, -) { - for (final s in services) { - for (final c in s.characteristics) { - if (c.properties.contains(CharacteristicProperty.read)) { - return (service: s.uuid, characteristic: c.uuid); - } - } - } - return null; -} - -({String service, String characteristic, String cccd})? -_findNotifiableWithCccd(List services) { - for (final s in services) { - for (final c in s.characteristics) { - if (!c.properties.contains(CharacteristicProperty.notify)) continue; - for (final d in c.descriptors) { - if (d.uuid.toUpperCase().startsWith('00002902')) { - return (service: s.uuid, characteristic: c.uuid, cccd: d.uuid); - } - } - } - } - return null; -} From 3655cd7e8ad1a94cf67cd219be904482d3f38569 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Tue, 24 Nov 2026 11:57:57 +0100 Subject: [PATCH 6/6] 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. --- README.md | 2 +- .../universal_ble/UniversalBlePlugin.kt | 11 +-- .../universal_ble/LinkLossOperationTest.kt | 73 +++++++++++++++++++ .../apple_gatt_disconnect_test.dart | 19 +++++ .../home/widgets/request_device_widget.dart | 13 ++++ lib/src/universal_ble.dart | 5 ++ 6 files changed, 117 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 26527d17..6ca71364 100644 --- a/README.md +++ b/README.md @@ -1000,7 +1000,7 @@ When a peripheral refuses a characteristic or descriptor read/write, or a subscr A read, write, descriptor access or subscription to a device whose link is down fails right away with `UniversalBleErrorCode.deviceDisconnected`, instead of waiting for the request timeout or reaching the stack. On Android and Apple the same applies to MTU requests, service discovery and RSSI reads. This holds whether or not the connection was made with `autoConnect`, and it relies on the system reporting the disconnection: if it never does, the plugin cannot tell the link is down. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. -Every platform runs this check before the characteristic or descriptor lookup, so a known device whose link is down reports `deviceDisconnected` even when its cached attribute tree no longer holds the characteristic. `characteristicNotFound` therefore means the link was up and the attribute is unknown. A device the plugin has already forgotten reports `deviceNotFound`: Android closes a client that `autoConnect` does not keep open, and Windows removes its device agent when the connection-status callback reports the drop. +Every platform runs this check before the characteristic or descriptor lookup, so a known device whose link is down reports `deviceDisconnected` even when its cached attribute tree no longer holds the characteristic. On a live link an unknown characteristic or descriptor still reports `characteristicNotFound`. That code is not a reliable "services changed, re-discover" signal on Android: a read the stack refuses to start — because another operation is in flight on the same link (callers can run parallel queues with `queueId`), or because the link dropped between the check and the call — is reported as `characteristicNotFound` too. A device the plugin has already forgotten reports `deviceNotFound`: Android closes a client that `autoConnect` does not keep open, and Windows removes its device agent when the connection-status callback reports the drop. ## Peripheral Mode diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index f7e99c04..117c4b41 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -963,8 +963,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE } - // Checked after the lookups so a caller still gets deviceNotFound, - // characteristicNotFound and the write-support errors it got before. + // Checked after the link check and the lookups so a wrong device, + // attribute or operation outranks a payload that is too long. if (value.size > MAX_ATTRIBUTE_VALUE_SIZE) { callback( Result.failure( @@ -1297,9 +1297,10 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), return } - // Checked after the lookups so a caller still gets deviceNotFound and - // the not-found errors it got before. writeDescriptor does not throw - // for a long value, but a value over the attribute cap cannot work. + // Checked after the link check and the lookups so a wrong device or + // attribute outranks a payload that is too long. writeDescriptor does + // not throw for a long value, but a value over the attribute cap + // cannot work. if (value.size > MAX_ATTRIBUTE_VALUE_SIZE) { callback( Result.failure( diff --git a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt index c9c3ecf2..f55c4a87 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt @@ -431,4 +431,77 @@ internal class LinkLossOperationTest { "a live link keeps reporting a missing characteristic as such", ) } + + @Test + fun anUnknownDescriptorOnADroppedLinkStillReportsDisconnected() { + // The descriptor paths check the link before the characteristic and + // descriptor lookups too, so an unknown attribute cannot shadow the + // connection the caller has to fix. + val plugin = connectedAutoConnectPlugin() + report(plugin, BluetoothGatt.STATE_DISCONNECTED) + + val unknown = UUID.randomUUID().toString() + val descriptorReads = mutableListOf>() + plugin.readDescriptorValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + unknown, + ) { descriptorReads.add(it) } + assertEquals(1, descriptorReads.size) + assertDeviceDisconnected(descriptorReads.single()) + + val descriptorWrites = mutableListOf>() + plugin.writeDescriptorValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + unknown, + ByteArray(2), + ) { descriptorWrites.add(it) } + assertEquals(1, descriptorWrites.size) + assertDeviceDisconnected(descriptorWrites.single()) + + Mockito.verify(gatt, Mockito.never()) + .readDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) + Mockito.verify(gatt, Mockito.never()) + .writeDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) + } + + @Test + fun anUnknownDescriptorOnALiveLinkStillReportsNotFound() { + val plugin = connectedAutoConnectPlugin() + + val unknown = UUID.randomUUID().toString() + val descriptorReads = mutableListOf>() + plugin.readDescriptorValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + unknown, + ) { descriptorReads.add(it) } + + assertEquals(1, descriptorReads.size) + assertEquals( + UniversalBleErrorCode.CHARACTERISTIC_NOT_FOUND.raw.toString(), + errorCode(descriptorReads.single()), + "a live link keeps reporting a missing descriptor as such", + ) + + val descriptorWrites = mutableListOf>() + plugin.writeDescriptorValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + unknown, + ByteArray(2), + ) { descriptorWrites.add(it) } + + assertEquals(1, descriptorWrites.size) + assertEquals( + UniversalBleErrorCode.CHARACTERISTIC_NOT_FOUND.raw.toString(), + errorCode(descriptorWrites.single()), + "a live link keeps reporting a missing descriptor as such", + ) + } } diff --git a/example/integration_test/apple_gatt_disconnect_test.dart b/example/integration_test/apple_gatt_disconnect_test.dart index 9e65e286..e9c5c7e5 100644 --- a/example/integration_test/apple_gatt_disconnect_test.dart +++ b/example/integration_test/apple_gatt_disconnect_test.dart @@ -100,6 +100,17 @@ void main() { print('DEVICE $deviceId ${target.name}'); await UniversalBle.connect(deviceId); + // A failed assertion below must not leave the peripheral connected: the next + // run would start from a different state. Ignore a disconnect that finds it + // already down. + addTearDown(() async { + try { + await UniversalBle.disconnect(deviceId); + } catch (_) { + // Already disconnected, which is the state the test sometimes leaves it + // in on purpose. + } + }); // ignore: avoid_print print('CONNECTED ${await UniversalBle.getConnectionState(deviceId)}'); @@ -195,6 +206,10 @@ void main() { raced.add('$label=${e.code}'); } on TimeoutException catch (_) { raced.add('$label=TIMEOUT'); + } catch (e) { + // Record the type instead of aborting the whole run: this window is + // expected to produce a range of platform errors. + raced.add('$label=${e.runtimeType}'); } } @@ -268,6 +283,10 @@ void main() { afterDrop.add('$label=${e.code}'); } on TimeoutException catch (_) { fail('$label reached CoreBluetooth and never completed'); + } catch (e) { + fail( + '$label threw ${e.runtimeType} instead of a UniversalBleException: $e', + ); } } diff --git a/example/lib/home/widgets/request_device_widget.dart b/example/lib/home/widgets/request_device_widget.dart index b549d6e1..7f6dd3f8 100644 --- a/example/lib/home/widgets/request_device_widget.dart +++ b/example/lib/home/widgets/request_device_widget.dart @@ -167,6 +167,19 @@ class _RequestDeviceWidgetState extends State { color: Colors.grey[700], ), ), + if (isIOS) ...[ + const SizedBox(height: 8), + Text( + 'This example omits the NSAccessorySetupKitSupports keys to get ' + 'the broad Bluetooth prompt on a first install, which means the ' + 'AccessorySetupKit picker cannot be shown. Add the keys from ' + 'example/README.md to try that flow: iOS may terminate an app ' + 'that opens the picker with undeclared discovery identifiers.', + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Colors.orange[800], + ), + ), + ], const SizedBox(height: 12), Wrap( spacing: 8, diff --git a/lib/src/universal_ble.dart b/lib/src/universal_ble.dart index 79e3d8fa..c8cdfbc1 100644 --- a/lib/src/universal_ble.dart +++ b/lib/src/universal_ble.dart @@ -716,6 +716,11 @@ class UniversalBle { /// **Best Practices:** Design for default ATT MTU (23 bytes), treat requests as /// opportunistic, and implement fragmentation for larger payloads. /// + /// Throws [UniversalBleException] if: + /// - The device is not connected (`deviceDisconnected`). This includes + /// iOS/macOS, where the value is computed locally rather than requested. + /// - The request fails + /// /// **Timeout:** [timeout] bounds each step separately, so on iOS/macOS and /// Linux a call that has to discover the services first can take up to roughly /// twice [timeout] before it settles. Pass a [timeout] that accounts for both.