diff --git a/CHANGELOG.md b/CHANGELOG.md index ec92534f..60e1b36a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ ## 3.4.1 +* 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). * 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 64cc9646..8097cc97 100644 --- a/README.md +++ b/README.md @@ -348,7 +348,7 @@ You can enable automatic reconnection by setting the `autoConnect` parameter to await bleDevice.connect(autoConnect: true); ``` -While the link is down — after the plugin reports a disconnection and before the system reconnects the client — a read, write, descriptor access, subscription, MTU request, service discovery or RSSI read for that device fails right away on Android with `UniversalBleErrorCode.deviceDisconnected` instead of waiting for the request timeout. This 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. +While the link is down — after the plugin reports a disconnection and before the system reconnects the client — a read, write, descriptor access, subscription, MTU request, service discovery or RSSI read for that device fails right away instead of waiting for the request timeout (see [Disconnected device](#disconnected-device)). #### Background connection events (iOS/macOS) @@ -996,6 +996,12 @@ The error parser automatically converts platform-specific error formats (strings When a peripheral refuses a characteristic or descriptor read/write, or a subscription, Android, Apple and Windows report the ATT error as the matching `UniversalBleErrorCode` (`insufficientEncryption`, `insufficientAuthentication`, `readNotPermitted`, ...) instead of a generic `failed`/`unknownError`. The raw native code is available in `UniversalBleException.details`. Service/characteristic discovery at connect time, and the Linux and Web backends, may still report a generic code. +### 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. + +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. + ## Peripheral Mode `universal_ble` provides peripheral mode through `UniversalBlePeripheral`, so your app can advertise as a peripheral "server" in addition to client mode. diff --git a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift index 1b4065db..1c5ffdfd 100644 --- a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift +++ b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift @@ -549,6 +549,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } if bleInputProperty == .notification && !gattCharacteristic.properties.contains(.notify) { completion(Result.failure(createFlutterError(code: .characteristicDoesNotSupportNotify, message: "Characteristic does not support notify"))) @@ -575,6 +579,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } if !gattCharacteristic.properties.contains(.read) { completion(Result.failure(createFlutterError(code: .characteristicDoesNotSupportRead, message: "Characteristic does not support read"))) return @@ -657,6 +665,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Descriptor not found:\(descriptor)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } peripheral.readValue(for: gattDescriptor) descriptorReadFutures.append(DescriptorReadFuture( deviceId: deviceId, @@ -677,6 +689,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Descriptor not found:\(descriptor)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } // CoreBluetooth throws NSInternalInconsistencyException if writeValue:forDescriptor: is called on CCCD (0x2902). // CoreBluetooth requires using setNotifyValue:forCharacteristic: for CCCD. diff --git a/lib/src/universal_ble_linux/universal_ble_linux.dart b/lib/src/universal_ble_linux/universal_ble_linux.dart index 57b9eef3..89f8dd63 100644 --- a/lib/src/universal_ble_linux/universal_ble_linux.dart +++ b/lib/src/universal_ble_linux/universal_ble_linux.dart @@ -245,7 +245,9 @@ class UniversalBleLinux extends UniversalBlePlatform { String service, String characteristic, ) { - final device = _findDeviceById(deviceId); + // Every GATT request resolves its characteristic here, so the link check + // covers reads, writes, descriptors and subscriptions in one place. + final device = _findConnectedDevice(deviceId); final s = device.gattServices.cast().firstWhere( (s) => s?.uuid.toString() == service, orElse: () => null, @@ -463,13 +465,7 @@ class UniversalBleLinux extends UniversalBlePlatform { @override Future requestMtu(String deviceId, int expectedMtu) async { - final device = _findDeviceById(deviceId); - if (!device.connected) { - throw UniversalBleException( - code: UniversalBleErrorCode.deviceDisconnected, - message: 'Device not connected', - ); - } + final device = _findConnectedDevice(deviceId); for (BlueZGattService service in device.gattServices) { for (BlueZGattCharacteristic characteristic in service.characteristics) { int? mtu = characteristic.mtu; @@ -572,6 +568,23 @@ class UniversalBleLinux extends UniversalBlePlatform { return device; } + /// [deviceId]'s device, provided its link is up. + /// + /// BlueZ drops a device's GATT object tree when the link goes down, so a + /// request submitted while disconnected otherwise fails as "characteristic + /// not found" — as if the device had changed its services. Name the real + /// condition instead, as Android and Apple do. + BlueZDevice _findConnectedDevice(String deviceId) { + final device = _findDeviceById(deviceId); + if (!device.connected) { + throw UniversalBleException( + code: UniversalBleErrorCode.deviceDisconnected, + message: 'Device Disconnected', + ); + } + return device; + } + /// Get device by id from cache or from client BlueZDevice? _getDeviceById(String deviceId) { // Every Linux device resolution funnels through here, so this is where the id becomes the diff --git a/lib/src/universal_ble_web/universal_ble_web.dart b/lib/src/universal_ble_web/universal_ble_web.dart index 77a9af39..a399465a 100644 --- a/lib/src/universal_ble_web/universal_ble_web.dart +++ b/lib/src/universal_ble_web/universal_ble_web.dart @@ -368,6 +368,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "SET_NOTIFY -> $deviceId $service $characteristic input=${bleInputProperty.name}", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); final bleCharacteristic = await _getBleCharacteristic( deviceId: deviceId, serviceId: service, @@ -426,6 +427,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "WRITE -> $deviceId $service $characteristic len=${value.length} property=${bleOutputProperty.name}", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); final bleCharacteristic = await _getBleCharacteristic( deviceId: deviceId, serviceId: service, @@ -460,6 +462,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "READ -> $deviceId $service $characteristic", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); var bleCharacteristic = await _getBleCharacteristic( deviceId: deviceId, serviceId: service, @@ -490,6 +493,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "READ_DESCRIPTOR -> $deviceId $service $characteristic $descriptor", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); var bleDescriptor = await _getBleDescriptor( deviceId: deviceId, serviceId: service, @@ -519,6 +523,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "WRITE_DESCRIPTOR -> $deviceId $service $characteristic $descriptor len=${value.length}", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); var bleDescriptor = await _getBleDescriptor( deviceId: deviceId, serviceId: service, @@ -677,6 +682,34 @@ class UniversalBleWeb extends UniversalBlePlatform { BluetoothDevice? _getDeviceById(String id) => _bluetoothDeviceList[id]; + /// [deviceId]'s device, provided its GATT link is up. + /// + /// Web Bluetooth rejects a GATT operation on a disconnected device with a + /// generic `NetworkError`, and the service cache is cleared on disconnection, + /// so without this the call would surface an unclassified error — or + /// "characteristic not found" — instead of naming the condition, as Android + /// and Apple do. + Future _requireConnectedDevice(String deviceId) async { + final device = _getDeviceById(deviceId); + if (device == null) { + throw UniversalBleException( + code: UniversalBleErrorCode.deviceNotFound, + message: '$deviceId Not Found', + ); + } + // Read the browser's own GATT flag instead of the `connected` stream: the + // stream is seeded from it, but only updates once the browser dispatches + // `gattserverdisconnected`, which happens in a task — so it still reports + // `true` right after `disconnect()` or a drop detected in the same turn. + // ignore: invalid_use_of_visible_for_testing_member + if (device.gatt?.connected != true) { + throw UniversalBleException( + code: UniversalBleErrorCode.deviceDisconnected, + message: 'Device Disconnected', + ); + } + } + /// Get services and their characteristics. /// Services and characteristics are cached. /// Clears cache on disconnection. diff --git a/windows/src/universal_ble_plugin.cpp b/windows/src/universal_ble_plugin.cpp index 4561310e..6acef467 100644 --- a/windows/src/universal_ble_plugin.cpp +++ b/windows/src/universal_ble_plugin.cpp @@ -586,6 +586,11 @@ void UniversalBlePlugin::ReadValue( 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 properties = gatt_characteristic.CharacteristicProperties(); if ((properties & GattCharacteristicProperties::Read) == @@ -679,6 +684,11 @@ void UniversalBlePlugin::WriteValue( 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 properties = gatt_characteristic.CharacteristicProperties(); auto write_option = GattWriteOption::WriteWithResponse; @@ -785,6 +795,11 @@ void UniversalBlePlugin::ReadDescriptorValue( characteristic); const GattCharacteristic gatt_characteristic = gatt_characteristic_lease.characteristic.obj; + if (!HasLiveLink(bluetooth_agent)) { + result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, + "Device Disconnected")); + return; + } gatt_characteristic .GetDescriptorsForUuidAsync(uuid_to_guid(descriptor), @@ -920,6 +935,11 @@ void UniversalBlePlugin::WriteDescriptorValue( characteristic); const GattCharacteristic gatt_characteristic = gatt_characteristic_lease.characteristic.obj; + if (!HasLiveLink(bluetooth_agent)) { + result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, + "Device Disconnected")); + return; + } gatt_characteristic .GetDescriptorsForUuidAsync(uuid_to_guid(descriptor), @@ -2442,6 +2462,22 @@ std::shared_ptr UniversalBlePlugin::GetConnectedDevice( return it == connected_devices_.end() ? nullptr : it->second; } +bool UniversalBlePlugin::HasLiveLink( + const std::shared_ptr &device_agent) { + if (!device_agent || !device_agent->IsActive()) return false; + try { + return device_agent->device.ConnectionStatus() == + BluetoothConnectionStatus::Connected; + } catch (const hresult_error &err) { + UniversalBleLogger::LogWarning( + "HasLiveLink: ConnectionStatus hresult_error hr=" + + std::to_string(err.code())); + } catch (...) { + UniversalBleLogger::LogWarning("HasLiveLink: ConnectionStatus failed"); + } + return true; +} + void UniversalBlePlugin::InvalidateConnectAttempt( const uint64_t bluetooth_address) { std::lock_guard lock(connected_devices_mutex_); @@ -3072,6 +3108,13 @@ fire_and_forget UniversalBlePlugin::SetNotifiableAsync( stage = "lookup-characteristic"; auto gatt_char = device_agent->FetchCharacteristic(service, characteristic); + stage = "check-link"; + if (!HasLiveLink(device_agent)) { + reply(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, + "Device Disconnected")); + co_return; + } + const auto properties = gatt_char.obj.CharacteristicProperties(); auto descriptor_value = GattClientCharacteristicConfigurationDescriptorValue::None; diff --git a/windows/src/universal_ble_plugin.h b/windows/src/universal_ble_plugin.h index 88c81774..c916ded8 100644 --- a/windows/src/universal_ble_plugin.h +++ b/windows/src/universal_ble_plugin.h @@ -483,6 +483,13 @@ class UniversalBlePlugin : public flutter::Plugin, const IInspectable &args); std::shared_ptr GetConnectedDevice( uint64_t bluetooth_address); + /// Whether [device_agent] still has a live link. + /// + /// The agent stays registered until WinRT reports the drop, so a request + /// submitted in between would otherwise be issued and fail with an unrelated + /// GATT status (Unreachable maps to `failed`). A status read that throws + /// counts as connected: the operation itself reports the real error. + bool HasLiveLink(const std::shared_ptr &device_agent); void InvalidateConnectAttempt(uint64_t bluetooth_address); std::shared_ptr RemoveConnectedDevice( uint64_t bluetooth_address,