diff --git a/CHANGELOG.md b/CHANGELOG.md index 72e00570..777bfbaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,9 @@ * 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 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 8097cc97..6ca71364 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 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. +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 4bb568f4..117c4b41 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,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("SET_NOTIFY -> $deviceId $service $characteristic input=$bleInputProperty") val gatt = gattRegistry.get(deviceId).gatt + // A disconnected device reports that, whatever the cache holds. + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -782,6 +787,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("READ -> $deviceId $service $characteristic") val gatt = gattRegistry.get(deviceId).gatt + // A disconnected device reports that, whatever the cache holds. + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -906,6 +916,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("WRITE -> $deviceId $service $characteristic len=${value.size} property=$bleOutputProperty") val gatt = gattRegistry.get(deviceId).gatt + // A disconnected device reports that, whatever the cache holds. + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -948,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( @@ -1126,6 +1141,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("READ_DESCRIPTOR -> $deviceId $service $characteristic $descriptor") val gatt = gattRegistry.get(deviceId).gatt + // A disconnected device reports that, whatever the cache holds. + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1247,6 +1267,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { UniversalBleLogger.logDebug("WRITE_DESCRIPTOR -> $deviceId $service $characteristic $descriptor len=${value.size}") val gatt = gattRegistry.get(deviceId).gatt + // A disconnected device reports that, whatever the cache holds. + if (!isLinkUp(gatt)) { + callback(Result.failure(deviceDisconnectedError())) + return + } val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1272,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( @@ -1511,6 +1537,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/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt index 1c3a5205..f55c4a87 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,136 @@ 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", + ) + } + + @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/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift index 1c5ffdfd..40e981cf 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 } @@ -545,14 +545,15 @@ 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 - } + // 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 } + 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 +576,15 @@ 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 - } + // 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 } + 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 +599,15 @@ 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 - } + // 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 } + 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 +664,15 @@ 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 - } + // Same precedence as the characteristic paths. 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 +689,15 @@ 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 - } + // Same precedence as the characteristic paths. 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. @@ -730,6 +735,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) @@ -750,6 +759,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/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/integration_test/apple_gatt_disconnect_test.dart b/example/integration_test/apple_gatt_disconnect_test.dart new file mode 100644 index 00000000..e9c5c7e5 --- /dev/null +++ b/example/integration_test/apple_gatt_disconnect_test.dart @@ -0,0 +1,359 @@ +// 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, 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. +// +// 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); + // 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)}'); + + 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'); + + 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. --- + 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'); + } 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}'); + } + } + + 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, + ), + ), + race('requestMtu', () => UniversalBle.requestMtu(deviceId, 185)), + race('readRssi', () => UniversalBle.readRssi(deviceId)), + ]); + 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. 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 { + 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, + 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'); + } catch (e) { + fail( + '$label threw ${e.runtimeType} instead of a UniversalBleException: $e', + ); + } + } + + 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, + ), + ); + await refused('requestMtu', () => UniversalBle.requestMtu(deviceId, 185)); + await refused('readRssi', () => UniversalBle.readRssi(deviceId)); + // 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/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 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. 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;