Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -1238,6 +1243,43 @@ 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.

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);
// Disable the timeout
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)`, 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
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).
Expand Down Expand Up @@ -1364,6 +1406,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;
Expand Down
23 changes: 23 additions & 0 deletions lib/src/universal_ble_peripheral.dart
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,29 @@ 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. 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
/// 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<void> updateCharacteristicValue({
required String characteristicId,
String? instanceId,
Expand Down
85 changes: 85 additions & 0 deletions test/ble_peripheral_command_queue_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -158,5 +161,87 @@ 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<void>();

final update = UniversalBlePeripheral.updateCharacteristicValue(
characteristicId: 'fa5a0003',
value: Uint8List.fromList([1]),
deviceId: 'device-1',
);

await expectLater(update, throwsA(isA<TimeoutException>()));
});

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<void>();

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',
);
// 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<TimeoutException>()));
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<void>();

final update = UniversalBlePeripheral.updateCharacteristicValue(
characteristicId: 'fa5a0003',
value: Uint8List.fromList([1]),
deviceId: 'device-1',
);

await expectLater(update, throwsA(isA<TimeoutException>()));
});

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<void>();
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<void>.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);
});
});
}
Loading