From ffdb5c7e4adbe66f3f43df49ae637994ee25603b Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Fri, 27 Nov 2026 07:12:14 +0100 Subject: [PATCH 1/2] Peripheral: document and test the updateCharacteristicValue timeout contract --- README.md | 31 ++++++++ lib/src/universal_ble_peripheral.dart | 16 ++++ test/ble_peripheral_command_queue_test.dart | 82 +++++++++++++++++++++ 3 files changed, 129 insertions(+) diff --git a/README.md b/README.md index d138fb3d..df846bfa 100644 --- a/README.md +++ b/README.md @@ -1238,6 +1238,34 @@ enabled; repeated failures for a characteristic are suppressed until a successful update. Selecting `QueueType.perDevice` or `QueueType.global` still serializes submission, but awaiting the future is what paces the radio. +The future is bounded by the peripheral command timeout: 10 seconds by default, +configurable with: + +```dart +UniversalBlePeripheral.timeout = const Duration(seconds: 5); +// Disable the timeout +UniversalBlePeripheral.timeout = null; +``` + +A timeout means only that the caller stops waiting: a packet the OS already +accepted cannot be recalled, and work still queued natively may yet be +delivered. To recover, await the failure (a `TimeoutException`) and then call +`UniversalBlePeripheral.clearPendingNotifications(deviceId)` to discard unsent +updates. A link that is truly wedged is settled when the central disconnects or +the Bluetooth adapter resets (off/on); either path fails every pending update, +whereas `clearPendingNotifications` only drops what has not been sent. + +No native timeout is added on top. Android's `onNotificationSent` carries no +packet identity, so a native watchdog that cleared the in-flight marker and +re-sent could not tell a lost callback from a slow link: it could mark a later +packet complete early (double sends, out-of-order notifications) or drop a +packet the stack did send. Apple's `peripheralManagerIsReady(toUpdateSubscribers:)` +is already the documented readiness signal, and its `updateValue` return value +reports acceptance. A stack that never settles a notification is +indistinguishable from one that is still sending, so the Dart-side timeout is +the caller-facing guarantee; a truncated bulk transfer is recovered through the +session boundary above rather than a blind re-send. + ### Subscribed Clients and Notify Length Useful to restore in-app state after a process restart (subscription callbacks are not replayed). @@ -1364,6 +1392,9 @@ full — so awaiting it between chunks paces a bulk transfer. It fails when a queued update is discarded: `clearPendingNotifications`, service removal, central unsubscription or adapter loss. Packets already accepted by the OS cannot be recalled, and remote acknowledgement remains a link-layer concern. +The wait is bounded by the peripheral command timeout (10 s by default); see +[Characteristic Updates](#characteristic-updates) for what a timeout does and +does not recall, and how to recover. Apple negotiates a high connection latency by default, which caps notification throughput. Ask for the low-latency mode before a bulk transfer (iOS and macOS; diff --git a/lib/src/universal_ble_peripheral.dart b/lib/src/universal_ble_peripheral.dart index e994833c..460317ae 100644 --- a/lib/src/universal_ble_peripheral.dart +++ b/lib/src/universal_ble_peripheral.dart @@ -247,6 +247,22 @@ class UniversalBlePeripheral { /// first error is reported. `clearPendingNotifications`, removing a service, a /// central unsubscribing and a Bluetooth reset fail updates that could never /// be sent. + /// + /// The future is bounded by the peripheral command timeout — 10 seconds by + /// default, configurable with `UniversalBlePeripheral.timeout` and disabled + /// with `null` — and fails with a `TimeoutException` when the platform never + /// settles the update. A timeout only stops the caller waiting: a packet the + /// OS already accepted cannot be recalled, and work still queued natively may + /// yet be delivered. Recovery is caller-driven: await the failure, then use + /// [clearPendingNotifications] to discard unsent work. A link that is truly + /// wedged is settled when the central disconnects or the adapter resets + /// (Bluetooth off/on), which fails every pending update. + /// + /// No native timeout is added on top: Android's `onNotificationSent` carries + /// no packet identity, so a watchdog that cleared the in-flight marker and + /// re-sent could not tell a lost callback from a slow link, and Apple's + /// `peripheralManagerIsReady(toUpdateSubscribers:)` is already the documented + /// readiness signal. The Dart-side timeout is the caller-facing guarantee. static Future updateCharacteristicValue({ required String characteristicId, String? instanceId, diff --git a/test/ble_peripheral_command_queue_test.dart b/test/ble_peripheral_command_queue_test.dart index 7a5850dc..1ddab952 100644 --- a/test/ble_peripheral_command_queue_test.dart +++ b/test/ble_peripheral_command_queue_test.dart @@ -62,6 +62,9 @@ void main() { tearDown(() { UniversalBlePeripheral.clearQueue(); UniversalBlePeripheral.queueType = QueueType.global; + // Restore the documented default so a test's short timeout cannot leak + // into the next one. + UniversalBlePeripheral.timeout = const Duration(seconds: 10); }); test('serializes updateCharacteristicValue in global queue mode', () async { @@ -158,5 +161,84 @@ void main() { release.complete(); await first; }); + + test( + 'updateCharacteristicValue times out when the native reply never arrives', + () async { + UniversalBlePeripheral.queueType = QueueType.perDevice; + UniversalBlePeripheral.timeout = const Duration(milliseconds: 50); + mockPlatform.notifyCompleter = Completer(); + + final update = UniversalBlePeripheral.updateCharacteristicValue( + characteristicId: 'fa5a0003', + value: Uint8List.fromList([1]), + deviceId: 'device-1', + ); + + await expectLater(update, throwsA(isA())); + }); + + test('a timed-out update does not wedge the peripheral queue', () async { + UniversalBlePeripheral.queueType = QueueType.perDevice; + UniversalBlePeripheral.timeout = const Duration(milliseconds: 50); + mockPlatform.notifyCompleter = Completer(); + + final stuck = UniversalBlePeripheral.updateCharacteristicValue( + characteristicId: 'fa5a0003', + value: Uint8List.fromList([1]), + deviceId: 'device-1', + ); + // Queued behind the update that will time out; the queue must run it once + // the timeout settles the first command. + final next = UniversalBlePeripheral.updateCharacteristicValue( + characteristicId: 'fa5a0003', + value: Uint8List.fromList([2, 3]), + deviceId: 'device-1', + ); + mockPlatform.notifyCompleter = null; + + await expectLater(stuck, throwsA(isA())); + await next; + + expect(mockPlatform.callLog, ['update:device-1:1', 'update:device-1:2']); + }); + + test('a command without a queue is bounded by the same timeout', () async { + UniversalBlePeripheral.queueType = QueueType.none; + UniversalBlePeripheral.timeout = const Duration(milliseconds: 50); + mockPlatform.notifyCompleter = Completer(); + + final update = UniversalBlePeripheral.updateCharacteristicValue( + characteristicId: 'fa5a0003', + value: Uint8List.fromList([1]), + deviceId: 'device-1', + ); + + await expectLater(update, throwsA(isA())); + }); + + test('timeout = null disables the peripheral command timeout', () async { + UniversalBlePeripheral.queueType = QueueType.perDevice; + UniversalBlePeripheral.timeout = const Duration(milliseconds: 50); + UniversalBlePeripheral.timeout = null; + + final release = Completer(); + mockPlatform.notifyCompleter = release; + var settled = false; + final update = UniversalBlePeripheral.updateCharacteristicValue( + characteristicId: 'fa5a0003', + value: Uint8List.fromList([1]), + deviceId: 'device-1', + ).whenComplete(() => settled = true); + + // Longer than the 50 ms timeout the test configured first. + await Future.delayed(const Duration(milliseconds: 150)); + expect(settled, isFalse, + reason: 'null must disable the timeout, not fall back to a default'); + + release.complete(); + await update; + expect(settled, isTrue); + }); }); } From d456598d29e33224e6559d63c6cb4919b609439b Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Fri, 27 Nov 2026 07:16:07 +0100 Subject: [PATCH 2/2] Peripheral: correct the timeout and recovery docs for updateCharacteristicValue The README and the dartdoc said the update future is bounded by the peripheral command timeout, but in QueueType.global and QueueType.perDevice the timeout starts only when the queue item runs: Queue._QueuedFuture.execute wraps closure() in .timeout() at that point, so time spent waiting behind earlier commands is not counted. QueueType.none, the QueueType.auto default on Apple and Windows, bounds the call as submitted. Say which one applies. The recovery advice also overclaimed clearPendingNotifications. On Android it drops the queued notifications and keeps the in-flight marker until onNotificationSent arrives (dropNotifications(includeInFlight = false), as asserted by clearPendingNotificationsFailsQueuedUpdatesButKeepsTheOneInFlight), so later updates for that client still wait behind the packet that timed out. Windows has no plugin-owned queue: ClearPendingNotifications returns without touching anything, so an operation already running cannot be cancelled. Spell out what the call discards and what it cannot recall. List UniversalBlePeripheral.timeout in the README Timeout section, which only covered UniversalBle.timeout, and cross-link the notification caveats. Also explain why the "does not wedge the queue" test releases its gate after the second submission: the fake reads the field when the platform call starts, so the first update keeps the never-completing completer. Verification: flutter analyze clean, flutter test 348 passed, and this test file also passes under flutter test --platform chrome. --- README.md | 26 ++++++++++++++++----- lib/src/universal_ble_peripheral.dart | 19 ++++++++++----- test/ble_peripheral_command_queue_test.dart | 3 +++ 3 files changed, 36 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index df846bfa..e5f8b03b 100644 --- a/README.md +++ b/README.md @@ -946,6 +946,11 @@ UniversalBle.timeout = null; You can also specify the `timeout` parameter when sending a command. This will override the global timeout. +Peripheral commands use a separate timeout, `UniversalBlePeripheral.timeout`, +also 10 seconds by default. See +[Characteristic Updates](#characteristic-updates) for what a notification +timeout does and does not recall, and how to recover. + ## Error Handling Universal BLE provides a unified and type-safe error handling system across all platforms. All errors are represented using the `UniversalBleException` base class with typed error codes from the `UniversalBleErrorCode` enum. @@ -1238,8 +1243,8 @@ enabled; repeated failures for a characteristic are suppressed until a successful update. Selecting `QueueType.perDevice` or `QueueType.global` still serializes submission, but awaiting the future is what paces the radio. -The future is bounded by the peripheral command timeout: 10 seconds by default, -configurable with: +Once it runs, the update is bounded by the peripheral command timeout: 10 +seconds by default, configurable with: ```dart UniversalBlePeripheral.timeout = const Duration(seconds: 5); @@ -1247,13 +1252,22 @@ UniversalBlePeripheral.timeout = const Duration(seconds: 5); UniversalBlePeripheral.timeout = null; ``` +The bound starts when the command reaches the front of its queue, so with +`QueueType.global` or `QueueType.perDevice` the time spent waiting behind +earlier commands is not counted; `QueueType.none` (the `QueueType.auto` default +on Apple and Windows) bounds the call as submitted. + A timeout means only that the caller stops waiting: a packet the OS already accepted cannot be recalled, and work still queued natively may yet be delivered. To recover, await the failure (a `TimeoutException`) and then call -`UniversalBlePeripheral.clearPendingNotifications(deviceId)` to discard unsent -updates. A link that is truly wedged is settled when the central disconnects or -the Bluetooth adapter resets (off/on); either path fails every pending update, -whereas `clearPendingNotifications` only drops what has not been sent. +`UniversalBlePeripheral.clearPendingNotifications(deviceId)`, which drops what +is still waiting — the Dart queue, plus the platform's pending queue on Android +and Apple. Nothing already handed to the OS is withdrawn: Android keeps the +in-flight marker until `onNotificationSent` arrives, so later updates for that +client wait behind it, and Windows has no plugin-owned queue, so an operation +already running there cannot be cancelled. A link that is truly wedged is +settled when the central disconnects or the Bluetooth adapter resets (off/on); +either path fails every pending update. No native timeout is added on top. Android's `onNotificationSent` carries no packet identity, so a native watchdog that cleared the in-flight marker and diff --git a/lib/src/universal_ble_peripheral.dart b/lib/src/universal_ble_peripheral.dart index 460317ae..5e9ecf86 100644 --- a/lib/src/universal_ble_peripheral.dart +++ b/lib/src/universal_ble_peripheral.dart @@ -251,12 +251,19 @@ class UniversalBlePeripheral { /// The future is bounded by the peripheral command timeout — 10 seconds by /// default, configurable with `UniversalBlePeripheral.timeout` and disabled /// with `null` — and fails with a `TimeoutException` when the platform never - /// settles the update. A timeout only stops the caller waiting: a packet the - /// OS already accepted cannot be recalled, and work still queued natively may - /// yet be delivered. Recovery is caller-driven: await the failure, then use - /// [clearPendingNotifications] to discard unsent work. A link that is truly - /// wedged is settled when the central disconnects or the adapter resets - /// (Bluetooth off/on), which fails every pending update. + /// settles the update. The bound starts when the command reaches the front of + /// its queue, so time spent waiting behind earlier commands in + /// [QueueType.global] or [QueueType.perDevice] is not counted. A timeout only + /// stops the caller waiting: a packet the OS already accepted cannot be + /// recalled, and work still queued natively may yet be delivered. Recovery is + /// caller-driven: await the failure, then use [clearPendingNotifications] to + /// drop what is still waiting — the Dart queue, plus the platform's pending + /// queue on Android and Apple. Nothing already handed to the OS is withdrawn: + /// Android keeps the in-flight marker until `onNotificationSent` arrives, so + /// later updates for that client wait behind it, and Windows has no + /// plugin-owned queue. A link that is truly wedged is settled when the central + /// disconnects or the adapter resets (Bluetooth off/on), which fails every + /// pending update. /// /// No native timeout is added on top: Android's `onNotificationSent` carries /// no packet identity, so a watchdog that cleared the in-flight marker and diff --git a/test/ble_peripheral_command_queue_test.dart b/test/ble_peripheral_command_queue_test.dart index 1ddab952..413136f8 100644 --- a/test/ble_peripheral_command_queue_test.dart +++ b/test/ble_peripheral_command_queue_test.dart @@ -195,6 +195,9 @@ void main() { value: Uint8List.fromList([2, 3]), deviceId: 'device-1', ); + // The mock reads the gate when the platform call starts, so this only + // releases the second update: the first already captured the completer + // above, which never completes. mockPlatform.notifyCompleter = null; await expectLater(stuck, throwsA(isA()));