Repository navigation
Peripheral: document and test the updateCharacteristicValue timeout contract - #406
Merged
Merged
Conversation
fotiDim
added a commit
that referenced
this pull request
Nov 27, 2026
drainNotifications pushes a refused payload (notifyCharacteristicChanged
returns false) back to the front of pendingNotifications and removes the
in-flight marker. Nothing then schedules another drain: the marker was absent
before the send, so there is no packet whose onNotificationSent would retry it.
The queued update therefore waits for an unrelated updateCharacteristic for the
same client, and every later update queues behind it. A payload enqueued in the
window between the isSubscribed check in updateCharacteristic and the enqueue (a
CCCD unsubscribe can land in between) could likewise be transmitted stale after
a resubscription.
A refusal now schedules a retry for that client on the existing main Handler.
At most one runnable exists per address, so further refusals coalesce into it.
The delay is 10 ms, doubled per consecutive refusal and capped at 500 ms; a
successful send clears the attempt count, leaving at most one int map entry per
device. The runnable re-checks the subscription outside the pendingNotifications
monitor, because isSubscribed takes subscribedCharDevicesMap and the
descriptor/cleanup paths take the two monitors in the opposite order. When the
client has unsubscribed, the queued payloads of the characteristic at the head
of its queue are dropped with dropNotifications(includeInFlight = false) and
settled with "Central unsubscribed", which ends the retry loop, and the client's
other characteristics still drain. Settlements still go through
settleNotifications, so no Dart callback runs on a binder thread. Disconnect,
adapter reset, removeService/clearServices, clearPendingNotifications and the
CCCD unsubscribe path cancel a retry that is no longer needed, and the
onNotificationSent flow that settles a successful send is unchanged.
Tests (PeripheralRegressionTest) add a captured postDelayed helper that runs
retries manually, never with real delays, and cover: one retry for a refusal
that succeeds when it runs, one retry for several queued updates, the
10/20/40/80/160/320/500/500 ms backoff, the unsubscribe drop with a failed
callback and no resend after resubscribing, reset and clearPendingNotifications
cancelling the runnable and failing the queue, and the attempt state cleared by
a successful send. The first test fails against the unfixed production file
("The refusal schedules exactly one retry ==> expected: <1> but was: <0>").
Verification: flutter analyze clean, flutter test 344 passed, Android unit tests
142 passed.
…isticValue 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up to #405 (issue #402). That PR made
UniversalBlePeripheral.updateCharacteristicValuecomplete when the native platform settles the notification. Its review left a residual risk: the async native reply has no timeout, so a stack that reports neitheronNotificationSentnorperipheralManagerIsReadyleaves the future pending. Is a timeout on the Dart side enough?Yes, as the caller-facing guarantee. This PR documents that contract and locks it down with tests; it does not change production behaviour.
Why the Dart timeout is sufficient for callers
updateCharacteristicValueis dispatched throughBleCommandQueue.queueCommand, so it inherits the peripheral queue timeout: 10 s by default, overridable withUniversalBlePeripheral.timeout, disabled withnull.QueueType.perDevice/global(Android, Web, Linux; or explicit): the queue item awaitsclosure().timeout(...), completes the caller's future with aTimeoutException, and itsonCompleteruns the next queued command. The bound starts when the item runs, so time spent waiting behind earlier commands is not counted.QueueType.none(Apple, Windows): the returned future is wrapped directly with.timeout(...)at submission.So the caller gets an answer once the command runs, and a timed-out command does not wedge later work.
Why a native timeout is unsafe
onNotificationSent(device, status)carries no packet identity.notificationsInFlightis keyed by client address and settles whatever is marked for that client. A native watchdog that cleared the marker and re-sent could not distinguish a lost callback from a slow link: it could mark a later packet complete early (double send, out-of-order notifications) or drop a packet the stack actually sent.peripheralManagerIsReady(toUpdateSubscribers:)is already the documented readiness signal, andCBPeripheralManager.updateValuereturns acceptance. A watchdog on top would have no additional identity to match against.The reliable teardown paths are the existing ones: a central disconnecting and the adapter-reset path settle every pending update.
Recovery guidance
Await the failure, then call
clearPendingNotifications(deviceId)to discard what is still waiting — the Dart queue, plus the platform's pending queue on Android and Apple. A packet already handed to the OS cannot be recalled, and work still queued natively may yet be delivered. The call cannot withdraw a packet already in flight: Android keeps its in-flight marker untilonNotificationSent, so later updates for that client still wait behind the timed-out packet, and Windows has no plugin-owned queue at all. If the link itself is wedged, have the central disconnect or reset the adapter (Bluetooth off/on), which fails every pending update;clearServices()also settles all pending updates if re-registering the services is acceptable.Residual gap: no remote acknowledgement is implied. The timeout tells the caller to stop waiting, not that the peer received or missed a packet. Applications that need delivery guarantees must implement an application-level acknowledgement.
Evidence
New tests in
test/ble_peripheral_command_queue_test.dartuse a fake peripheral platform whoseupdateCharacteristicValuenever completes:UniversalBlePeripheral.updateCharacteristicValuewithTimeoutExceptioninQueueType.perDevice;QueueType.nonepath used on Apple/Windows;UniversalBlePeripheral.timeout = nulldisables the timeout (a command released after the previously configured 50 ms succeeds).The timeouts only need "eventually times out", with no upper bound on the passing path, so a slow runner cannot flake them.
UniversalBlePeripheral.timeoutis static state;tearDownrestores the 10 s default, andsetUpreconfigures it for each test.flutter analyzeclean,flutter test348/348 passing, this test file passing underflutter test --platform chrome, and the Android plugin unit tests (:universal_ble:testDebugUnitTest) pass.Files:
lib/src/universal_ble_peripheral.dart(API contract),README.md(timeout and recovery contract, why no native watchdog),test/ble_peripheral_command_queue_test.dart(four regression tests).