From 02d9dd65feecb2258aae37b2c860a0cf6bfe5e9e Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:58:07 +0100 Subject: [PATCH 1/5] Linux/Web: name a disconnected device in GATT request failures (#394) Neither platform supports autoConnect, so a dropped link removes the GATT objects (BlueZ) or clears the service cache (Web) instead of leaving a client open. A request submitted while disconnected therefore failed as 'characteristic not found' on Linux, and on Web as an unclassified browser NetworkError or a missing characteristic, even though the device was still known and simply not connected. Resolve the device once and refuse the request with deviceDisconnected when the link is down, for reads, writes, descriptor reads/writes and subscriptions - the same set Android gates. A BlueZ device is checked through the platform's Connected property; on Web the connection state comes from the dependency's seeded connected stream, as getConnectionState already reads it. Unknown devices now report deviceNotFound on Web too. --- .../universal_ble_linux.dart | 29 +++++++++++++----- .../universal_ble_web/universal_ble_web.dart | 30 +++++++++++++++++++ 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/lib/src/universal_ble_linux/universal_ble_linux.dart b/lib/src/universal_ble_linux/universal_ble_linux.dart index 57b9eef3..8bcd979a 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 not connected', + ); + } + 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..9663b556 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,31 @@ 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', + ); + } + // `connected` is seeded with the current GATT state, so the first event is + // the live value (the same way getConnectionState reads it). + if (!await device.connected.first) { + throw UniversalBleException( + code: UniversalBleErrorCode.deviceDisconnected, + message: 'Device $deviceId is not connected', + ); + } + } + /// Get services and their characteristics. /// Services and characteristics are cached. /// Clears cache on disconnection. From 6e9df47a9fe00f034df7401bddf3209909dea6b1 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:58:11 +0100 Subject: [PATCH 2/5] Windows: refuse GATT requests on a link that is already down (#394) A Windows connection has no autoConnect, but the agent stays registered until the ConnectionStatusChanged handler runs. A request submitted between the drop and that callback was issued to WinRT anyway and completed with Unreachable, which maps to failed rather than deviceDisconnected. Check the link before issuing a read, write, descriptor read/write or subscription, and refuse it with deviceDisconnected. A status read that throws counts as connected so the operation still reports the real error. --- windows/src/universal_ble_plugin.cpp | 43 ++++++++++++++++++++++++++++ windows/src/universal_ble_plugin.h | 7 +++++ 2 files changed, 50 insertions(+) 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, From 24b45872553fb3ca3a94ee97682e0949c3b53f1f Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:58:11 +0100 Subject: [PATCH 3/5] Apple: refuse GATT requests on a disconnected peripheral (#394) Only writeValue and discoverServices guarded on peripheral.state, so a read, descriptor read/write or subscription submitted while the peripheral was disconnected was handed to CoreBluetooth, which cannot serve it. Guard them the same way writeValue does since #378: characteristic/descriptor lookup first, then deviceDisconnected. No test: these paths need a connected CBPeripheral. The sources typecheck against FlutterMacOS.framework and the isolated Apple test helpers still pass. --- .../universal_ble/UniversalBlePlugin.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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. From 5c06823c8fa206ec01f8aa0e79f0f57f5781ff4d Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:58:11 +0100 Subject: [PATCH 4/5] Document the platform-wide disconnect behaviour --- CHANGELOG.md | 4 ++++ README.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) 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..872feb44 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 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. #### Background connection events (iOS/macOS) From e0452121f7e4ac223e928f75da9f119bdaf87d68 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:38:31 +0100 Subject: [PATCH 5/5] Web: read the live GATT flag for the disconnect check (#394) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The seeded `connected` stream only learns about a drop once the browser dispatches `gattserverdisconnected`, which happens in a task, so a request issued right after `disconnect()` — or in the turn a drop is detected — still saw the device as connected. It then reached the dependency's discoverServices(), which throws "Cannot discover services if the device is not connected", so the caller got an unclassified error instead of deviceDisconnected. Read the browser's own `gatt.connected` flag instead. The getter is `@visibleForTesting`, so the read is scoped with an ignore. Also align the Linux and Web message with the "Device Disconnected" text Android, Windows and Apple emit, and document the behaviour under Error Handling in the README, including that Linux and Web report deviceDisconnected before the characteristic lookup. --- README.md | 8 +++++++- lib/src/universal_ble_linux/universal_ble_linux.dart | 2 +- lib/src/universal_ble_web/universal_ble_web.dart | 11 +++++++---- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 872feb44..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 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/lib/src/universal_ble_linux/universal_ble_linux.dart b/lib/src/universal_ble_linux/universal_ble_linux.dart index 8bcd979a..89f8dd63 100644 --- a/lib/src/universal_ble_linux/universal_ble_linux.dart +++ b/lib/src/universal_ble_linux/universal_ble_linux.dart @@ -579,7 +579,7 @@ class UniversalBleLinux extends UniversalBlePlatform { if (!device.connected) { throw UniversalBleException( code: UniversalBleErrorCode.deviceDisconnected, - message: 'Device not connected', + message: 'Device Disconnected', ); } return device; diff --git a/lib/src/universal_ble_web/universal_ble_web.dart b/lib/src/universal_ble_web/universal_ble_web.dart index 9663b556..a399465a 100644 --- a/lib/src/universal_ble_web/universal_ble_web.dart +++ b/lib/src/universal_ble_web/universal_ble_web.dart @@ -697,12 +697,15 @@ class UniversalBleWeb extends UniversalBlePlatform { message: '$deviceId Not Found', ); } - // `connected` is seeded with the current GATT state, so the first event is - // the live value (the same way getConnectionState reads it). - if (!await device.connected.first) { + // 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 $deviceId is not connected', + message: 'Device Disconnected', ); } }