diff --git a/CHANGELOG.md b/CHANGELOG.md index 67ba8838..0f402461 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## Unreleased * 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). ## 3.4.1 * Android: a `setNotifiable` call whose CCCD write throws now fails with a classified error instead of being left pending. The old code withdrew the pending result twice — once in the inner handler and again in the outer one — so the second withdrawal found nothing to fail and the Dart call hung until its timeout. The CCCD write is now one helper, and the request is withdrawn once before its single reply. 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 f8ed78c8..8c71fac7 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt @@ -16,6 +16,7 @@ import android.bluetooth.BluetoothGattServerCallback import android.bluetooth.BluetoothGattService import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothStatusCodes import android.bluetooth.le.AdvertiseCallback import android.bluetooth.le.AdvertiseData import android.bluetooth.le.AdvertiseSettings @@ -86,6 +87,11 @@ class UniversalBlePeripheralPlugin( * returns false while the previous one is in flight), so they are drained * FIFO from [BluetoothGattServerCallback.onNotificationSent]. Ordering matters: * a HID release must never overtake the press it releases. + * + * This monitor also guards the transmit itself. Below API 33 the payload + * travels in the shared [BluetoothGattCharacteristic.value], so the check, + * the dequeue, that assignment and the notify call must not interleave with + * another drain or with an update (#403). */ private val pendingNotifications: ArrayDeque = ArrayDeque() private val notificationsInFlight: MutableSet = HashSet() @@ -491,7 +497,6 @@ class UniversalBlePeripheralPlugin( val characteristic = characteristicId.findGattCharacteristic(characteristicInstanceId) ?: throw Exception("Characteristic not found") - characteristic.value = value.copyOf() val targetDevices = synchronized(bluetoothDevicesMap) { if (deviceId != null) { val dev = bluetoothDevicesMap[deviceId] @@ -505,13 +510,25 @@ class UniversalBlePeripheralPlugin( } val indicate = (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0 + // Resolved before taking pendingNotifications: isSubscribed takes + // 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) { - targetDevices.filter { isSubscribed(it.address, characteristic) }.forEach { device -> + 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. + @Suppress("DEPRECATION") + characteristic.value = value.copyOf() + return + } + subscribedDevices.forEach { device -> pendingNotifications.addLast( PendingNotification(device, characteristic, value.copyOf(), indicate) ) } - targetDevices.forEach { drainNotifications(it.address) } + subscribedDevices.forEach { drainNotifications(it.address) } } } @@ -523,24 +540,39 @@ class UniversalBlePeripheralPlugin( } private fun drainNotifications(deviceAddress: String) { - if (notificationsInFlight.contains(deviceAddress)) return - val next: PendingNotification - val server: BluetoothGattServer synchronized(pendingNotifications) { + if (notificationsInFlight.contains(deviceAddress)) return val index = pendingNotifications.indexOfFirst { it.device.address == deviceAddress } if (index < 0) return - next = pendingNotifications.removeAt(index) - server = gattServer ?: 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) - } - next.characteristic.value = next.value - val sent = kotlin.runCatching { - server.notifyCharacteristicChanged(next.device, next.characteristic, next.indicate) - }.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. - synchronized(pendingNotifications) { + // 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 + // would transmit the wrong chunk (#403). + val sent = kotlin.runCatching { + @Suppress("DEPRECATION") + next.characteristic.value = next.value + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + server.notifyCharacteristicChanged( + next.device, + next.characteristic, + next.indicate, + next.value, + ) == BluetoothStatusCodes.SUCCESS + } else { + @Suppress("DEPRECATION") + server.notifyCharacteristicChanged(next.device, next.characteristic, next.indicate) + } + }.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. notificationsInFlight.remove(deviceAddress) pendingNotifications.addFirst(next) } 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 605628cc..badca6b5 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/PeripheralRegressionTest.kt @@ -159,6 +159,44 @@ internal class PeripheralRegressionTest { Mockito.verify(characteristic).setValue(value) } + // #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 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) + } + // #385: a service registered a second time must resolve to the new // characteristics, not the ones the server no longer holds. @Test fun clearServicesForgetsTheRegisteredCharacteristics() {