diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f402461..a3379c50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,7 @@ ## Unreleased +* Peripheral mode: `updateCharacteristicValue` now completes when the notification is settled instead of when it was submitted, so awaiting it paces a bulk transfer and reports failures that previously only reached a log. Android completes on `onNotificationSent` (failing on a non-success GATT status), Apple when `CBPeripheralManager.updateValue` accepts the value — immediately or after `peripheralManagerIsReady(toUpdateSubscribers:)` — and Windows when `NotifyValueAsync` completes. A queued update that can never be sent fails instead of hanging: `clearPendingNotifications`, `removeService`, `clearServices`, central unsubscription, a Bluetooth reset and a device disconnect all settle their targets with an error. This is a behavioural change, not a signature break: the parameter list is unchanged, but code that awaited the future without minding the delay now waits for delivery, so bulk senders should keep awaiting it between chunks (#402). +* Apple peripheral: the notification FIFO is now an O(1) head-indexed queue instead of `Array.removeFirst()`, which shifted the whole tail per chunk and made a bulk transfer O(N²) on the main queue. Each accepted element is settled exactly once, and discarded updates fail their Dart futures with a descriptive error instead of waiting forever (#402). +* Apple peripheral: add `UniversalBlePeripheral.setDesiredConnectionLatency(deviceId, PeripheralConnectionLatency.low|medium|high)`, mapped to `CBPeripheralManager.setDesiredConnectionLatency(_:for:)`. Apple otherwise negotiates a high latency, which caps notification throughput. No-op on non-Apple platforms (#402). * Windows: connecting to a device whose GATT database holds a service Windows reserves for itself — HID over GATT, `0x1812` — no longer fails. Windows answers `GetCharacteristicsAsync` with `AccessDenied` for it whether or not the device is paired, and since 2.2.0 that error ended the connection attempt during discovery. A denied service is now left out: its characteristics are not reported by `discoverServices`, the rest of the database connects normally, and a GATT service refresh skips it instead of keeping the previous map. A denied service that discovery already reported is the exception — the refresh keeps the previous services then, so reads and subscriptions on it do not silently disappear. A device whose every service was denied still connects, reports no services, and logs a warning. `Unreachable` and `ProtocolError` still fail the connection, so a discovery cut short by a link drop is still reported (#400). * Android peripheral: an update no longer races the notification the stack is already sending. Below API 33 the payload travels in the shared `BluetoothGattCharacteristic.value`, and `updateCharacteristic` wrote it on the main thread while `onNotificationSent` drained the next queued payload on a binder thread: the assignment could land between that drain's value write and its `notifyCharacteristicChanged` call, so a same-length payload was silently transmitted with the wrong content. The in-flight check, the dequeue, the value assignment and the send now all happen under the pending-notification monitor, and the drain no longer reads the subscription map while holding it — the descriptor and cleanup paths take it in the opposite order. API 33+ uses the stateless four-argument overload and treats only `BluetoothStatusCodes.SUCCESS` as sent, and the value a read returns is written only when no target device is subscribed rather than on every update (#403). diff --git a/README.md b/README.md index 7568280b..d138fb3d 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ Looking for Bluetooth Classic? Check [universal_bluetooth_classic](https://pub.d | getSubscribedClients | ✔️ | ✔️ | ✔️ | ✔️ | 🚧 | — | | getMaximumNotifyLength | ✔️ | ✔️ | ✔️ | ✔️ | 🚧 | — | | setAutoConnect | ✔️ | — | — | — | — | — | +| setDesiredConnectionLatency | — | ✔️ | ✔️ | — | — | — | | event streams\*\*\* | ✔️ | ✔️ | ✔️ | ✔️ | 🚧 | — | \* `getAvailabilityState` returns a snapshot. Listen to `advertisingStateStream`, `connectionStateStream`, and related streams for runtime updates. @@ -1212,9 +1213,30 @@ await UniversalBlePeripheral.updateCharacteristicValue( value: Uint8List.fromList([88]), deviceId: deviceId, ); + +// Pace a bulk transfer by awaiting each chunk. The future completes once the +// platform accepted (Apple) or sent (Android/Windows) the notification. +for (final chunk in chunks) { + await UniversalBlePeripheral.updateCharacteristicValue( + characteristicId: batteryLevelChar, + value: chunk, + ); +} ``` -On Windows, the returned future completes after submitting the notification. Awaiting it or selecting `QueueType.perDevice` or `QueueType.global` serializes submission only: notification operations can still overlap, and delivery order is not guaranteed. Transport failures and truncated values are logged when `UniversalBle.setLogLevel(BleLogLevel.error)` (or a more verbose level) is enabled. Repeated failures for a characteristic are suppressed until a successful update. +On Android, Apple and Windows the returned future is a backpressure signal: it +completes when the notification has been settled by the platform — Android on +`onNotificationSent` (failing on a non-success GATT status), Apple when +`CBPeripheralManager.updateValue` accepts the value (immediately or after +`peripheralManagerIsReady(toUpdateSubscribers:)`), Windows when +`NotifyValueAsync` completes. Failing an update that can never be sent — through +`clearPendingNotifications`, `removeService`, central unsubscription or a +Bluetooth reset — also completes it with an error. On Windows, transport +failures and truncated values are additionally logged when +`UniversalBle.setLogLevel(BleLogLevel.error)` (or a more verbose level) is +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. ### Subscribed Clients and Notify Length @@ -1332,13 +1354,27 @@ before replacement. Install listeners before configuration, then query `getSubscribedClients` to reconcile readiness. Explicit force-quit recovery and background discoverability are governed by CoreBluetooth and are not guaranteed. -Apple notifications remain FIFO while CoreBluetooth applies backpressure. Use -`await UniversalBlePeripheral.clearPendingNotifications(deviceId)` at an explicit -session boundary or suspension to discard unsent updates, then publish neutral -state before new input. Native unsubscription, service removal, and adapter loss -also invalidate pending Apple updates. Packets already accepted by the OS cannot -be recalled. Completion of `updateCharacteristicValue` means accepted by the -plugin, not acknowledged by the remote device. +Apple notifications remain FIFO while CoreBluetooth applies backpressure. +Use `await UniversalBlePeripheral.clearPendingNotifications(deviceId)` at an +explicit session boundary or suspension to discard unsent updates, then publish +neutral state before new input. `updateCharacteristicValue` completes once +`CBPeripheralManager.updateValue` accepts the value — immediately, or later from +`peripheralManagerIsReady(toUpdateSubscribers:)` when the transmit queue was +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. + +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; +no-op elsewhere): + +```dart +await UniversalBlePeripheral.setDesiredConnectionLatency( + deviceId, + PeripheralConnectionLatency.low, +); +``` Run `./darwin/test/run_peripheral_reliability_tests.sh` on macOS for native characteristic, restored-identity, and notification-FIFO regression checks. diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBle.g.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBle.g.kt index 5c31d4c0..22c44127 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBle.g.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBle.g.kt @@ -404,6 +404,25 @@ enum class PeripheralAdvertisingState(val raw: Int) { } } +/** + * Desired connection latency for a subscribed central on Apple platforms. + * + * Maps to CoreBluetooth `CBPeripheralManagerConnectionLatency`. A lower + * latency trades radio time for responsiveness; Apple negotiates a higher + * latency (and therefore lower throughput) when nothing asks for otherwise. + */ +enum class PeripheralConnectionLatency(val raw: Int) { + LOW(0), + MEDIUM(1), + HIGH(2); + + companion object { + fun ofRaw(raw: Int): PeripheralConnectionLatency? { + return values().firstOrNull { it.raw == raw } + } + } +} + /** Unified error codes for all platforms */ enum class UniversalBleErrorCode(val raw: Int) { UNKNOWN_ERROR(0), @@ -1897,135 +1916,140 @@ private open class UniversalBlePigeonCodec : StandardMessageCodec() { } 143.toByte() -> { return (readValue(buffer) as Long?)?.let { - UniversalBleErrorCode.ofRaw(it.toInt()) + PeripheralConnectionLatency.ofRaw(it.toInt()) } } 144.toByte() -> { + return (readValue(buffer) as Long?)?.let { + UniversalBleErrorCode.ofRaw(it.toInt()) + } + } + 145.toByte() -> { return (readValue(buffer) as? List)?.let { UniversalBleScanResult.fromList(it) } } - 145.toByte() -> { + 146.toByte() -> { return (readValue(buffer) as? List)?.let { UniversalDevicePickerResult.fromList(it) } } - 146.toByte() -> { + 147.toByte() -> { return (readValue(buffer) as? List)?.let { UniversalBleService.fromList(it) } } - 147.toByte() -> { + 148.toByte() -> { return (readValue(buffer) as? List)?.let { UniversalBleCharacteristic.fromList(it) } } - 148.toByte() -> { + 149.toByte() -> { return (readValue(buffer) as? List)?.let { UniversalBleDescriptor.fromList(it) } } - 149.toByte() -> { + 150.toByte() -> { return (readValue(buffer) as? List)?.let { BleConnectionParametersChange.fromList(it) } } - 150.toByte() -> { + 151.toByte() -> { return (readValue(buffer) as? List)?.let { AndroidOptions.fromList(it) } } - 151.toByte() -> { + 152.toByte() -> { return (readValue(buffer) as? List)?.let { UniversalScanConfig.fromList(it) } } - 152.toByte() -> { + 153.toByte() -> { return (readValue(buffer) as? List)?.let { UniversalScanFilter.fromList(it) } } - 153.toByte() -> { + 154.toByte() -> { return (readValue(buffer) as? List)?.let { ManufacturerDataFilter.fromList(it) } } - 154.toByte() -> { + 155.toByte() -> { return (readValue(buffer) as? List)?.let { UniversalManufacturerData.fromList(it) } } - 155.toByte() -> { + 156.toByte() -> { return (readValue(buffer) as? List)?.let { AppleConnectionOptions.fromList(it) } } - 156.toByte() -> { + 157.toByte() -> { return (readValue(buffer) as? List)?.let { AppleAccessoryPickerItem.fromList(it) } } - 157.toByte() -> { + 158.toByte() -> { return (readValue(buffer) as? List)?.let { AppleAccessorySetupOptions.fromList(it) } } - 158.toByte() -> { + 159.toByte() -> { return (readValue(buffer) as? List)?.let { AndroidConnectionOptions.fromList(it) } } - 159.toByte() -> { + 160.toByte() -> { return (readValue(buffer) as? List)?.let { ConnectionPlatformConfig.fromList(it) } } - 160.toByte() -> { + 161.toByte() -> { return (readValue(buffer) as? List)?.let { AndroidDiscoverServicesOptions.fromList(it) } } - 161.toByte() -> { + 162.toByte() -> { return (readValue(buffer) as? List)?.let { AppleDiscoverServicesOptions.fromList(it) } } - 162.toByte() -> { + 163.toByte() -> { return (readValue(buffer) as? List)?.let { DiscoverServicesPlatformConfig.fromList(it) } } - 163.toByte() -> { + 164.toByte() -> { return (readValue(buffer) as? List)?.let { PeripheralAndroidOptions.fromList(it) } } - 164.toByte() -> { + 165.toByte() -> { return (readValue(buffer) as? List)?.let { PeripheralPlatformConfig.fromList(it) } } - 165.toByte() -> { + 166.toByte() -> { return (readValue(buffer) as? List)?.let { PeripheralService.fromList(it) } } - 166.toByte() -> { + 167.toByte() -> { return (readValue(buffer) as? List)?.let { PeripheralCharacteristic.fromList(it) } } - 167.toByte() -> { + 168.toByte() -> { return (readValue(buffer) as? List)?.let { PeripheralDescriptor.fromList(it) } } - 168.toByte() -> { + 169.toByte() -> { return (readValue(buffer) as? List)?.let { PeripheralReadRequestResult.fromList(it) } } - 169.toByte() -> { + 170.toByte() -> { return (readValue(buffer) as? List)?.let { PeripheralWriteRequestResult.fromList(it) } @@ -2091,112 +2115,116 @@ private open class UniversalBlePigeonCodec : StandardMessageCodec() { stream.write(142) writeValue(stream, value.raw.toLong()) } - is UniversalBleErrorCode -> { + is PeripheralConnectionLatency -> { stream.write(143) writeValue(stream, value.raw.toLong()) } - is UniversalBleScanResult -> { + is UniversalBleErrorCode -> { stream.write(144) + writeValue(stream, value.raw.toLong()) + } + is UniversalBleScanResult -> { + stream.write(145) writeValue(stream, value.toList()) } is UniversalDevicePickerResult -> { - stream.write(145) + stream.write(146) writeValue(stream, value.toList()) } is UniversalBleService -> { - stream.write(146) + stream.write(147) writeValue(stream, value.toList()) } is UniversalBleCharacteristic -> { - stream.write(147) + stream.write(148) writeValue(stream, value.toList()) } is UniversalBleDescriptor -> { - stream.write(148) + stream.write(149) writeValue(stream, value.toList()) } is BleConnectionParametersChange -> { - stream.write(149) + stream.write(150) writeValue(stream, value.toList()) } is AndroidOptions -> { - stream.write(150) + stream.write(151) writeValue(stream, value.toList()) } is UniversalScanConfig -> { - stream.write(151) + stream.write(152) writeValue(stream, value.toList()) } is UniversalScanFilter -> { - stream.write(152) + stream.write(153) writeValue(stream, value.toList()) } is ManufacturerDataFilter -> { - stream.write(153) + stream.write(154) writeValue(stream, value.toList()) } is UniversalManufacturerData -> { - stream.write(154) + stream.write(155) writeValue(stream, value.toList()) } is AppleConnectionOptions -> { - stream.write(155) + stream.write(156) writeValue(stream, value.toList()) } is AppleAccessoryPickerItem -> { - stream.write(156) + stream.write(157) writeValue(stream, value.toList()) } is AppleAccessorySetupOptions -> { - stream.write(157) + stream.write(158) writeValue(stream, value.toList()) } is AndroidConnectionOptions -> { - stream.write(158) + stream.write(159) writeValue(stream, value.toList()) } is ConnectionPlatformConfig -> { - stream.write(159) + stream.write(160) writeValue(stream, value.toList()) } is AndroidDiscoverServicesOptions -> { - stream.write(160) + stream.write(161) writeValue(stream, value.toList()) } is AppleDiscoverServicesOptions -> { - stream.write(161) + stream.write(162) writeValue(stream, value.toList()) } is DiscoverServicesPlatformConfig -> { - stream.write(162) + stream.write(163) writeValue(stream, value.toList()) } is PeripheralAndroidOptions -> { - stream.write(163) + stream.write(164) writeValue(stream, value.toList()) } is PeripheralPlatformConfig -> { - stream.write(164) + stream.write(165) writeValue(stream, value.toList()) } is PeripheralService -> { - stream.write(165) + stream.write(166) writeValue(stream, value.toList()) } is PeripheralCharacteristic -> { - stream.write(166) + stream.write(167) writeValue(stream, value.toList()) } is PeripheralDescriptor -> { - stream.write(167) + stream.write(168) writeValue(stream, value.toList()) } is PeripheralReadRequestResult -> { - stream.write(168) + stream.write(169) writeValue(stream, value.toList()) } is PeripheralWriteRequestResult -> { - stream.write(169) + stream.write(170) writeValue(stream, value.toList()) } else -> super.writeValue(stream, value) @@ -2918,7 +2946,16 @@ interface UniversalBlePeripheralChannel { fun clearServices() fun getServices(): List fun startAdvertising(services: List, localName: String?, timeout: Long?, manufacturerData: UniversalManufacturerData?, platformConfig: PeripheralPlatformConfig?) - fun updateCharacteristic(characteristicId: String, characteristicInstanceId: String?, value: ByteArray, deviceId: String?) + /** + * Sends [value] to the clients subscribed to [characteristicId]. + * + * The reply is sent once every targeted client's notification is settled: + * accepted by the platform queue (Apple, when `updateValue` returns `true`), + * sent (`onNotificationSent` on Android) or completed (`NotifyValueAsync` on + * Windows). A failure is reported once all of them have settled and at least + * one failed. + */ + fun updateCharacteristic(characteristicId: String, characteristicInstanceId: String?, value: ByteArray, deviceId: String?, callback: (Result) -> Unit) /** * Returns peripheral-client device ids currently subscribed to the * characteristic identified by [characteristicId] (and, when supplied, @@ -3092,13 +3129,14 @@ interface UniversalBlePeripheralChannel { val characteristicInstanceIdArg = args[1] as String? val valueArg = args[2] as ByteArray val deviceIdArg = args[3] as String? - val wrapped: List = try { - api.updateCharacteristic(characteristicIdArg, characteristicInstanceIdArg, valueArg, deviceIdArg) - listOf(null) - } catch (exception: Throwable) { - UniversalBlePigeonUtils.wrapError(exception) + api.updateCharacteristic(characteristicIdArg, characteristicInstanceIdArg, valueArg, deviceIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(UniversalBlePigeonUtils.wrapError(error)) + } else { + reply.reply(UniversalBlePigeonUtils.wrapResult(null)) + } } - reply.reply(wrapped) } } else { channel.setMessageHandler(null) @@ -3179,12 +3217,14 @@ interface UniversalBlePeripheralChannel { } } /** - * Flutter -> Native (Apple peripheral restoration only). + * Flutter -> Native (Apple peripheral-only APIs). * * Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface UniversalBleDarwinPeripheralChannel { fun configureRestoration(restorationIdentifier: String) + /** Sets the connection latency CoreBluetooth negotiates with [deviceId]. */ + fun setDesiredConnectionLatency(deviceId: String, latency: PeripheralConnectionLatency) companion object { /** The codec used by UniversalBleDarwinPeripheralChannel. */ @@ -3213,6 +3253,25 @@ interface UniversalBleDarwinPeripheralChannel { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.universal_ble.UniversalBleDarwinPeripheralChannel.setDesiredConnectionLatency$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val deviceIdArg = args[0] as String + val latencyArg = args[1] as PeripheralConnectionLatency + val wrapped: List = try { + api.setDesiredConnectionLatency(deviceIdArg, latencyArg) + listOf(null) + } catch (exception: Throwable) { + UniversalBlePigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } } } } diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt index 8c71fac7..c0c000ef 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt @@ -29,6 +29,8 @@ import android.os.Handler import android.os.ParcelUuid import android.util.Log import io.flutter.plugin.common.BinaryMessenger +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference private const val TAG = "UniversalBlePeripheral" private const val REQUEST_CODE_ENABLE_BLUETOOTH = 2342717 @@ -79,6 +81,8 @@ class UniversalBlePeripheralPlugin( val characteristic: BluetoothGattCharacteristic, val value: ByteArray, val indicate: Boolean, + /** Called exactly once, on [handler], with null when the stack accepted/sent it. */ + val onSettled: (Throwable?) -> Unit, ) /** @@ -94,7 +98,45 @@ class UniversalBlePeripheralPlugin( * another drain or with an update (#403). */ private val pendingNotifications: ArrayDeque = ArrayDeque() - private val notificationsInFlight: MutableSet = HashSet() + + /** + * The notification each client currently owns, keyed by client address. It + * is the one [BluetoothGattServerCallback.onNotificationSent] settles; the + * key is also the client's "busy" marker, so a later packet cannot overtake + * it before that callback. + */ + private val notificationsInFlight: MutableMap = HashMap() + + /** + * Settles [notifications] with [error] on the main thread. A GATT callback + * runs on a binder thread, so completing the Pigeon result there would reply + * to Dart from the wrong thread. + */ + private fun settleNotifications(notifications: List, error: Throwable?) { + if (notifications.isEmpty()) return + handler.post { + notifications.forEach { it.onSettled(error) } + } + } + + /** + * Removes the notifications matching [predicate] from both the pending queue + * and the in-flight map, and returns them so their callers can be failed. + * Whatever is returned will not be reported by [onNotificationSent] again. + */ + private fun dropNotifications( + includeInFlight: Boolean = true, + predicate: (PendingNotification) -> Boolean, + ): List = synchronized(pendingNotifications) { + val removed = pendingNotifications.filter(predicate).toMutableList() + pendingNotifications.removeAll(predicate) + if (includeInFlight) { + val droppedInFlight = notificationsInFlight.filterValues(predicate) + notificationsInFlight.values.removeAll(predicate) + removed.addAll(droppedInFlight.values) + } + removed + } /** * A [BluetoothGattServer] and a [BluetoothLeAdvertiser] do not survive an @@ -134,8 +176,12 @@ class UniversalBlePeripheralPlugin( }.onFailure { UniversalBleLogger.logWarning("Failed to unregister the adapter receiver: ${it.message}") } - resetPeripheralState() + // Drop callbacks posted for the previous state first, then let the + // reset post the settlements for the notifications it discards. Doing it + // the other way round would sweep those settlements away and leave their + // Dart futures pending. handler.removeCallbacksAndMessages(null) + resetPeripheralState() isEnableBluetoothPromptPending = false } @@ -157,11 +203,14 @@ class UniversalBlePeripheralPlugin( // Queued notifications belong to the server that is being dropped, so // discard them before the caches that resolve their characteristics. clearPendingNotifications(null) - synchronized(pendingNotifications) { + val droppedInFlight = synchronized(pendingNotifications) { // The old server will never report these as sent, and a leftover // marker would block that client's queue forever. + val current = notificationsInFlight.values.toList() notificationsInFlight.clear() + current } + settleNotifications(droppedInFlight, IllegalStateException("Peripheral reset")) kotlin.runCatching { gattServer?.close() } gattServer = null gattServerSession = -1 @@ -352,9 +401,8 @@ class UniversalBlePeripheralPlugin( override fun removeService(serviceId: String) { serviceId.findService()?.let { service -> - synchronized(pendingNotifications) { - pendingNotifications.removeAll { it.characteristic.service === service } - } + val removed = dropNotifications { it.characteristic.service === service } + settleNotifications(removed, IllegalStateException("Service removed")) // The service and its characteristics are no longer registered, so // nothing may keep resolving them: a later registration of the same // UUID would notify through these orphaned objects (#385). Done even @@ -372,6 +420,12 @@ class UniversalBlePeripheralPlugin( // Queued notifications are dropped before the caches that resolve their // characteristics, so none can be re-queued for services that are gone. clearPendingNotifications(null) + val droppedInFlight = synchronized(pendingNotifications) { + val current = notificationsInFlight.values.toList() + notificationsInFlight.clear() + current + } + settleNotifications(droppedInFlight, IllegalStateException("Services cleared")) try { requireGattServer().clearServices() } finally { @@ -492,21 +546,32 @@ class UniversalBlePeripheralPlugin( characteristicInstanceId: String?, value: ByteArray, deviceId: String?, + callback: (Result) -> Unit, ) { - requireGattServer() - val characteristic = - characteristicId.findGattCharacteristic(characteristicInstanceId) - ?: throw Exception("Characteristic not found") - val targetDevices = synchronized(bluetoothDevicesMap) { - if (deviceId != null) { - val dev = bluetoothDevicesMap[deviceId] - ?: bluetoothDevicesMap[deviceId.uppercase()] - ?: bluetoothDevicesMap[deviceId.lowercase()] - ?: throw Exception("Device not found") - listOf(dev) - } else { - bluetoothDevicesMap.values.toList() + // A failure or an empty subscriber set completes immediately; when there + // is something to notify, the callback fires once every target client's + // notification has settled. + val characteristic: BluetoothGattCharacteristic + val targetDevices: List + try { + requireGattServer() + characteristic = + characteristicId.findGattCharacteristic(characteristicInstanceId) + ?: throw Exception("Characteristic not found") + targetDevices = synchronized(bluetoothDevicesMap) { + if (deviceId != null) { + val dev = bluetoothDevicesMap[deviceId] + ?: bluetoothDevicesMap[deviceId.uppercase()] + ?: bluetoothDevicesMap[deviceId.lowercase()] + ?: throw Exception("Device not found") + listOf(dev) + } else { + bluetoothDevicesMap.values.toList() + } } + } catch (e: Throwable) { + callback(Result.failure(e)) + return } val indicate = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0 @@ -514,18 +579,32 @@ class UniversalBlePeripheralPlugin( // subscribedCharDevicesMap, and the descriptor/cleanup paths take those two // monitors in the opposite order, so nesting them here would deadlock. val subscribedDevices = targetDevices.filter { isSubscribed(it.address, characteristic) } - synchronized(pendingNotifications) { - if (subscribedDevices.isEmpty()) { - // Nobody to notify: the value is only the static one a read returns. - // Written under this monitor so it cannot land between another - // drain's value assignment and its notify call. + if (subscribedDevices.isEmpty()) { + // Nobody to notify: the value is only the static one a read returns. + // Written under this monitor so it cannot land between another + // drain's value assignment and its notify call. + synchronized(pendingNotifications) { @Suppress("DEPRECATION") characteristic.value = value.copyOf() - return } + callback(Result.success(Unit)) + return + } + val remaining = AtomicInteger(subscribedDevices.size) + val firstError = AtomicReference(null) + val settleOne: (Throwable?) -> Unit = { error -> + if (error != null) firstError.compareAndSet(null, error) + if (remaining.decrementAndGet() == 0) { + val err = firstError.get() + if (err != null) callback(Result.failure(err)) else callback(Result.success(Unit)) + } + } + // Assigning characteristic.value here would race the packet already in + // flight (#403): the value is applied per packet in drainNotifications. + synchronized(pendingNotifications) { subscribedDevices.forEach { device -> pendingNotifications.addLast( - PendingNotification(device, characteristic, value.copyOf(), indicate) + PendingNotification(device, characteristic, value.copyOf(), indicate, settleOne) ) } subscribedDevices.forEach { drainNotifications(it.address) } @@ -540,17 +619,19 @@ class UniversalBlePeripheralPlugin( } private fun drainNotifications(deviceAddress: String) { + // Everything the packet owns is done under one monitor (#403): a second + // update submitted while this one is in flight must neither dequeue it + // nor overwrite the value the stack is about to send. synchronized(pendingNotifications) { - if (notificationsInFlight.contains(deviceAddress)) return + if (notificationsInFlight.containsKey(deviceAddress)) return val index = pendingNotifications.indexOfFirst { it.device.address == deviceAddress } if (index < 0) return val next = pendingNotifications.removeAt(index) val server = gattServer ?: run { - // Nothing to send on; keep the payload for the next drain. pendingNotifications.addFirst(next) return } - notificationsInFlight.add(deviceAddress) + notificationsInFlight[deviceAddress] = next // The in-flight check, the dequeue, the value assignment and the send // all happen under this monitor. Below API 33 the value is carried by // the shared characteristic, so another thread writing it in between @@ -571,21 +652,46 @@ class UniversalBlePeripheralPlugin( } }.getOrDefault(false) if (!sent) { - // Native queue still busy. Put the payload back at the front and wait - // for onNotificationSent to retry; never drop a release. + // Native queue still busy. Put the payload back at the front and + // wait for onNotificationSent to retry; never drop a release. notificationsInFlight.remove(deviceAddress) pendingNotifications.addFirst(next) } } } + /** + * Settles the packet [BluetoothGattServerCallback.onNotificationSent] reports + * and starts the next queued one. Runs on a binder thread, so the settlement + * itself is posted to [handler]. Internal so the unit tests can drive it. + */ + internal fun handleNotificationSent(device: BluetoothDevice, status: Int) { + val address = device.address + val completed = synchronized(pendingNotifications) { + notificationsInFlight.remove(address) + } + // Queue the settlement before the next packet can be handed to the + // stack, so two updates for the same client complete in submission + // order. Posting never invokes the reply here. + if (completed != null) { + val error = if (status == BluetoothGatt.GATT_SUCCESS) null + else IllegalStateException("Notification failed with status $status") + settleNotifications(listOf(completed), error) + } + drainNotifications(address) + } + override fun clearPendingNotifications(deviceId: String?) { - synchronized(pendingNotifications) { - if (deviceId == null) pendingNotifications.clear() - else pendingNotifications.removeAll { it.device.address.equals(deviceId, ignoreCase = true) } - // In-flight packets are already owned by Android. Keep their busy - // markers until onNotificationSent, so a neutral cannot overtake them. + // In-flight packets are already owned by Android. Keep their busy + // markers until onNotificationSent, so a neutral cannot overtake them. + val removed = if (deviceId == null) { + dropNotifications(includeInFlight = false) { true } + } else { + dropNotifications(includeInFlight = false) { + it.device.address.equals(deviceId, ignoreCase = true) + } } + settleNotifications(removed, IllegalStateException("Notification cancelled")) } override fun getSubscribedClients( @@ -648,10 +754,8 @@ class UniversalBlePeripheralPlugin( ) {} } } - synchronized(pendingNotifications) { - pendingNotifications.removeAll { it.device.address == deviceAddress } - notificationsInFlight.remove(deviceAddress) - } + val removed = dropNotifications { it.device.address == deviceAddress } + settleNotifications(removed, IllegalStateException("Device disconnected")) } private val advertiseCallback = object : AdvertiseCallback() { @@ -712,11 +816,7 @@ class UniversalBlePeripheralPlugin( override fun onNotificationSent(device: BluetoothDevice, status: Int) { super.onNotificationSent(device, status) - val address = device.address - synchronized(pendingNotifications) { - notificationsInFlight.remove(address) - drainNotifications(address) - } + handleNotificationSent(device, status) } override fun onCharacteristicReadRequest( @@ -892,10 +992,11 @@ class UniversalBlePeripheralPlugin( charSet.remove(subscriptionId) } } - if (!isSubscribed) synchronized(pendingNotifications) { - pendingNotifications.removeAll { + if (!isSubscribed) { + val removed = dropNotifications { it.device.address == address && it.characteristic === characteristic } + settleNotifications(removed, IllegalStateException("Central unsubscribed")) } } } diff --git a/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt index badca6b5..7e50bd1d 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt @@ -84,10 +84,19 @@ internal class PeripheralRegressionTest { plugin.setField("bluetoothDevicesMap", HashMap()) plugin.setField("mtuByDeviceId", HashMap()) plugin.setField("pendingNotifications", ArrayDeque()) - plugin.setField("notificationsInFlight", HashSet()) + plugin.setField("notificationsInFlight", HashMap()) return plugin } + /** Makes settlement (posted by the plugin) run immediately in unit tests. */ + private fun UniversalBlePeripheralPlugin.runPostedRunnablesImmediately() { + val handler = field("handler") + Mockito.`when`(handler.post(Mockito.any(Runnable::class.java))).thenAnswer { + (it.arguments[0] as Runnable).run() + true + } + } + private fun UniversalBlePeripheralPlugin.setField(name: String, value: Any?) { val field = UniversalBlePeripheralPlugin::class.java.getDeclaredField(name) field.isAccessible = true @@ -127,6 +136,40 @@ internal class PeripheralRegressionTest { return device } + /** A notify characteristic subscribed by [deviceAddress], registered as "report-1". */ + private fun UniversalBlePeripheralPlugin.subscribedNotifyCharacteristic(): + BluetoothGattCharacteristic { + val service = mockService(hid) + val characteristic = Mockito.mock(BluetoothGattCharacteristic::class.java) + Mockito.`when`(characteristic.uuid).thenReturn(UUID.fromString(report)) + Mockito.`when`(characteristic.service).thenReturn(service) + Mockito.`when`(characteristic.properties) + .thenReturn(BluetoothGattCharacteristic.PROPERTY_NOTIFY) + characteristics()[report] = characteristic + characteristics()["report-1"] = characteristic + characteristicInstanceIds()[characteristic] = "report-1" + subscribedCharDevicesMap[deviceAddress] = mutableSetOf("report-1") + connectedDevice() + return characteristic + } + + /** The pre-API-33 path the JVM tests take: the stack accepts the notification. */ + private fun BluetoothGattServer.acceptNotifications() { + Mockito.`when`( + notifyCharacteristicChanged( + Mockito.any(BluetoothDevice::class.java), + Mockito.any(BluetoothGattCharacteristic::class.java), + Mockito.anyBoolean(), + ), + ).thenReturn(true) + } + + /** Every value the plugin assigned to [characteristic], in order. */ + private fun valuesSetOn(characteristic: BluetoothGattCharacteristic): List> = + Mockito.mockingDetails(characteristic).invocations + .filter { it.method.name == "setValue" } + .map { invocation -> (invocation.arguments[0] as ByteArray).map(Byte::toInt) } + @Test fun findsServiceByItsServiceUuid() { val service = Mockito.mock(BluetoothGattService::class.java) Mockito.`when`(service.uuid).thenReturn(UUID.fromString(hid)) @@ -155,46 +198,119 @@ internal class PeripheralRegressionTest { Mockito.`when`(characteristic.properties).thenReturn(BluetoothGattCharacteristic.PROPERTY_READ) characteristics()[report] = characteristic val value = byteArrayOf(42) - plugin.updateCharacteristic(report, null, value, null) + val results = mutableListOf>() + plugin.updateCharacteristic(report, null, value, null) { results.add(it) } Mockito.verify(characteristic).setValue(value) + assertEquals(1, results.size) + assertTrue(results.single().isSuccess) } - // #403: below API 33 the payload travels in the shared characteristic value. - // A second update queued behind an in-flight notification must not overwrite - // it before that drain runs, or the wrong chunk is transmitted. + @Test fun acceptedNotificationCompletesOnlyAfterOnNotificationSent() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + plugin.subscribedNotifyCharacteristic() + server.acceptNotifications() + val results = mutableListOf>() + + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + + assertTrue(results.isEmpty(), "The callback must wait until the packet is sent") + plugin.handleNotificationSent(plugin.connectedDevice(), BluetoothGatt.GATT_SUCCESS) + assertEquals(1, results.size) + assertTrue(results.single().isSuccess) + } + + @Test fun failedNotificationSentFailsTheCallback() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + plugin.subscribedNotifyCharacteristic() + server.acceptNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + + plugin.handleNotificationSent(plugin.connectedDevice(), BluetoothGatt.GATT_FAILURE) + + assertEquals(1, results.size) + assertTrue(results.single().isFailure) + } + + // #403: a queued update must not overwrite the value the stack is sending + // for the packet already in flight. @Test fun queuedUpdateDoesNotOverwriteInFlightCharacteristicValue() { val server = Mockito.mock(BluetoothGattServer::class.java) - val plugin = peripheralPlugin(server) - val characteristic = mockCharacteristic(report, mockService(hid)) - Mockito.`when`(characteristic.properties).thenReturn(BluetoothGattCharacteristic.PROPERTY_NOTIFY) - characteristics()[report] = characteristic - val device = plugin.connectedDevice() - subscribedCharDevicesMap[deviceAddress] = mutableSetOf(report) - @Suppress("DEPRECATION") - Mockito.`when`(server.notifyCharacteristicChanged(device, characteristic, false)).thenReturn(true) - - val first = byteArrayOf(1, 2, 3) - val second = byteArrayOf(4, 5, 6) - plugin.updateCharacteristic(report, null, first, deviceAddress) - // The first notification is in flight now. Queueing the second must leave - // characteristic.value alone until the native queue accepts it. - plugin.updateCharacteristic(report, null, second, deviceAddress) - - Mockito.verify(characteristic, Mockito.times(1)).setValue(first) - Mockito.verify(characteristic, Mockito.never()).setValue(second) - - // What onNotificationSent does: release the marker, then drain the queue. - plugin.field>("notificationsInFlight").remove(deviceAddress) - val drain = UniversalBlePeripheralPlugin::class.java - .getDeclaredMethod("drainNotifications", String::class.java) - drain.isAccessible = true - drain.invoke(plugin, deviceAddress) - - // setValue is the same mock invocation as characteristic.value = second. - Mockito.verify(characteristic, Mockito.times(1)).setValue(first) - Mockito.verify(characteristic, Mockito.times(1)).setValue(second) - @Suppress("DEPRECATION") - Mockito.verify(server, Mockito.times(2)).notifyCharacteristicChanged(device, characteristic, false) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + val characteristic = plugin.subscribedNotifyCharacteristic() + server.acceptNotifications() + val results = mutableListOf>() + + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + assertEquals(listOf(listOf(1)), valuesSetOn(characteristic)) + + plugin.updateCharacteristic(report, "report-1", byteArrayOf(2), deviceAddress) { + results.add(it) + } + assertEquals( + listOf(listOf(1)), + valuesSetOn(characteristic), + ) + assertTrue(results.isEmpty(), "The second packet waits for the first to be sent") + + plugin.handleNotificationSent(plugin.connectedDevice(), BluetoothGatt.GATT_SUCCESS) + assertEquals( + listOf(listOf(1), listOf(2)), + valuesSetOn(characteristic), + ) + assertEquals(1, results.size) + assertTrue(results.single().isSuccess) + + plugin.handleNotificationSent(plugin.connectedDevice(), BluetoothGatt.GATT_SUCCESS) + assertEquals(2, results.size) + assertTrue(results[1].isSuccess) + } + + @Test fun clearPendingNotificationsFailsQueuedUpdatesButKeepsTheOneInFlight() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + plugin.subscribedNotifyCharacteristic() + server.acceptNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + plugin.updateCharacteristic(report, "report-1", byteArrayOf(2), deviceAddress) { + results.add(it) + } + + plugin.clearPendingNotifications(deviceAddress) + + assertEquals(1, results.size, "Only the queued update is cancelled") + assertTrue(results.single().isFailure) + plugin.handleNotificationSent(plugin.connectedDevice(), BluetoothGatt.GATT_SUCCESS) + assertEquals(2, results.size) + assertTrue(results[1].isSuccess, "The in-flight packet is still settled by its callback") + } + + @Test fun resetFailsTheNotificationInFlight() { + val server = Mockito.mock(BluetoothGattServer::class.java) + val plugin = peripheralPlugin(server).also { it.runPostedRunnablesImmediately() } + plugin.subscribedNotifyCharacteristic() + server.acceptNotifications() + val results = mutableListOf>() + plugin.updateCharacteristic(report, "report-1", byteArrayOf(1), deviceAddress) { + results.add(it) + } + + plugin.onAdapterStateChanged(BluetoothAdapter.STATE_TURNING_OFF) + + assertEquals(1, results.size) + assertTrue(results.single().isFailure) + assertTrue(plugin.field>("notificationsInFlight").isEmpty()) } // #385: a service registered a second time must resolve to the new diff --git a/darwin/test/peripheral_reliability_test.swift b/darwin/test/peripheral_reliability_test.swift index 7669ea93..da90b34a 100644 --- a/darwin/test/peripheral_reliability_test.swift +++ b/darwin/test/peripheral_reliability_test.swift @@ -46,29 +46,55 @@ struct PeripheralReliabilityTests { } var queue = PeripheralNotificationQueue() var delivered = [Int]() + var settled = [Int]() queue.append(1) - queue.drain { _ in false } + queue.drain({ _ in false }, onSent: { settled.append($0) }) queue.append(2) - queue.drain { + queue.drain({ delivered.append($0) return true - } + }, onSent: { settled.append($0) }) precondition(delivered.isEmpty, "New release must not bypass blocked press") + precondition(settled.isEmpty, "A blocked element is not settled until it is sent") + precondition(queue.pending.count == 2, "A refused element stays queued") queue.resume() - queue.drain { + queue.drain({ delivered.append($0) return true - } + }, onSent: { settled.append($0) }) precondition(delivered == [1, 2]) + precondition(settled == [1, 2], "Each accepted element is reported exactly once") queue.append(3) queue.drain { _ in false } - queue.removeAll { $0 == 3 } + let dropped = queue.removeAll { $0 == 3 } + precondition(dropped == [3], "removeAll(where:) must return what it discarded") queue.append(4) - queue.drain { + queue.drain({ delivered.append($0) return true - } + }, onSent: { settled.append($0) }) precondition(delivered == [1, 2, 4], "Old session input must be discarded") + precondition(settled == [1, 2, 4], "A discarded element is never reported as sent") + + var cleared = PeripheralNotificationQueue() + cleared.append(7) + cleared.append(8) + let removedAll = cleared.removeAll() + precondition(removedAll == [7, 8], "removeAll must return what it discarded") + precondition(cleared.isEmpty && cleared.pending.isEmpty) + cleared.append(9) + cleared.drain({ $0 == 9 }, onSent: { settled.append($0) }) + precondition(settled == [1, 2, 4, 9], "The queue must be reusable after removal") + + var headIndexed = PeripheralNotificationQueue() + for value in 0..<200 { headIndexed.append(value) } + var drained = [Int]() + headIndexed.drain({ + drained.append($0) + return true + }) + precondition(drained == Array(0..<200) && headIndexed.isEmpty) + precondition(headIndexed.pending.isEmpty) var reports = PeripheralNotificationQueue<(central: Int, characteristic: Int)>() reports.append((1, 1)) diff --git a/darwin/universal_ble/Sources/universal_ble/PeripheralNotificationQueue.swift b/darwin/universal_ble/Sources/universal_ble/PeripheralNotificationQueue.swift index 937fdf69..3d17d6ca 100644 --- a/darwin/universal_ble/Sources/universal_ble/PeripheralNotificationQueue.swift +++ b/darwin/universal_ble/Sources/universal_ble/PeripheralNotificationQueue.swift @@ -1,28 +1,79 @@ import Foundation -/// Main-queue FIFO. Backpressure blocks all newer reports until the delegate resumes it. +/// Main-queue O(1) FIFO. Backpressure blocks all newer notifications until the +/// delegate resumes it. +/// +/// The queue keeps a read head index instead of removing the first element on +/// every drain: `Array.removeFirst()` shifts the whole tail, so draining a bulk +/// transfer one chunk at a time was O(N²). Elements are compacted away in +/// batches, and the storage is released once the queue is drained. struct PeripheralNotificationQueue { - private(set) var pending = [Element]() + private var storage = [Element]() + private var head = 0 private var blocked = false - mutating func append(_ element: Element) { pending.append(element) } + var pending: ArraySlice { storage[head...] } + var isEmpty: Bool { head >= storage.count } + + mutating func append(_ element: Element) { storage.append(element) } mutating func resume() { blocked = false } - mutating func removeAll() { - pending.removeAll() + + /// Discards every pending element and returns them, so their callers can be + /// failed instead of waiting forever. + @discardableResult + mutating func removeAll() -> [Element] { + let removed = Array(storage[head...]) + storage.removeAll(keepingCapacity: false) + head = 0 blocked = false + return removed } - mutating func removeAll(where predicate: (Element) -> Bool) { - pending.removeAll(where: predicate) - if pending.isEmpty { blocked = false } + + /// Discards the pending elements matching [predicate] and returns them. + @discardableResult + mutating func removeAll(where predicate: (Element) -> Bool) -> [Element] { + var removed = [Element]() + var kept = [Element]() + kept.reserveCapacity(storage.count - head) + for index in head.. Bool) { + + /// Sends pending elements in FIFO order until [send] refuses one. Each + /// accepted element is reported exactly once through [onSent]; a refused one + /// stays queued and blocks the queue until [resume]. + mutating func drain(_ send: (Element) -> Bool, onSent: (Element) -> Void = { _ in }) { guard !blocked else { return } - while let first = pending.first { + while head < storage.count { + let first = storage[head] guard send(first) else { blocked = true + compactIfNeeded() return } - pending.removeFirst() + head += 1 + onSent(first) + } + compactIfNeeded() + } + + private mutating func compactIfNeeded() { + if head >= storage.count { + storage.removeAll(keepingCapacity: false) + head = 0 + } else if head >= 64 && head * 2 >= storage.count { + storage.removeFirst(head) + head = 0 } } } diff --git a/darwin/universal_ble/Sources/universal_ble/UniversalBle.g.swift b/darwin/universal_ble/Sources/universal_ble/UniversalBle.g.swift index b7a78ed9..47d29547 100644 --- a/darwin/universal_ble/Sources/universal_ble/UniversalBle.g.swift +++ b/darwin/universal_ble/Sources/universal_ble/UniversalBle.g.swift @@ -309,6 +309,17 @@ enum PeripheralAdvertisingState: Int, CaseIterable { case error = 4 } +/// Desired connection latency for a subscribed central on Apple platforms. +/// +/// Maps to CoreBluetooth `CBPeripheralManagerConnectionLatency`. A lower +/// latency trades radio time for responsiveness; Apple negotiates a higher +/// latency (and therefore lower throughput) when nothing asks for otherwise. +enum PeripheralConnectionLatency: Int, CaseIterable { + case low = 0 + case medium = 1 + case high = 2 +} + /// Unified error codes for all platforms enum UniversalBleErrorCode: Int, CaseIterable { case unknownError = 0 @@ -1772,60 +1783,66 @@ private class UniversalBlePigeonCodecReader: FlutterStandardReader { case 143: let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) if let enumResultAsInt = enumResultAsInt { - return UniversalBleErrorCode(rawValue: enumResultAsInt) + return PeripheralConnectionLatency(rawValue: enumResultAsInt) } return nil case 144: - return UniversalBleScanResult.fromList(self.readValue() as! [Any?]) + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return UniversalBleErrorCode(rawValue: enumResultAsInt) + } + return nil case 145: - return UniversalDevicePickerResult.fromList(self.readValue() as! [Any?]) + return UniversalBleScanResult.fromList(self.readValue() as! [Any?]) case 146: - return UniversalBleService.fromList(self.readValue() as! [Any?]) + return UniversalDevicePickerResult.fromList(self.readValue() as! [Any?]) case 147: - return UniversalBleCharacteristic.fromList(self.readValue() as! [Any?]) + return UniversalBleService.fromList(self.readValue() as! [Any?]) case 148: - return UniversalBleDescriptor.fromList(self.readValue() as! [Any?]) + return UniversalBleCharacteristic.fromList(self.readValue() as! [Any?]) case 149: - return BleConnectionParametersChange.fromList(self.readValue() as! [Any?]) + return UniversalBleDescriptor.fromList(self.readValue() as! [Any?]) case 150: - return AndroidOptions.fromList(self.readValue() as! [Any?]) + return BleConnectionParametersChange.fromList(self.readValue() as! [Any?]) case 151: - return UniversalScanConfig.fromList(self.readValue() as! [Any?]) + return AndroidOptions.fromList(self.readValue() as! [Any?]) case 152: - return UniversalScanFilter.fromList(self.readValue() as! [Any?]) + return UniversalScanConfig.fromList(self.readValue() as! [Any?]) case 153: - return ManufacturerDataFilter.fromList(self.readValue() as! [Any?]) + return UniversalScanFilter.fromList(self.readValue() as! [Any?]) case 154: - return UniversalManufacturerData.fromList(self.readValue() as! [Any?]) + return ManufacturerDataFilter.fromList(self.readValue() as! [Any?]) case 155: - return AppleConnectionOptions.fromList(self.readValue() as! [Any?]) + return UniversalManufacturerData.fromList(self.readValue() as! [Any?]) case 156: - return AppleAccessoryPickerItem.fromList(self.readValue() as! [Any?]) + return AppleConnectionOptions.fromList(self.readValue() as! [Any?]) case 157: - return AppleAccessorySetupOptions.fromList(self.readValue() as! [Any?]) + return AppleAccessoryPickerItem.fromList(self.readValue() as! [Any?]) case 158: - return AndroidConnectionOptions.fromList(self.readValue() as! [Any?]) + return AppleAccessorySetupOptions.fromList(self.readValue() as! [Any?]) case 159: - return ConnectionPlatformConfig.fromList(self.readValue() as! [Any?]) + return AndroidConnectionOptions.fromList(self.readValue() as! [Any?]) case 160: - return AndroidDiscoverServicesOptions.fromList(self.readValue() as! [Any?]) + return ConnectionPlatformConfig.fromList(self.readValue() as! [Any?]) case 161: - return AppleDiscoverServicesOptions.fromList(self.readValue() as! [Any?]) + return AndroidDiscoverServicesOptions.fromList(self.readValue() as! [Any?]) case 162: - return DiscoverServicesPlatformConfig.fromList(self.readValue() as! [Any?]) + return AppleDiscoverServicesOptions.fromList(self.readValue() as! [Any?]) case 163: - return PeripheralAndroidOptions.fromList(self.readValue() as! [Any?]) + return DiscoverServicesPlatformConfig.fromList(self.readValue() as! [Any?]) case 164: - return PeripheralPlatformConfig.fromList(self.readValue() as! [Any?]) + return PeripheralAndroidOptions.fromList(self.readValue() as! [Any?]) case 165: - return PeripheralService.fromList(self.readValue() as! [Any?]) + return PeripheralPlatformConfig.fromList(self.readValue() as! [Any?]) case 166: - return PeripheralCharacteristic.fromList(self.readValue() as! [Any?]) + return PeripheralService.fromList(self.readValue() as! [Any?]) case 167: - return PeripheralDescriptor.fromList(self.readValue() as! [Any?]) + return PeripheralCharacteristic.fromList(self.readValue() as! [Any?]) case 168: - return PeripheralReadRequestResult.fromList(self.readValue() as! [Any?]) + return PeripheralDescriptor.fromList(self.readValue() as! [Any?]) case 169: + return PeripheralReadRequestResult.fromList(self.readValue() as! [Any?]) + case 170: return PeripheralWriteRequestResult.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) @@ -1877,86 +1894,89 @@ private class UniversalBlePigeonCodecWriter: FlutterStandardWriter { } else if let value = value as? PeripheralAdvertisingState { super.writeByte(142) super.writeValue(value.rawValue) - } else if let value = value as? UniversalBleErrorCode { + } else if let value = value as? PeripheralConnectionLatency { super.writeByte(143) super.writeValue(value.rawValue) - } else if let value = value as? UniversalBleScanResult { + } else if let value = value as? UniversalBleErrorCode { super.writeByte(144) + super.writeValue(value.rawValue) + } else if let value = value as? UniversalBleScanResult { + super.writeByte(145) super.writeValue(value.toList()) } else if let value = value as? UniversalDevicePickerResult { - super.writeByte(145) + super.writeByte(146) super.writeValue(value.toList()) } else if let value = value as? UniversalBleService { - super.writeByte(146) + super.writeByte(147) super.writeValue(value.toList()) } else if let value = value as? UniversalBleCharacteristic { - super.writeByte(147) + super.writeByte(148) super.writeValue(value.toList()) } else if let value = value as? UniversalBleDescriptor { - super.writeByte(148) + super.writeByte(149) super.writeValue(value.toList()) } else if let value = value as? BleConnectionParametersChange { - super.writeByte(149) + super.writeByte(150) super.writeValue(value.toList()) } else if let value = value as? AndroidOptions { - super.writeByte(150) + super.writeByte(151) super.writeValue(value.toList()) } else if let value = value as? UniversalScanConfig { - super.writeByte(151) + super.writeByte(152) super.writeValue(value.toList()) } else if let value = value as? UniversalScanFilter { - super.writeByte(152) + super.writeByte(153) super.writeValue(value.toList()) } else if let value = value as? ManufacturerDataFilter { - super.writeByte(153) + super.writeByte(154) super.writeValue(value.toList()) } else if let value = value as? UniversalManufacturerData { - super.writeByte(154) + super.writeByte(155) super.writeValue(value.toList()) } else if let value = value as? AppleConnectionOptions { - super.writeByte(155) + super.writeByte(156) super.writeValue(value.toList()) } else if let value = value as? AppleAccessoryPickerItem { - super.writeByte(156) + super.writeByte(157) super.writeValue(value.toList()) } else if let value = value as? AppleAccessorySetupOptions { - super.writeByte(157) + super.writeByte(158) super.writeValue(value.toList()) } else if let value = value as? AndroidConnectionOptions { - super.writeByte(158) + super.writeByte(159) super.writeValue(value.toList()) } else if let value = value as? ConnectionPlatformConfig { - super.writeByte(159) + super.writeByte(160) super.writeValue(value.toList()) } else if let value = value as? AndroidDiscoverServicesOptions { - super.writeByte(160) + super.writeByte(161) super.writeValue(value.toList()) } else if let value = value as? AppleDiscoverServicesOptions { - super.writeByte(161) + super.writeByte(162) super.writeValue(value.toList()) } else if let value = value as? DiscoverServicesPlatformConfig { - super.writeByte(162) + super.writeByte(163) super.writeValue(value.toList()) } else if let value = value as? PeripheralAndroidOptions { - super.writeByte(163) + super.writeByte(164) super.writeValue(value.toList()) } else if let value = value as? PeripheralPlatformConfig { - super.writeByte(164) + super.writeByte(165) super.writeValue(value.toList()) } else if let value = value as? PeripheralService { - super.writeByte(165) + super.writeByte(166) super.writeValue(value.toList()) } else if let value = value as? PeripheralCharacteristic { - super.writeByte(166) + super.writeByte(167) super.writeValue(value.toList()) } else if let value = value as? PeripheralDescriptor { - super.writeByte(167) + super.writeByte(168) super.writeValue(value.toList()) } else if let value = value as? PeripheralReadRequestResult { - super.writeByte(168) + super.writeByte(169) super.writeValue(value.toList()) } else if let value = value as? PeripheralWriteRequestResult { - super.writeByte(169) + super.writeByte(170) super.writeValue(value.toList()) } else { super.writeValue(value) @@ -2640,7 +2660,14 @@ protocol UniversalBlePeripheralChannel { func clearServices() throws func getServices() throws -> [String] func startAdvertising(services: [String], localName: String?, timeout: Int64?, manufacturerData: UniversalManufacturerData?, platformConfig: PeripheralPlatformConfig?) throws - func updateCharacteristic(characteristicId: String, characteristicInstanceId: String?, value: FlutterStandardTypedData, deviceId: String?) throws + /// Sends [value] to the clients subscribed to [characteristicId]. + /// + /// The reply is sent once every targeted client's notification is settled: + /// accepted by the platform queue (Apple, when `updateValue` returns `true`), + /// sent (`onNotificationSent` on Android) or completed (`NotifyValueAsync` on + /// Windows). A failure is reported once all of them have settled and at least + /// one failed. + func updateCharacteristic(characteristicId: String, characteristicInstanceId: String?, value: FlutterStandardTypedData, deviceId: String?, completion: @escaping (Result) -> Void) /// Returns peripheral-client device ids currently subscribed to the /// characteristic identified by [characteristicId] (and, when supplied, /// [characteristicInstanceId]). @@ -2778,6 +2805,13 @@ class UniversalBlePeripheralChannelSetup { } else { startAdvertisingChannel.setMessageHandler(nil) } + /// Sends [value] to the clients subscribed to [characteristicId]. + /// + /// The reply is sent once every targeted client's notification is settled: + /// accepted by the platform queue (Apple, when `updateValue` returns `true`), + /// sent (`onNotificationSent` on Android) or completed (`NotifyValueAsync` on + /// Windows). A failure is reported once all of them have settled and at least + /// one failed. let updateCharacteristicChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.universal_ble.UniversalBlePeripheralChannel.updateCharacteristic\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) if let api = api { updateCharacteristicChannel.setMessageHandler { message, reply in @@ -2786,11 +2820,13 @@ class UniversalBlePeripheralChannelSetup { let characteristicInstanceIdArg: String? = nilOrValue(args[1]) let valueArg = args[2] as! FlutterStandardTypedData let deviceIdArg: String? = nilOrValue(args[3]) - do { - try api.updateCharacteristic(characteristicId: characteristicIdArg, characteristicInstanceId: characteristicInstanceIdArg, value: valueArg, deviceId: deviceIdArg) - reply(wrapResult(nil)) - } catch { - reply(wrapError(error)) + api.updateCharacteristic(characteristicId: characteristicIdArg, characteristicInstanceId: characteristicInstanceIdArg, value: valueArg, deviceId: deviceIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } } } } else { @@ -2870,11 +2906,13 @@ class UniversalBlePeripheralChannelSetup { } } } -/// Flutter -> Native (Apple peripheral restoration only). +/// Flutter -> Native (Apple peripheral-only APIs). /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UniversalBleDarwinPeripheralChannel { func configureRestoration(restorationIdentifier: String) throws + /// Sets the connection latency CoreBluetooth negotiates with [deviceId]. + func setDesiredConnectionLatency(deviceId: String, latency: PeripheralConnectionLatency) throws } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -2898,6 +2936,23 @@ class UniversalBleDarwinPeripheralChannelSetup { } else { configureRestorationChannel.setMessageHandler(nil) } + /// Sets the connection latency CoreBluetooth negotiates with [deviceId]. + let setDesiredConnectionLatencyChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.universal_ble.UniversalBleDarwinPeripheralChannel.setDesiredConnectionLatency\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setDesiredConnectionLatencyChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let deviceIdArg = args[0] as! String + let latencyArg = args[1] as! PeripheralConnectionLatency + do { + try api.setDesiredConnectionLatency(deviceId: deviceIdArg, latency: latencyArg) + reply(wrapResult(nil)) + } catch { + reply(wrapError(error)) + } + } + } else { + setDesiredConnectionLatencyChannel.setMessageHandler(nil) + } } } /// Flutter -> Native (Android only) diff --git a/darwin/universal_ble/Sources/universal_ble/UniversalBlePeripheralPlugin.swift b/darwin/universal_ble/Sources/universal_ble/UniversalBlePeripheralPlugin.swift index eb86363b..c19d2bb4 100644 --- a/darwin/universal_ble/Sources/universal_ble/UniversalBlePeripheralPlugin.swift +++ b/darwin/universal_ble/Sources/universal_ble/UniversalBlePeripheralPlugin.swift @@ -39,6 +39,22 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne let value: Data let characteristic: CBMutableCharacteristic let central: CBCentral + /// Called exactly once: `nil` when CoreBluetooth accepted the value, or the + /// error that made the notification unsendable. + let onSettled: (Error?) -> Void + } + + /// Fails the notifications a path discards, so the Dart calls that enqueued + /// them do not wait for a settlement that can never arrive. + private func cancelNotifications( + _ notifications: [PendingNotification], + message: String = "Notification cancelled" + ) { + guard !notifications.isEmpty else { return } + let error = UniversalBlePeripheralError.failed(message) + for notification in notifications { + notification.onSettled(error) + } } init(callbackChannel: UniversalBlePeripheralCallback) { @@ -87,6 +103,7 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne } deinit { + cancelNotifications(pendingNotifications.removeAll()) peripheralManager?.stopAdvertising() peripheralManager?.removeAllServices() clearCentrals() @@ -237,7 +254,7 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne } } pendingServices.removeAll() - pendingNotifications.removeAll() + cancelNotifications(pendingNotifications.removeAll(), message: "Services cleared") serviceRegistry.clear() serviceModels.removeAll() initialValues.removeAll() @@ -252,11 +269,12 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne func clearPendingNotifications(deviceId: String?) throws { if let deviceId { - pendingNotifications.removeAll { + let removed = pendingNotifications.removeAll { $0.central.identifier.uuidString.caseInsensitiveCompare(deviceId) == .orderedSame } + cancelNotifications(removed) } else { - pendingNotifications.removeAll() + cancelNotifications(pendingNotifications.removeAll()) } } @@ -310,21 +328,26 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne characteristicId: String, characteristicInstanceId: String?, value: FlutterStandardTypedData, - deviceId: String? - ) throws { + deviceId: String?, + completion: @escaping (Result) -> Void + ) { guard let characteristic = serviceRegistry.characteristic( characteristicId, instanceId: characteristicInstanceId ) else { - throw UniversalBlePeripheralError.notFound("\(characteristicId) characteristic not found") + completion( + .failure( + UniversalBlePeripheralError.notFound("\(characteristicId) characteristic not found"))) + return } let targets = characteristic.subscribedCentrals ?? [] let centrals: [CBCentral] if let deviceId { guard central(for: deviceId) != nil else { - throw UniversalBlePeripheralError.notFound("\(deviceId) device not found") + completion(.failure(UniversalBlePeripheralError.notFound("\(deviceId) device not found"))) + return } centrals = targets.filter { $0.identifier.uuidString.caseInsensitiveCompare(deviceId) == .orderedSame @@ -333,23 +356,60 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne centrals = targets } let data = value.toData() + // Kept so a read returns the last value. One assignment per update; it is + // not copied per chunk and is not what made the queue O(N²). initialValues[ObjectIdentifier(characteristic)] = data + // Nothing to notify: a static/readable value update is already complete. + guard !centrals.isEmpty else { + completion(.success(())) + return + } + // Complete once every targeted central has settled, with the first error. + // Everything runs on the main queue, so the shared counters need no lock; + // `settled` keeps a late double settlement from completing twice. + var remaining = centrals.count + var firstError: Error? + var settled = false + let settleOne: (Error?) -> Void = { error in + guard !settled else { return } + if firstError == nil, let error { + firstError = error + } + remaining -= 1 + guard remaining <= 0 else { return } + settled = true + if let firstError { + completion(.failure(firstError)) + } else { + completion(.success(())) + } + } // Capture actual subscribers now. A future subscriber must never receive // a broadcast queued during a previous session. for central in centrals { pendingNotifications.append( - PendingNotification(value: data, characteristic: characteristic, central: central)) + PendingNotification( + value: data, + characteristic: characteristic, + central: central, + onSettled: settleOne)) } drainPendingNotifications() } private func drainPendingNotifications() { - pendingNotifications.drain { notification in - guard let manager = peripheralManager, manager.state == .poweredOn else { return false } - return manager.updateValue( - notification.value, for: notification.characteristic, - onSubscribedCentrals: [notification.central]) - } + pendingNotifications.drain( + { notification in + guard let manager = peripheralManager, manager.state == .poweredOn else { return false } + return manager.updateValue( + notification.value, for: notification.characteristic, + onSubscribedCentrals: [notification.central]) + }, + onSent: { notification in + // `updateValue` returned true: CoreBluetooth owns the data now. The + // remote device acknowledging it is a link-layer concern. + notification.onSettled(nil) + }) } nonisolated func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) { @@ -377,7 +437,9 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne if peripheral.state == .unknown && !hasBeenPoweredOn { return } requestGeneration += 1 for service in serviceRegistry.allServices { invalidateSubscriptions(of: service) } - pendingNotifications.removeAll() + cancelNotifications( + pendingNotifications.removeAll(), + message: "Bluetooth peripheral became unavailable") clearCentrals() // Fail outstanding adds, so their Dart futures cannot outlive the adapter. let pending = pendingServices.values.map { $0.1.uuid } @@ -461,7 +523,7 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne _ peripheral: CBPeripheralManager, willRestoreState dict: [String: Any] ) { peripheralManager = peripheral - pendingNotifications.removeAll() + cancelNotifications(pendingNotifications.removeAll()) serviceRegistry.clear() clearCentrals() let saved = savedIdentities() @@ -514,7 +576,8 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne private func invalidateSubscriptions(of service: CBMutableService) { for characteristic in service.characteristics ?? [] { - pendingNotifications.removeAll { $0.characteristic === characteristic } + let removed = pendingNotifications.removeAll { $0.characteristic === characteristic } + cancelNotifications(removed, message: "Service removed") initialValues.removeValue(forKey: ObjectIdentifier(characteristic)) let subscriptionId = serviceRegistry.instanceId(of: characteristic) ?? characteristic.uuid.uuidString @@ -576,9 +639,10 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne centralId: central.identifier.uuidString, subscriptionId: instanceId ?? characteristic.uuid.uuidString ) - pendingNotifications.removeAll { + let removed = pendingNotifications.removeAll { $0.central.identifier == central.identifier && $0.characteristic === characteristic } + cancelNotifications(removed, message: "Central unsubscribed") initialValues.removeValue(forKey: ObjectIdentifier(characteristic)) subscriptionEvent(central, characteristic, subscribed: false) } @@ -771,6 +835,25 @@ final class UniversalBlePeripheralPlugin: NSObject, UniversalBlePeripheralChanne func setAutoConnect(autoConnect: Bool) throws { // Android-only option; no-op on Darwin. } + + func setDesiredConnectionLatency( + deviceId: String, + latency: PeripheralConnectionLatency + ) throws { + guard let central = central(for: deviceId) else { + throw UniversalBlePeripheralError.notFound("\(deviceId) device not found") + } + let cbLatency: CBPeripheralManagerConnectionLatency + switch latency { + case .low: + cbLatency = .low + case .medium: + cbLatency = .medium + case .high: + cbLatency = .high + } + ensurePeripheralManager().setDesiredConnectionLatency(cbLatency, for: central) + } } /// Services this peripheral advertises, and the characteristics they expose. diff --git a/lib/src/interfaces/universal_ble_peripheral_platform_interface.dart b/lib/src/interfaces/universal_ble_peripheral_platform_interface.dart index 857ca603..2c27e7f4 100644 --- a/lib/src/interfaces/universal_ble_peripheral_platform_interface.dart +++ b/lib/src/interfaces/universal_ble_peripheral_platform_interface.dart @@ -111,6 +111,15 @@ abstract class UniversalBlePeripheralPlatform { /// Supported on Android; no-op elsewhere. Future setAutoConnect(bool autoConnect) async {} + /// Sets the connection latency CoreBluetooth negotiates with a subscribed + /// central (`CBPeripheralManager.setDesiredConnectionLatency(_:for:)`). + /// + /// Supported on iOS and macOS; no-op elsewhere. + Future setDesiredConnectionLatency( + String deviceId, + PeripheralConnectionLatency latency, + ) async {} + /// Whether this platform identifies GATT clients by a Bluetooth *address* — a MAC on /// Android/Windows/Linux, a UUID on Apple — which is case-insensitive. Central ids are /// therefore canonicalised on ingestion, so every stream event, request handler and diff --git a/lib/src/universal_ble.g.dart b/lib/src/universal_ble.g.dart index 858850f3..5319adb1 100644 --- a/lib/src/universal_ble.g.dart +++ b/lib/src/universal_ble.g.dart @@ -230,6 +230,17 @@ enum PeripheralAdvertisingState { error; } +/// Desired connection latency for a subscribed central on Apple platforms. +/// +/// Maps to CoreBluetooth `CBPeripheralManagerConnectionLatency`. A lower +/// latency trades radio time for responsiveness; Apple negotiates a higher +/// latency (and therefore lower throughput) when nothing asks for otherwise. +enum PeripheralConnectionLatency { + low, + medium, + high; +} + /// Unified error codes for all platforms enum UniversalBleErrorCode { unknownError, @@ -2009,86 +2020,89 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is PeripheralAdvertisingState) { buffer.putUint8(142); writeValue(buffer, value.index); - } else if (value is UniversalBleErrorCode) { + } else if (value is PeripheralConnectionLatency) { buffer.putUint8(143); writeValue(buffer, value.index); - } else if (value is UniversalBleScanResult) { + } else if (value is UniversalBleErrorCode) { buffer.putUint8(144); + writeValue(buffer, value.index); + } else if (value is UniversalBleScanResult) { + buffer.putUint8(145); writeValue(buffer, value.encode()); } else if (value is UniversalDevicePickerResult) { - buffer.putUint8(145); + buffer.putUint8(146); writeValue(buffer, value.encode()); } else if (value is UniversalBleService) { - buffer.putUint8(146); + buffer.putUint8(147); writeValue(buffer, value.encode()); } else if (value is UniversalBleCharacteristic) { - buffer.putUint8(147); + buffer.putUint8(148); writeValue(buffer, value.encode()); } else if (value is UniversalBleDescriptor) { - buffer.putUint8(148); + buffer.putUint8(149); writeValue(buffer, value.encode()); } else if (value is BleConnectionParametersChange) { - buffer.putUint8(149); + buffer.putUint8(150); writeValue(buffer, value.encode()); } else if (value is AndroidOptions) { - buffer.putUint8(150); + buffer.putUint8(151); writeValue(buffer, value.encode()); } else if (value is UniversalScanConfig) { - buffer.putUint8(151); + buffer.putUint8(152); writeValue(buffer, value.encode()); } else if (value is UniversalScanFilter) { - buffer.putUint8(152); + buffer.putUint8(153); writeValue(buffer, value.encode()); } else if (value is ManufacturerDataFilter) { - buffer.putUint8(153); + buffer.putUint8(154); writeValue(buffer, value.encode()); } else if (value is UniversalManufacturerData) { - buffer.putUint8(154); + buffer.putUint8(155); writeValue(buffer, value.encode()); } else if (value is AppleConnectionOptions) { - buffer.putUint8(155); + buffer.putUint8(156); writeValue(buffer, value.encode()); } else if (value is AppleAccessoryPickerItem) { - buffer.putUint8(156); + buffer.putUint8(157); writeValue(buffer, value.encode()); } else if (value is AppleAccessorySetupOptions) { - buffer.putUint8(157); + buffer.putUint8(158); writeValue(buffer, value.encode()); } else if (value is AndroidConnectionOptions) { - buffer.putUint8(158); + buffer.putUint8(159); writeValue(buffer, value.encode()); } else if (value is ConnectionPlatformConfig) { - buffer.putUint8(159); + buffer.putUint8(160); writeValue(buffer, value.encode()); } else if (value is AndroidDiscoverServicesOptions) { - buffer.putUint8(160); + buffer.putUint8(161); writeValue(buffer, value.encode()); } else if (value is AppleDiscoverServicesOptions) { - buffer.putUint8(161); + buffer.putUint8(162); writeValue(buffer, value.encode()); } else if (value is DiscoverServicesPlatformConfig) { - buffer.putUint8(162); + buffer.putUint8(163); writeValue(buffer, value.encode()); } else if (value is PeripheralAndroidOptions) { - buffer.putUint8(163); + buffer.putUint8(164); writeValue(buffer, value.encode()); } else if (value is PeripheralPlatformConfig) { - buffer.putUint8(164); + buffer.putUint8(165); writeValue(buffer, value.encode()); } else if (value is PeripheralService) { - buffer.putUint8(165); + buffer.putUint8(166); writeValue(buffer, value.encode()); } else if (value is PeripheralCharacteristic) { - buffer.putUint8(166); + buffer.putUint8(167); writeValue(buffer, value.encode()); } else if (value is PeripheralDescriptor) { - buffer.putUint8(167); + buffer.putUint8(168); writeValue(buffer, value.encode()); } else if (value is PeripheralReadRequestResult) { - buffer.putUint8(168); + buffer.putUint8(169); writeValue(buffer, value.encode()); } else if (value is PeripheralWriteRequestResult) { - buffer.putUint8(169); + buffer.putUint8(170); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); @@ -2144,58 +2158,61 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : PeripheralAdvertisingState.values[value]; case 143: final value = readValue(buffer) as int?; - return value == null ? null : UniversalBleErrorCode.values[value]; + return value == null ? null : PeripheralConnectionLatency.values[value]; case 144: - return UniversalBleScanResult.decode(readValue(buffer)!); + final value = readValue(buffer) as int?; + return value == null ? null : UniversalBleErrorCode.values[value]; case 145: - return UniversalDevicePickerResult.decode(readValue(buffer)!); + return UniversalBleScanResult.decode(readValue(buffer)!); case 146: - return UniversalBleService.decode(readValue(buffer)!); + return UniversalDevicePickerResult.decode(readValue(buffer)!); case 147: - return UniversalBleCharacteristic.decode(readValue(buffer)!); + return UniversalBleService.decode(readValue(buffer)!); case 148: - return UniversalBleDescriptor.decode(readValue(buffer)!); + return UniversalBleCharacteristic.decode(readValue(buffer)!); case 149: - return BleConnectionParametersChange.decode(readValue(buffer)!); + return UniversalBleDescriptor.decode(readValue(buffer)!); case 150: - return AndroidOptions.decode(readValue(buffer)!); + return BleConnectionParametersChange.decode(readValue(buffer)!); case 151: - return UniversalScanConfig.decode(readValue(buffer)!); + return AndroidOptions.decode(readValue(buffer)!); case 152: - return UniversalScanFilter.decode(readValue(buffer)!); + return UniversalScanConfig.decode(readValue(buffer)!); case 153: - return ManufacturerDataFilter.decode(readValue(buffer)!); + return UniversalScanFilter.decode(readValue(buffer)!); case 154: - return UniversalManufacturerData.decode(readValue(buffer)!); + return ManufacturerDataFilter.decode(readValue(buffer)!); case 155: - return AppleConnectionOptions.decode(readValue(buffer)!); + return UniversalManufacturerData.decode(readValue(buffer)!); case 156: - return AppleAccessoryPickerItem.decode(readValue(buffer)!); + return AppleConnectionOptions.decode(readValue(buffer)!); case 157: - return AppleAccessorySetupOptions.decode(readValue(buffer)!); + return AppleAccessoryPickerItem.decode(readValue(buffer)!); case 158: - return AndroidConnectionOptions.decode(readValue(buffer)!); + return AppleAccessorySetupOptions.decode(readValue(buffer)!); case 159: - return ConnectionPlatformConfig.decode(readValue(buffer)!); + return AndroidConnectionOptions.decode(readValue(buffer)!); case 160: - return AndroidDiscoverServicesOptions.decode(readValue(buffer)!); + return ConnectionPlatformConfig.decode(readValue(buffer)!); case 161: - return AppleDiscoverServicesOptions.decode(readValue(buffer)!); + return AndroidDiscoverServicesOptions.decode(readValue(buffer)!); case 162: - return DiscoverServicesPlatformConfig.decode(readValue(buffer)!); + return AppleDiscoverServicesOptions.decode(readValue(buffer)!); case 163: - return PeripheralAndroidOptions.decode(readValue(buffer)!); + return DiscoverServicesPlatformConfig.decode(readValue(buffer)!); case 164: - return PeripheralPlatformConfig.decode(readValue(buffer)!); + return PeripheralAndroidOptions.decode(readValue(buffer)!); case 165: - return PeripheralService.decode(readValue(buffer)!); + return PeripheralPlatformConfig.decode(readValue(buffer)!); case 166: - return PeripheralCharacteristic.decode(readValue(buffer)!); + return PeripheralService.decode(readValue(buffer)!); case 167: - return PeripheralDescriptor.decode(readValue(buffer)!); + return PeripheralCharacteristic.decode(readValue(buffer)!); case 168: - return PeripheralReadRequestResult.decode(readValue(buffer)!); + return PeripheralDescriptor.decode(readValue(buffer)!); case 169: + return PeripheralReadRequestResult.decode(readValue(buffer)!); + case 170: return PeripheralWriteRequestResult.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -3131,6 +3148,13 @@ class UniversalBlePeripheralChannel { ); } + /// Sends [value] to the clients subscribed to [characteristicId]. + /// + /// The reply is sent once every targeted client's notification is settled: + /// accepted by the platform queue (Apple, when `updateValue` returns `true`), + /// sent (`onNotificationSent` on Android) or completed (`NotifyValueAsync` on + /// Windows). A failure is reported once all of them have settled and at least + /// one failed. Future updateCharacteristic( String characteristicId, String? characteristicInstanceId, @@ -3245,7 +3269,7 @@ class UniversalBlePeripheralChannel { } } -/// Flutter -> Native (Apple peripheral restoration only). +/// Flutter -> Native (Apple peripheral-only APIs). class UniversalBleDarwinPeripheralChannel { /// Constructor for [UniversalBleDarwinPeripheralChannel]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default @@ -3280,6 +3304,27 @@ class UniversalBleDarwinPeripheralChannel { isNullValid: true, ); } + + /// Sets the connection latency CoreBluetooth negotiates with [deviceId]. + Future setDesiredConnectionLatency( + String deviceId, PeripheralConnectionLatency latency) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.universal_ble.UniversalBleDarwinPeripheralChannel.setDesiredConnectionLatency$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([deviceId, latency]); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + } } /// Flutter -> Native (Android only) diff --git a/lib/src/universal_ble_peripheral.dart b/lib/src/universal_ble_peripheral.dart index d163ad93..e994833c 100644 --- a/lib/src/universal_ble_peripheral.dart +++ b/lib/src/universal_ble_peripheral.dart @@ -232,13 +232,21 @@ class UniversalBlePeripheral { /// `getCapabilities().supportsTargetedCharacteristicUpdate`); omit it to /// notify every subscribed client. /// - /// The returned future completes once the update has been handed to the - /// platform, not once it has been transmitted. On Windows and Android a - /// transport failure is not reported through this future (Windows logs it - /// when `UniversalBle.setLogLevel` enables error output), while Apple reports - /// a full transmit queue. On Windows, [QueueType.perDevice] and - /// [QueueType.global] serialize submission only; awaiting this future does - /// not prevent overlapping transmissions or guarantee their delivery order. + /// The returned future completes once the platform has accepted or sent the + /// notification, which provides backpressure for bulk transfers: awaiting it + /// between chunks paces them instead of filling a native queue. + /// + /// - Apple completes when `CBPeripheralManager.updateValue` accepts the value + /// (immediately or after `peripheralManagerIsReady(toUpdateSubscribers:)`). + /// - Android completes when `onNotificationSent` reports the packet, failing on + /// a non-success GATT status. + /// - Windows completes when `NotifyValueAsync` completes, failing when it does + /// not. + /// + /// It completes once every targeted client has settled; when several fail, the + /// first error is reported. `clearPendingNotifications`, removing a service, a + /// central unsubscribing and a Bluetooth reset fail updates that could never + /// be sent. static Future updateCharacteristicValue({ required String characteristicId, String? instanceId, @@ -301,6 +309,18 @@ class UniversalBlePeripheral { static Future setAutoConnect(bool autoConnect) => _platform.setAutoConnect(autoConnect); + /// Sets the connection latency CoreBluetooth negotiates for a central + /// (`CBPeripheralManager.setDesiredConnectionLatency(_:for:)`). + /// + /// Use [PeripheralConnectionLatency.low] before a bulk transfer: Apple + /// otherwise negotiates a higher latency, which caps notification throughput. + /// Supported on iOS and macOS; no-op elsewhere. + static Future setDesiredConnectionLatency( + String deviceId, + PeripheralConnectionLatency latency, + ) => + _platform.setDesiredConnectionLatency(deviceId, latency); + static UniversalBlePeripheralPlatform _defaultPlatform() { if (!BleCapabilities.supportsPeripheralApi) { return UniversalBlePeripheralUnsupported(); diff --git a/lib/src/universal_ble_pigeon/universal_ble_peripheral_pigeon.dart b/lib/src/universal_ble_pigeon/universal_ble_peripheral_pigeon.dart index 1b2a0e8c..0dc56cd1 100644 --- a/lib/src/universal_ble_pigeon/universal_ble_peripheral_pigeon.dart +++ b/lib/src/universal_ble_pigeon/universal_ble_peripheral_pigeon.dart @@ -184,6 +184,21 @@ class UniversalBlePeripheralPigeon extends UniversalBlePeripheralPlatform Future setAutoConnect(bool autoConnect) => _channel.setAutoConnect(autoConnect); + @override + Future setDesiredConnectionLatency( + String deviceId, + PeripheralConnectionLatency latency, + ) async { + if (!kIsWeb && + (defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS)) { + await UniversalBleDarwinPeripheralChannel().setDesiredConnectionLatency( + deviceId.toDeviceId(isAddress: hasAddressDeviceIds).native, + latency, + ); + } + } + @override void setReadRequestHandler(OnPeripheralReadRequest? handler) => _readRequestHandler = handler; diff --git a/lib/universal_ble.dart b/lib/universal_ble.dart index fbe89f52..ace07bf6 100644 --- a/lib/universal_ble.dart +++ b/lib/universal_ble.dart @@ -36,6 +36,7 @@ export 'package:universal_ble/src/universal_ble.g.dart' CharacteristicProperty, PeripheralAttributePermission, PeripheralAdvertisingState, + PeripheralConnectionLatency, PeripheralReadinessState, PeripheralReadRequestResult, PeripheralWriteRequestResult; diff --git a/pigeon/universal_ble.dart b/pigeon/universal_ble.dart index 251c0d72..8e4cfe61 100644 --- a/pigeon/universal_ble.dart +++ b/pigeon/universal_ble.dart @@ -143,6 +143,13 @@ enum PeripheralAttributePermission { enum PeripheralAdvertisingState { idle, starting, advertising, stopping, error } +/// Desired connection latency for a subscribed central on Apple platforms. +/// +/// Maps to CoreBluetooth `CBPeripheralManagerConnectionLatency`. A lower +/// latency trades radio time for responsiveness; Apple negotiates a higher +/// latency (and therefore lower throughput) when nothing asks for otherwise. +enum PeripheralConnectionLatency { low, medium, high } + /// Central/GATT models class UniversalBleService { String uuid; @@ -685,6 +692,14 @@ abstract class UniversalBlePeripheralChannel { PeripheralPlatformConfig? platformConfig, ); + /// Sends [value] to the clients subscribed to [characteristicId]. + /// + /// The reply is sent once every targeted client's notification is settled: + /// accepted by the platform queue (Apple, when `updateValue` returns `true`), + /// sent (`onNotificationSent` on Android) or completed (`NotifyValueAsync` on + /// Windows). A failure is reported once all of them have settled and at least + /// one failed. + @asyncCallback void updateCharacteristic( String characteristicId, String? characteristicInstanceId, @@ -715,10 +730,16 @@ abstract class UniversalBlePeripheralChannel { void setAutoConnect(bool autoConnect); } -/// Flutter -> Native (Apple peripheral restoration only). +/// Flutter -> Native (Apple peripheral-only APIs). @HostApi() abstract class UniversalBleDarwinPeripheralChannel { void configureRestoration(String restorationIdentifier); + + /// Sets the connection latency CoreBluetooth negotiates with [deviceId]. + void setDesiredConnectionLatency( + String deviceId, + PeripheralConnectionLatency latency, + ); } /// Flutter -> Native (Android only) diff --git a/test/peripheral_reliability_test.dart b/test/peripheral_reliability_test.dart index c54dfde8..9b101bd1 100644 --- a/test/peripheral_reliability_test.dart +++ b/test/peripheral_reliability_test.dart @@ -25,7 +25,8 @@ void main() { 'UniversalBlePeripheralChannel.clearPendingNotifications', 'UniversalBlePeripheralChannel.addService', 'UniversalBlePeripheralChannel.setAutoConnect', - 'UniversalBleDarwinPeripheralChannel.configureRestoration' + 'UniversalBleDarwinPeripheralChannel.configureRestoration', + 'UniversalBleDarwinPeripheralChannel.setDesiredConnectionLatency' ]) { messenger.setMockDecodedMessageHandler( BasicMessageChannel('$prefix$method', @@ -138,4 +139,74 @@ void main() { await platform.addService(service); expect(attempts, 2); }); + + test('setDesiredConnectionLatency forwards on Apple and is a no-op elsewhere', + () async { + final calls = <(String, PeripheralConnectionLatency)>[]; + mock('UniversalBleDarwinPeripheralChannel.setDesiredConnectionLatency', + (message) async { + final args = message as List; + calls.add((args[0] as String, args[1] as PeripheralConnectionLatency)); + return [null]; + }); + + debugDefaultTargetPlatformOverride = TargetPlatform.android; + await UniversalBlePeripheralPigeon.instance.setDesiredConnectionLatency( + 'aa:bb:cc:dd:ee:ff', + PeripheralConnectionLatency.low, + ); + expect(calls, isEmpty); + + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + await UniversalBlePeripheralPigeon.instance.setDesiredConnectionLatency( + 'abcdef01-2345-6789-abcd-ef0123456789', + PeripheralConnectionLatency.low, + ); + if (kIsWeb) { + expect(calls, isEmpty); + } else { + expect(calls, [ + ( + 'ABCDEF01-2345-6789-ABCD-EF0123456789', + PeripheralConnectionLatency.low + ) + ]); + } + }); + + test('updateCharacteristicValue awaits the native settlement reply', () async { + final reply = Completer(); + mock('UniversalBlePeripheralChannel.updateCharacteristic', + (message) => reply.future); + + var completed = false; + final update = UniversalBlePeripheralPigeon.instance + .updateCharacteristicValue( + characteristicId: '2a4d', + value: Uint8List.fromList([1, 2, 3]), + ) + .whenComplete(() => completed = true); + + await Future.delayed(Duration.zero); + expect(completed, isFalse, + reason: 'The future must not complete before the native reply'); + + reply.complete([null]); + await update; + expect(completed, isTrue); + }); + + test('updateCharacteristicValue surfaces a native settlement failure', + () async { + mock('UniversalBlePeripheralChannel.updateCharacteristic', + (message) async => throw PlatformException(code: 'failed')); + + await expectLater( + UniversalBlePeripheralPigeon.instance.updateCharacteristicValue( + characteristicId: '2a4d', + value: Uint8List.fromList([1, 2, 3]), + ), + throwsA(isA()), + ); + }); } diff --git a/windows/src/generated/universal_ble.g.cpp b/windows/src/generated/universal_ble.g.cpp index 1eefc0bf..d366dc28 100644 --- a/windows/src/generated/universal_ble.g.cpp +++ b/windows/src/generated/universal_ble.g.cpp @@ -3395,84 +3395,89 @@ EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( case 143: { const auto& encodable_enum_arg = ReadValue(stream); const int64_t enum_arg_value = encodable_enum_arg.IsNull() ? 0 : encodable_enum_arg.LongValue(); - return encodable_enum_arg.IsNull() ? EncodableValue() : CustomEncodableValue(static_cast(enum_arg_value)); + return encodable_enum_arg.IsNull() ? EncodableValue() : CustomEncodableValue(static_cast(enum_arg_value)); } case 144: { - return CustomEncodableValue(UniversalBleScanResult::FromEncodableList(std::get(ReadValue(stream)))); + const auto& encodable_enum_arg = ReadValue(stream); + const int64_t enum_arg_value = encodable_enum_arg.IsNull() ? 0 : encodable_enum_arg.LongValue(); + return encodable_enum_arg.IsNull() ? EncodableValue() : CustomEncodableValue(static_cast(enum_arg_value)); } case 145: { - return CustomEncodableValue(UniversalDevicePickerResult::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(UniversalBleScanResult::FromEncodableList(std::get(ReadValue(stream)))); } case 146: { - return CustomEncodableValue(UniversalBleService::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(UniversalDevicePickerResult::FromEncodableList(std::get(ReadValue(stream)))); } case 147: { - return CustomEncodableValue(UniversalBleCharacteristic::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(UniversalBleService::FromEncodableList(std::get(ReadValue(stream)))); } case 148: { - return CustomEncodableValue(UniversalBleDescriptor::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(UniversalBleCharacteristic::FromEncodableList(std::get(ReadValue(stream)))); } case 149: { - return CustomEncodableValue(BleConnectionParametersChange::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(UniversalBleDescriptor::FromEncodableList(std::get(ReadValue(stream)))); } case 150: { - return CustomEncodableValue(AndroidOptions::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(BleConnectionParametersChange::FromEncodableList(std::get(ReadValue(stream)))); } case 151: { - return CustomEncodableValue(UniversalScanConfig::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(AndroidOptions::FromEncodableList(std::get(ReadValue(stream)))); } case 152: { - return CustomEncodableValue(UniversalScanFilter::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(UniversalScanConfig::FromEncodableList(std::get(ReadValue(stream)))); } case 153: { - return CustomEncodableValue(ManufacturerDataFilter::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(UniversalScanFilter::FromEncodableList(std::get(ReadValue(stream)))); } case 154: { - return CustomEncodableValue(UniversalManufacturerData::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(ManufacturerDataFilter::FromEncodableList(std::get(ReadValue(stream)))); } case 155: { - return CustomEncodableValue(AppleConnectionOptions::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(UniversalManufacturerData::FromEncodableList(std::get(ReadValue(stream)))); } case 156: { - return CustomEncodableValue(AppleAccessoryPickerItem::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(AppleConnectionOptions::FromEncodableList(std::get(ReadValue(stream)))); } case 157: { - return CustomEncodableValue(AppleAccessorySetupOptions::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(AppleAccessoryPickerItem::FromEncodableList(std::get(ReadValue(stream)))); } case 158: { - return CustomEncodableValue(AndroidConnectionOptions::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(AppleAccessorySetupOptions::FromEncodableList(std::get(ReadValue(stream)))); } case 159: { - return CustomEncodableValue(ConnectionPlatformConfig::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(AndroidConnectionOptions::FromEncodableList(std::get(ReadValue(stream)))); } case 160: { - return CustomEncodableValue(AndroidDiscoverServicesOptions::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(ConnectionPlatformConfig::FromEncodableList(std::get(ReadValue(stream)))); } case 161: { - return CustomEncodableValue(AppleDiscoverServicesOptions::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(AndroidDiscoverServicesOptions::FromEncodableList(std::get(ReadValue(stream)))); } case 162: { - return CustomEncodableValue(DiscoverServicesPlatformConfig::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(AppleDiscoverServicesOptions::FromEncodableList(std::get(ReadValue(stream)))); } case 163: { - return CustomEncodableValue(PeripheralAndroidOptions::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(DiscoverServicesPlatformConfig::FromEncodableList(std::get(ReadValue(stream)))); } case 164: { - return CustomEncodableValue(PeripheralPlatformConfig::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(PeripheralAndroidOptions::FromEncodableList(std::get(ReadValue(stream)))); } case 165: { - return CustomEncodableValue(PeripheralService::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(PeripheralPlatformConfig::FromEncodableList(std::get(ReadValue(stream)))); } case 166: { - return CustomEncodableValue(PeripheralCharacteristic::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(PeripheralService::FromEncodableList(std::get(ReadValue(stream)))); } case 167: { - return CustomEncodableValue(PeripheralDescriptor::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(PeripheralCharacteristic::FromEncodableList(std::get(ReadValue(stream)))); } case 168: { - return CustomEncodableValue(PeripheralReadRequestResult::FromEncodableList(std::get(ReadValue(stream)))); + return CustomEncodableValue(PeripheralDescriptor::FromEncodableList(std::get(ReadValue(stream)))); } case 169: { + return CustomEncodableValue(PeripheralReadRequestResult::FromEncodableList(std::get(ReadValue(stream)))); + } + case 170: { return CustomEncodableValue(PeripheralWriteRequestResult::FromEncodableList(std::get(ReadValue(stream)))); } default: @@ -3554,138 +3559,143 @@ void PigeonInternalCodecSerializer::WriteValue( WriteValue(EncodableValue(static_cast(std::any_cast(*custom_value))), stream); return; } - if (custom_value->type() == typeid(UniversalBleErrorCode)) { + if (custom_value->type() == typeid(PeripheralConnectionLatency)) { stream->WriteByte(143); + WriteValue(EncodableValue(static_cast(std::any_cast(*custom_value))), stream); + return; + } + if (custom_value->type() == typeid(UniversalBleErrorCode)) { + stream->WriteByte(144); WriteValue(EncodableValue(static_cast(std::any_cast(*custom_value))), stream); return; } if (custom_value->type() == typeid(UniversalBleScanResult)) { - stream->WriteByte(144); + stream->WriteByte(145); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(UniversalDevicePickerResult)) { - stream->WriteByte(145); + stream->WriteByte(146); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(UniversalBleService)) { - stream->WriteByte(146); + stream->WriteByte(147); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(UniversalBleCharacteristic)) { - stream->WriteByte(147); + stream->WriteByte(148); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(UniversalBleDescriptor)) { - stream->WriteByte(148); + stream->WriteByte(149); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(BleConnectionParametersChange)) { - stream->WriteByte(149); + stream->WriteByte(150); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AndroidOptions)) { - stream->WriteByte(150); + stream->WriteByte(151); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(UniversalScanConfig)) { - stream->WriteByte(151); + stream->WriteByte(152); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(UniversalScanFilter)) { - stream->WriteByte(152); + stream->WriteByte(153); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(ManufacturerDataFilter)) { - stream->WriteByte(153); + stream->WriteByte(154); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(UniversalManufacturerData)) { - stream->WriteByte(154); + stream->WriteByte(155); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AppleConnectionOptions)) { - stream->WriteByte(155); + stream->WriteByte(156); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AppleAccessoryPickerItem)) { - stream->WriteByte(156); + stream->WriteByte(157); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AppleAccessorySetupOptions)) { - stream->WriteByte(157); + stream->WriteByte(158); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AndroidConnectionOptions)) { - stream->WriteByte(158); + stream->WriteByte(159); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(ConnectionPlatformConfig)) { - stream->WriteByte(159); + stream->WriteByte(160); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AndroidDiscoverServicesOptions)) { - stream->WriteByte(160); + stream->WriteByte(161); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AppleDiscoverServicesOptions)) { - stream->WriteByte(161); + stream->WriteByte(162); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(DiscoverServicesPlatformConfig)) { - stream->WriteByte(162); + stream->WriteByte(163); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(PeripheralAndroidOptions)) { - stream->WriteByte(163); + stream->WriteByte(164); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(PeripheralPlatformConfig)) { - stream->WriteByte(164); + stream->WriteByte(165); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(PeripheralService)) { - stream->WriteByte(165); + stream->WriteByte(166); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(PeripheralCharacteristic)) { - stream->WriteByte(166); + stream->WriteByte(167); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(PeripheralDescriptor)) { - stream->WriteByte(167); + stream->WriteByte(168); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(PeripheralReadRequestResult)) { - stream->WriteByte(168); + stream->WriteByte(169); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(PeripheralWriteRequestResult)) { - stream->WriteByte(169); + stream->WriteByte(170); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } @@ -4978,14 +4988,15 @@ void UniversalBlePeripheralChannel::SetUp( const auto& value_arg = std::get>(encodable_value_arg); const auto& encodable_device_id_arg = args.at(3); const auto* device_id_arg = std::get_if(&encodable_device_id_arg); - std::optional output = api->UpdateCharacteristic(characteristic_id_arg, characteristic_instance_id_arg, value_arg, device_id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); + api->UpdateCharacteristic(characteristic_id_arg, characteristic_instance_id_arg, value_arg, device_id_arg, [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } @@ -5172,6 +5183,40 @@ void UniversalBleDarwinPeripheralChannel::SetUp( channel.SetMessageHandler(nullptr); } } + { + BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.universal_ble.UniversalBleDarwinPeripheralChannel.setDesiredConnectionLatency" + prepended_suffix, &GetCodec()); + if (api != nullptr) { + channel.SetMessageHandler([api](const EncodableValue& message, const ::flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_device_id_arg = args.at(0); + if (encodable_device_id_arg.IsNull()) { + reply(WrapError("device_id_arg unexpectedly null.")); + return; + } + const auto& device_id_arg = std::get(encodable_device_id_arg); + const auto& encodable_latency_arg = args.at(1); + if (encodable_latency_arg.IsNull()) { + reply(WrapError("latency_arg unexpectedly null.")); + return; + } + const auto& latency_arg = std::any_cast(std::get(encodable_latency_arg)); + std::optional output = api->SetDesiredConnectionLatency(device_id_arg, latency_arg); + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel.SetMessageHandler(nullptr); + } + } } EncodableValue UniversalBleDarwinPeripheralChannel::WrapError(std::string_view error_message) { diff --git a/windows/src/generated/universal_ble.g.h b/windows/src/generated/universal_ble.g.h index fc60172b..27b1a7fa 100644 --- a/windows/src/generated/universal_ble.g.h +++ b/windows/src/generated/universal_ble.g.h @@ -183,6 +183,17 @@ enum class PeripheralAdvertisingState { kError = 4 }; +// Desired connection latency for a subscribed central on Apple platforms. +// +// Maps to CoreBluetooth `CBPeripheralManagerConnectionLatency`. A lower +// latency trades radio time for responsiveness; Apple negotiates a higher +// latency (and therefore lower throughput) when nothing asks for otherwise. +enum class PeripheralConnectionLatency { + kLow = 0, + kMedium = 1, + kHigh = 2 +}; + // Unified error codes for all platforms enum class UniversalBleErrorCode { kUnknownError = 0, @@ -1774,11 +1785,19 @@ class UniversalBlePeripheralChannel { const int64_t* timeout, const UniversalManufacturerData* manufacturer_data, const PeripheralPlatformConfig* platform_config) = 0; - virtual std::optional UpdateCharacteristic( + // Sends [value] to the clients subscribed to [characteristicId]. + // + // The reply is sent once every targeted client's notification is settled: + // accepted by the platform queue (Apple, when `updateValue` returns `true`), + // sent (`onNotificationSent` on Android) or completed (`NotifyValueAsync` on + // Windows). A failure is reported once all of them have settled and at least + // one failed. + virtual void UpdateCharacteristic( const std::string& characteristic_id, const std::string* characteristic_instance_id, const std::vector& value, - const std::string* device_id) = 0; + const std::string* device_id, + std::function reply)> result) = 0; // Returns peripheral-client device ids currently subscribed to the // characteristic identified by [characteristicId] (and, when supplied, // [characteristicInstanceId]). @@ -1812,7 +1831,7 @@ class UniversalBlePeripheralChannel { protected: UniversalBlePeripheralChannel() = default; }; -// Flutter -> Native (Apple peripheral restoration only). +// Flutter -> Native (Apple peripheral-only APIs). // // Generated interface from Pigeon that represents a handler of messages from Flutter. class UniversalBleDarwinPeripheralChannel { @@ -1821,6 +1840,10 @@ class UniversalBleDarwinPeripheralChannel { UniversalBleDarwinPeripheralChannel& operator=(const UniversalBleDarwinPeripheralChannel&) = delete; virtual ~UniversalBleDarwinPeripheralChannel() {} virtual std::optional ConfigureRestoration(const std::string& restoration_identifier) = 0; + // Sets the connection latency CoreBluetooth negotiates with [deviceId]. + virtual std::optional SetDesiredConnectionLatency( + const std::string& device_id, + const PeripheralConnectionLatency& latency) = 0; // The codec used by UniversalBleDarwinPeripheralChannel. static const ::flutter::StandardMessageCodec& GetCodec(); diff --git a/windows/src/universal_ble_plugin.cpp b/windows/src/universal_ble_plugin.cpp index aaa8d4a5..0497c436 100644 --- a/windows/src/universal_ble_plugin.cpp +++ b/windows/src/universal_ble_plugin.cpp @@ -3760,35 +3760,40 @@ void UniversalBlePlugin::DisposeAdvertisementPublisher() { } } -std::optional UniversalBlePlugin::UpdateCharacteristic( +void UniversalBlePlugin::UpdateCharacteristic( const std::string &characteristic_id, const std::string *characteristic_instance_id, - const std::vector &value, const std::string *device_id) { + const std::vector &value, const std::string *device_id, + std::function reply)> result) { if (characteristic_instance_id != nullptr) { - return FlutterError("not-supported", + result(FlutterError("not-supported", "Windows does not support characteristic instance IDs", - nullptr); + nullptr)); + return; } GattLocalCharacteristic local_char = nullptr; IBuffer buffer = nullptr; { std::lock_guard lock(peripheral_mutex_); if (device_id != nullptr) { - return FlutterError("not-supported", + result(FlutterError("not-supported", "Windows does not support targeting a specific " "device for notifications", - nullptr); + nullptr)); + return; } bool ambiguous_match = false; auto *characteristic_object = FindPeripheralGattCharacteristicObject( characteristic_id, &ambiguous_match); if (ambiguous_match) { - return FlutterError("ambiguous-characteristic", + result(FlutterError("ambiguous-characteristic", "Characteristic UUID exists in multiple services; " "cannot update uniquely", - nullptr); + nullptr)); + return; } if (characteristic_object == nullptr) { - return FlutterError("not-found", "Characteristic not found", nullptr); + result(FlutterError("not-found", "Characteristic not found", nullptr)); + return; } IBuffer bytes = from_bytevc(value); DataWriter writer; @@ -3799,32 +3804,44 @@ std::optional UniversalBlePlugin::UpdateCharacteristic( } try { - // NotifyValueAsync completes only once the value has been handed to every - // subscribed client, so waiting for it costs the platform thread a full - // GATT round trip (and blocks it for good when a client link is wedged). - // Apple and Android queue the update and return, so submit it and report - // the per-client outcome from the completion handler instead. Consecutive - // calls are still submitted from the platform thread in call order, but - // Windows does not promise that overlapping operations are serialized or - // delivered in that order. + // NotifyValueAsync completes once the value has been handed to every + // subscribed client; waiting for it on the platform thread would block a + // full GATT round trip (and block it for good when a client link is wedged). + // Submit it and reply from the completion handler instead, so awaiting the + // Dart future is a real backpressure signal. const auto value_size = buffer.Length(); + // Captured by copy, not moved: the catch path below still has to reply with + // the same callback, and a moved-from std::function would throw + // std::bad_function_call instead. local_char.NotifyValueAsync(buffer).Completed( - [characteristic_id, value_size]( + [characteristic_id, value_size, result]( const IAsyncOperation> &sender, const AsyncStatus status) { LogPeripheralNotificationResult(characteristic_id, value_size, sender, status); + if (status == AsyncStatus::Completed) { + safe_reply("UpdateCharacteristic", result, std::nullopt); + } else { + safe_reply( + "UpdateCharacteristic", result, + FlutterError( + "failed", + "Failed to notify subscribed clients for characteristic " + "update", + nullptr)); + } }); } catch (...) { // Starting the operation failed (for example the characteristic object is // no longer valid); that is still reported synchronously. - return FlutterError( - "failed", - "Failed to notify subscribed clients for characteristic update", - nullptr); + safe_reply("UpdateCharacteristic", result, + FlutterError( + "failed", + "Failed to notify subscribed clients for characteristic " + "update", + nullptr)); } - return std::nullopt; } // Runs on a WinRT thread pool thread, possibly after this plugin is gone, which diff --git a/windows/src/universal_ble_plugin.h b/windows/src/universal_ble_plugin.h index ab42924d..67bbf13a 100644 --- a/windows/src/universal_ble_plugin.h +++ b/windows/src/universal_ble_plugin.h @@ -700,9 +700,10 @@ class UniversalBlePlugin : public flutter::Plugin, const int64_t *timeout, const UniversalManufacturerData *manufacturer_data, const PeripheralPlatformConfig *platform_config) override; - std::optional UpdateCharacteristic( + void UpdateCharacteristic( const std::string &characteristic_id, const std::string *characteristic_instance_id, - const std::vector &value, const std::string *device_id) override; + const std::vector &value, const std::string *device_id, + std::function reply)> result) override; ErrorOr GetSubscribedClients( const std::string &characteristic_id, const std::string *characteristic_instance_id) override; std::optional ClearPendingNotifications(const std::string *device_id) override;