From 6ae6bb2c3acdbf059871f197e10892ae8ebeb814 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:46:53 +0100 Subject: [PATCH 01/13] Android: refuse requests on a disconnected autoConnect client (#394) An autoConnect client stays open after a link loss, so writeValue could still find the cached characteristic and the stack could accept the write and drop it without ever calling onCharacteristicWrite. The orphaned pending entry was then completed by the first callback of the reconnected link, so every later write lagged by one and timed out after 10 s - about one write per timeout with the per-device queue. Register a request only while its client's link is up, under the same lock the disconnect cleanup sweeps, so a concurrent submit is either swept or refused with deviceDisconnected. Apply that to reads, writes, descriptor reads/writes and CCCD subscriptions. As a backstop, a client kept open by autoConnect that reports STATE_CONNECTED again fails anything still pending from its previous link. readDescriptorValue now registers its pending result before issuing the read, as readValue already does. --- CHANGELOG.md | 3 + README.md | 2 + .../universal_ble/UniversalBlePlugin.kt | 200 ++++++++--- .../GattCallbackCompletionTest.kt | 12 +- .../universal_ble/LinkLossOperationTest.kt | 338 ++++++++++++++++++ .../universal_ble/PluginTestSupport.kt | 25 ++ .../universal_ble/WriteRefusalTest.kt | 2 +- example/pubspec.lock | 2 +- pubspec.yaml | 2 +- 9 files changed, 535 insertions(+), 51 deletions(-) create mode 100644 android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 91ee6b45..49ad7da4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 3.4.1 +* Android: a read, write, descriptor read/write or notification subscription submitted to an `autoConnect` client after its link dropped now fails right away with `deviceDisconnected` instead of reaching the stack. The client stays open and keeps its cached services after the link loss, and below API 33 the stack accepts such a request and then drops it without a callback, leaving a pending entry that the first callback of the reconnected link completes — so every later write lagged by one and timed out after 10 s, giving about one write per timeout. The link check shares the lock with the disconnect cleanup, so a request submitted concurrently is either registered in time to be swept or refused; as a backstop, a client whose link comes back now also fails anything still pending from the previous link. `readDescriptorValue` registers its pending result before issuing the read, as `readValue` already did (#394). + ## 3.4.0 * Subscription state is now tracked per characteristic instance instead of per characteristic UUID, so a device that exposes the same UUID in several services no longer reports every instance as subscribed when one is, and unsubscribing one instance no longer clears the state that describes the others. `UniversalBle.isSubscribed` and `UniversalBle.getSubscribedCharacteristics` take an optional `serviceId` to ask about one service; without it they keep the previous answer, which is `true` when any service exposes the characteristic, and `BleCharacteristic.isSubscribed` now uses the characteristic's own service. `getSubscribedCharacteristics` still returns deduplicated UUIDs, now sorted rather than in subscription order (#393). * Characteristic values now carry the UUID of the service that owns the characteristic, so two characteristics with the same UUID in different services are told apart. The Pigeon `onValueChanged` callback passes the service, `BleCharacteristicValue` gains `serviceId`, `characteristicValueStream` takes an optional `serviceId` filter, and `BleCharacteristic.onValueReceived` uses the characteristic's own service automatically. Android, Apple, Windows, Linux and Web report the owning service. A value whose service a platform does not report — a custom platform implementation, or an unusable service id — still reaches a service-filtered stream, so existing callers and platforms keep their behaviour (#391). diff --git a/README.md b/README.md index 8113fabe..5f60665d 100644 --- a/README.md +++ b/README.md @@ -348,6 +348,8 @@ You can enable automatic reconnection by setting the `autoConnect` parameter to await bleDevice.connect(autoConnect: true); ``` +While the link is down — after the plugin reports a disconnection and before the system reconnects the client — a read, write, descriptor access or subscription to that device fails right away on Android with `UniversalBleErrorCode.deviceDisconnected` instead of waiting for the request timeout. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. + #### Background connection events (iOS/macOS) By default, a suspended app does not get woken for connection events. Set `AppleConnectionOptions` to have the system alert the user and relaunch your app into the background when a connection event occurs while the app is suspended — e.g. to keep reacting to a previously paired peripheral (auto-reconnect) during a workout while the phone is locked. Requires the `bluetooth-central` background mode on iOS. diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index 60b19f8b..9a3d4ae3 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -103,6 +103,12 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // another engine, and detach releases only this engine's clients. private val gattRegistry = GattRegistry() + // GATT clients that a link loss left open for autoConnect, until they + // report a connection again. The next STATE_CONNECTED for one of them is a + // new link, which inherits nothing from the previous one (#394). + private val awaitingReconnectGatts: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + /** * When enabled, close every known GATT client on engine detach. The * plugin otherwise leaves GATT open, so a killed app keeps the @@ -358,6 +364,9 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), "Connection already in progress" ) } + // The client below replaces this one, so it will never be the client + // that reports the reconnect. + awaitingReconnectGatts.remove(it) } val shouldAutoConnect = autoConnect ?: false @@ -384,6 +393,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), autoConnectDevices.remove(deviceId) val gatt = gattRegistry.find(deviceId) if (gatt == null) { + awaitingReconnectGatts.removeAll { it.device.address == deviceId } cleanUpConnection(deviceId) mainThreadHandler?.post { callbackChannel?.onConnectionChanged(deviceId, false, null, null, null) {} @@ -668,8 +678,13 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), callback, ) if (pending != null) { - synchronized(subscriptionResultFutureList) { - subscriptionResultFutureList.add(pending) + // Only register while the link is up (see writeValue): a CCCD + // write the stack accepts on a disconnected autoConnect client + // can be dropped without a callback, and the stranded entry + // would then consume the next subscription's completion (#394). + if (!subscriptionResultFutureList.addIfLinkedUp(gatt, pending)) { + callback(Result.failure(deviceDisconnectedError())) + return } pendingFuture = pending } @@ -792,6 +807,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // arrives on a binder thread and a future added afterwards is never // matched (the callback finds nothing to complete), leaving the Dart // call awaiting forever. Every access to the list holds its lock. + // The link check shares the lock, so a disconnected client cannot + // leave a read that the stack drops without a callback (#394). val readFuture = ReadResultFuture( gatt, gatt.device.address, @@ -799,8 +816,9 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), gattCharacteristic.service.uuid.toString(), callback ) - synchronized(readResultFutureList) { - readResultFutureList.add(readFuture) + if (!readResultFutureList.addIfLinkedUp(gatt, readFuture)) { + callback(Result.failure(deviceDisconnectedError())) + return } val started = try { @@ -972,14 +990,22 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), gattCharacteristic.service.uuid.toString(), callback ) - writeFuture = future // Wait for the result. The list is mutated both here (main thread) // and in onCharacteristicWrite / cleanUpConnection (Bluetooth // binder threads), so every access must hold the lock. - synchronized(writeResultFutureList) { - writeResultFutureList.add(future) + // + // Register only while the link is up, and under that same lock: an + // autoConnect client stays open after a link loss, so the stack can + // accept a write and then drop it without ever calling + // onCharacteristicWrite. The orphaned entry would take the next + // write's completion, and after the reconnect every write would lag + // by one and time out (#394). + if (!writeResultFutureList.addIfLinkedUp(gatt, future)) { + callback(Result.failure(deviceDisconnectedError())) + return } + writeFuture = future val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { gatt.writeCharacteristic(gattCharacteristic, value, writeType) @@ -1127,7 +1153,35 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) return } - if (!gatt.readDescriptor(gattDescriptor)) { + val readFuture = ReadDescriptorResultFuture( + gatt, + gatt.device.address, + gattDescriptor.uuid.toString(), + gattCharacteristic.uuid.toString(), + gattCharacteristic.service.uuid.toString(), + callback + ) + // Register before issuing the read, as readValue does: the response + // can otherwise arrive before the future is pending, and the link + // check shares the lock with the disconnect cleanup (#394). + if (!readDescriptorResultFutureList.addIfLinkedUp(gatt, readFuture)) { + callback(Result.failure(deviceDisconnectedError())) + return + } + + val started = try { + gatt.readDescriptor(gattDescriptor) + } catch (e: Exception) { + // A callback or disconnect may already own the reply. + synchronized(readDescriptorResultFutureList) { + if (!readDescriptorResultFutureList.remove(readFuture)) return + } + throw e + } + if (!started) { + synchronized(readDescriptorResultFutureList) { + if (!readDescriptorResultFutureList.remove(readFuture)) return + } callback( Result.failure( createFlutterError( @@ -1136,19 +1190,6 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) ) ) - return - } - synchronized(readDescriptorResultFutureList) { - readDescriptorResultFutureList.add( - ReadDescriptorResultFuture( - gatt, - gatt.device.address, - gattDescriptor.uuid.toString(), - gattCharacteristic.uuid.toString(), - gattCharacteristic.service.uuid.toString(), - callback - ) - ) } } catch (e: FlutterError) { callback(Result.failure(e)) @@ -1270,11 +1311,15 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), gattCharacteristic.service.uuid.toString(), callback ) - writeFuture = future - synchronized(writeDescriptorResultFutureList) { - writeDescriptorResultFutureList.add(future) + // Same rule as writeValue: only register while the link is up, under + // the lock the disconnect cleanup takes, so a request the stack + // accepts and then drops cannot survive as a stale entry (#394). + if (!writeDescriptorResultFutureList.addIfLinkedUp(gatt, future)) { + callback(Result.failure(deviceDisconnectedError())) + return } + writeFuture = future val status = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { gatt.writeDescriptor(gattDescriptor, value) @@ -1472,6 +1517,44 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), private fun isCurrentClient(gatt: BluetoothGatt?): Boolean = gatt != null && gattRegistry.find(gatt.device.address) === gatt + /** + * Whether [gatt] has a link the platform can deliver operations on. + * + * `connectedGatts` is updated from `onConnectionStateChange` on a binder + * thread, so an operation must read this inside the same lock that the + * disconnect cleanup takes: either the check sees the link already gone and + * refuses the call, or the pending result is registered in time for the + * cleanup to sweep it. Reading it outside that lock leaves a window where + * the check passes, cleanup sweeps, and the result is added afterwards — + * stranded until a later callback completes it one behind (#394). + */ + private fun isLinkUp(gatt: BluetoothGatt): Boolean = connectedGatts.contains(gatt) + + /** + * Adds [future] to this pending list while holding its lock, but only if + * [gatt] still has a live link. Returns whether it was added; a caller that + * gets false must fail its call with `deviceDisconnected` instead of + * submitting the operation. + * + * Adding under the list's own lock is what closes the race described in + * [isLinkUp]: the disconnect cleanup sweeps the same list under the same + * lock. + */ + private fun MutableList.addIfLinkedUp(gatt: BluetoothGatt, future: T): Boolean = + synchronized(this) { + if (isLinkUp(gatt)) { + add(future) + true + } else { + false + } + } + + private fun deviceDisconnectedError(): FlutterError = createFlutterError( + UniversalBleErrorCode.DEVICE_DISCONNECTED, + "Device Disconnected", + ) + override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) { val deviceId = gatt?.device?.address ?: return // Only the registered client may report or cache an MTU; a stale client @@ -1724,10 +1807,30 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), return futureGatt !== gattRegistry.find(deviceId) } - val deviceDisconnectedError: FlutterError = createFlutterError( - UniversalBleErrorCode.DEVICE_DISCONNECTED, - "Device Disconnected", - ) + failPendingOperations(::owns) + // The observed MTU belonged to the link that is gone; the next + // connection negotiates its own. + synchronized(mtuResultFutureList) { + if (gatt != null) { + negotiatedMtus.remove(gatt) + } else { + negotiatedMtus.keys.removeAll { it.device.address == deviceId } + } + } + } + + /** + * Fails every pending operation that [owns] selects with + * `deviceDisconnected`, each on the main thread. + * + * Each list is swept under its own lock, which the request paths share + * with their link check: a request submitted concurrently either lands in + * time to be swept or is refused because its link is gone (#394). + */ + private fun failPendingOperations( + owns: (futureGatt: BluetoothGatt, futureDeviceId: String) -> Boolean, + ) { + val error: FlutterError = deviceDisconnectedError() val pendingReads: List synchronized(readResultFutureList) { pendingReads = readResultFutureList.filter { @@ -1738,7 +1841,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), for (future in pendingReads) { postToMainLooper { try { - future.result(Result.failure(deviceDisconnectedError)) + future.result(Result.failure(error)) } catch (e: Exception) { UniversalBleLogger.logError("Read completion delivery failed: $e") } @@ -1754,7 +1857,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), for (future in pendingWrites) { postToMainLooper { try { - future.result(Result.failure(deviceDisconnectedError)) + future.result(Result.failure(error)) } catch (e: Exception) { UniversalBleLogger.logError("Write completion delivery failed: $e") } @@ -1770,7 +1873,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), for (future in pendingDescriptorReads) { postToMainLooper { try { - future.result(Result.failure(deviceDisconnectedError)) + future.result(Result.failure(error)) } catch (e: Exception) { UniversalBleLogger.logError("Read descriptor completion delivery failed: $e") } @@ -1786,7 +1889,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), for (future in pendingDescriptorWrites) { postToMainLooper { try { - future.result(Result.failure(deviceDisconnectedError)) + future.result(Result.failure(error)) } catch (e: Exception) { UniversalBleLogger.logError("Write descriptor completion delivery failed: $e") } @@ -1802,7 +1905,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), for (future in pendingSubscriptions) { postToMainLooper { try { - future.result(Result.failure(deviceDisconnectedError)) + future.result(Result.failure(error)) } catch (e: Exception) { UniversalBleLogger.logError("Subscription completion delivery failed: $e") } @@ -1814,14 +1917,9 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), owns(it.gatt, it.deviceId) } mtuResultFutureList.removeAll(pendingMtus) - if (gatt != null) { - negotiatedMtus.remove(gatt) - } else { - negotiatedMtus.keys.removeAll { it.device.address == deviceId } - } } for (future in pendingMtus) { - postMtuResult(future.result, Result.failure(deviceDisconnectedError)) + postMtuResult(future.result, Result.failure(error)) } val pendingDiscoveries: List synchronized(discoverServicesFutureList) { @@ -1833,7 +1931,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), for (future in pendingDiscoveries) { postToMainLooper { try { - future.result(Result.failure(deviceDisconnectedError)) + future.result(Result.failure(error)) } catch (e: Exception) { UniversalBleLogger.logError( "Discover services completion delivery failed: $e" @@ -1851,7 +1949,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), for (future in pendingRssis) { postToMainLooper { try { - future.result(Result.failure(deviceDisconnectedError)) + future.result(Result.failure(error)) } catch (e: Exception) { UniversalBleLogger.logError("RSSI completion delivery failed: $e") } @@ -1862,6 +1960,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), private fun cleanConnection(gatt: BluetoothGatt) { val deviceId = gatt.device.address gattRegistry.remove(gatt) + awaitingReconnectGatts.remove(gatt) cleanUpConnection(deviceId, gatt) closingGatts.add(gatt) gatt.disconnect() @@ -1870,6 +1969,9 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), mainThreadHandler?.postDelayed({ if (closingGatts.remove(gatt)) { UniversalBleLogger.logDebug("No STATE_DISCONNECTED for $deviceId, closing gatt") + // No callback ever reported the link down, so drop the state that + // describes it; the closed client must not be taken for connected. + connectedGatts.remove(gatt) gatt.close() // A newer connect() owns this address now; its state is not ours to report. if (!gattRegistry.isKnown(deviceId)) { @@ -2020,6 +2122,16 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), return } connectedGatts.add(gatt) + // A client that kept the link loss open for autoConnect is now on a + // new link, which inherits nothing from the previous one. An + // operation the stack accepted just before that loss can be dropped + // without ever calling back; its entry would then complete with the + // new link's first callback and every later operation would lag by + // one. Fail whatever is still attributed to this client — and only + // to it (#394). + if (awaitingReconnectGatts.remove(gatt)) { + failPendingOperations { futureGatt, _ -> futureGatt === gatt } + } mainThreadHandler?.post { callbackChannel?.onConnectionChanged( gatt.device.address, true, status.parseHciErrorCode(), status.toConnectionErrorCode(), status.toGattErrorCode() @@ -2054,12 +2166,16 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), if (closingByRequest || !shouldAutoConnect) { // Only keep the client open when autoConnect should let Android reconnect it + awaitingReconnectGatts.remove(gatt) gattRegistry.remove(gatt) gatt.disconnect() UniversalBleLogger.logDebug("Closing gatt for $deviceId") gatt.close() + } else if (!superseded) { + // When autoConnect is enabled, keep GATT open for Android to + // reconnect; its next STATE_CONNECTED starts a new link. + awaitingReconnectGatts.add(gatt) } - // When autoConnect is enabled, keep GATT open for Android to reconnect } } diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt index 8ab3953d..d6e3b9ea 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt @@ -431,7 +431,7 @@ internal class GattCallbackCompletionTest { ) true } - plugin.gattRegistry().put(gatt) + plugin.attachConnectedGatt(gatt) plugin.readValue(deviceAddress, serviceUuid.toString(), charUuid.toString()) { reads.add(it) @@ -454,7 +454,7 @@ internal class GattCallbackCompletionTest { val characteristic = mockCharacteristic() val gatt = mockGattWithService(characteristic) Mockito.`when`(gatt.readCharacteristic(characteristic)).thenReturn(false) - plugin.gattRegistry().put(gatt) + plugin.attachConnectedGatt(gatt) plugin.readValue(deviceAddress, serviceUuid.toString(), charUuid.toString()) { reads.add(it) @@ -483,7 +483,7 @@ internal class GattCallbackCompletionTest { if (throwsOnRead) throw IllegalStateException("GATT client closed") false } - plugin.gattRegistry().put(gatt) + plugin.attachConnectedGatt(gatt) plugin.readValue(deviceAddress, serviceUuid.toString(), charUuid.toString()) { reads.add(it) @@ -509,7 +509,7 @@ internal class GattCallbackCompletionTest { val gatt = mockGattWithService(characteristic) Mockito.`when`(gatt.readCharacteristic(characteristic)) .thenThrow(IllegalStateException("Read failed")) - plugin.gattRegistry().put(gatt) + plugin.attachConnectedGatt(gatt) plugin.readValue(deviceAddress, serviceUuid.toString(), charUuid.toString()) { reads.add(it) @@ -540,7 +540,7 @@ internal class GattCallbackCompletionTest { plugin.onDescriptorWrite(gatt, cccd, BluetoothGatt.GATT_SUCCESS) true } - plugin.gattRegistry().put(gatt) + plugin.attachConnectedGatt(gatt) val pending = plugin.getField>( "subscriptionResultFutureList" ) @@ -570,7 +570,7 @@ internal class GattCallbackCompletionTest { Mockito.`when`(characteristic.getDescriptor(ccdCharacteristic)).thenReturn(cccd) val gatt = mockGattWithService(characteristic) Mockito.`when`(gatt.writeDescriptor(cccd)).thenReturn(false) - plugin.gattRegistry().put(gatt) + plugin.attachConnectedGatt(gatt) plugin.setNotifiable( deviceAddress, diff --git a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt new file mode 100644 index 00000000..bb967194 --- /dev/null +++ b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt @@ -0,0 +1,338 @@ +package com.navideck.universal_ble + +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import android.bluetooth.BluetoothGattService +import android.os.Handler +import java.util.UUID +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import org.mockito.Mockito + +/* + * An autoConnect client stays open after a link loss, so between the + * STATE_DISCONNECTED callback and the reconnect the stack still hands the plugin + * a live BluetoothGatt with its cached service tree. A request submitted in that + * window can be accepted by the stack and then dropped without any callback + * (below API 33 `writeCharacteristic` returns true for a disconnected client). + * The orphaned pending entry would then be completed by the first callback of + * the reconnected link, so every later request would lag by one and the + * per-device Dart queue would time out at about one write per timeout (#394). + * + * The plugin must therefore refuse a request whose client has no live link, and + * as a backstop fail anything still pending when a client that lost its link + * reports STATE_CONNECTED again. Tests drive the real plugin through its + * connection callbacks. + */ +internal class LinkLossOperationTest { + private val deviceAddress = "AA:BB:CC:DD:EE:FF" + private val serviceUuid = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb") + private val charUuid = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb") + private val cccdUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") + private val descriptorUuid = UUID.fromString("00002901-0000-1000-8000-00805f9b34fb") + + private val service = Mockito.mock(BluetoothGattService::class.java) + private val characteristic = Mockito.mock(BluetoothGattCharacteristic::class.java) + private val gatt = Mockito.mock(BluetoothGatt::class.java) + + init { + val device = Mockito.mock(BluetoothDevice::class.java) + Mockito.`when`(device.address).thenReturn(deviceAddress) + Mockito.`when`(gatt.device).thenReturn(device) + + Mockito.`when`(service.uuid).thenReturn(serviceUuid) + Mockito.`when`(characteristic.uuid).thenReturn(charUuid) + Mockito.`when`(characteristic.service).thenReturn(service) + Mockito.`when`(characteristic.properties).thenReturn( + BluetoothGattCharacteristic.PROPERTY_READ or + BluetoothGattCharacteristic.PROPERTY_WRITE or + BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, + ) + Mockito.`when`(service.getCharacteristic(charUuid)).thenReturn(characteristic) + Mockito.`when`(gatt.getService(serviceUuid)).thenReturn(service) + // JVM tests run with Build.VERSION.SDK_INT == 0, so the pre-33 overloads + // are the ones reached. The stack accepts each operation unless a test + // says otherwise, as it does on a live link. + Mockito.`when`( + gatt.writeCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) + ).thenReturn(true) + Mockito.`when`( + gatt.readCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) + ).thenReturn(true) + Mockito.`when`( + gatt.readDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) + ).thenReturn(true) + Mockito.`when`( + gatt.writeDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) + ).thenReturn(true) + Mockito.`when`( + gatt.setCharacteristicNotification( + Mockito.any(BluetoothGattCharacteristic::class.java), + Mockito.anyBoolean(), + ) + ).thenReturn(true) + } + + private fun plugin(): UniversalBlePlugin { + val plugin = UniversalBlePlugin() + // Completions are posted to the main looper; run them inline so the test + // observes them synchronously. + val handler = Mockito.mock(Handler::class.java) + Mockito.doAnswer { invocation -> + invocation.getArgument(0).run() + true + }.`when`(handler).post(Mockito.any()) + plugin.setField("mainThreadHandler", handler) + return plugin + } + + /** A plugin with an autoConnect client that has reported STATE_CONNECTED. */ + private fun connectedAutoConnectPlugin(): UniversalBlePlugin { + val plugin = plugin() + plugin.autoConnectDevices().add(deviceAddress) + plugin.gattRegistry().put(gatt) + report(plugin, BluetoothGatt.STATE_CONNECTED) + return plugin + } + + private fun report(plugin: UniversalBlePlugin, state: Int, status: Int = BluetoothGatt.GATT_SUCCESS) { + plugin.onConnectionStateChange(gatt, status, state) + } + + private fun UniversalBlePlugin.pendingWrites(): MutableList = + getField("writeResultFutureList") + + private fun UniversalBlePlugin.pendingDescriptorWrites(): MutableList = + getField("writeDescriptorResultFutureList") + + private fun UniversalBlePlugin.pendingReads(): MutableList = + getField("readResultFutureList") + + private fun UniversalBlePlugin.pendingDescriptorReads(): MutableList = + getField("readDescriptorResultFutureList") + + private fun UniversalBlePlugin.pendingSubscriptions(): MutableList = + getField("subscriptionResultFutureList") + + private fun errorCode(result: Result<*>): String? = + (result.exceptionOrNull() as? FlutterError)?.code + + private fun assertDeviceDisconnected(result: Result<*>) { + assertEquals( + UniversalBleErrorCode.DEVICE_DISCONNECTED.raw.toString(), + errorCode(result), + ) + } + + private fun write(plugin: UniversalBlePlugin, acks: MutableList>) { + plugin.writeValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + ByteArray(12), + BleOutputProperty.WITHOUT_RESPONSE, + ) { acks.add(it) } + } + + private fun writeWithResponse(plugin: UniversalBlePlugin, acks: MutableList>) { + plugin.writeValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + ByteArray(12), + BleOutputProperty.WITH_RESPONSE, + ) { acks.add(it) } + } + + @Test + fun aWriteAfterALinkLossFailsImmediatelyAndNeverReachesTheStack() { + val plugin = connectedAutoConnectPlugin() + // The link drops; autoConnect keeps the client open and its services + // cached, so writeValue can still find the characteristic. + report(plugin, BluetoothGatt.STATE_DISCONNECTED) + + val acks = mutableListOf>() + write(plugin, acks) + + assertEquals(1, acks.size, "the write must fail instead of waiting for the Dart timeout") + assertDeviceDisconnected(acks.single()) + assertTrue(plugin.pendingWrites().isEmpty(), "a refused write must not stay pending") + assertTrue( + plugin.awaitingReconnectGatts().contains(gatt), + "autoConnect keeps the client open for the system to reconnect", + ) + Mockito.verify(gatt, Mockito.never()) + .writeCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) + } + + @Test + fun aWriteAfterTheAutoReconnectCompletesOnItsOwnCallback() { + val plugin = connectedAutoConnectPlugin() + report(plugin, BluetoothGatt.STATE_DISCONNECTED) + val refused = mutableListOf>() + write(plugin, refused) + assertTrue(refused.single().isFailure) + + // Android reconnects the same BluetoothGatt instance. + report(plugin, BluetoothGatt.STATE_CONNECTED) + assertTrue( + plugin.awaitingReconnectGatts().isEmpty(), + "the client is connected again, so nothing is waiting for a reconnect", + ) + val acks = mutableListOf>() + writeWithResponse(plugin, acks) + + assertEquals(1, plugin.pendingWrites().size, "the write must await its own callback") + plugin.onCharacteristicWrite(gatt, characteristic, BluetoothGatt.GATT_SUCCESS) + + assertEquals(1, acks.size) + assertTrue(acks.single().isSuccess, "the write must complete, not lag by one") + assertTrue(plugin.pendingWrites().isEmpty()) + } + + @Test + fun aRequestLeftFromThePreviousLinkIsFailedOnReconnect() { + val plugin = connectedAutoConnectPlugin() + report(plugin, BluetoothGatt.STATE_DISCONNECTED) + // A request that the submission gate cannot cover (or one that slipped + // in before the disconnect was processed) outlives its link. + val stale = mutableListOf>() + plugin.pendingWrites().add( + WriteResultFuture(gatt, deviceAddress, charUuid.toString(), serviceUuid.toString()) { + stale.add(it) + } + ) + + report(plugin, BluetoothGatt.STATE_CONNECTED) + + assertEquals(1, stale.size, "the new link must not inherit the previous one's request") + assertDeviceDisconnected(stale.single()) + assertTrue( + plugin.pendingWrites().isEmpty(), + "a stale entry must not consume the new link's first write completion", + ) + + val acks = mutableListOf>() + writeWithResponse(plugin, acks) + plugin.onCharacteristicWrite(gatt, characteristic, BluetoothGatt.GATT_SUCCESS) + assertEquals(1, acks.size) + assertTrue(acks.single().isSuccess) + } + + @Test + fun theBackstopTouchesOnlyTheReconnectingClient() { + val plugin = plugin() + val reconnecting = gatt + val other = Mockito.mock(BluetoothGatt::class.java) + val otherDevice = Mockito.mock(BluetoothDevice::class.java) + val otherAddress = "11:22:33:44:55:66" + Mockito.`when`(otherDevice.address).thenReturn(otherAddress) + Mockito.`when`(other.device).thenReturn(otherDevice) + plugin.autoConnectDevices().add(deviceAddress) + plugin.gattRegistry().put(other) + plugin.connectedGatts().add(other) + plugin.gattRegistry().put(reconnecting) + plugin.connectedGatts().add(reconnecting) + + val otherResult = mutableListOf>() + plugin.pendingWrites().add( + WriteResultFuture(other, otherAddress, charUuid.toString(), serviceUuid.toString()) { + otherResult.add(it) + } + ) + val reconnectingResult = mutableListOf>() + plugin.pendingWrites().add( + WriteResultFuture( + reconnecting, deviceAddress, charUuid.toString(), serviceUuid.toString() + ) { reconnectingResult.add(it) } + ) + + report(plugin, BluetoothGatt.STATE_DISCONNECTED) + report(plugin, BluetoothGatt.STATE_CONNECTED) + + assertEquals(0, otherResult.size, "another device's write is still in flight") + assertEquals(1, plugin.pendingWrites().size) + assertEquals(1, reconnectingResult.size) + assertDeviceDisconnected(reconnectingResult.single()) + } + + @Test + fun aDuplicateConnectedCallbackDoesNotFailRequestsInFlight() { + val plugin = connectedAutoConnectPlugin() + val acks = mutableListOf>() + writeWithResponse(plugin, acks) + + // No link loss in between: a repeated STATE_CONNECTED is not a new link. + report(plugin, BluetoothGatt.STATE_CONNECTED) + + assertTrue(acks.isEmpty(), "a write in flight must not be failed by a repeated event") + assertEquals(1, plugin.pendingWrites().size) + } + + @Test + fun readsDescriptorWritesAndSubscriptionsAreRefusedAfterALinkLoss() { + val plugin = connectedAutoConnectPlugin() + val cccd = Mockito.mock(BluetoothGattDescriptor::class.java) + Mockito.`when`(cccd.uuid).thenReturn(cccdUuid) + Mockito.`when`(cccd.characteristic).thenReturn(characteristic) + Mockito.`when`(characteristic.getDescriptor(cccdUuid)).thenReturn(cccd) + val descriptor = Mockito.mock(BluetoothGattDescriptor::class.java) + Mockito.`when`(descriptor.uuid).thenReturn(descriptorUuid) + Mockito.`when`(descriptor.characteristic).thenReturn(characteristic) + Mockito.`when`(characteristic.getDescriptor(descriptorUuid)).thenReturn(descriptor) + + report(plugin, BluetoothGatt.STATE_DISCONNECTED) + + val reads = mutableListOf>() + plugin.readValue(deviceAddress, serviceUuid.toString(), charUuid.toString()) { + reads.add(it) + } + assertEquals(1, reads.size) + assertDeviceDisconnected(reads.single()) + + val descriptorReads = mutableListOf>() + plugin.readDescriptorValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + descriptorUuid.toString(), + ) { descriptorReads.add(it) } + assertEquals(1, descriptorReads.size) + assertDeviceDisconnected(descriptorReads.single()) + + val descriptorWrites = mutableListOf>() + plugin.writeDescriptorValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + descriptorUuid.toString(), + ByteArray(4), + ) { descriptorWrites.add(it) } + assertEquals(1, descriptorWrites.size) + assertDeviceDisconnected(descriptorWrites.single()) + + val subscriptions = mutableListOf>() + plugin.setNotifiable( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + BleInputProperty.NOTIFICATION, + ) { subscriptions.add(it) } + assertEquals(1, subscriptions.size) + assertDeviceDisconnected(subscriptions.single()) + + assertTrue(plugin.pendingReads().isEmpty()) + assertTrue(plugin.pendingDescriptorReads().isEmpty()) + assertTrue(plugin.pendingDescriptorWrites().isEmpty()) + assertTrue(plugin.pendingSubscriptions().isEmpty()) + Mockito.verify(gatt, Mockito.never()) + .readCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) + Mockito.verify(gatt, Mockito.never()) + .readDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) + Mockito.verify(gatt, Mockito.never()) + .writeDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) + } +} diff --git a/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt b/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt index 7c31071f..882fe89f 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt @@ -1,5 +1,7 @@ package com.navideck.universal_ble +import android.bluetooth.BluetoothGatt + /** * Shared access to [UniversalBlePlugin]'s private state for unit tests. Kept in * one place so a renamed field breaks a single helper instead of every test. @@ -18,3 +20,26 @@ internal fun UniversalBlePlugin.getField(name: String): T { } internal fun UniversalBlePlugin.gattRegistry(): GattRegistry = getField("gattRegistry") + +@Suppress("UNCHECKED_CAST") +internal fun UniversalBlePlugin.connectedGatts(): MutableSet = + getField("connectedGatts") + +@Suppress("UNCHECKED_CAST") +internal fun UniversalBlePlugin.awaitingReconnectGatts(): MutableSet = + getField("awaitingReconnectGatts") + +@Suppress("UNCHECKED_CAST") +internal fun UniversalBlePlugin.autoConnectDevices(): MutableSet = + getField("autoConnectDevices") + +/** + * Registers [gatt] as the plugin's client and marks its link up, as a + * `STATE_CONNECTED` callback does. Requests submitted through the public API + * require both: without a live link they are refused with `deviceDisconnected` + * instead of reaching the stack (#394). + */ +internal fun UniversalBlePlugin.attachConnectedGatt(gatt: BluetoothGatt) { + gattRegistry().put(gatt) + connectedGatts().add(gatt) +} diff --git a/android/src/test/kotlin/com/navideck/universal_ble/WriteRefusalTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/WriteRefusalTest.kt index 1fe32443..e2aada69 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/WriteRefusalTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/WriteRefusalTest.kt @@ -67,7 +67,7 @@ internal class WriteRefusalTest { } private fun pluginWithGatt(): UniversalBlePlugin = - pluginWithInlineHandler().also { it.gattRegistry().put(gatt) } + pluginWithInlineHandler().also { it.attachConnectedGatt(gatt) } private fun UniversalBlePlugin.pendingWrites(): List = getField("writeResultFutureList") diff --git a/example/pubspec.lock b/example/pubspec.lock index db18dba3..176e2e85 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -426,7 +426,7 @@ packages: path: ".." relative: true source: path - version: "3.4.0" + version: "3.4.1" vector_math: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index e3036886..49987ac9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: universal_ble description: A cross-platform (Android/iOS/macOS/Windows/Linux/Web) Bluetooth Low Energy (BLE) plugin for Flutter -version: 3.4.0 +version: 3.4.1 homepage: https://navideck.com repository: https://github.com/Navideck/universal_ble issue_tracker: https://github.com/Navideck/universal_ble/issues From 870ab02ab9184f1fb27a346ffdd7f93e926a5ded Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:58:07 +0100 Subject: [PATCH 02/13] Linux/Web: name a disconnected device in GATT request failures (#394) Neither platform supports autoConnect, so a dropped link removes the GATT objects (BlueZ) or clears the service cache (Web) instead of leaving a client open. A request submitted while disconnected therefore failed as 'characteristic not found' on Linux, and on Web as an unclassified browser NetworkError or a missing characteristic, even though the device was still known and simply not connected. Resolve the device once and refuse the request with deviceDisconnected when the link is down, for reads, writes, descriptor reads/writes and subscriptions - the same set Android gates. A BlueZ device is checked through the platform's Connected property; on Web the connection state comes from the dependency's seeded connected stream, as getConnectionState already reads it. Unknown devices now report deviceNotFound on Web too. --- .../universal_ble_linux.dart | 29 +++++++++++++----- .../universal_ble_web/universal_ble_web.dart | 30 +++++++++++++++++++ 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/lib/src/universal_ble_linux/universal_ble_linux.dart b/lib/src/universal_ble_linux/universal_ble_linux.dart index 57b9eef3..8bcd979a 100644 --- a/lib/src/universal_ble_linux/universal_ble_linux.dart +++ b/lib/src/universal_ble_linux/universal_ble_linux.dart @@ -245,7 +245,9 @@ class UniversalBleLinux extends UniversalBlePlatform { String service, String characteristic, ) { - final device = _findDeviceById(deviceId); + // Every GATT request resolves its characteristic here, so the link check + // covers reads, writes, descriptors and subscriptions in one place. + final device = _findConnectedDevice(deviceId); final s = device.gattServices.cast().firstWhere( (s) => s?.uuid.toString() == service, orElse: () => null, @@ -463,13 +465,7 @@ class UniversalBleLinux extends UniversalBlePlatform { @override Future requestMtu(String deviceId, int expectedMtu) async { - final device = _findDeviceById(deviceId); - if (!device.connected) { - throw UniversalBleException( - code: UniversalBleErrorCode.deviceDisconnected, - message: 'Device not connected', - ); - } + final device = _findConnectedDevice(deviceId); for (BlueZGattService service in device.gattServices) { for (BlueZGattCharacteristic characteristic in service.characteristics) { int? mtu = characteristic.mtu; @@ -572,6 +568,23 @@ class UniversalBleLinux extends UniversalBlePlatform { return device; } + /// [deviceId]'s device, provided its link is up. + /// + /// BlueZ drops a device's GATT object tree when the link goes down, so a + /// request submitted while disconnected otherwise fails as "characteristic + /// not found" — as if the device had changed its services. Name the real + /// condition instead, as Android and Apple do. + BlueZDevice _findConnectedDevice(String deviceId) { + final device = _findDeviceById(deviceId); + if (!device.connected) { + throw UniversalBleException( + code: UniversalBleErrorCode.deviceDisconnected, + message: 'Device not connected', + ); + } + return device; + } + /// Get device by id from cache or from client BlueZDevice? _getDeviceById(String deviceId) { // Every Linux device resolution funnels through here, so this is where the id becomes the diff --git a/lib/src/universal_ble_web/universal_ble_web.dart b/lib/src/universal_ble_web/universal_ble_web.dart index 77a9af39..9663b556 100644 --- a/lib/src/universal_ble_web/universal_ble_web.dart +++ b/lib/src/universal_ble_web/universal_ble_web.dart @@ -368,6 +368,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "SET_NOTIFY -> $deviceId $service $characteristic input=${bleInputProperty.name}", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); final bleCharacteristic = await _getBleCharacteristic( deviceId: deviceId, serviceId: service, @@ -426,6 +427,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "WRITE -> $deviceId $service $characteristic len=${value.length} property=${bleOutputProperty.name}", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); final bleCharacteristic = await _getBleCharacteristic( deviceId: deviceId, serviceId: service, @@ -460,6 +462,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "READ -> $deviceId $service $characteristic", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); var bleCharacteristic = await _getBleCharacteristic( deviceId: deviceId, serviceId: service, @@ -490,6 +493,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "READ_DESCRIPTOR -> $deviceId $service $characteristic $descriptor", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); var bleDescriptor = await _getBleDescriptor( deviceId: deviceId, serviceId: service, @@ -519,6 +523,7 @@ class UniversalBleWeb extends UniversalBlePlatform { "WRITE_DESCRIPTOR -> $deviceId $service $characteristic $descriptor len=${value.length}", withTimestamp: true, ); + await _requireConnectedDevice(deviceId); var bleDescriptor = await _getBleDescriptor( deviceId: deviceId, serviceId: service, @@ -677,6 +682,31 @@ class UniversalBleWeb extends UniversalBlePlatform { BluetoothDevice? _getDeviceById(String id) => _bluetoothDeviceList[id]; + /// [deviceId]'s device, provided its GATT link is up. + /// + /// Web Bluetooth rejects a GATT operation on a disconnected device with a + /// generic `NetworkError`, and the service cache is cleared on disconnection, + /// so without this the call would surface an unclassified error — or + /// "characteristic not found" — instead of naming the condition, as Android + /// and Apple do. + Future _requireConnectedDevice(String deviceId) async { + final device = _getDeviceById(deviceId); + if (device == null) { + throw UniversalBleException( + code: UniversalBleErrorCode.deviceNotFound, + message: '$deviceId Not Found', + ); + } + // `connected` is seeded with the current GATT state, so the first event is + // the live value (the same way getConnectionState reads it). + if (!await device.connected.first) { + throw UniversalBleException( + code: UniversalBleErrorCode.deviceDisconnected, + message: 'Device $deviceId is not connected', + ); + } + } + /// Get services and their characteristics. /// Services and characteristics are cached. /// Clears cache on disconnection. From 595d00d197fe3cf77daf443180c317c46044e2c9 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:58:11 +0100 Subject: [PATCH 03/13] Windows: refuse GATT requests on a link that is already down (#394) A Windows connection has no autoConnect, but the agent stays registered until the ConnectionStatusChanged handler runs. A request submitted between the drop and that callback was issued to WinRT anyway and completed with Unreachable, which maps to failed rather than deviceDisconnected. Check the link before issuing a read, write, descriptor read/write or subscription, and refuse it with deviceDisconnected. A status read that throws counts as connected so the operation still reports the real error. --- windows/src/universal_ble_plugin.cpp | 43 ++++++++++++++++++++++++++++ windows/src/universal_ble_plugin.h | 7 +++++ 2 files changed, 50 insertions(+) diff --git a/windows/src/universal_ble_plugin.cpp b/windows/src/universal_ble_plugin.cpp index 4561310e..6acef467 100644 --- a/windows/src/universal_ble_plugin.cpp +++ b/windows/src/universal_ble_plugin.cpp @@ -586,6 +586,11 @@ void UniversalBlePlugin::ReadValue( characteristic); const GattCharacteristic gatt_characteristic = gatt_characteristic_lease.characteristic.obj; + if (!HasLiveLink(bluetooth_agent)) { + result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, + "Device Disconnected")); + return; + } const auto properties = gatt_characteristic.CharacteristicProperties(); if ((properties & GattCharacteristicProperties::Read) == @@ -679,6 +684,11 @@ void UniversalBlePlugin::WriteValue( characteristic); const GattCharacteristic gatt_characteristic = gatt_characteristic_lease.characteristic.obj; + if (!HasLiveLink(bluetooth_agent)) { + result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, + "Device Disconnected")); + return; + } const auto properties = gatt_characteristic.CharacteristicProperties(); auto write_option = GattWriteOption::WriteWithResponse; @@ -785,6 +795,11 @@ void UniversalBlePlugin::ReadDescriptorValue( characteristic); const GattCharacteristic gatt_characteristic = gatt_characteristic_lease.characteristic.obj; + if (!HasLiveLink(bluetooth_agent)) { + result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, + "Device Disconnected")); + return; + } gatt_characteristic .GetDescriptorsForUuidAsync(uuid_to_guid(descriptor), @@ -920,6 +935,11 @@ void UniversalBlePlugin::WriteDescriptorValue( characteristic); const GattCharacteristic gatt_characteristic = gatt_characteristic_lease.characteristic.obj; + if (!HasLiveLink(bluetooth_agent)) { + result(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, + "Device Disconnected")); + return; + } gatt_characteristic .GetDescriptorsForUuidAsync(uuid_to_guid(descriptor), @@ -2442,6 +2462,22 @@ std::shared_ptr UniversalBlePlugin::GetConnectedDevice( return it == connected_devices_.end() ? nullptr : it->second; } +bool UniversalBlePlugin::HasLiveLink( + const std::shared_ptr &device_agent) { + if (!device_agent || !device_agent->IsActive()) return false; + try { + return device_agent->device.ConnectionStatus() == + BluetoothConnectionStatus::Connected; + } catch (const hresult_error &err) { + UniversalBleLogger::LogWarning( + "HasLiveLink: ConnectionStatus hresult_error hr=" + + std::to_string(err.code())); + } catch (...) { + UniversalBleLogger::LogWarning("HasLiveLink: ConnectionStatus failed"); + } + return true; +} + void UniversalBlePlugin::InvalidateConnectAttempt( const uint64_t bluetooth_address) { std::lock_guard lock(connected_devices_mutex_); @@ -3072,6 +3108,13 @@ fire_and_forget UniversalBlePlugin::SetNotifiableAsync( stage = "lookup-characteristic"; auto gatt_char = device_agent->FetchCharacteristic(service, characteristic); + stage = "check-link"; + if (!HasLiveLink(device_agent)) { + reply(create_flutter_error(UniversalBleErrorCode::kDeviceDisconnected, + "Device Disconnected")); + co_return; + } + const auto properties = gatt_char.obj.CharacteristicProperties(); auto descriptor_value = GattClientCharacteristicConfigurationDescriptorValue::None; diff --git a/windows/src/universal_ble_plugin.h b/windows/src/universal_ble_plugin.h index 88c81774..c916ded8 100644 --- a/windows/src/universal_ble_plugin.h +++ b/windows/src/universal_ble_plugin.h @@ -483,6 +483,13 @@ class UniversalBlePlugin : public flutter::Plugin, const IInspectable &args); std::shared_ptr GetConnectedDevice( uint64_t bluetooth_address); + /// Whether [device_agent] still has a live link. + /// + /// The agent stays registered until WinRT reports the drop, so a request + /// submitted in between would otherwise be issued and fail with an unrelated + /// GATT status (Unreachable maps to `failed`). A status read that throws + /// counts as connected: the operation itself reports the real error. + bool HasLiveLink(const std::shared_ptr &device_agent); void InvalidateConnectAttempt(uint64_t bluetooth_address); std::shared_ptr RemoveConnectedDevice( uint64_t bluetooth_address, From 0c159f79ca7d6bdfbdf96141f2e8715babe497ad Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:58:11 +0100 Subject: [PATCH 04/13] Apple: refuse GATT requests on a disconnected peripheral (#394) Only writeValue and discoverServices guarded on peripheral.state, so a read, descriptor read/write or subscription submitted while the peripheral was disconnected was handed to CoreBluetooth, which cannot serve it. Guard them the same way writeValue does since #378: characteristic/descriptor lookup first, then deviceDisconnected. No test: these paths need a connected CBPeripheral. The sources typecheck against FlutterMacOS.framework and the isolated Apple test helpers still pass. --- .../universal_ble/UniversalBlePlugin.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift index 1b4065db..1c5ffdfd 100644 --- a/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift +++ b/darwin/universal_ble/Sources/universal_ble/UniversalBlePlugin.swift @@ -549,6 +549,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } if bleInputProperty == .notification && !gattCharacteristic.properties.contains(.notify) { completion(Result.failure(createFlutterError(code: .characteristicDoesNotSupportNotify, message: "Characteristic does not support notify"))) @@ -575,6 +579,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Unknown characteristic:\(characteristic)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } if !gattCharacteristic.properties.contains(.read) { completion(Result.failure(createFlutterError(code: .characteristicDoesNotSupportRead, message: "Characteristic does not support read"))) return @@ -657,6 +665,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Descriptor not found:\(descriptor)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } peripheral.readValue(for: gattDescriptor) descriptorReadFutures.append(DescriptorReadFuture( deviceId: deviceId, @@ -677,6 +689,10 @@ private class BleCentralDarwin: NSObject, UniversalBlePlatformChannel, CBCentral completion(Result.failure(createFlutterError(code: .characteristicNotFound, message: "Descriptor not found:\(descriptor)"))) return } + guard peripheral.state == .connected else { + completion(Result.failure(createFlutterError(code: .deviceDisconnected, message: "Device Disconnected"))) + return + } // CoreBluetooth throws NSInternalInconsistencyException if writeValue:forDescriptor: is called on CCCD (0x2902). // CoreBluetooth requires using setNotifyValue:forCharacteristic: for CCCD. From ef02884785f063969787f21b5e72004f4f443288 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 20:58:11 +0100 Subject: [PATCH 05/13] Document the platform-wide disconnect behaviour --- CHANGELOG.md | 4 ++++ README.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 49ad7da4..4287f85a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ ## 3.4.1 +* Linux: a read, write, descriptor read/write or subscription submitted while the device is disconnected now fails with `deviceDisconnected` instead of `characteristicNotFound` or a generic `readFailed`/`writeFailed`. BlueZ drops the GATT object tree together with the link, so the lookup used to report the characteristic as unknown — as if the device had changed its services — and a request that reached D-Bus failed with `NotConnected` under a generic code (#394). +* Web: the same requests now fail with `deviceDisconnected` instead of surfacing the browser's `NetworkError` as an unclassified error, and an unknown device reports `deviceNotFound` instead of a missing characteristic. The service cache is cleared on disconnection, so the lookup previously failed before the browser could say the link was gone (#394). +* Windows: the same requests now fail with `deviceDisconnected` when the link is down but the connection-status callback has not removed the client yet. The operation used to be submitted anyway and completed with `Unreachable`, which surfaced as `failed` (#394). +* Apple: reads, descriptor reads and writes, and subscriptions now refuse a disconnected peripheral with `deviceDisconnected`, as `writeValue` already did since #378, instead of submitting a request the peripheral cannot serve (#394). * Android: a read, write, descriptor read/write or notification subscription submitted to an `autoConnect` client after its link dropped now fails right away with `deviceDisconnected` instead of reaching the stack. The client stays open and keeps its cached services after the link loss, and below API 33 the stack accepts such a request and then drops it without a callback, leaving a pending entry that the first callback of the reconnected link completes — so every later write lagged by one and timed out after 10 s, giving about one write per timeout. The link check shares the lock with the disconnect cleanup, so a request submitted concurrently is either registered in time to be swept or refused; as a backstop, a client whose link comes back now also fails anything still pending from the previous link. `readDescriptorValue` registers its pending result before issuing the read, as `readValue` already did (#394). ## 3.4.0 diff --git a/README.md b/README.md index 5f60665d..54a19ae3 100644 --- a/README.md +++ b/README.md @@ -348,7 +348,7 @@ You can enable automatic reconnection by setting the `autoConnect` parameter to await bleDevice.connect(autoConnect: true); ``` -While the link is down — after the plugin reports a disconnection and before the system reconnects the client — a read, write, descriptor access or subscription to that device fails right away on Android with `UniversalBleErrorCode.deviceDisconnected` instead of waiting for the request timeout. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. +While the link is down — after the plugin reports a disconnection and before the system reconnects the client — a read, write, descriptor access or subscription to that device fails right away with `UniversalBleErrorCode.deviceDisconnected` instead of waiting for the request timeout. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. #### Background connection events (iOS/macOS) From 0e471ad3795932cecf1ab6c579fe284695b80dd2 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:09:00 +0100 Subject: [PATCH 06/13] Share the Android test fixture for GATT wiring Ten test classes rebuilt the same mock device, gatt, service, characteristic and main-looper handler, and most of them repeated the reflection keys for the pending-operation lists. A change to the plugin's internals, or to PluginTestSupport's reflection helpers, had to be mirrored a dozen times. Add GattFixture (one mock peripheral: gatt + service + characteristic + descriptors, optional stack-accepting stubs), pluginWithInlineLooper / pluginWithRecordedLooper with drainPosts, mockGatt / mockCharacteristic, and typed pending-list accessors in PluginTestSupport. Migrate the test classes onto them; no test logic changes. --- .../universal_ble/DisconnectCloseTest.kt | 48 ++--- .../GattCallbackCompletionTest.kt | 173 +++++++----------- .../com/navideck/universal_ble/GattFixture.kt | 153 ++++++++++++++++ .../universal_ble/GattOwnershipTest.kt | 34 +--- .../universal_ble/LinkLossOperationTest.kt | 106 ++--------- .../universal_ble/MtuCompletionTest.kt | 21 +-- .../NotificationOwnershipTest.kt | 45 ++--- .../universal_ble/PluginTestSupport.kt | 27 +++ .../ScanCallbackConnectableTest.kt | 8 +- .../universal_ble/WriteCompletionTest.kt | 44 +---- .../universal_ble/WriteRefusalTest.kt | 65 ++----- 11 files changed, 317 insertions(+), 407 deletions(-) create mode 100644 android/src/test/kotlin/com/navideck/universal_ble/GattFixture.kt diff --git a/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt index 9faaf87d..8535e535 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt @@ -38,34 +38,18 @@ internal class DisconnectCloseTest { null } - private fun plugin(): UniversalBlePlugin { - val plugin = UniversalBlePlugin() - // Callbacks are posted to the main looper; run them inline. - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { invocation -> - invocation.getArgument(0).run() - true - }.`when`(handler).post(any()) - plugin.setField("mainThreadHandler", handler) - plugin.setField("callbackChannel", callbackChannel) - return plugin - } + private fun plugin(): UniversalBlePlugin = + pluginWithInlineLooper().also { it.setField("callbackChannel", callbackChannel) } private fun closingGatts(plugin: UniversalBlePlugin): MutableSet = plugin.getField("closingGatts") - private fun mockGatt(): BluetoothGatt { - val device = Mockito.mock(BluetoothDevice::class.java) - Mockito.`when`(device.address).thenReturn(deviceAddress) - val gatt = Mockito.mock(BluetoothGatt::class.java) - Mockito.`when`(gatt.device).thenReturn(device) - return gatt - } + @Test fun closingClientIsClosedAndReportedOnDisconnect() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(deviceAddress) closingGatts(plugin).add(gatt) plugin.onConnectionStateChange( @@ -80,7 +64,7 @@ internal class DisconnectCloseTest { @Test fun peerDisconnectAfterConnectReportsDeviceDisconnected() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(deviceAddress) plugin.gattRegistry().put(gatt) plugin.onConnectionStateChange( @@ -108,7 +92,7 @@ internal class DisconnectCloseTest { @Test fun disconnectBeforeConnectReportsConnectionFailed() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(deviceAddress) plugin.gattRegistry().put(gatt) plugin.onConnectionStateChange( @@ -132,8 +116,8 @@ internal class DisconnectCloseTest { @Test fun supersededClientConnectIsNotReported() { val plugin = plugin() - val oldGatt = mockGatt() - val newGatt = mockGatt() + val oldGatt = mockGatt(deviceAddress) + val newGatt = mockGatt(deviceAddress) plugin.gattRegistry().put(newGatt) plugin.onConnectionStateChange( @@ -146,8 +130,8 @@ internal class DisconnectCloseTest { @Test fun supersededClientClosesWithoutTouchingTheNewOne() { val plugin = plugin() - val oldGatt = mockGatt() - val newGatt = mockGatt() + val oldGatt = mockGatt(deviceAddress) + val newGatt = mockGatt(deviceAddress) closingGatts(plugin).add(oldGatt) plugin.gattRegistry().put(newGatt) @@ -163,7 +147,7 @@ internal class DisconnectCloseTest { @Test fun connectThatReportsBeforeItIsRegisteredIsStillDelivered() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(deviceAddress) val device = Mockito.mock(BluetoothDevice::class.java) Mockito.`when`(device.address).thenReturn(deviceAddress) // connectGatt() is given no Handler, so the stack can report CONNECTED @@ -201,7 +185,7 @@ internal class DisconnectCloseTest { @Test fun connectStateFromAClientBeingClosedIsDropped() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(deviceAddress) // disconnect() is tearing this client down; it must not come back as a // connection for the address. closingGatts(plugin).add(gatt) @@ -217,11 +201,11 @@ internal class DisconnectCloseTest { fun replacedClientDisconnectDoesNotReportOrFailTheNewConnection() { val plugin = plugin() // connect() replaced the client, so the old one is never in closingGatts. - val replaced = mockGatt() - val current = mockGatt() + val replaced = mockGatt(deviceAddress) + val current = mockGatt(deviceAddress) plugin.gattRegistry().put(current) val reads = mutableListOf>() - plugin.getField>("readResultFutureList").add( + plugin.pendingReads().add( ReadResultFuture(current, deviceAddress, charUuid.toString(), serviceUuid.toString()) { reads.add(it) } @@ -238,7 +222,7 @@ internal class DisconnectCloseTest { assertTrue(reads.isEmpty(), "the current connection's read is still in flight") assertEquals( 1, - plugin.getField>("readResultFutureList").size + plugin.pendingReads().size ) Mockito.verify(replaced).close() } diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt index d6e3b9ea..c74ed315 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt @@ -34,46 +34,17 @@ internal class GattCallbackCompletionTest { private val serviceUuid = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb") private val charUuid = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb") - private val requestGatt by lazy { mockGatt() } + private val requestGatt by lazy { mockGatt(deviceAddress) } /** Runnables the plugin posted to the main looper, in submission order. */ private val mainLooper = mutableListOf() - private fun plugin(): UniversalBlePlugin { - val plugin = UniversalBlePlugin() + private fun plugin(): UniversalBlePlugin = // Record instead of running: a completion must not be delivered on the // thread the callback arrived on. - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { invocation -> - mainLooper.add(invocation.getArgument(0)) - true - }.`when`(handler).post(Mockito.any()) - plugin.setField("mainThreadHandler", handler) - return plugin - } - - private fun drainMainLooper() { - while (mainLooper.isNotEmpty()) { - mainLooper.removeAt(0).run() - } - } - - private fun mockGatt(): BluetoothGatt { - val device = Mockito.mock(BluetoothDevice::class.java) - Mockito.`when`(device.address).thenReturn(deviceAddress) - val gatt = Mockito.mock(BluetoothGatt::class.java) - Mockito.`when`(gatt.device).thenReturn(device) - return gatt - } + pluginWithRecordedLooper(mainLooper) - private fun mockCharacteristic(): BluetoothGattCharacteristic { - val service = Mockito.mock(BluetoothGattService::class.java) - Mockito.`when`(service.uuid).thenReturn(serviceUuid) - val characteristic = Mockito.mock(BluetoothGattCharacteristic::class.java) - Mockito.`when`(characteristic.uuid).thenReturn(charUuid) - Mockito.`when`(characteristic.service).thenReturn(service) - return characteristic - } + private fun drainMainLooper() = drainPosts(mainLooper) private fun pluginWithPreferences(): UniversalBlePlugin { // Service discovery caches the discovered UUIDs in SharedPreferences. @@ -98,13 +69,13 @@ internal class GattCallbackCompletionTest { val plugin = plugin() val firstReads = mutableListOf>() val secondReads = mutableListOf>() - val pending = plugin.getField>("readResultFutureList") + val pending = plugin.pendingReads() pending.add(readFuture(firstReads)) pending.add(readFuture(secondReads)) plugin.onCharacteristicRead( requestGatt, - mockCharacteristic(), + mockCharacteristic(serviceUuid, charUuid), byteArrayOf(0x2A), BluetoothGatt.GATT_SUCCESS ) @@ -128,7 +99,7 @@ internal class GattCallbackCompletionTest { // Its own response completes the remaining read, exactly once. plugin.onCharacteristicRead( requestGatt, - mockCharacteristic(), + mockCharacteristic(serviceUuid, charUuid), byteArrayOf(0x2B), BluetoothGatt.GATT_SUCCESS ) @@ -143,13 +114,13 @@ internal class GattCallbackCompletionTest { val plugin = plugin() val firstReads = mutableListOf>() val secondReads = mutableListOf>() - val pending = plugin.getField>("readResultFutureList") + val pending = plugin.pendingReads() pending.add(readFuture(firstReads)) pending.add(readFuture(secondReads)) plugin.onCharacteristicRead( requestGatt, - mockCharacteristic(), + mockCharacteristic(serviceUuid, charUuid), byteArrayOf(), BluetoothGatt.GATT_FAILURE ) @@ -174,7 +145,7 @@ internal class GattCallbackCompletionTest { val plugin = plugin() val firstReadings = mutableListOf>() val secondReadings = mutableListOf>() - val pending = plugin.getField>("rssiResultFutureList") + val pending = plugin.pendingRssis() pending.add(RssiResultFuture(requestGatt, deviceAddress) { firstReadings.add(it) }) pending.add(RssiResultFuture(requestGatt, deviceAddress) { secondReadings.add(it) }) @@ -193,9 +164,7 @@ internal class GattCallbackCompletionTest { val plugin = plugin() val firstDiscoveries = mutableListOf>>() val secondDiscoveries = mutableListOf>>() - val pending = plugin.getField>( - "discoverServicesFutureList" - ) + val pending = plugin.pendingDiscoveries() pending.add(DiscoverServicesFuture(requestGatt, deviceAddress, false) { firstDiscoveries.add(it) }) pending.add(DiscoverServicesFuture(requestGatt, deviceAddress, true) { secondDiscoveries.add(it) }) @@ -221,9 +190,7 @@ internal class GattCallbackCompletionTest { val firstDiscoveries = mutableListOf>>() val secondDiscoveries = mutableListOf>>() - val pending = plugin.getField>( - "discoverServicesFutureList" - ) + val pending = plugin.pendingDiscoveries() pending.add(DiscoverServicesFuture(requestGatt, deviceAddress, false) { firstDiscoveries.add(it) }) pending.add(DiscoverServicesFuture(requestGatt, deviceAddress, false) { secondDiscoveries.add(it) }) // Only the client the registry holds may publish the service cache, so @@ -248,16 +215,14 @@ internal class GattCallbackCompletionTest { @Test fun subscriptionCompletionIsPostedToTheMainLooper() { val plugin = plugin() - val gatt = mockGatt() - val characteristic = mockCharacteristic() + val gatt = mockGatt(deviceAddress) + val characteristic = mockCharacteristic(serviceUuid, charUuid) val descriptor = Mockito.mock(BluetoothGattDescriptor::class.java) Mockito.`when`(descriptor.uuid).thenReturn(ccdCharacteristic) Mockito.`when`(descriptor.characteristic).thenReturn(characteristic) val subscriptions = mutableListOf>() - val pending = plugin.getField>( - "subscriptionResultFutureList" - ) + val pending = plugin.pendingSubscriptions() pending.add( SubscriptionResultFuture( gatt, @@ -286,9 +251,9 @@ internal class GattCallbackCompletionTest { @Test fun staleSubscriptionCallbackCannotCompleteReplacementConnection() { val plugin = plugin() - val oldGatt = mockGatt() - val currentGatt = mockGatt() - val characteristic = mockCharacteristic() + val oldGatt = mockGatt(deviceAddress) + val currentGatt = mockGatt(deviceAddress) + val characteristic = mockCharacteristic(serviceUuid, charUuid) fun descriptor(): BluetoothGattDescriptor { val descriptor = Mockito.mock(BluetoothGattDescriptor::class.java) Mockito.`when`(descriptor.uuid).thenReturn(ccdCharacteristic) @@ -298,9 +263,7 @@ internal class GattCallbackCompletionTest { val oldDescriptor = descriptor() val currentDescriptor = descriptor() val subscriptions = mutableListOf>() - val pending = plugin.getField>( - "subscriptionResultFutureList" - ) + val pending = plugin.pendingSubscriptions() pending.add( SubscriptionResultFuture( currentGatt, currentDescriptor, deviceAddress @@ -329,17 +292,15 @@ internal class GattCallbackCompletionTest { @Test fun rebuiltDescriptorStillCompletesItsSubscription() { val plugin = plugin() - val gatt = mockGatt() - val characteristic = mockCharacteristic() + val gatt = mockGatt(deviceAddress) + val characteristic = mockCharacteristic(serviceUuid, charUuid) val submitted = mockDescriptor(characteristic, "00002902-0000-1000-8000-00805f9b34fb") // A discoverServices() completing between the CCCD write and its // callback rebuilds the service tree, so the framework reports a new // descriptor object for the same attribute. val rebuilt = mockDescriptor(characteristic, "00002902-0000-1000-8000-00805f9b34fb") val results = mutableListOf>() - val pending = plugin.getField>( - "subscriptionResultFutureList" - ) + val pending = plugin.pendingSubscriptions() pending.add(SubscriptionResultFuture(gatt, submitted, deviceAddress) { results.add(it) }) // The CCCD of another characteristic carries the same descriptor UUID @@ -372,19 +333,19 @@ internal class GattCallbackCompletionTest { val discoveries = mutableListOf>>() val subscriptions = mutableListOf>() val rssis = mutableListOf>() - plugin.getField>("readResultFutureList") + plugin.pendingReads() .add(readFuture(reads)) - plugin.getField>("discoverServicesFutureList") + plugin.pendingDiscoveries() .add(DiscoverServicesFuture(requestGatt, deviceAddress, false) { discoveries.add(it) }) - plugin.getField>("subscriptionResultFutureList") + plugin.pendingSubscriptions() .add( SubscriptionResultFuture( - mockGatt(), + mockGatt(deviceAddress), Mockito.mock(BluetoothGattDescriptor::class.java), deviceAddress ) { subscriptions.add(it) } ) - plugin.getField>("rssiResultFutureList") + plugin.pendingRssis() .add(RssiResultFuture(requestGatt, deviceAddress) { rssis.add(it) }) plugin.disconnect(deviceAddress) @@ -417,7 +378,7 @@ internal class GattCallbackCompletionTest { fun readValueRegistersTheFutureBeforeTheReadCanRespond() { val plugin = plugin() val reads = mutableListOf>() - val characteristic = mockCharacteristic() + val characteristic = mockCharacteristic(serviceUuid, charUuid) val gatt = mockGattWithService(characteristic) // The stack can answer on a binder thread before readCharacteristic() // returns; a future registered only afterwards would never be matched @@ -442,7 +403,7 @@ internal class GattCallbackCompletionTest { assertTrue(reads[0].isSuccess) assertEquals(0x2A.toByte(), reads[0].getOrThrow().single()) assertTrue( - plugin.getField>("readResultFutureList").isEmpty(), + plugin.pendingReads().isEmpty(), "a completed read must leave the pending list" ) } @@ -451,7 +412,7 @@ internal class GattCallbackCompletionTest { fun rejectedReadLeavesNoPendingFuture() { val plugin = plugin() val reads = mutableListOf>() - val characteristic = mockCharacteristic() + val characteristic = mockCharacteristic(serviceUuid, charUuid) val gatt = mockGattWithService(characteristic) Mockito.`when`(gatt.readCharacteristic(characteristic)).thenReturn(false) plugin.attachConnectedGatt(gatt) @@ -463,7 +424,7 @@ internal class GattCallbackCompletionTest { assertEquals(1, reads.size) assertTrue(reads[0].isFailure) assertTrue( - plugin.getField>("readResultFutureList").isEmpty(), + plugin.pendingReads().isEmpty(), "a read the stack refused must not stay registered for a later callback" ) } @@ -473,7 +434,7 @@ internal class GattCallbackCompletionTest { for (throwsOnRead in listOf(false, true)) { val plugin = plugin() val reads = mutableListOf>() - val characteristic = mockCharacteristic() + val characteristic = mockCharacteristic(serviceUuid, charUuid) val gatt = mockGattWithService(characteristic) Mockito.`when`(gatt.readCharacteristic(characteristic)).thenAnswer { // A binder-thread disconnect can close the client before the read starts. @@ -497,7 +458,7 @@ internal class GattCallbackCompletionTest { UniversalBleErrorCode.DEVICE_DISCONNECTED.raw.toString(), (reads.single().exceptionOrNull() as FlutterError).code ) - assertTrue(plugin.getField>("readResultFutureList").isEmpty()) + assertTrue(plugin.pendingReads().isEmpty()) } } @@ -505,7 +466,7 @@ internal class GattCallbackCompletionTest { fun throwingReadLeavesNoPendingFuture() { val plugin = plugin() val reads = mutableListOf>() - val characteristic = mockCharacteristic() + val characteristic = mockCharacteristic(serviceUuid, charUuid) val gatt = mockGattWithService(characteristic) Mockito.`when`(gatt.readCharacteristic(characteristic)) .thenThrow(IllegalStateException("Read failed")) @@ -521,14 +482,14 @@ internal class GattCallbackCompletionTest { UniversalBleErrorCode.READ_FAILED.raw.toString(), (reads.single().exceptionOrNull() as FlutterError).code ) - assertTrue(plugin.getField>("readResultFutureList").isEmpty()) + assertTrue(plugin.pendingReads().isEmpty()) } @Test fun setNotifiableRegistersTheFutureBeforeTheCccdWriteCanRespond() { val plugin = plugin() val results = mutableListOf>() - val characteristic = mockCharacteristic() + val characteristic = mockCharacteristic(serviceUuid, charUuid) val cccd = mockDescriptor(characteristic, "00002902-0000-1000-8000-00805f9b34fb") Mockito.`when`(characteristic.getDescriptor(ccdCharacteristic)).thenReturn(cccd) val gatt = mockGattWithService(characteristic) @@ -541,9 +502,7 @@ internal class GattCallbackCompletionTest { true } plugin.attachConnectedGatt(gatt) - val pending = plugin.getField>( - "subscriptionResultFutureList" - ) + val pending = plugin.pendingSubscriptions() plugin.setNotifiable( deviceAddress, @@ -565,7 +524,7 @@ internal class GattCallbackCompletionTest { fun rejectedSubscriptionLeavesNoPendingFuture() { val plugin = plugin() val results = mutableListOf>() - val characteristic = mockCharacteristic() + val characteristic = mockCharacteristic(serviceUuid, charUuid) val cccd = mockDescriptor(characteristic, "00002902-0000-1000-8000-00805f9b34fb") Mockito.`when`(characteristic.getDescriptor(ccdCharacteristic)).thenReturn(cccd) val gatt = mockGattWithService(characteristic) @@ -582,9 +541,7 @@ internal class GattCallbackCompletionTest { assertEquals(1, results.size) assertTrue(results[0].isFailure) assertTrue( - plugin.getField>( - "subscriptionResultFutureList" - ).isEmpty(), + plugin.pendingSubscriptions().isEmpty(), "a write the stack refused must not stay registered for a later callback" ) } @@ -593,9 +550,9 @@ internal class GattCallbackCompletionTest { fun oldGattCallbacksDoNotConsumeReplacementRequests() { for (status in listOf(BluetoothGatt.GATT_SUCCESS, BluetoothGatt.GATT_FAILURE)) { val plugin = plugin() - val old = mockGatt() - val current = mockGatt() - val characteristic = mockCharacteristic() + val old = mockGatt(deviceAddress) + val current = mockGatt(deviceAddress) + val characteristic = mockCharacteristic(serviceUuid, charUuid) val descriptor = mockDescriptor(characteristic, "00002901-0000-1000-8000-00805f9b34fb") val cccd = mockDescriptor(characteristic, "00002902-0000-1000-8000-00805f9b34fb") val results = mutableListOf() @@ -623,10 +580,10 @@ internal class GattCallbackCompletionTest { @Test fun oldGattCleanupPreservesReplacementRequests() { val plugin = plugin() - val old = mockGatt() - val current = mockGatt() + val old = mockGatt(deviceAddress) + val current = mockGatt(deviceAddress) plugin.gattRegistry().put(current) - val characteristic = mockCharacteristic() + val characteristic = mockCharacteristic(serviceUuid, charUuid) val descriptor = mockDescriptor(characteristic, "00002901-0000-1000-8000-00805f9b34fb") val cccd = mockDescriptor(characteristic, "00002902-0000-1000-8000-00805f9b34fb") val oldResults = mutableListOf() @@ -649,8 +606,8 @@ internal class GattCallbackCompletionTest { @Test fun cleanupKeepsARequestWhoseClientIsRegisteredWhileItIsSwept() { val plugin = plugin() - val old = mockGatt() - val current = mockGatt() + val old = mockGatt(deviceAddress) + val current = mockGatt(deviceAddress) val results = mutableListOf>() val items = mutableListOf( ReadResultFuture( @@ -680,21 +637,21 @@ internal class GattCallbackCompletionTest { @Test fun cleanupFailsOperationsLeftByAClientThatIsNoLongerRegistered() { val plugin = plugin() - val current = mockGatt() - val superseded = mockGatt() + val current = mockGatt(deviceAddress) + val superseded = mockGatt(deviceAddress) plugin.gattRegistry().put(current) - val characteristic = mockCharacteristic() + val characteristic = mockCharacteristic(serviceUuid, charUuid) val cccd = mockDescriptor(characteristic, "00002902-0000-1000-8000-00805f9b34fb") // A client replaced by a newer connect() that never reported // STATE_DISCONNECTED keeps its futures registered (#277). val orphanResults = mutableListOf() - plugin.getField>("readResultFutureList") + plugin.pendingReads() .add( ReadResultFuture( superseded, deviceAddress, charUuid.toString(), serviceUuid.toString() ) { orphanResults.add(it.isSuccess) } ) - plugin.getField>("subscriptionResultFutureList") + plugin.pendingSubscriptions() .add(SubscriptionResultFuture(superseded, cccd, deviceAddress) { orphanResults.add(it.isSuccess) }) @@ -707,19 +664,17 @@ internal class GattCallbackCompletionTest { orphanResults, "cleanup for the address must not leave a superseded client's operations pending" ) - assertTrue(plugin.getField>("readResultFutureList").isEmpty()) + assertTrue(plugin.pendingReads().isEmpty()) assertTrue( - plugin.getField>( - "subscriptionResultFutureList" - ).isEmpty() + plugin.pendingSubscriptions().isEmpty() ) } @Test fun oldDiscoveryCannotOverwriteReplacementServiceCache() { val plugin = pluginWithPreferences() - val current = mockGatt() - val old = mockGatt() + val current = mockGatt(deviceAddress) + val old = mockGatt(deviceAddress) plugin.gattRegistry().put(current) // Stub the discovered services: Mockito's default empty list would make // the cache guard look exercised when it is not. @@ -748,19 +703,19 @@ internal class GattCallbackCompletionTest { cccd: BluetoothGattDescriptor, results: MutableList, ) { - plugin.getField>("readResultFutureList") + plugin.pendingReads() .add(ReadResultFuture(gatt, deviceAddress, charUuid.toString(), serviceUuid.toString()) { results.add(it.isSuccess) }) - plugin.getField>("writeResultFutureList") + plugin.pendingWrites() .add(WriteResultFuture(gatt, deviceAddress, charUuid.toString(), serviceUuid.toString()) { results.add(it.isSuccess) }) - plugin.getField>("rssiResultFutureList") + plugin.pendingRssis() .add(RssiResultFuture(gatt, deviceAddress) { results.add(it.isSuccess) }) - plugin.getField>("discoverServicesFutureList") + plugin.pendingDiscoveries() .add(DiscoverServicesFuture(gatt, deviceAddress, false) { results.add(it.isSuccess) }) - plugin.getField>("readDescriptorResultFutureList") + plugin.pendingDescriptorReads() .add(ReadDescriptorResultFuture(gatt, deviceAddress, descriptor.uuid.toString(), charUuid.toString(), serviceUuid.toString()) { results.add(it.isSuccess) }) - plugin.getField>("writeDescriptorResultFutureList") + plugin.pendingDescriptorWrites() .add(WriteDescriptorResultFuture(gatt, deviceAddress, descriptor.uuid.toString(), charUuid.toString(), serviceUuid.toString()) { results.add(it.isSuccess) }) - plugin.getField>("subscriptionResultFutureList") + plugin.pendingSubscriptions() .add(SubscriptionResultFuture(gatt, cccd, deviceAddress) { results.add(it.isSuccess) }) } @@ -771,7 +726,7 @@ internal class GattCallbackCompletionTest { val service = Mockito.mock(BluetoothGattService::class.java) Mockito.`when`(service.uuid).thenReturn(serviceUuid) Mockito.`when`(service.getCharacteristic(charUuid)).thenReturn(characteristic) - val gatt = mockGatt() + val gatt = mockGatt(deviceAddress) Mockito.`when`(gatt.getService(serviceUuid)).thenReturn(service) return gatt } diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattFixture.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattFixture.kt new file mode 100644 index 00000000..ceff76fe --- /dev/null +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattFixture.kt @@ -0,0 +1,153 @@ +package com.navideck.universal_ble + +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import android.bluetooth.BluetoothGattService +import android.os.Handler +import java.util.UUID +import org.mockito.Mockito + +/** + * Shared test wiring for the Android plugin's GATT paths. + * + * Every test used to rebuild the same mock device, gatt, service and + * characteristic, and the same main-looper handler. Keeping them here means a + * change to the plugin's internals (or to the reflection helpers in + * [PluginTestSupport]) is updated in one place instead of a dozen. + */ + +/** The address and UUIDs the fixtures default to. */ +internal object GattIds { + const val ADDRESS = "AA:BB:CC:DD:EE:FF" + const val OTHER_ADDRESS = "11:22:33:44:55:66" + + val SERVICE: UUID = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb") + val CHARACTERISTIC: UUID = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb") + val OTHER_CHARACTERISTIC: UUID = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb") + val CCCD: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") + val DESCRIPTOR: UUID = UUID.fromString("00002901-0000-1000-8000-00805f9b34fb") +} + +/** + * A plugin whose main-looper posts run inline. Use it when a test expects a + * completion to be observed synchronously. + */ +internal fun pluginWithInlineLooper(): UniversalBlePlugin = + UniversalBlePlugin().also { plugin -> + val handler = Mockito.mock(Handler::class.java) + Mockito.doAnswer { invocation -> + invocation.getArgument(0).run() + true + }.`when`(handler).post(Mockito.any()) + plugin.setField("mainThreadHandler", handler) + } + +/** + * A plugin that records main-looper posts instead of running them, so a test + * can assert that a completion is not delivered on a binder thread and can + * control when it runs. Drain it with [drainPosts]. + */ +internal fun pluginWithRecordedLooper(posts: MutableCollection): UniversalBlePlugin = + UniversalBlePlugin().also { plugin -> + val handler = Mockito.mock(Handler::class.java) + Mockito.doAnswer { invocation -> + posts.add(invocation.getArgument(0)) + true + }.`when`(handler).post(Mockito.any()) + plugin.setField("mainThreadHandler", handler) + } + +/** Runs every post recorded by [pluginWithRecordedLooper], in submission order. */ +internal fun drainPosts(posts: MutableCollection) { + while (posts.isNotEmpty()) { + val next = posts.first() + posts.remove(next) + next.run() + } +} + +/** A gatt for [address] with no services resolved yet. */ +internal fun mockGatt(address: String = GattIds.ADDRESS): BluetoothGatt { + val device = Mockito.mock(BluetoothDevice::class.java) + Mockito.`when`(device.address).thenReturn(address) + return Mockito.mock(BluetoothGatt::class.java).also { + Mockito.`when`(it.device).thenReturn(device) + } +} + +/** A characteristic in [serviceUuid], with no properties set. */ +internal fun mockCharacteristic( + serviceUuid: UUID = GattIds.SERVICE, + characteristicUuid: UUID = GattIds.CHARACTERISTIC, +): BluetoothGattCharacteristic { + val service = Mockito.mock(BluetoothGattService::class.java) + Mockito.`when`(service.uuid).thenReturn(serviceUuid) + return Mockito.mock(BluetoothGattCharacteristic::class.java).also { + Mockito.`when`(it.uuid).thenReturn(characteristicUuid) + Mockito.`when`(it.service).thenReturn(service) + } +} + +/** + * One mock peripheral: a gatt whose [serviceUuid] service exposes + * [characteristic] (with read/write properties) and, on demand, descriptors. + */ +internal class GattFixture( + val address: String = GattIds.ADDRESS, + val serviceUuid: UUID = GattIds.SERVICE, + val characteristicUuid: UUID = GattIds.CHARACTERISTIC, +) { + val service: BluetoothGattService = Mockito.mock(BluetoothGattService::class.java) + val characteristic: BluetoothGattCharacteristic = + Mockito.mock(BluetoothGattCharacteristic::class.java) + val gatt: BluetoothGatt = mockGatt(address) + + init { + Mockito.`when`(service.uuid).thenReturn(serviceUuid) + Mockito.`when`(service.getCharacteristic(characteristicUuid)).thenReturn(characteristic) + Mockito.`when`(characteristic.uuid).thenReturn(characteristicUuid) + Mockito.`when`(characteristic.service).thenReturn(service) + Mockito.`when`(characteristic.properties).thenReturn( + BluetoothGattCharacteristic.PROPERTY_READ or + BluetoothGattCharacteristic.PROPERTY_WRITE or + BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, + ) + Mockito.`when`(gatt.getService(serviceUuid)).thenReturn(service) + } + + /** A descriptor of [characteristic], registered for lookup by [uuid]. */ + fun descriptor(uuid: UUID = GattIds.CCCD): BluetoothGattDescriptor { + val descriptor = Mockito.mock(BluetoothGattDescriptor::class.java) + Mockito.`when`(descriptor.uuid).thenReturn(uuid) + Mockito.`when`(descriptor.characteristic).thenReturn(characteristic) + Mockito.`when`(characteristic.getDescriptor(uuid)).thenReturn(descriptor) + return descriptor + } + + /** + * Stubs the pre-33 stack calls as accepted, as a live link does. JVM tests + * run with Build.VERSION.SDK_INT == 0, so these are the overloads reached. + */ + fun acceptOperations() { + Mockito.`when`( + gatt.writeCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) + ).thenReturn(true) + Mockito.`when`( + gatt.readCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) + ).thenReturn(true) + Mockito.`when`( + gatt.readDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) + ).thenReturn(true) + Mockito.`when`( + gatt.writeDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) + ).thenReturn(true) + Mockito.`when`( + gatt.setCharacteristicNotification( + Mockito.any(BluetoothGattCharacteristic::class.java), + Mockito.anyBoolean(), + ) + ).thenReturn(true) + } +} diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattOwnershipTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattOwnershipTest.kt index 5bf92e7e..c9eaad8e 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/GattOwnershipTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattOwnershipTest.kt @@ -25,18 +25,8 @@ import org.mockito.Mockito internal class GattOwnershipTest { private val address = "AA:BB:CC:DD:EE:FF" - private fun plugin(): UniversalBlePlugin { - val plugin = UniversalBlePlugin() - // Callbacks are posted to the main looper; run them inline. - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { invocation -> - invocation.getArgument(0).run() - true - }.`when`(handler).post(any()) - plugin.setField("mainThreadHandler", handler) - plugin.setField("bluetoothManager", bluetoothManager()) - return plugin - } + private fun plugin(): UniversalBlePlugin = + pluginWithInlineLooper().also { it.setField("bluetoothManager", bluetoothManager()) } // Reports the device as connected at the OS level (as if another engine had // opened the link), which is exactly when the stale cache used to win. @@ -51,19 +41,13 @@ internal class GattOwnershipTest { return manager } - private fun mockGatt(): BluetoothGatt { - val device = Mockito.mock(BluetoothDevice::class.java) - Mockito.`when`(device.address).thenReturn(address) - val gatt = Mockito.mock(BluetoothGatt::class.java) - Mockito.`when`(gatt.device).thenReturn(device) - return gatt - } + @Test fun aClientRegisteredInOneRegistryIsUnknownToAnother() { val background = GattRegistry() val ui = GattRegistry() - val gatt = mockGatt() + val gatt = mockGatt(address) background.put(gatt) assertTrue(background.isKnown(address)) @@ -76,7 +60,7 @@ internal class GattOwnershipTest { fun connectionStateIgnoresAClientOwnedByAnotherEngine() { val backgroundEngine = plugin() val uiEngine = plugin() - backgroundEngine.gattRegistry().put(mockGatt()) + backgroundEngine.gattRegistry().put(mockGatt(address)) // The OS reports CONNECTED for both, but only the owning engine may // claim it; the other reports DISCONNECTED instead of a dead client. @@ -88,8 +72,8 @@ internal class GattOwnershipTest { fun releasingOneRegistrysClientLeavesAnothersUntouched() { val first = GattRegistry() val second = GattRegistry() - val firstGatt = mockGatt() - val secondGatt = mockGatt() + val firstGatt = mockGatt(address) + val secondGatt = mockGatt(address) first.put(firstGatt) second.put(secondGatt) @@ -102,8 +86,8 @@ internal class GattOwnershipTest { @Test fun removingAReplacedClientDoesNotEvictTheNewerOne() { val registry = GattRegistry() - val oldGatt = mockGatt() - val newGatt = mockGatt() + val oldGatt = mockGatt(address) + val newGatt = mockGatt(address) registry.put(oldGatt) registry.put(newGatt) diff --git a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt index bb967194..1ec003ad 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt @@ -1,11 +1,8 @@ package com.navideck.universal_ble -import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattDescriptor -import android.bluetooth.BluetoothGattService -import android.os.Handler import java.util.UUID import kotlin.test.Test import kotlin.test.assertEquals @@ -28,70 +25,19 @@ import org.mockito.Mockito * connection callbacks. */ internal class LinkLossOperationTest { - private val deviceAddress = "AA:BB:CC:DD:EE:FF" - private val serviceUuid = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb") - private val charUuid = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb") - private val cccdUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") - private val descriptorUuid = UUID.fromString("00002901-0000-1000-8000-00805f9b34fb") - - private val service = Mockito.mock(BluetoothGattService::class.java) - private val characteristic = Mockito.mock(BluetoothGattCharacteristic::class.java) - private val gatt = Mockito.mock(BluetoothGatt::class.java) - - init { - val device = Mockito.mock(BluetoothDevice::class.java) - Mockito.`when`(device.address).thenReturn(deviceAddress) - Mockito.`when`(gatt.device).thenReturn(device) - - Mockito.`when`(service.uuid).thenReturn(serviceUuid) - Mockito.`when`(characteristic.uuid).thenReturn(charUuid) - Mockito.`when`(characteristic.service).thenReturn(service) - Mockito.`when`(characteristic.properties).thenReturn( - BluetoothGattCharacteristic.PROPERTY_READ or - BluetoothGattCharacteristic.PROPERTY_WRITE or - BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, - ) - Mockito.`when`(service.getCharacteristic(charUuid)).thenReturn(characteristic) - Mockito.`when`(gatt.getService(serviceUuid)).thenReturn(service) - // JVM tests run with Build.VERSION.SDK_INT == 0, so the pre-33 overloads - // are the ones reached. The stack accepts each operation unless a test - // says otherwise, as it does on a live link. - Mockito.`when`( - gatt.writeCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) - ).thenReturn(true) - Mockito.`when`( - gatt.readCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) - ).thenReturn(true) - Mockito.`when`( - gatt.readDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) - ).thenReturn(true) - Mockito.`when`( - gatt.writeDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) - ).thenReturn(true) - Mockito.`when`( - gatt.setCharacteristicNotification( - Mockito.any(BluetoothGattCharacteristic::class.java), - Mockito.anyBoolean(), - ) - ).thenReturn(true) - } + private val deviceAddress = GattIds.ADDRESS + private val serviceUuid = GattIds.SERVICE + private val charUuid = GattIds.CHARACTERISTIC + private val cccdUuid = GattIds.CCCD + private val descriptorUuid = GattIds.DESCRIPTOR - private fun plugin(): UniversalBlePlugin { - val plugin = UniversalBlePlugin() - // Completions are posted to the main looper; run them inline so the test - // observes them synchronously. - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { invocation -> - invocation.getArgument(0).run() - true - }.`when`(handler).post(Mockito.any()) - plugin.setField("mainThreadHandler", handler) - return plugin - } + private val fixture = GattFixture().also { it.acceptOperations() } + private val gatt get() = fixture.gatt + private val characteristic get() = fixture.characteristic /** A plugin with an autoConnect client that has reported STATE_CONNECTED. */ private fun connectedAutoConnectPlugin(): UniversalBlePlugin { - val plugin = plugin() + val plugin = pluginWithInlineLooper() plugin.autoConnectDevices().add(deviceAddress) plugin.gattRegistry().put(gatt) report(plugin, BluetoothGatt.STATE_CONNECTED) @@ -102,21 +48,6 @@ internal class LinkLossOperationTest { plugin.onConnectionStateChange(gatt, status, state) } - private fun UniversalBlePlugin.pendingWrites(): MutableList = - getField("writeResultFutureList") - - private fun UniversalBlePlugin.pendingDescriptorWrites(): MutableList = - getField("writeDescriptorResultFutureList") - - private fun UniversalBlePlugin.pendingReads(): MutableList = - getField("readResultFutureList") - - private fun UniversalBlePlugin.pendingDescriptorReads(): MutableList = - getField("readDescriptorResultFutureList") - - private fun UniversalBlePlugin.pendingSubscriptions(): MutableList = - getField("subscriptionResultFutureList") - private fun errorCode(result: Result<*>): String? = (result.exceptionOrNull() as? FlutterError)?.code @@ -224,13 +155,10 @@ internal class LinkLossOperationTest { @Test fun theBackstopTouchesOnlyTheReconnectingClient() { - val plugin = plugin() + val plugin = pluginWithInlineLooper() val reconnecting = gatt - val other = Mockito.mock(BluetoothGatt::class.java) - val otherDevice = Mockito.mock(BluetoothDevice::class.java) - val otherAddress = "11:22:33:44:55:66" - Mockito.`when`(otherDevice.address).thenReturn(otherAddress) - Mockito.`when`(other.device).thenReturn(otherDevice) + val otherAddress = GattIds.OTHER_ADDRESS + val other = mockGatt(otherAddress) plugin.autoConnectDevices().add(deviceAddress) plugin.gattRegistry().put(other) plugin.connectedGatts().add(other) @@ -275,14 +203,8 @@ internal class LinkLossOperationTest { @Test fun readsDescriptorWritesAndSubscriptionsAreRefusedAfterALinkLoss() { val plugin = connectedAutoConnectPlugin() - val cccd = Mockito.mock(BluetoothGattDescriptor::class.java) - Mockito.`when`(cccd.uuid).thenReturn(cccdUuid) - Mockito.`when`(cccd.characteristic).thenReturn(characteristic) - Mockito.`when`(characteristic.getDescriptor(cccdUuid)).thenReturn(cccd) - val descriptor = Mockito.mock(BluetoothGattDescriptor::class.java) - Mockito.`when`(descriptor.uuid).thenReturn(descriptorUuid) - Mockito.`when`(descriptor.characteristic).thenReturn(characteristic) - Mockito.`when`(characteristic.getDescriptor(descriptorUuid)).thenReturn(descriptor) + fixture.descriptor(cccdUuid) + fixture.descriptor(descriptorUuid) report(plugin, BluetoothGatt.STATE_DISCONNECTED) diff --git a/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt index 5c4cda78..46c4c570 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt @@ -14,28 +14,15 @@ import org.mockito.Mockito internal class MtuCompletionTest { private val address = "AA:BB:CC:DD:EE:FF" private val posted = ConcurrentLinkedQueue() - private val plugin = UniversalBlePlugin().also { - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { call -> - posted.add(call.getArgument(0)) - true - }.`when`(handler).post(Mockito.any()) - it.setField("mainThreadHandler", handler) - } + private val plugin = pluginWithRecordedLooper(posted) - private fun gatt(id: String = address): BluetoothGatt { - val device = Mockito.mock(BluetoothDevice::class.java) - Mockito.`when`(device.address).thenReturn(id) - return Mockito.mock(BluetoothGatt::class.java).also { - Mockito.`when`(it.device).thenReturn(device) + private fun gatt(id: String = address): BluetoothGatt = + mockGatt(id).also { Mockito.`when`(it.requestMtu(Mockito.anyInt())).thenReturn(true) plugin.gattRegistry().put(it) } - } - private fun drainMain() { - while (true) (posted.poll() ?: return).run() - } + private fun drainMain() = drainPosts(posted) @AfterTest fun clearConnections() { diff --git a/android/src/test/kotlin/com/navideck/universal_ble/NotificationOwnershipTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/NotificationOwnershipTest.kt index 3e78a462..c57e0bb2 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/NotificationOwnershipTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/NotificationOwnershipTest.kt @@ -44,45 +44,22 @@ internal class NotificationOwnershipTest { null } - private fun plugin(): UniversalBlePlugin { - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { invocation -> - mainLooper.add(invocation.getArgument(0)) - true - }.`when`(handler).post(Mockito.any()) - return UniversalBlePlugin().also { - it.setField("mainThreadHandler", handler) + private fun plugin(): UniversalBlePlugin = + pluginWithRecordedLooper(mainLooper).also { it.setField("callbackChannel", callbackChannel) } - } - private fun drainMainLooper() { - while (mainLooper.isNotEmpty()) { - mainLooper.removeAt(0).run() - } - } + private fun drainMainLooper() = drainPosts(mainLooper) - private fun mockGatt(): BluetoothGatt { - val device = Mockito.mock(BluetoothDevice::class.java) - Mockito.`when`(device.address).thenReturn(address) - val gatt = Mockito.mock(BluetoothGatt::class.java) - Mockito.`when`(gatt.device).thenReturn(device) - return gatt - } - private fun characteristic(): BluetoothGattCharacteristic { - val service = Mockito.mock(BluetoothGattService::class.java) - Mockito.`when`(service.uuid).thenReturn(serviceUuid) - val characteristic = Mockito.mock(BluetoothGattCharacteristic::class.java) - Mockito.`when`(characteristic.uuid).thenReturn(charUuid) - Mockito.`when`(characteristic.service).thenReturn(service) - return characteristic - } + + private fun characteristic(): BluetoothGattCharacteristic = + mockCharacteristic(serviceUuid, charUuid) @Test fun registeredClientDeliversItsNotifications() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(address) plugin.gattRegistry().put(gatt) plugin.onCharacteristicChanged(gatt, characteristic(), byteArrayOf(0x01)) @@ -99,9 +76,9 @@ internal class NotificationOwnershipTest { @Test fun supersededClientNotificationsAreDropped() { val plugin = plugin() - val current = mockGatt() + val current = mockGatt(address) // Same address, not the registered client: a connect() replaced it. - val superseded = mockGatt() + val superseded = mockGatt(address) plugin.gattRegistry().put(current) plugin.onCharacteristicChanged(superseded, characteristic(), byteArrayOf(0x01)) @@ -116,7 +93,7 @@ internal class NotificationOwnershipTest { @Test fun notificationsAfterDisconnectAreDropped() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(address) plugin.gattRegistry().put(gatt) plugin.disconnect(address) @@ -130,7 +107,7 @@ internal class NotificationOwnershipTest { @Test fun autoConnectClientKeepsDeliveringAcrossALinkLoss() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(address) plugin.gattRegistry().put(gatt) plugin.getField>("autoConnectDevices").add(address) diff --git a/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt b/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt index 882fe89f..d252a94c 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt @@ -43,3 +43,30 @@ internal fun UniversalBlePlugin.attachConnectedGatt(gatt: BluetoothGatt) { gattRegistry().put(gatt) connectedGatts().add(gatt) } + +// The pending-operation lists, typed, so a test does not spell out a reflection +// key every time. They are the live lists, not copies. + +internal fun UniversalBlePlugin.pendingReads(): MutableList = + getField("readResultFutureList") + +internal fun UniversalBlePlugin.pendingWrites(): MutableList = + getField("writeResultFutureList") + +internal fun UniversalBlePlugin.pendingDescriptorReads(): MutableList = + getField("readDescriptorResultFutureList") + +internal fun UniversalBlePlugin.pendingDescriptorWrites(): MutableList = + getField("writeDescriptorResultFutureList") + +internal fun UniversalBlePlugin.pendingSubscriptions(): MutableList = + getField("subscriptionResultFutureList") + +internal fun UniversalBlePlugin.pendingMtus(): MutableList = + getField("mtuResultFutureList") + +internal fun UniversalBlePlugin.pendingRssis(): MutableList = + getField("rssiResultFutureList") + +internal fun UniversalBlePlugin.pendingDiscoveries(): MutableList = + getField("discoverServicesFutureList") diff --git a/android/src/test/kotlin/com/navideck/universal_ble/ScanCallbackConnectableTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/ScanCallbackConnectableTest.kt index 7d1217e1..6eea588f 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/ScanCallbackConnectableTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/ScanCallbackConnectableTest.kt @@ -26,14 +26,8 @@ internal class ScanCallbackConnectableTest { private val scanResults = mutableListOf() private fun plugin(): UniversalBlePlugin { - val plugin = UniversalBlePlugin() // Callbacks are posted to the main looper; run them inline. - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { invocation -> - invocation.getArgument(0).run() - true - }.`when`(handler).post(any()) - plugin.setField("mainThreadHandler", handler) + val plugin = pluginWithInlineLooper() plugin.setField( "callbackChannel", Mockito.mock(UniversalBleCallbackChannel::class.java) { invocation -> diff --git a/android/src/test/kotlin/com/navideck/universal_ble/WriteCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/WriteCompletionTest.kt index 6f114746..e49e59e1 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/WriteCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/WriteCompletionTest.kt @@ -27,40 +27,10 @@ internal class WriteCompletionTest { private val serviceUuid = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb") private val charUuid = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb") - private val requestGatt by lazy { mockGatt() } - - private fun pluginWithInlineHandler(): UniversalBlePlugin { - val plugin = UniversalBlePlugin() - // Completions are posted to the main looper; execute them inline so - // the test observes them synchronously. - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { invocation -> - invocation.getArgument(0).run() - true - }.`when`(handler).post(Mockito.any()) - plugin.setField("mainThreadHandler", handler) - return plugin - } + private val requestGatt by lazy { mockGatt(deviceAddress) } private fun pendingWrites(plugin: UniversalBlePlugin): MutableList = - plugin.getField("writeResultFutureList") - - private fun mockGatt(): BluetoothGatt { - val device = Mockito.mock(BluetoothDevice::class.java) - Mockito.`when`(device.address).thenReturn(deviceAddress) - val gatt = Mockito.mock(BluetoothGatt::class.java) - Mockito.`when`(gatt.device).thenReturn(device) - return gatt - } - - private fun mockCharacteristic(): BluetoothGattCharacteristic { - val service = Mockito.mock(BluetoothGattService::class.java) - Mockito.`when`(service.uuid).thenReturn(serviceUuid) - val characteristic = Mockito.mock(BluetoothGattCharacteristic::class.java) - Mockito.`when`(characteristic.uuid).thenReturn(charUuid) - Mockito.`when`(characteristic.service).thenReturn(service) - return characteristic - } + plugin.pendingWrites() private fun pendingFuture(acks: MutableList>) = WriteResultFuture( requestGatt, @@ -71,7 +41,7 @@ internal class WriteCompletionTest { @Test fun oneWriteCompletionMustNotAckOtherPendingWrites() { - val plugin = pluginWithInlineHandler() + val plugin = pluginWithInlineLooper() val firstAcks = mutableListOf>() val secondAcks = mutableListOf>() val pending = pendingWrites(plugin) @@ -81,7 +51,7 @@ internal class WriteCompletionTest { } // The ATT response of the FIRST write arrives. - plugin.onCharacteristicWrite(requestGatt, mockCharacteristic(), BluetoothGatt.GATT_SUCCESS) + plugin.onCharacteristicWrite(requestGatt, mockCharacteristic(serviceUuid, charUuid), BluetoothGatt.GATT_SUCCESS) assertEquals(1, firstAcks.size, "oldest pending write should be acknowledged") assertTrue(firstAcks[0].isSuccess) @@ -93,14 +63,14 @@ internal class WriteCompletionTest { ) // The second write's own response must then complete it - exactly once. - plugin.onCharacteristicWrite(requestGatt, mockCharacteristic(), BluetoothGatt.GATT_SUCCESS) + plugin.onCharacteristicWrite(requestGatt, mockCharacteristic(serviceUuid, charUuid), BluetoothGatt.GATT_SUCCESS) assertEquals(1, secondAcks.size, "second write acknowledged by its own response") assertEquals(1, firstAcks.size, "first write must not be acknowledged twice") } @Test fun failedCompletionMustFailOnlyTheOldestPendingWrite() { - val plugin = pluginWithInlineHandler() + val plugin = pluginWithInlineLooper() val firstAcks = mutableListOf>() val secondAcks = mutableListOf>() val pending = pendingWrites(plugin) @@ -109,7 +79,7 @@ internal class WriteCompletionTest { pending.add(pendingFuture(secondAcks)) } - plugin.onCharacteristicWrite(requestGatt, mockCharacteristic(), BluetoothGatt.GATT_FAILURE) + plugin.onCharacteristicWrite(requestGatt, mockCharacteristic(serviceUuid, charUuid), BluetoothGatt.GATT_FAILURE) assertEquals(1, firstAcks.size, "oldest pending write should be failed") assertTrue(firstAcks[0].isFailure) diff --git a/android/src/test/kotlin/com/navideck/universal_ble/WriteRefusalTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/WriteRefusalTest.kt index e2aada69..47a1f08c 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/WriteRefusalTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/WriteRefusalTest.kt @@ -1,12 +1,8 @@ package com.navideck.universal_ble -import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattDescriptor -import android.bluetooth.BluetoothGattService -import android.os.Handler -import java.util.UUID import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue @@ -28,52 +24,17 @@ import org.mockito.Mockito */ @Suppress("DEPRECATION") // The pre-33 overloads are the ones JVM tests reach. internal class WriteRefusalTest { - private val deviceAddress = "AA:BB:CC:DD:EE:FF" - private val serviceUuid = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb") - private val charUuid = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb") - private val descriptorUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") - - private val service = Mockito.mock(BluetoothGattService::class.java) - private val characteristic = Mockito.mock(BluetoothGattCharacteristic::class.java) - private val gatt = Mockito.mock(BluetoothGatt::class.java) - - init { - val device = Mockito.mock(BluetoothDevice::class.java) - Mockito.`when`(device.address).thenReturn(deviceAddress) - Mockito.`when`(gatt.device).thenReturn(device) - - Mockito.`when`(service.uuid).thenReturn(serviceUuid) - Mockito.`when`(characteristic.uuid).thenReturn(charUuid) - Mockito.`when`(characteristic.service).thenReturn(service) - Mockito.`when`(characteristic.properties).thenReturn( - BluetoothGattCharacteristic.PROPERTY_WRITE or - BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, - ) - Mockito.`when`(service.getCharacteristic(charUuid)).thenReturn(characteristic) - Mockito.`when`(gatt.getService(serviceUuid)).thenReturn(service) - } + private val deviceAddress = GattIds.ADDRESS + private val serviceUuid = GattIds.SERVICE + private val charUuid = GattIds.CHARACTERISTIC + private val descriptorUuid = GattIds.CCCD - private fun pluginWithInlineHandler(): UniversalBlePlugin { - val plugin = UniversalBlePlugin() - // Completions are posted to the main looper; run them inline so the test - // observes them synchronously. - val handler = Mockito.mock(Handler::class.java) - Mockito.doAnswer { invocation -> - invocation.getArgument(0).run() - true - }.`when`(handler).post(Mockito.any()) - plugin.setField("mainThreadHandler", handler) - return plugin - } + private val fixture = GattFixture() + private val gatt get() = fixture.gatt + private val characteristic get() = fixture.characteristic private fun pluginWithGatt(): UniversalBlePlugin = - pluginWithInlineHandler().also { it.attachConnectedGatt(gatt) } - - private fun UniversalBlePlugin.pendingWrites(): List = - getField("writeResultFutureList") - - private fun UniversalBlePlugin.pendingDescriptorWrites(): List = - getField("writeDescriptorResultFutureList") + pluginWithInlineLooper().also { it.attachConnectedGatt(gatt) } private fun errorCode(result: Result): String? = (result.exceptionOrNull() as? FlutterError)?.code @@ -167,7 +128,7 @@ internal class WriteRefusalTest { fun anOversizedValueStillReportsAMissingDevice() { // The length check runs after the lookups, so it does not shadow the // errors a caller got before it existed. - val plugin = pluginWithInlineHandler() + val plugin = pluginWithInlineLooper() val acks = mutableListOf>() plugin.writeValue( @@ -189,9 +150,7 @@ internal class WriteRefusalTest { @Test fun aRefusedDescriptorWriteWithdrawsItsPendingResult() { val plugin = pluginWithGatt() - val descriptor = Mockito.mock(BluetoothGattDescriptor::class.java) - Mockito.`when`(descriptor.uuid).thenReturn(descriptorUuid) - Mockito.`when`(characteristic.getDescriptor(descriptorUuid)).thenReturn(descriptor) + fixture.descriptor(descriptorUuid) Mockito.doThrow(IllegalArgumentException("Descriptor must have a non-null characteristic")) .`when`(gatt).writeDescriptor(Mockito.any(BluetoothGattDescriptor::class.java)) @@ -214,9 +173,7 @@ internal class WriteRefusalTest { @Test fun anOversizedDescriptorValueIsRejectedBeforeItReachesTheStack() { val plugin = pluginWithGatt() - val descriptor = Mockito.mock(BluetoothGattDescriptor::class.java) - Mockito.`when`(descriptor.uuid).thenReturn(descriptorUuid) - Mockito.`when`(characteristic.getDescriptor(descriptorUuid)).thenReturn(descriptor) + fixture.descriptor(descriptorUuid) val acks = mutableListOf>() plugin.writeDescriptorValue( From 0eba025c9e02e335bf5c13def9092f6507db9d73 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:12:14 +0100 Subject: [PATCH 07/13] Track each GATT client's lifecycle in one state field The plugin kept one client's connection state in five places: the address registry, connectedGatts, closingGatts, awaitingReconnectGatts and autoConnectDevices. Every transition in connect() / disconnect() / onConnectionStateChange() / cleanConnection() had to update several of them, and the close fallback timer needed extra bookkeeping to notice that a set had already been cleared. Give each client a GattClient record holding its gatt, its State (CONNECTING, CONNECTED, AWAITING_RECONNECT, CLOSING, CLOSED) and its autoConnect flag, and keep those in GattRegistry. The registry maps an address to the client API calls resolve, and separately tracks clients that are closing or were replaced, so a replacement can be published while the previous client still owes its teardown. Reads that were set membership tests are now state reads: isLinkUp, the superseded check, the keep-open decision and the fallback timer. finishClose() is a compare-and-set, so STATE_DISCONNECTED and the fallback timer cannot close the same client twice. autoConnect moves from an address set to the client: connect() copies the decision onto the client it replaces, and disconnect() withdraws it from every client of the address. --- .../navideck/universal_ble/GattRegistry.kt | 133 +++++++++++++++-- .../universal_ble/UniversalBlePlugin.kt | 139 ++++++++---------- .../universal_ble/DisconnectCloseTest.kt | 18 +-- .../GattCallbackCompletionTest.kt | 2 +- .../universal_ble/GattOwnershipTest.kt | 10 +- .../universal_ble/LinkLossOperationTest.kt | 21 ++- .../universal_ble/MtuCompletionTest.kt | 2 +- .../NotificationOwnershipTest.kt | 3 +- .../universal_ble/PluginTestSupport.kt | 17 +-- 9 files changed, 213 insertions(+), 132 deletions(-) diff --git a/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt b/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt index 4facfb02..853c5859 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt @@ -2,38 +2,145 @@ package com.navideck.universal_ble import android.bluetooth.BluetoothGatt import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicReference /** - * GATT clients owned by one [UniversalBlePlugin]. This must stay per plugin + * One GATT client and the connection state the plugin keeps for it. + * + * The lifecycle used to live in several address sets (`connectedGatts`, + * `closingGatts`, `awaitingReconnectGatts`, `autoConnectDevices`), so every + * transition had to update each of them. It is one field now: reads such as + * "is the link up", "is this client being torn down" and "may the stack + * reconnect it" are answered by [state] and [autoConnect]. + */ +internal class GattClient(val gatt: BluetoothGatt) { + enum class State { + /** connectGatt() returned; no callback has arrived yet. */ + CONNECTING, + + /** STATE_CONNECTED: the platform can deliver operations on this link. */ + CONNECTED, + + /** A link loss left the client open for autoConnect to reconnect it. */ + AWAITING_RECONNECT, + + /** disconnect() or a teardown is closing it; close() has not run yet. */ + CLOSING, + + /** close() has run; the client is no longer tracked. */ + CLOSED, + } + + private val stateRef = AtomicReference(State.CONNECTING) + + /** Whether Android may reconnect this client after a link loss. */ + @Volatile + var autoConnect: Boolean = false + + val address: String get() = gatt.device.address + + val state: State get() = stateRef.get() + + /** Whether this client's link is up, i.e. operations may reach the platform. */ + val isLinkUp: Boolean get() = state == State.CONNECTED + + fun setState(next: State) { + stateRef.set(next) + } + + /** + * Moves the client from [expected] to [next], returning false when another + * thread got there first. Used where two paths race to finish a teardown + * (STATE_DISCONNECTED and the close fallback timer). + */ + fun compareAndSetState(expected: State, next: State): Boolean = + stateRef.compareAndSet(expected, next) + + override fun toString(): String = "GattClient($address, $state)" +} + +/** + * The GATT clients owned by one [UniversalBlePlugin]. This must stay per plugin * instance (one per FlutterEngine) rather than process-wide: a `connect()` must * not reuse a client whose callbacks are wired to another (possibly destroyed) * engine, and detaching one engine must release only its own clients. + * + * [active] maps an address to the client its callbacks and API calls currently + * belong to. [clients] tracks every client the plugin still owes a teardown, + * including ones that were replaced or are closing, so a late callback can + * still be attributed (and ignored) and its close is still driven. A connect() + * can publish a replacement only after the previous client's link is gone, and + * that client may still be waiting for its own STATE_DISCONNECTED — the reason + * the two maps exist. */ internal class GattRegistry { - private val clients = ConcurrentHashMap() + private val active = ConcurrentHashMap() + private val clients = ConcurrentHashMap() + + /** The client API calls resolve for [deviceId], if the address has one. */ + fun find(deviceId: String): GattClient? = active[deviceId] - fun find(deviceId: String): BluetoothGatt? = clients[deviceId] + /** The tracked client for [gatt], including one that is closing. */ + fun find(gatt: BluetoothGatt): GattClient? = clients[gatt] - fun isKnown(deviceId: String): Boolean = find(deviceId) != null + fun isKnown(deviceId: String): Boolean = active.containsKey(deviceId) - fun get(deviceId: String): BluetoothGatt = + fun get(deviceId: String): GattClient = find(deviceId) ?: throw createFlutterError( UniversalBleErrorCode.DEVICE_NOT_FOUND, "Unknown deviceId: $deviceId", ) - fun put(gatt: BluetoothGatt) { - clients[gatt.device.address] = gatt + /** + * Publishes [gatt] as the address's active client. A client the plugin + * already tracks for this gatt keeps its state: connectGatt() is given no + * Handler, so STATE_CONNECTED can arrive before connect() reaches this call, + * and resetting it here would make a live link look like it is connecting. + */ + fun put(gatt: BluetoothGatt, autoConnect: Boolean = false): GattClient { + val client = clients.computeIfAbsent(gatt) { GattClient(it) } + client.autoConnect = autoConnect + active[client.address] = client + return client + } + + /** + * Every client tracked for [deviceId], in any state. Used by `disconnect()` + * and detach to withdraw autoConnect from clients that a replacement has + * already taken out of the active slot. + */ + fun forAddress(deviceId: String): List = + clients.values.filter { it.address == deviceId } + + /** + * Starts closing [client]: it leaves the active slot immediately, so API + * calls for the address fail with `deviceNotFound`, while [clients] keeps + * tracking it until close() runs. + */ + fun beginClose(client: GattClient) { + // Only unpublish it if it is still the address's client; a connect() + // may already have published a replacement. + active.remove(client.address, client) + client.setState(GattClient.State.CLOSING) } /** - * Removes [gatt] only while it is still the registered client; a newer - * `connect()` may have replaced it for the same address. + * Stops tracking [client] once close() has run, returning false when + * another path (STATE_DISCONNECTED or the fallback timer) closed it first. + * The compare-and-set keeps the two from closing the same client twice. */ - fun remove(gatt: BluetoothGatt) { - clients.remove(gatt.device.address, gatt) + fun finishClose(client: GattClient): Boolean { + while (true) { + val current = client.state + if (current == GattClient.State.CLOSED) return false + if (client.compareAndSetState(current, GattClient.State.CLOSED)) { + active.remove(client.address, client) + clients.remove(client.gatt) + return true + } + } } - /** Snapshot of the registered clients, safe to iterate while releasing them. */ - fun snapshot(): List = clients.values.toList() + /** The active clients, safe to iterate while releasing them. */ + fun snapshot(): List = active.values.toList() } diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index 9a3d4ae3..25b08460 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -28,10 +28,8 @@ import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.plugin.common.PluginRegistry -import java.util.Collections import java.util.UUID import java.util.WeakHashMap -import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import androidx.core.content.edit @@ -91,24 +89,13 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // instead of letting Dart's pairing-state dedup swallow it (#325). private val bondingAttempts = mutableSetOf() private val rssiResultFutureList = mutableListOf() - private val autoConnectDevices = mutableSetOf() - - // GATT clients that reached STATE_CONNECTED, so a later STATE_DISCONNECTED can be told - // apart from a failed connection attempt (Android reports both the same way). - private val connectedGatts: MutableSet = - Collections.newSetFromMap(ConcurrentHashMap()) // Per plugin instance (one per FlutterEngine): the GATT clients this engine - // owns (see [GattRegistry]). A connect() here never reuses a client from - // another engine, and detach releases only this engine's clients. + // owns and the link state of each (see [GattRegistry]). A connect() here + // never reuses a client from another engine, and detach releases only this + // engine's clients. private val gattRegistry = GattRegistry() - // GATT clients that a link loss left open for autoConnect, until they - // report a connection again. The next STATE_CONNECTED for one of them is a - // new link, which inherits nothing from the previous one (#394). - private val awaitingReconnectGatts: MutableSet = - Collections.newSetFromMap(ConcurrentHashMap()) - /** * When enabled, close every known GATT client on engine detach. The * plugin otherwise leaves GATT open, so a killed app keeps the @@ -116,9 +103,6 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), */ private var closeGattOnDetach = false - // Clients that disconnect() is tearing down; closed on STATE_DISCONNECTED or by the fallback timer. - private val closingGatts: MutableSet = - Collections.newSetFromMap(ConcurrentHashMap()) private val gattCloseTimeoutMs = 1500L override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { @@ -152,7 +136,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { // Release only the clients this engine created. The snapshot avoids mutating // the map while clients are released. - if (closeGattOnDetach) gattRegistry.snapshot().forEach(::cleanConnection) + if (closeGattOnDetach) gattRegistry.snapshot().forEach { cleanConnection(it.gatt) } // A detached engine may have no adapter; a null one must not abort the // teardown before the receiver and the peripheral plugin are released. bluetoothManager.adapter?.bluetoothLeScanner?.stopScan(scanCallback) @@ -347,11 +331,14 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) { platformConfig?.android?.closeGattOnDetach?.let { closeGattOnDetach = it } + val shouldAutoConnect = autoConnect ?: false + // Note: platformConfig carries platform-specific connection options // If already connected, send connected message, // if connecting, do nothing - gattRegistry.find(deviceId)?.let { - val currentState = bluetoothManager.getConnectionState(it.device, BluetoothProfile.GATT) + gattRegistry.find(deviceId)?.let { existing -> + val currentState = + bluetoothManager.getConnectionState(existing.gatt.device, BluetoothProfile.GATT) if (currentState == BluetoothGatt.STATE_CONNECTED) { UniversalBleLogger.logError("$deviceId Already connected") mainThreadHandler?.post { @@ -364,17 +351,12 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), "Connection already in progress" ) } - // The client below replaces this one, so it will never be the client - // that reports the reconnect. - awaitingReconnectGatts.remove(it) + // The client below replaces this one: it inherits the address's + // reconnect decision, and is no longer the client that can report + // the reconnect. + existing.autoConnect = shouldAutoConnect } - val shouldAutoConnect = autoConnect ?: false - if (shouldAutoConnect) { - autoConnectDevices.add(deviceId) - } else { - autoConnectDevices.remove(deviceId) - } val remoteDevice = bluetoothManager.adapter.getRemoteDevice(deviceId) val gatt = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { remoteDevice.connectGatt( @@ -386,20 +368,21 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } else { remoteDevice.connectGatt(context, shouldAutoConnect, this) } - gattRegistry.put(gatt) + gattRegistry.put(gatt, shouldAutoConnect) } override fun disconnect(deviceId: String) { - autoConnectDevices.remove(deviceId) - val gatt = gattRegistry.find(deviceId) - if (gatt == null) { - awaitingReconnectGatts.removeAll { it.device.address == deviceId } + // An explicit disconnect cancels the address's autoConnect, for the + // active client and for any client a replacement left behind. + gattRegistry.forAddress(deviceId).forEach { it.autoConnect = false } + val client = gattRegistry.find(deviceId) + if (client == null) { cleanUpConnection(deviceId) mainThreadHandler?.post { callbackChannel?.onConnectionChanged(deviceId, false, null, null, null) {} } } else { - cleanConnection(gatt) + cleanConnection(client.gatt) } } @@ -447,7 +430,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), override fun readRssi(deviceId: String, callback: (Result) -> Unit) { try { - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt if (gatt.readRemoteRssi()) { // Pending futures are mutated both here (main thread) and in // onReadRemoteRssi / cleanUpConnection (binder threads), so @@ -512,7 +495,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), callback: (Result>) -> Unit, ) { try { - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt if (platformConfig?.android?.clearGattCache == true && !gatt.refreshGattCache()) { callback( Result.failure( @@ -565,7 +548,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), pending = discoverServicesFutureList.filter { it.gatt === gatt } discoverServicesFutureList.removeAll(pending) } - if (services != null && gattRegistry.find(deviceId) === gatt) { + if (services != null && gattRegistry.find(deviceId)?.gatt === gatt) { try { setCachedServices(deviceId, services.map { it.uuid.toString() }) } catch (e: Exception) { @@ -640,7 +623,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), var pendingFuture: SubscriptionResultFuture? = null try { UniversalBleLogger.logDebug("SET_NOTIFY -> $deviceId $service $characteristic input=$bleInputProperty") - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt val gattCharacteristic: BluetoothGattCharacteristic? = gatt.getCharacteristic(service, characteristic) @@ -790,7 +773,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) { try { UniversalBleLogger.logDebug("READ -> $deviceId $service $characteristic") - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -926,7 +909,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), var writeFuture: WriteResultFuture? = null try { UniversalBleLogger.logDebug("WRITE -> $deviceId $service $characteristic len=${value.size} property=$bleOutputProperty") - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1128,7 +1111,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) { try { UniversalBleLogger.logDebug("READ_DESCRIPTOR -> $deviceId $service $characteristic $descriptor") - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1262,7 +1245,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), var writeFuture: WriteDescriptorResultFuture? = null try { UniversalBleLogger.logDebug("WRITE_DESCRIPTOR -> $deviceId $service $characteristic $descriptor len=${value.size}") - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1370,7 +1353,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), override fun requestMtu(deviceId: String, expectedMtu: Long, callback: (Result) -> Unit) { UniversalBleLogger.logDebug("REQUEST_MTU -> $deviceId expected=$expectedMtu") val gatt = try { - gattRegistry.get(deviceId) + gattRegistry.get(deviceId).gatt } catch (e: FlutterError) { postMtuResult(callback, Result.failure(e)) return @@ -1442,7 +1425,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), callback: (Result) -> Unit, ) { try { - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt val androidPriority = when (priority) { BleConnectionPriority.BALANCED -> BluetoothGatt.CONNECTION_PRIORITY_BALANCED BleConnectionPriority.HIGH_PERFORMANCE -> BluetoothGatt.CONNECTION_PRIORITY_HIGH @@ -1515,7 +1498,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), * it open, so it keeps reporting once the link recovers. */ private fun isCurrentClient(gatt: BluetoothGatt?): Boolean = - gatt != null && gattRegistry.find(gatt.device.address) === gatt + gatt != null && gattRegistry.find(gatt.device.address)?.gatt === gatt /** * Whether [gatt] has a link the platform can deliver operations on. @@ -1528,7 +1511,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), * the check passes, cleanup sweeps, and the result is added afterwards — * stranded until a later callback completes it one behind (#394). */ - private fun isLinkUp(gatt: BluetoothGatt): Boolean = connectedGatts.contains(gatt) + private fun isLinkUp(gatt: BluetoothGatt): Boolean = + gattRegistry.find(gatt)?.isLinkUp == true /** * Adds [future] to this pending list while holding its lock, but only if @@ -1717,7 +1701,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } // If its a known gatt, just discover services - gattRegistry.find(device.address)?.let { gatt -> + gattRegistry.find(device.address)?.let { client -> + val gatt = client.gatt gatt.services?.let { services -> updateCallback(services.map { service -> service.uuid.toString() }) return @@ -1804,7 +1789,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // after its own gatt was published to the registry, so an entry // whose gatt is not visible here cannot be in the list being // filtered. - return futureGatt !== gattRegistry.find(deviceId) + return futureGatt !== gattRegistry.find(deviceId)?.gatt } failPendingOperations(::owns) @@ -1959,19 +1944,16 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), private fun cleanConnection(gatt: BluetoothGatt) { val deviceId = gatt.device.address - gattRegistry.remove(gatt) - awaitingReconnectGatts.remove(gatt) + val client = gattRegistry.find(gatt) ?: gattRegistry.put(gatt) + client.autoConnect = false + gattRegistry.beginClose(client) cleanUpConnection(deviceId, gatt) - closingGatts.add(gatt) gatt.disconnect() // close() runs from onConnectionStateChange once the link is down. A client that never // reached CONNECTED gets no callback at all, so release it anyway after a while (#277). mainThreadHandler?.postDelayed({ - if (closingGatts.remove(gatt)) { + if (client.state == GattClient.State.CLOSING && gattRegistry.finishClose(client)) { UniversalBleLogger.logDebug("No STATE_DISCONNECTED for $deviceId, closing gatt") - // No callback ever reported the link down, so drop the state that - // describes it; the closed client must not be taken for connected. - connectedGatts.remove(gatt) gatt.close() // A newer connect() owns this address now; its state is not ours to report. if (!gattRegistry.isKnown(deviceId)) { @@ -2115,13 +2097,16 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // connect() waiting for a link that is in fact up, and its timeout // then tears the link down. val owner = gattRegistry.find(gatt.device.address) - if ((owner != null && owner !== gatt) || closingGatts.contains(gatt)) { + val tracked = gattRegistry.find(gatt) + if ((owner != null && owner.gatt !== gatt) || + tracked?.state == GattClient.State.CLOSING + ) { UniversalBleLogger.logDebug( "CONNECTED ignored from a superseded client <- ${gatt.device.address}" ) return } - connectedGatts.add(gatt) + val client = if (owner?.gatt === gatt) owner else gattRegistry.put(gatt) // A client that kept the link loss open for autoConnect is now on a // new link, which inherits nothing from the previous one. An // operation the stack accepted just before that loss can be dropped @@ -2129,7 +2114,9 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // new link's first callback and every later operation would lag by // one. Fail whatever is still attributed to this client — and only // to it (#394). - if (awaitingReconnectGatts.remove(gatt)) { + val reconnected = client.state == GattClient.State.AWAITING_RECONNECT + client.setState(GattClient.State.CONNECTED) + if (reconnected) { failPendingOperations { futureGatt, _ -> futureGatt === gatt } } mainThreadHandler?.post { @@ -2139,14 +2126,17 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } } else if (newState == BluetoothGatt.STATE_DISCONNECTED) { val deviceId = gatt.device.address - val wasConnected = connectedGatts.remove(gatt) - val shouldAutoConnect = autoConnectDevices.contains(deviceId) - val closingByRequest = closingGatts.remove(gatt) - // A client the registry no longer holds was replaced, whether by a - // newer connect() or by disconnect(): its requests and its - // connection state are not the current connection's to fail or + val client = gattRegistry.find(gatt) + // Android reports a failed connection attempt the same way, so only + // a client that reached CONNECTED owes a disconnect report. + val wasConnected = client?.state == GattClient.State.CONNECTED + val closingByRequest = client?.state == GattClient.State.CLOSING + // A client the registry no longer holds as active was replaced, + // whether by a newer connect() or by disconnect(): its requests and + // its connection state are not the current connection's to fail or // report. Same rule as the close fallback timer in cleanConnection(). - val superseded = gattRegistry.find(deviceId)?.let { it !== gatt } == true + val active = gattRegistry.find(deviceId) + val superseded = active != null && active.gatt !== gatt if (!superseded) { // Always clean up internal state (futures, etc.) @@ -2164,17 +2154,14 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } } - if (closingByRequest || !shouldAutoConnect) { - // Only keep the client open when autoConnect should let Android reconnect it - awaitingReconnectGatts.remove(gatt) - gattRegistry.remove(gatt) + // Only keep the client open when autoConnect should let Android + // reconnect it; its next STATE_CONNECTED starts a new link. + if (!closingByRequest && client?.autoConnect == true) { + client.setState(GattClient.State.AWAITING_RECONNECT) + } else if (client == null || gattRegistry.finishClose(client)) { gatt.disconnect() UniversalBleLogger.logDebug("Closing gatt for $deviceId") gatt.close() - } else if (!superseded) { - // When autoConnect is enabled, keep GATT open for Android to - // reconnect; its next STATE_CONNECTED starts a new link. - awaitingReconnectGatts.add(gatt) } } } diff --git a/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt index 8535e535..2fd38b4c 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt @@ -10,6 +10,7 @@ import android.os.Handler import java.util.UUID import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue import org.mockito.ArgumentMatchers.any @@ -41,16 +42,13 @@ internal class DisconnectCloseTest { private fun plugin(): UniversalBlePlugin = pluginWithInlineLooper().also { it.setField("callbackChannel", callbackChannel) } - private fun closingGatts(plugin: UniversalBlePlugin): MutableSet = - plugin.getField("closingGatts") - @Test fun closingClientIsClosedAndReportedOnDisconnect() { val plugin = plugin() val gatt = mockGatt(deviceAddress) - closingGatts(plugin).add(gatt) + plugin.gattRegistry().beginClose(plugin.gattRegistry().put(gatt)) plugin.onConnectionStateChange( gatt, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_DISCONNECTED @@ -58,7 +56,7 @@ internal class DisconnectCloseTest { Mockito.verify(gatt).close() assertEquals(listOf(listOf(deviceAddress, false, null, null, null)), connectionChanges) - assertTrue(closingGatts(plugin).isEmpty()) + assertNull(plugin.gattRegistry().find(gatt)) } @Test @@ -132,7 +130,7 @@ internal class DisconnectCloseTest { val plugin = plugin() val oldGatt = mockGatt(deviceAddress) val newGatt = mockGatt(deviceAddress) - closingGatts(plugin).add(oldGatt) + plugin.gattRegistry().beginClose(plugin.gattRegistry().put(oldGatt)) plugin.gattRegistry().put(newGatt) plugin.onConnectionStateChange( @@ -141,7 +139,7 @@ internal class DisconnectCloseTest { Mockito.verify(oldGatt).close() assertTrue(connectionChanges.isEmpty()) - assertSame(newGatt, plugin.gattRegistry().find(deviceAddress)) + assertSame(newGatt, plugin.gattRegistry().find(deviceAddress)?.gatt) } @Test @@ -179,7 +177,7 @@ internal class DisconnectCloseTest { connectionChanges, "a link that reports before it is registered still belongs to this connect()", ) - assertSame(gatt, plugin.gattRegistry().find(deviceAddress)) + assertSame(gatt, plugin.gattRegistry().find(deviceAddress)?.gatt) } @Test @@ -188,7 +186,7 @@ internal class DisconnectCloseTest { val gatt = mockGatt(deviceAddress) // disconnect() is tearing this client down; it must not come back as a // connection for the address. - closingGatts(plugin).add(gatt) + plugin.gattRegistry().beginClose(plugin.gattRegistry().put(gatt)) plugin.onConnectionStateChange( gatt, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_CONNECTED @@ -200,7 +198,7 @@ internal class DisconnectCloseTest { @Test fun replacedClientDisconnectDoesNotReportOrFailTheNewConnection() { val plugin = plugin() - // connect() replaced the client, so the old one is never in closingGatts. + // connect() replaced the client, so the old one is never tracked as closing. val replaced = mockGatt(deviceAddress) val current = mockGatt(deviceAddress) plugin.gattRegistry().put(current) diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt index c74ed315..d435aeb3 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt @@ -631,7 +631,7 @@ internal class GattCallbackCompletionTest { drainMainLooper() assertTrue(results.isEmpty(), "the replacement's read is still in flight") - assertSame(current, plugin.gattRegistry().find(deviceAddress)) + assertSame(current, plugin.gattRegistry().find(deviceAddress)?.gatt) } @Test diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattOwnershipTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattOwnershipTest.kt index c9eaad8e..bc7c6077 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/GattOwnershipTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattOwnershipTest.kt @@ -51,7 +51,7 @@ internal class GattOwnershipTest { background.put(gatt) assertTrue(background.isKnown(address)) - assertSame(gatt, background.find(address)) + assertSame(gatt, background.find(address)?.gatt) assertFalse(ui.isKnown(address)) assertNull(ui.find(address)) } @@ -77,10 +77,10 @@ internal class GattOwnershipTest { first.put(firstGatt) second.put(secondGatt) - first.remove(firstGatt) + first.finishClose(first.find(firstGatt)!!) assertNull(first.find(address)) - assertSame(secondGatt, second.find(address)) + assertSame(secondGatt, second.find(address)?.gatt) } @Test @@ -91,9 +91,9 @@ internal class GattOwnershipTest { registry.put(oldGatt) registry.put(newGatt) - registry.remove(oldGatt) + registry.finishClose(registry.find(oldGatt)!!) - assertSame(newGatt, registry.find(address)) + assertSame(newGatt, registry.find(address)?.gatt) } @Test diff --git a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt index 1ec003ad..4f19cd5b 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt @@ -38,8 +38,7 @@ internal class LinkLossOperationTest { /** A plugin with an autoConnect client that has reported STATE_CONNECTED. */ private fun connectedAutoConnectPlugin(): UniversalBlePlugin { val plugin = pluginWithInlineLooper() - plugin.autoConnectDevices().add(deviceAddress) - plugin.gattRegistry().put(gatt) + plugin.gattRegistry().put(gatt, autoConnect = true) report(plugin, BluetoothGatt.STATE_CONNECTED) return plugin } @@ -91,8 +90,9 @@ internal class LinkLossOperationTest { assertEquals(1, acks.size, "the write must fail instead of waiting for the Dart timeout") assertDeviceDisconnected(acks.single()) assertTrue(plugin.pendingWrites().isEmpty(), "a refused write must not stay pending") - assertTrue( - plugin.awaitingReconnectGatts().contains(gatt), + assertEquals( + GattClient.State.AWAITING_RECONNECT, + plugin.gattClient(gatt)?.state, "autoConnect keeps the client open for the system to reconnect", ) Mockito.verify(gatt, Mockito.never()) @@ -109,8 +109,9 @@ internal class LinkLossOperationTest { // Android reconnects the same BluetoothGatt instance. report(plugin, BluetoothGatt.STATE_CONNECTED) - assertTrue( - plugin.awaitingReconnectGatts().isEmpty(), + assertEquals( + GattClient.State.CONNECTED, + plugin.gattClient(gatt)?.state, "the client is connected again, so nothing is waiting for a reconnect", ) val acks = mutableListOf>() @@ -159,11 +160,9 @@ internal class LinkLossOperationTest { val reconnecting = gatt val otherAddress = GattIds.OTHER_ADDRESS val other = mockGatt(otherAddress) - plugin.autoConnectDevices().add(deviceAddress) - plugin.gattRegistry().put(other) - plugin.connectedGatts().add(other) - plugin.gattRegistry().put(reconnecting) - plugin.connectedGatts().add(reconnecting) + plugin.gattRegistry().put(other).setState(GattClient.State.CONNECTED) + plugin.gattRegistry().put(reconnecting, autoConnect = true) + .setState(GattClient.State.CONNECTED) val otherResult = mutableListOf>() plugin.pendingWrites().add( diff --git a/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt index 46c4c570..a4548473 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt @@ -26,7 +26,7 @@ internal class MtuCompletionTest { @AfterTest fun clearConnections() { - plugin.gattRegistry().snapshot().forEach { plugin.gattRegistry().remove(it) } + plugin.gattRegistry().snapshot().forEach { plugin.gattRegistry().finishClose(it) } } @Test diff --git a/android/src/test/kotlin/com/navideck/universal_ble/NotificationOwnershipTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/NotificationOwnershipTest.kt index c57e0bb2..54cfab1c 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/NotificationOwnershipTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/NotificationOwnershipTest.kt @@ -108,8 +108,7 @@ internal class NotificationOwnershipTest { fun autoConnectClientKeepsDeliveringAcrossALinkLoss() { val plugin = plugin() val gatt = mockGatt(address) - plugin.gattRegistry().put(gatt) - plugin.getField>("autoConnectDevices").add(address) + plugin.gattRegistry().put(gatt, autoConnect = true) // autoConnect keeps the client registered so Android can reconnect it. plugin.onConnectionStateChange( diff --git a/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt b/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt index d252a94c..4f47e839 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt @@ -21,17 +21,9 @@ internal fun UniversalBlePlugin.getField(name: String): T { internal fun UniversalBlePlugin.gattRegistry(): GattRegistry = getField("gattRegistry") -@Suppress("UNCHECKED_CAST") -internal fun UniversalBlePlugin.connectedGatts(): MutableSet = - getField("connectedGatts") - -@Suppress("UNCHECKED_CAST") -internal fun UniversalBlePlugin.awaitingReconnectGatts(): MutableSet = - getField("awaitingReconnectGatts") - -@Suppress("UNCHECKED_CAST") -internal fun UniversalBlePlugin.autoConnectDevices(): MutableSet = - getField("autoConnectDevices") +/** The plugin's tracked client for [gatt], if any. */ +internal fun UniversalBlePlugin.gattClient(gatt: BluetoothGatt): GattClient? = + gattRegistry().find(gatt) /** * Registers [gatt] as the plugin's client and marks its link up, as a @@ -40,8 +32,7 @@ internal fun UniversalBlePlugin.autoConnectDevices(): MutableSet = * instead of reaching the stack (#394). */ internal fun UniversalBlePlugin.attachConnectedGatt(gatt: BluetoothGatt) { - gattRegistry().put(gatt) - connectedGatts().add(gatt) + gattRegistry().put(gatt).setState(GattClient.State.CONNECTED) } // The pending-operation lists, typed, so a test does not spell out a reflection From f8ec0a97adcb4d10ce8e879c4579e998429ad11d Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:15:14 +0100 Subject: [PATCH 08/13] Give pending GATT operations one typed registry Eight hand-written lists held near-identical future classes that differed only in their completion type. Registering, matching the oldest entry, sweeping on a disconnect and delivering the failure were copy-pasted per list: the disconnect sweep alone was eight blocks, and each operation kind had its own lock. Each future now implements PendingOperation (gatt, deviceId, fail), and PendingOperations owns the list under its own monitor with add, addIfLinkedUp, remove, takeOldest, drainMatching, failMatching, any and size. Completion still goes through the plugin's main-looper delivery, with the same per-kind log label. failPendingOperations is eight one-line sweeps, the withdraw helpers are plain remove calls, and the MTU cache shares the MTU collection's lock. The collection also owns the link check the submission paths used to repeat, so a request is still either registered before the sweep or refused (#394). --- .../universal_ble/PendingOperations.kt | 114 +++++ .../universal_ble/UniversalBleHelper.kt | 68 +-- .../universal_ble/UniversalBlePlugin.kt | 396 +++++------------- .../GattCallbackCompletionTest.kt | 10 +- .../universal_ble/PluginTestSupport.kt | 32 +- .../universal_ble/WriteCompletionTest.kt | 2 +- 6 files changed, 283 insertions(+), 339 deletions(-) create mode 100644 android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt diff --git a/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt b/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt new file mode 100644 index 00000000..3712fb5b --- /dev/null +++ b/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt @@ -0,0 +1,114 @@ +package com.navideck.universal_ble + +import android.bluetooth.BluetoothGatt + +/** + * A request awaiting a platform callback. + * + * Every operation the plugin tracks is one of these, so registering it, + * matching it to its callback, sweeping it on a disconnect and failing it can + * be expressed once instead of per operation kind. + */ +internal interface PendingOperation { + val gatt: BluetoothGatt + val deviceId: String + + /** + * Fails this operation with [error]. Called by [PendingOperations] on the + * main thread, where platform-channel replies must be sent. + */ + fun fail(error: FlutterError) +} + +/** + * The pending requests of one kind (reads, writes, service discovery, ...). + * + * All access is under this object's monitor, which is also the lock the + * submission paths take: a request is either registered in time for a + * disconnect sweep to fail it, or refused because its link is gone (#394). + * Completion is delivered through [post] because platform-channel replies must + * be sent from the main thread, while callbacks arrive on binder threads. + */ +internal class PendingOperations( + /** How a completion reaches the main thread. */ + private val post: (() -> Unit) -> Unit, + /** Used in the delivery-failure log, e.g. "Write". */ + private val label: String, +) { + private val pending = mutableListOf() + + /** + * Runs immediately before a drain, inside the collection's lock. Unit tests + * use it to publish a state change mid-sweep (a `connect()` completing + * while a disconnect cleans up); production never sets it. + */ + internal var beforeDrain: (() -> Unit)? = null + + /** Adds [future] under the lock. */ + fun add(future: T) { + synchronized(this) { pending.add(future) } + } + + /** + * Adds [future] only if [isLinkUp] says its client still has a live link. + * Returns false when the caller must fail its call instead of submitting + * the operation. + */ + fun addIfLinkedUp( + gatt: BluetoothGatt, + future: T, + isLinkUp: (BluetoothGatt) -> Boolean, + ): Boolean = synchronized(this) { + if (!isLinkUp(gatt)) { + false + } else { + pending.add(future) + true + } + } + + /** Removes [future] while it is still registered. */ + fun remove(future: T): Boolean = synchronized(this) { pending.remove(future) } + + fun isEmpty(): Boolean = synchronized(this) { pending.isEmpty() } + + fun any(predicate: (T) -> Boolean): Boolean = + synchronized(this) { pending.any(predicate) } + + val size: Int get() = synchronized(this) { pending.size } + + /** + * Removes and returns the oldest operation matching [predicate]. A callback + * belongs to the oldest request of its kind: completing every match would + * acknowledge operations still in flight. + */ + fun takeOldest(predicate: (T) -> Boolean): T? = synchronized(this) { + val match = pending.firstOrNull(predicate) + match?.let { pending.remove(it) } + match + } + + /** Removes and returns every operation matching [predicate]. */ + fun drainMatching(predicate: (T) -> Boolean): List = synchronized(this) { + beforeDrain?.invoke() + val matches = pending.filter(predicate) + pending.removeAll(matches) + matches + } + + /** Removes and fails every operation matching [predicate]. */ + fun failMatching(error: FlutterError, predicate: (T) -> Boolean) { + for (future in drainMatching(predicate)) { + post { + try { + future.fail(error) + } catch (e: Exception) { + UniversalBleLogger.logError("$label completion delivery failed: $e") + } + } + } + } + + /** Runs [action] under this collection's lock. */ + fun withLock(action: () -> R): R = synchronized(this, action) +} diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBleHelper.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBleHelper.kt index 92b13357..cbb48580 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBleHelper.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBleHelper.kt @@ -478,35 +478,45 @@ fun Int.parseHciErrorCode(): String? { } } -// Future result classes +// Future result classes. Each implements [PendingOperation], so one collection +// can register, match, sweep and fail them. + class DiscoverServicesFuture( - val gatt: BluetoothGatt, - val deviceId: String, + override val gatt: BluetoothGatt, + override val deviceId: String, val withDescriptors: Boolean, val result: (Result>) -> Unit, -) +) : PendingOperation { + override fun fail(error: FlutterError) = result(Result.failure(error)) +} class MtuResultFuture( - val deviceId: String, - val gatt: BluetoothGatt, + override val deviceId: String, + override val gatt: BluetoothGatt, val result: (Result) -> Unit, -) +) : PendingOperation { + override fun fail(error: FlutterError) = result(Result.failure(error)) +} class ReadResultFuture( - val gatt: BluetoothGatt, - val deviceId: String, + override val gatt: BluetoothGatt, + override val deviceId: String, val characteristicId: String, val serviceId: String, val result: (Result) -> Unit, -) +) : PendingOperation { + override fun fail(error: FlutterError) = result(Result.failure(error)) +} class WriteResultFuture( - val gatt: BluetoothGatt, - val deviceId: String, + override val gatt: BluetoothGatt, + override val deviceId: String, val characteristicId: String, val serviceId: String, val result: (Result) -> Unit, -) +) : PendingOperation { + override fun fail(error: FlutterError) = result(Result.failure(error)) +} /** * A CCCD write awaiting its callback. [gatt] and [descriptor] identify the @@ -514,35 +524,43 @@ class WriteResultFuture( * they are not duplicated here. */ class SubscriptionResultFuture( - val gatt: BluetoothGatt, + override val gatt: BluetoothGatt, val descriptor: BluetoothGattDescriptor, - val deviceId: String, + override val deviceId: String, val result: (Result) -> Unit, -) +) : PendingOperation { + override fun fail(error: FlutterError) = result(Result.failure(error)) +} class RssiResultFuture( - val gatt: BluetoothGatt, - val deviceId: String, + override val gatt: BluetoothGatt, + override val deviceId: String, val result: (Result) -> Unit, -) +) : PendingOperation { + override fun fail(error: FlutterError) = result(Result.failure(error)) +} class ReadDescriptorResultFuture( - val gatt: BluetoothGatt, - val deviceId: String, + override val gatt: BluetoothGatt, + override val deviceId: String, val descriptorId: String, val characteristicId: String, val serviceId: String, val result: (Result) -> Unit, -) +) : PendingOperation { + override fun fail(error: FlutterError) = result(Result.failure(error)) +} class WriteDescriptorResultFuture( - val gatt: BluetoothGatt, - val deviceId: String, + override val gatt: BluetoothGatt, + override val deviceId: String, val descriptorId: String, val characteristicId: String, val serviceId: String, val result: (Result) -> Unit, -) +) : PendingOperation { + override fun fail(error: FlutterError) = result(Result.failure(error)) +} // Android 14+ negotiates once per connection. Older releases can request an // increase, but an MTU already meeting the requested size needs no new exchange. diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index 25b08460..6c751cc3 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -72,23 +72,26 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // Flutter Futures private var bluetoothEnableRequestFuture: ((Result) -> Unit)? = null private var bluetoothDisableRequestFuture: ((Result) -> Unit)? = null - private val discoverServicesFutureList = mutableListOf() - private val mtuResultFutureList = mutableListOf() - // Protected by mtuResultFutureList's lock. An observed MTU belongs to this - // GATT client, never to a later connection using the same device address. + private val discoveryOperations = pendingOperations("Discover services") + private val mtuOperations = pendingOperations("MTU") + // Protected by mtuOperations' lock. An observed MTU belongs to this GATT + // client, never to a later connection using the same device address. private val negotiatedMtus = WeakHashMap() - private val readResultFutureList = mutableListOf() - private val writeResultFutureList = mutableListOf() - private val readDescriptorResultFutureList = mutableListOf() - private val writeDescriptorResultFutureList = mutableListOf() - private val subscriptionResultFutureList = mutableListOf() + private val readOperations = pendingOperations("Read") + private val writeOperations = pendingOperations("Write") + private val descriptorReadOperations = + pendingOperations("Read descriptor") + private val descriptorWriteOperations = + pendingOperations("Write descriptor") + private val subscriptionOperations = + pendingOperations("Subscription") private val pairResultFutures = mutableMapOf) -> Unit>() // Addresses seen go through BOND_BONDING. A return to BOND_NONE while an address is in here is a // failed/declined bond (an event), not a steady BOND_NONE, so onBondStateUpdate() marks it as a failure // instead of letting Dart's pairing-state dedup swallow it (#325). private val bondingAttempts = mutableSetOf() - private val rssiResultFutureList = mutableListOf() + private val rssiOperations = pendingOperations("RSSI") // Per plugin instance (one per FlutterEngine): the GATT clients this engine // owns and the link state of each (see [GattRegistry]). A connect() here @@ -432,12 +435,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), try { val gatt = gattRegistry.get(deviceId).gatt if (gatt.readRemoteRssi()) { - // Pending futures are mutated both here (main thread) and in - // onReadRemoteRssi / cleanUpConnection (binder threads), so - // every access must hold the list's lock. - synchronized(rssiResultFutureList) { - rssiResultFutureList.add(RssiResultFuture(gatt, deviceId, callback)) - } + rssiOperations.add(RssiResultFuture(gatt, deviceId, callback)) } else { callback( Result.failure( @@ -460,11 +458,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // there). Every readRemoteRssi() has its own response, so this callback // belongs to the oldest pending request only — completing every match // would report one reading to a request still in flight. - val future: RssiResultFuture? - synchronized(rssiResultFutureList) { - future = rssiResultFutureList.firstOrNull { it.gatt === gatt } - future?.let { rssiResultFutureList.remove(it) } - } + val future = rssiOperations.takeOldest { it.gatt === gatt } if (future == null) { return } @@ -508,19 +502,14 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), return } if (gatt.discoverServices()) { - // Pending futures are mutated both here (main thread) and in - // onServicesDiscovered / cleanUpConnection (binder threads), so - // every access must hold the list's lock. - synchronized(discoverServicesFutureList) { - discoverServicesFutureList.add( - DiscoverServicesFuture( - gatt, - deviceId, - withDescriptors, - callback - ) + discoveryOperations.add( + DiscoverServicesFuture( + gatt, + deviceId, + withDescriptors, + callback ) - } + ) } else { callback( Result.failure( @@ -543,11 +532,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // without a result would never complete. val services: List? = if (status == BluetoothGatt.GATT_SUCCESS) gatt.services else null - val pending: List - synchronized(discoverServicesFutureList) { - pending = discoverServicesFutureList.filter { it.gatt === gatt } - discoverServicesFutureList.removeAll(pending) - } + val pending = discoveryOperations.drainMatching { it.gatt === gatt } if (services != null && gattRegistry.find(deviceId)?.gatt === gatt) { try { setCachedServices(deviceId, services.map { it.uuid.toString() }) @@ -665,7 +650,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // write the stack accepts on a disconnected autoConnect client // can be dropped without a callback, and the stranded entry // would then consume the next subscription's completion (#394). - if (!subscriptionResultFutureList.addIfLinkedUp(gatt, pending)) { + if (!subscriptionOperations.addIfLinkedUp(gatt, pending, ::isLinkUp)) { callback(Result.failure(deviceDisconnectedError())) return } @@ -760,9 +745,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), */ private fun removeSubscriptionFuture(future: SubscriptionResultFuture?): Boolean { if (future == null) return true - synchronized(subscriptionResultFutureList) { - return subscriptionResultFutureList.remove(future) - } + return subscriptionOperations.remove(future) } override fun readValue( @@ -799,7 +782,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), gattCharacteristic.service.uuid.toString(), callback ) - if (!readResultFutureList.addIfLinkedUp(gatt, readFuture)) { + if (!readOperations.addIfLinkedUp(gatt, readFuture, ::isLinkUp)) { callback(Result.failure(deviceDisconnectedError())) return } @@ -808,15 +791,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), gatt.readCharacteristic(gattCharacteristic) } catch (e: Exception) { // A callback or disconnect may already own the reply. - synchronized(readResultFutureList) { - if (!readResultFutureList.remove(readFuture)) return - } + if (!readOperations.remove(readFuture)) return throw e } if (!started) { - synchronized(readResultFutureList) { - if (!readResultFutureList.remove(readFuture)) return - } + if (!readOperations.remove(readFuture)) return callback( Result.failure( createFlutterError( @@ -859,15 +838,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), val deviceId = gatt.device.address val characteristicId = characteristic.uuid.toString() val serviceUuid = characteristic.service?.uuid?.toString() - val future: ReadResultFuture? - synchronized(readResultFutureList) { - future = readResultFutureList.firstOrNull { - it.gatt === gatt && - it.deviceId == deviceId && - it.characteristicId == characteristicId && - it.serviceId == serviceUuid - } - future?.let { readResultFutureList.remove(it) } + val future = readOperations.takeOldest { + it.gatt === gatt && + it.deviceId == deviceId && + it.characteristicId == characteristicId && + it.serviceId == serviceUuid } if (status != BluetoothGatt.GATT_SUCCESS) { UniversalBleLogger.logError( @@ -984,7 +959,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // onCharacteristicWrite. The orphaned entry would take the next // write's completion, and after the reconnect every write would lag // by one and time out (#394). - if (!writeResultFutureList.addIfLinkedUp(gatt, future)) { + if (!writeOperations.addIfLinkedUp(gatt, future, ::isLinkUp)) { callback(Result.failure(deviceDisconnectedError())) return } @@ -1036,11 +1011,12 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } private fun withdrawWriteFuture(future: WriteResultFuture) { - synchronized(writeResultFutureList) { - writeResultFutureList.remove(future) - } + writeOperations.remove(future) } + private fun pendingOperations(label: String) = + PendingOperations({ action: () -> Unit -> postToMainLooper(action) }, label) + // Deliver on the main looper. Platform-channel replies must be sent there, // and because matching futures are removed from their list before delivery, // a completion must never be dropped just because the cached handler was @@ -1064,15 +1040,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // OLDEST pending write on this characteristic — completing every match // would acknowledge later writes that are still in flight (or not yet // accepted natively) with this operation's status. - val future: WriteResultFuture? - synchronized(writeResultFutureList) { - future = writeResultFutureList.firstOrNull { - it.gatt === gatt && - it.deviceId == gatt?.device?.address && - it.characteristicId == characteristic.uuid.toString() && - it.serviceId == characteristic.service?.uuid?.toString() - } - future?.let { writeResultFutureList.remove(it) } + val future = writeOperations.takeOldest { + it.gatt === gatt && + it.deviceId == gatt?.device?.address && + it.characteristicId == characteristic.uuid.toString() && + it.serviceId == characteristic.service?.uuid?.toString() } if (status != BluetoothGatt.GATT_SUCCESS) { UniversalBleLogger.logError( @@ -1147,7 +1119,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // Register before issuing the read, as readValue does: the response // can otherwise arrive before the future is pending, and the link // check shares the lock with the disconnect cleanup (#394). - if (!readDescriptorResultFutureList.addIfLinkedUp(gatt, readFuture)) { + if (!descriptorReadOperations.addIfLinkedUp(gatt, readFuture, ::isLinkUp)) { callback(Result.failure(deviceDisconnectedError())) return } @@ -1156,15 +1128,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), gatt.readDescriptor(gattDescriptor) } catch (e: Exception) { // A callback or disconnect may already own the reply. - synchronized(readDescriptorResultFutureList) { - if (!readDescriptorResultFutureList.remove(readFuture)) return - } + if (!descriptorReadOperations.remove(readFuture)) return throw e } if (!started) { - synchronized(readDescriptorResultFutureList) { - if (!readDescriptorResultFutureList.remove(readFuture)) return - } + if (!descriptorReadOperations.remove(readFuture)) return callback( Result.failure( createFlutterError( @@ -1195,16 +1163,12 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), status: Int, value: ByteArray, ) { - val future: ReadDescriptorResultFuture? - synchronized(readDescriptorResultFutureList) { - future = readDescriptorResultFutureList.firstOrNull { - it.gatt === gatt && - it.deviceId == gatt.device.address && - it.descriptorId == descriptor.uuid.toString() && - it.characteristicId == descriptor.characteristic.uuid.toString() && - it.serviceId == descriptor.characteristic.service.uuid.toString() - } - future?.let { readDescriptorResultFutureList.remove(it) } + val future = descriptorReadOperations.takeOldest { + it.gatt === gatt && + it.deviceId == gatt.device.address && + it.descriptorId == descriptor.uuid.toString() && + it.characteristicId == descriptor.characteristic.uuid.toString() && + it.serviceId == descriptor.characteristic.service.uuid.toString() } if (future != null) { postToMainLooper { @@ -1298,7 +1262,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // Same rule as writeValue: only register while the link is up, under // the lock the disconnect cleanup takes, so a request the stack // accepts and then drops cannot survive as a stale entry (#394). - if (!writeDescriptorResultFutureList.addIfLinkedUp(gatt, future)) { + if (!descriptorWriteOperations.addIfLinkedUp(gatt, future, ::isLinkUp)) { callback(Result.failure(deviceDisconnectedError())) return } @@ -1345,9 +1309,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } private fun withdrawWriteDescriptorFuture(future: WriteDescriptorResultFuture) { - synchronized(writeDescriptorResultFutureList) { - writeDescriptorResultFutureList.remove(future) - } + descriptorWriteOperations.remove(future) } override fun requestMtu(deviceId: String, expectedMtu: Long, callback: (Result) -> Unit) { @@ -1360,16 +1322,16 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } var reusedMtu: Int? = null var shouldRequest = false - synchronized(mtuResultFutureList) { + mtuOperations.withLock { val cached = negotiatedMtus[gatt] // Android 14+ ignores subsequent negotiations. Earlier versions // can still request an increase when the observed MTU is smaller. if (cached != null && canReuseNegotiatedMtu(cached, expectedMtu.toInt(), Build.VERSION.SDK_INT)) { reusedMtu = cached } else { - val alreadyPending = mtuResultFutureList.any { it.gatt === gatt } + val alreadyPending = mtuOperations.any { it.gatt === gatt } // Register before requestMtu: its callback can arrive immediately. - mtuResultFutureList.add(MtuResultFuture(deviceId, gatt, callback)) + mtuOperations.add(MtuResultFuture(deviceId, gatt, callback)) shouldRequest = !alreadyPending } } @@ -1408,11 +1370,9 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } private fun completeMtu(gatt: BluetoothGatt, result: Result) { - val pending: List - synchronized(mtuResultFutureList) { + val pending = mtuOperations.withLock { result.getOrNull()?.let { negotiatedMtus[gatt] = it.toInt() } - pending = mtuResultFutureList.filter { it.gatt === gatt } - mtuResultFutureList.removeAll(pending) + mtuOperations.drainMatching { it.gatt === gatt } } // GATT callbacks run on Binder threads. Match the main-looper delivery // used by other BLE completions, after removing requests under the lock. @@ -1503,37 +1463,18 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), /** * Whether [gatt] has a link the platform can deliver operations on. * - * `connectedGatts` is updated from `onConnectionStateChange` on a binder - * thread, so an operation must read this inside the same lock that the - * disconnect cleanup takes: either the check sees the link already gone and - * refuses the call, or the pending result is registered in time for the - * cleanup to sweep it. Reading it outside that lock leaves a window where - * the check passes, cleanup sweeps, and the result is added afterwards — - * stranded until a later callback completes it one behind (#394). + * Client state is updated from `onConnectionStateChange` on a binder + * thread, so an operation must read this inside the lock its pending + * collection takes (see [PendingOperations.addIfLinkedUp]): either the + * check sees the link already gone and refuses the call, or the pending + * result is registered in time for the cleanup sweep to fail it. Reading it + * outside that lock leaves a window where the check passes, cleanup sweeps, + * and the result is added afterwards — stranded until a later callback + * completes it one behind (#394). */ private fun isLinkUp(gatt: BluetoothGatt): Boolean = gattRegistry.find(gatt)?.isLinkUp == true - /** - * Adds [future] to this pending list while holding its lock, but only if - * [gatt] still has a live link. Returns whether it was added; a caller that - * gets false must fail its call with `deviceDisconnected` instead of - * submitting the operation. - * - * Adding under the list's own lock is what closes the race described in - * [isLinkUp]: the disconnect cleanup sweeps the same list under the same - * lock. - */ - private fun MutableList.addIfLinkedUp(gatt: BluetoothGatt, future: T): Boolean = - synchronized(this) { - if (isLinkUp(gatt)) { - add(future) - true - } else { - false - } - } - private fun deviceDisconnectedError(): FlutterError = createFlutterError( UniversalBleErrorCode.DEVICE_DISCONNECTED, "Device Disconnected", @@ -1710,21 +1651,19 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), if (gatt.discoverServices()) { // Completed by onServicesDiscovered on a binder thread. - synchronized(discoverServicesFutureList) { - discoverServicesFutureList.add( - DiscoverServicesFuture( - gatt, - device.address, - false - ) { uuids: Result> -> - if (uuids.isSuccess) { - updateCallback(uuids.getOrNull()?.map { it.uuid }) - } else { - updateCallback(null) - } + discoveryOperations.add( + DiscoverServicesFuture( + gatt, + device.address, + false + ) { uuids: Result> -> + if (uuids.isSuccess) { + updateCallback(uuids.getOrNull()?.map { it.uuid }) + } else { + updateCallback(null) } - ) - } + } + ) return } } @@ -1795,7 +1734,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), failPendingOperations(::owns) // The observed MTU belonged to the link that is gone; the next // connection negotiates its own. - synchronized(mtuResultFutureList) { + mtuOperations.withLock { if (gatt != null) { negotiatedMtus.remove(gatt) } else { @@ -1816,130 +1755,15 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), owns: (futureGatt: BluetoothGatt, futureDeviceId: String) -> Boolean, ) { val error: FlutterError = deviceDisconnectedError() - val pendingReads: List - synchronized(readResultFutureList) { - pendingReads = readResultFutureList.filter { - owns(it.gatt, it.deviceId) - } - readResultFutureList.removeAll(pendingReads) - } - for (future in pendingReads) { - postToMainLooper { - try { - future.result(Result.failure(error)) - } catch (e: Exception) { - UniversalBleLogger.logError("Read completion delivery failed: $e") - } - } - } - val pendingWrites: List - synchronized(writeResultFutureList) { - pendingWrites = writeResultFutureList.filter { - owns(it.gatt, it.deviceId) - } - writeResultFutureList.removeAll(pendingWrites) - } - for (future in pendingWrites) { - postToMainLooper { - try { - future.result(Result.failure(error)) - } catch (e: Exception) { - UniversalBleLogger.logError("Write completion delivery failed: $e") - } - } - } - val pendingDescriptorReads: List - synchronized(readDescriptorResultFutureList) { - pendingDescriptorReads = readDescriptorResultFutureList.filter { - owns(it.gatt, it.deviceId) - } - readDescriptorResultFutureList.removeAll(pendingDescriptorReads) - } - for (future in pendingDescriptorReads) { - postToMainLooper { - try { - future.result(Result.failure(error)) - } catch (e: Exception) { - UniversalBleLogger.logError("Read descriptor completion delivery failed: $e") - } - } - } - val pendingDescriptorWrites: List - synchronized(writeDescriptorResultFutureList) { - pendingDescriptorWrites = writeDescriptorResultFutureList.filter { - owns(it.gatt, it.deviceId) - } - writeDescriptorResultFutureList.removeAll(pendingDescriptorWrites) - } - for (future in pendingDescriptorWrites) { - postToMainLooper { - try { - future.result(Result.failure(error)) - } catch (e: Exception) { - UniversalBleLogger.logError("Write descriptor completion delivery failed: $e") - } - } - } - val pendingSubscriptions: List - synchronized(subscriptionResultFutureList) { - pendingSubscriptions = subscriptionResultFutureList.filter { - owns(it.gatt, it.deviceId) - } - subscriptionResultFutureList.removeAll(pendingSubscriptions) - } - for (future in pendingSubscriptions) { - postToMainLooper { - try { - future.result(Result.failure(error)) - } catch (e: Exception) { - UniversalBleLogger.logError("Subscription completion delivery failed: $e") - } - } - } - val pendingMtus: List - synchronized(mtuResultFutureList) { - pendingMtus = mtuResultFutureList.filter { - owns(it.gatt, it.deviceId) - } - mtuResultFutureList.removeAll(pendingMtus) - } - for (future in pendingMtus) { - postMtuResult(future.result, Result.failure(error)) - } - val pendingDiscoveries: List - synchronized(discoverServicesFutureList) { - pendingDiscoveries = discoverServicesFutureList.filter { - owns(it.gatt, it.deviceId) - } - discoverServicesFutureList.removeAll(pendingDiscoveries) - } - for (future in pendingDiscoveries) { - postToMainLooper { - try { - future.result(Result.failure(error)) - } catch (e: Exception) { - UniversalBleLogger.logError( - "Discover services completion delivery failed: $e" - ) - } - } - } - val pendingRssis: List - synchronized(rssiResultFutureList) { - pendingRssis = rssiResultFutureList.filter { - owns(it.gatt, it.deviceId) - } - rssiResultFutureList.removeAll(pendingRssis) - } - for (future in pendingRssis) { - postToMainLooper { - try { - future.result(Result.failure(error)) - } catch (e: Exception) { - UniversalBleLogger.logError("RSSI completion delivery failed: $e") - } - } - } + val matches = { future: PendingOperation -> owns(future.gatt, future.deviceId) } + readOperations.failMatching(error, matches) + writeOperations.failMatching(error, matches) + descriptorReadOperations.failMatching(error, matches) + descriptorWriteOperations.failMatching(error, matches) + subscriptionOperations.failMatching(error, matches) + mtuOperations.failMatching(error, matches) + discoveryOperations.failMatching(error, matches) + rssiOperations.failMatching(error, matches) } private fun cleanConnection(gatt: BluetoothGatt) { @@ -2205,16 +2029,12 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // testOptions.unitTests.returnDefaultValues, which would also make // every other unstubbed android.jar call in the suite fail silently. if (descriptor != null) { - val future: WriteDescriptorResultFuture? - synchronized(writeDescriptorResultFutureList) { - future = writeDescriptorResultFutureList.firstOrNull { - it.gatt === gatt && - it.deviceId == gatt?.device?.address && - it.descriptorId == descriptor.uuid.toString() && - it.characteristicId == descriptor.characteristic?.uuid?.toString() && - it.serviceId == descriptor.characteristic?.service?.uuid?.toString() - } - future?.let { writeDescriptorResultFutureList.remove(it) } + val future = descriptorWriteOperations.takeOldest { + it.gatt === gatt && + it.deviceId == gatt?.device?.address && + it.descriptorId == descriptor.uuid.toString() && + it.characteristicId == descriptor.characteristic?.uuid?.toString() && + it.serviceId == descriptor.characteristic?.service?.uuid?.toString() } if (future != null) { postToMainLooper { @@ -2248,21 +2068,17 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // Runs on a binder thread (the CCCD write callback): match and remove // under the lock, then complete on the main thread, where // platform-channel replies must be sent. - val future: SubscriptionResultFuture? - synchronized(subscriptionResultFutureList) { - // A replaced connection can report the same address and UUIDs. - // Only the exact GATT and descriptor that submitted the request own it. - future = subscriptionResultFutureList.firstOrNull { - it.gatt === gatt && it.descriptor === descriptor - } ?: subscriptionResultFutureList.firstOrNull { - // A discoverServices() completing between the CCCD write and its - // callback rebuilds the service tree, so the framework reports a - // fresh descriptor object for the same attribute. Match on that - // identity instead; without it the caller would await forever. - // The GATT check keeps a replaced connection out. - it.gatt === gatt && it.descriptor.sameAttributeAs(descriptor) - } - future?.let { subscriptionResultFutureList.remove(it) } + // A replaced connection can report the same address and UUIDs. Only the + // exact GATT and descriptor that submitted the request own it. + val future = subscriptionOperations.takeOldest { + it.gatt === gatt && it.descriptor === descriptor + } ?: subscriptionOperations.takeOldest { + // A discoverServices() completing between the CCCD write and its + // callback rebuilds the service tree, so the framework reports a + // fresh descriptor object for the same attribute. Match on that + // identity instead; without it the caller would await forever. + // The GATT check keeps a replaced connection out. + it.gatt === gatt && it.descriptor.sameAttributeAs(descriptor) } if (future == null) { return diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt index d435aeb3..ef5694a4 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt @@ -609,7 +609,8 @@ internal class GattCallbackCompletionTest { val old = mockGatt(deviceAddress) val current = mockGatt(deviceAddress) val results = mutableListOf>() - val items = mutableListOf( + val reads = plugin.pendingReads() + reads.add( ReadResultFuture( current, deviceAddress, charUuid.toString(), serviceUuid.toString() ) { results.add(it) } @@ -617,12 +618,7 @@ internal class GattCallbackCompletionTest { // A connect() publishes the replacement while this sweep is running: // the requests that client owns must survive, so the registry has to be // read at match time rather than once when the sweep starts. - plugin.setField("readResultFutureList", object : MutableList by items { - override fun iterator(): MutableIterator { - plugin.gattRegistry().put(current) - return items.iterator() - } - }) + reads.beforeDrain = { plugin.gattRegistry().put(current) } val cleanup = UniversalBlePlugin::class.java.getDeclaredMethod( "cleanUpConnection", String::class.java, BluetoothGatt::class.java ).apply { isAccessible = true } diff --git a/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt b/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt index 4f47e839..5e970632 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/PluginTestSupport.kt @@ -38,26 +38,26 @@ internal fun UniversalBlePlugin.attachConnectedGatt(gatt: BluetoothGatt) { // The pending-operation lists, typed, so a test does not spell out a reflection // key every time. They are the live lists, not copies. -internal fun UniversalBlePlugin.pendingReads(): MutableList = - getField("readResultFutureList") +internal fun UniversalBlePlugin.pendingReads(): PendingOperations = + getField("readOperations") -internal fun UniversalBlePlugin.pendingWrites(): MutableList = - getField("writeResultFutureList") +internal fun UniversalBlePlugin.pendingWrites(): PendingOperations = + getField("writeOperations") -internal fun UniversalBlePlugin.pendingDescriptorReads(): MutableList = - getField("readDescriptorResultFutureList") +internal fun UniversalBlePlugin.pendingDescriptorReads(): PendingOperations = + getField("descriptorReadOperations") -internal fun UniversalBlePlugin.pendingDescriptorWrites(): MutableList = - getField("writeDescriptorResultFutureList") +internal fun UniversalBlePlugin.pendingDescriptorWrites(): PendingOperations = + getField("descriptorWriteOperations") -internal fun UniversalBlePlugin.pendingSubscriptions(): MutableList = - getField("subscriptionResultFutureList") +internal fun UniversalBlePlugin.pendingSubscriptions(): PendingOperations = + getField("subscriptionOperations") -internal fun UniversalBlePlugin.pendingMtus(): MutableList = - getField("mtuResultFutureList") +internal fun UniversalBlePlugin.pendingMtus(): PendingOperations = + getField("mtuOperations") -internal fun UniversalBlePlugin.pendingRssis(): MutableList = - getField("rssiResultFutureList") +internal fun UniversalBlePlugin.pendingRssis(): PendingOperations = + getField("rssiOperations") -internal fun UniversalBlePlugin.pendingDiscoveries(): MutableList = - getField("discoverServicesFutureList") +internal fun UniversalBlePlugin.pendingDiscoveries(): PendingOperations = + getField("discoveryOperations") diff --git a/android/src/test/kotlin/com/navideck/universal_ble/WriteCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/WriteCompletionTest.kt index e49e59e1..aac24f52 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/WriteCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/WriteCompletionTest.kt @@ -29,7 +29,7 @@ internal class WriteCompletionTest { private val requestGatt by lazy { mockGatt(deviceAddress) } - private fun pendingWrites(plugin: UniversalBlePlugin): MutableList = + private fun pendingWrites(plugin: UniversalBlePlugin): PendingOperations = plugin.pendingWrites() private fun pendingFuture(acks: MutableList>) = WriteResultFuture( From e34cfe1b3a3abe07865f7d9085deb4210ff309f1 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:16:37 +0100 Subject: [PATCH 09/13] Submit GATT requests through one path readValue, writeValue, readDescriptorValue and writeDescriptorValue each repeated the same sequence: resolve the characteristic or descriptor, validate it, register a pending result with the link check, call the stack, withdraw and fail when it refused, and withdraw again in the exception handler. The validation ordering was a comment in three of them, and the refusal mapping was easy to get subtly different. submitGattRequest() now owns registration, submission and withdrawal. It keeps the link check and the registration under the pending collection's lock, so the disconnect sweep cannot strand a request that is accepted afterwards (#394), and it withdraws a refused or throwing call so a completion cannot be delivered to an orphaned entry (#387). Callers pass their stack call and the error their operation reports for a refusal, which keeps deviceNotFound, characteristicNotFound, the write-support codes and invalidAttributeLength in their existing order. The withdrawal now also reports whether another path already claimed the reply. A disconnect that sweeps a read or write while its stack call is running answers the Dart call once, instead of racing a second reply. --- .../universal_ble/UniversalBlePlugin.kt | 316 +++++++++--------- 1 file changed, 159 insertions(+), 157 deletions(-) diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index 6c751cc3..da57fba7 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -775,35 +775,32 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // call awaiting forever. Every access to the list holds its lock. // The link check shares the lock, so a disconnected client cannot // leave a read that the stack drops without a callback (#394). - val readFuture = ReadResultFuture( + submitGattRequest( gatt, - gatt.device.address, - gattCharacteristic.uuid.toString(), - gattCharacteristic.service.uuid.toString(), - callback - ) - if (!readOperations.addIfLinkedUp(gatt, readFuture, ::isLinkUp)) { - callback(Result.failure(deviceDisconnectedError())) - return - } - - val started = try { - gatt.readCharacteristic(gattCharacteristic) - } catch (e: Exception) { - // A callback or disconnect may already own the reply. - if (!readOperations.remove(readFuture)) return - throw e - } - if (!started) { - if (!readOperations.remove(readFuture)) return - callback( - Result.failure( - createFlutterError( - UniversalBleErrorCode.CHARACTERISTIC_NOT_FOUND, - "$characteristic not found", - ) + readOperations, + ReadResultFuture( + gatt, + gatt.device.address, + gattCharacteristic.uuid.toString(), + gattCharacteristic.service.uuid.toString(), + callback + ), + issue = { + if (gatt.readCharacteristic(gattCharacteristic)) { + BluetoothGatt.GATT_SUCCESS + } else { + BluetoothGatt.GATT_FAILURE + } + }, + statusError = { + createFlutterError( + UniversalBleErrorCode.CHARACTERISTIC_NOT_FOUND, + "$characteristic not found", ) - ) + }, + )?.let { failure -> + callback(Result.failure(failure)) + return } } catch (e: FlutterError) { callback(Result.failure(e)) @@ -881,7 +878,6 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), bleOutputProperty: BleOutputProperty, callback: (Result) -> Unit, ) { - var writeFuture: WriteResultFuture? = null try { UniversalBleLogger.logDebug("WRITE -> $deviceId $service $characteristic len=${value.size} property=$bleOutputProperty") val gatt = gattRegistry.get(deviceId).gatt @@ -941,63 +937,48 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), return } - val future = WriteResultFuture( + submitGattRequest( gatt, - gatt.device.address, - gattCharacteristic.uuid.toString(), - gattCharacteristic.service.uuid.toString(), - callback - ) - - // Wait for the result. The list is mutated both here (main thread) - // and in onCharacteristicWrite / cleanUpConnection (Bluetooth - // binder threads), so every access must hold the lock. - // - // Register only while the link is up, and under that same lock: an - // autoConnect client stays open after a link loss, so the stack can - // accept a write and then drop it without ever calling - // onCharacteristicWrite. The orphaned entry would take the next - // write's completion, and after the reconnect every write would lag - // by one and time out (#394). - if (!writeOperations.addIfLinkedUp(gatt, future, ::isLinkUp)) { - callback(Result.failure(deviceDisconnectedError())) - return - } - writeFuture = future - - val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - gatt.writeCharacteristic(gattCharacteristic, value, writeType) - } else { - @Suppress("DEPRECATION") - gattCharacteristic.value = value - gattCharacteristic.writeType = writeType - @Suppress("DEPRECATION") - val status = gatt.writeCharacteristic(gattCharacteristic) - if (status) BluetoothGatt.GATT_SUCCESS else BluetoothGatt.GATT_FAILURE - } - - if (result != BluetoothGatt.GATT_SUCCESS) { - withdrawWriteFuture(future) - callback( - Result.failure( - createFlutterError( - gattStatusToUniversalBleErrorCode(result), - "Failed to write", - result.toString() - ) + writeOperations, + WriteResultFuture( + gatt, + gatt.device.address, + gattCharacteristic.uuid.toString(), + gattCharacteristic.service.uuid.toString(), + callback + ), + issue = { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + gatt.writeCharacteristic(gattCharacteristic, value, writeType) + } else { + @Suppress("DEPRECATION") + gattCharacteristic.value = value + gattCharacteristic.writeType = writeType + @Suppress("DEPRECATION") + if (gatt.writeCharacteristic(gattCharacteristic)) { + BluetoothGatt.GATT_SUCCESS + } else { + BluetoothGatt.GATT_FAILURE + } + } + }, + statusError = { status -> + createFlutterError( + gattStatusToUniversalBleErrorCode(status), + "Failed to write", + status.toString() ) - ) + }, + )?.let { failure -> + callback(Result.failure(failure)) } } catch (e: FlutterError) { - writeFuture?.let(::withdrawWriteFuture) callback(Result.failure(e)) } catch (e: Exception) { // A write the stack refuses by throwing (a characteristic whose // service is gone, for example) never reaches onCharacteristicWrite. - // Fail this call and unregister its result: otherwise the next - // completion is delivered to the orphaned future and every later - // write lags by one. - writeFuture?.let(::withdrawWriteFuture) + // The submission already unregistered its result, so the next + // completion cannot be delivered to the orphaned future. callback( Result.failure( createFlutterError( @@ -1010,13 +991,49 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } } - private fun withdrawWriteFuture(future: WriteResultFuture) { - writeOperations.remove(future) - } - private fun pendingOperations(label: String) = PendingOperations({ action: () -> Unit -> postToMainLooper(action) }, label) + /** + * Registers [pending] for a GATT request and submits it with [issue]. + * + * Returns null when the request is pending, i.e. the platform is expected + * to report it through a callback, or the failure to deliver when it was + * refused. A request is registered only while its client's link is up, and + * under the pending collection's lock, so a disconnect cannot sweep the + * list in between and strand it (#394). A stack call that refuses the + * request, by returning a non-success [BluetoothGatt] status or by + * throwing, has its registration withdrawn here: otherwise the next + * completion would be delivered to the orphaned entry and every later + * operation would lag by one (#387). + * + * Callers keep their own error mapping: [statusError] turns a refusal into + * the code that operation has always reported. + */ + private fun submitGattRequest( + gatt: BluetoothGatt, + operations: PendingOperations, + pending: T, + issue: () -> Int, + statusError: (Int) -> FlutterError, + ): FlutterError? { + if (!operations.addIfLinkedUp(gatt, pending, ::isLinkUp)) { + return deviceDisconnectedError() + } + val status = try { + issue() + } catch (e: Exception) { + // A callback (or a disconnect sweep) may already own the reply. + if (!operations.remove(pending)) return null + throw e + } + if (status == BluetoothGatt.GATT_SUCCESS) return null + // A sweep or callback may have claimed the reply while the stack call + // was running; in that case it already answered for this request. + if (!operations.remove(pending)) return null + return statusError(status) + } + // Deliver on the main looper. Platform-channel replies must be sent there, // and because matching futures are removed from their list before delivery, // a completion must never be dropped just because the cached handler was @@ -1108,39 +1125,35 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) return } - val readFuture = ReadDescriptorResultFuture( - gatt, - gatt.device.address, - gattDescriptor.uuid.toString(), - gattCharacteristic.uuid.toString(), - gattCharacteristic.service.uuid.toString(), - callback - ) // Register before issuing the read, as readValue does: the response - // can otherwise arrive before the future is pending, and the link - // check shares the lock with the disconnect cleanup (#394). - if (!descriptorReadOperations.addIfLinkedUp(gatt, readFuture, ::isLinkUp)) { - callback(Result.failure(deviceDisconnectedError())) - return - } - - val started = try { - gatt.readDescriptor(gattDescriptor) - } catch (e: Exception) { - // A callback or disconnect may already own the reply. - if (!descriptorReadOperations.remove(readFuture)) return - throw e - } - if (!started) { - if (!descriptorReadOperations.remove(readFuture)) return - callback( - Result.failure( - createFlutterError( - UniversalBleErrorCode.READ_FAILED, - "Failed to read descriptor" - ) + // can otherwise arrive before the future is pending (#394). + submitGattRequest( + gatt, + descriptorReadOperations, + ReadDescriptorResultFuture( + gatt, + gatt.device.address, + gattDescriptor.uuid.toString(), + gattCharacteristic.uuid.toString(), + gattCharacteristic.service.uuid.toString(), + callback + ), + issue = { + if (gatt.readDescriptor(gattDescriptor)) { + BluetoothGatt.GATT_SUCCESS + } else { + BluetoothGatt.GATT_FAILURE + } + }, + statusError = { + createFlutterError( + UniversalBleErrorCode.READ_FAILED, + "Failed to read descriptor" ) - ) + }, + )?.let { failure -> + callback(Result.failure(failure)) + return } } catch (e: FlutterError) { callback(Result.failure(e)) @@ -1206,7 +1219,6 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), value: ByteArray, callback: (Result) -> Unit, ) { - var writeFuture: WriteDescriptorResultFuture? = null try { UniversalBleLogger.logDebug("WRITE_DESCRIPTOR -> $deviceId $service $characteristic $descriptor len=${value.size}") val gatt = gattRegistry.get(deviceId).gatt @@ -1250,52 +1262,46 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), return } - val future = WriteDescriptorResultFuture( + submitGattRequest( gatt, - gatt.device.address, - gattDescriptor.uuid.toString(), - gattCharacteristic.uuid.toString(), - gattCharacteristic.service.uuid.toString(), - callback - ) - - // Same rule as writeValue: only register while the link is up, under - // the lock the disconnect cleanup takes, so a request the stack - // accepts and then drops cannot survive as a stale entry (#394). - if (!descriptorWriteOperations.addIfLinkedUp(gatt, future, ::isLinkUp)) { - callback(Result.failure(deviceDisconnectedError())) - return - } - writeFuture = future - - val status = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - gatt.writeDescriptor(gattDescriptor, value) - } else { - @Suppress("DEPRECATION") - gattDescriptor.value = value - @Suppress("DEPRECATION") - if (gatt.writeDescriptor(gattDescriptor)) BluetoothGatt.GATT_SUCCESS else BluetoothGatt.GATT_FAILURE - } - - if (status != BluetoothGatt.GATT_SUCCESS) { - withdrawWriteDescriptorFuture(future) - callback( - Result.failure( - createFlutterError( - gattStatusToUniversalBleErrorCode(status), - "Failed to write descriptor", - status.toString() - ) + descriptorWriteOperations, + WriteDescriptorResultFuture( + gatt, + gatt.device.address, + gattDescriptor.uuid.toString(), + gattCharacteristic.uuid.toString(), + gattCharacteristic.service.uuid.toString(), + callback + ), + issue = { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + gatt.writeDescriptor(gattDescriptor, value) + } else { + @Suppress("DEPRECATION") + gattDescriptor.value = value + @Suppress("DEPRECATION") + if (gatt.writeDescriptor(gattDescriptor)) { + BluetoothGatt.GATT_SUCCESS + } else { + BluetoothGatt.GATT_FAILURE + } + } + }, + statusError = { status -> + createFlutterError( + gattStatusToUniversalBleErrorCode(status), + "Failed to write descriptor", + status.toString() ) - ) + }, + )?.let { failure -> + callback(Result.failure(failure)) } } catch (e: FlutterError) { - writeFuture?.let(::withdrawWriteDescriptorFuture) callback(Result.failure(e)) } catch (e: Exception) { - // Withdraw the pending result before failing the call, so a refused - // descriptor write cannot consume the next completion. - writeFuture?.let(::withdrawWriteDescriptorFuture) + // The submission unregistered the pending result before rethrowing, + // so a refused descriptor write cannot consume the next completion. callback( Result.failure( createFlutterError( @@ -1308,10 +1314,6 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } } - private fun withdrawWriteDescriptorFuture(future: WriteDescriptorResultFuture) { - descriptorWriteOperations.remove(future) - } - override fun requestMtu(deviceId: String, expectedMtu: Long, callback: (Result) -> Unit) { UniversalBleLogger.logDebug("REQUEST_MTU -> $deviceId expected=$expectedMtu") val gatt = try { From 58276ffeb2c954366dad949045eb2594e67ebfbc Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:19:24 +0100 Subject: [PATCH 10/13] Split setNotifiable into a CCCD write and the notification toggle The function carried two local closures, a reassigned pending future, nested try/catch around the deprecated and the API 33+ descriptor overloads, and a switch to the characteristic notification. The reply bookkeeping was the hardest part to follow, and it had a real bug: the inner handler withdrew the pending result and rethrew, then the outer handler tried to withdraw again, found nothing, and sent no reply at all. A throwing CCCD write (a descriptor rebuilt by a concurrent discovery, a closed client) left the Dart call awaiting until its timeout. Extract writeCccdDescriptor() and its status mapping, and give the function a single reply path: the pending future is withdrawn once, and the failure is delivered by the same place that detected it. A CCCD callback or disconnect that already owns the reply still wins, so nothing is answered twice. Cover both directions: a throwing CCCD write answers exactly once, and a write swept by a disconnect while the stack refuses it is not answered twice. --- CHANGELOG.md | 1 + .../universal_ble/UniversalBlePlugin.kt | 164 +++++++++--------- .../GattCallbackCompletionTest.kt | 65 +++++++ 3 files changed, 147 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4287f85a..2c37f019 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ ## 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. * Linux: a read, write, descriptor read/write or subscription submitted while the device is disconnected now fails with `deviceDisconnected` instead of `characteristicNotFound` or a generic `readFailed`/`writeFailed`. BlueZ drops the GATT object tree together with the link, so the lookup used to report the characteristic as unknown — as if the device had changed its services — and a request that reached D-Bus failed with `NotConnected` under a generic code (#394). * Web: the same requests now fail with `deviceDisconnected` instead of surfacing the browser's `NetworkError` as an unclassified error, and an unknown device reports `deviceNotFound` instead of a missing characteristic. The service cache is cleared on disconnection, so the lookup previously failed before the browser could say the link was gone (#394). * Windows: the same requests now fail with `deviceDisconnected` when the link is down but the connection-status callback has not removed the client yet. The operation used to be submitted anyway and completed with `Unreachable`, which surfaced as `failed` (#394). diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index da57fba7..5d460b26 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -11,7 +11,6 @@ import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothGattService import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile -import android.bluetooth.BluetoothStatusCodes import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanFilter import android.bluetooth.le.ScanResult @@ -603,15 +602,14 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), bleInputProperty: BleInputProperty, callback: (Result) -> Unit, ) { - // Assigned once the CCCD request is registered; declared out here so the - // error paths below can withdraw it too. - var pendingFuture: SubscriptionResultFuture? = null + // Assigned once the CCCD request is registered. Every failure below + // withdraws it before replying, so the Dart call gets exactly one + // answer: from here, from the CCCD callback, or from a disconnect. + var pending: SubscriptionResultFuture? = null try { UniversalBleLogger.logDebug("SET_NOTIFY -> $deviceId $service $characteristic input=$bleInputProperty") val gatt = gattRegistry.get(deviceId).gatt - val gattCharacteristic: BluetoothGattCharacteristic? = - gatt.getCharacteristic(service, characteristic) - + val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( Result.failure( @@ -623,89 +621,49 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) return } - - val descriptor: BluetoothGattDescriptor? = - gattCharacteristic.getDescriptor(ccdCharacteristic) - + val descriptor = gattCharacteristic.getDescriptor(ccdCharacteristic) val (value, enable) = when (bleInputProperty) { BleInputProperty.NOTIFICATION -> BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE to true BleInputProperty.INDICATION -> BluetoothGattDescriptor.ENABLE_INDICATION_VALUE to true else -> BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE to false } - // Register before issuing the CCCD write, as readValue does: the - // write's callback arrives on a binder thread and a future added - // afterwards is never matched (updateSubscriptionState finds - // nothing to complete), leaving the Dart call awaiting forever. - // Every access to the list holds its lock. - val pending: SubscriptionResultFuture? = - if (descriptor == null) null else SubscriptionResultFuture( + /** Withdraws the pending request, then answers the Dart call once. */ + fun fail(error: FlutterError) { + val future = pending + if (!removeSubscriptionFuture(future)) return + if (future == null) callback(Result.failure(error)) else future.fail(error) + } + + if (descriptor != null) { + pending = SubscriptionResultFuture( gatt, descriptor, gatt.device.address, callback, ) - if (pending != null) { - // Only register while the link is up (see writeValue): a CCCD - // write the stack accepts on a disconnected autoConnect client - // can be dropped without a callback, and the stranded entry - // would then consume the next subscription's completion (#394). + // Register before issuing the CCCD write, as readValue does: the + // write's callback arrives on a binder thread and a future added + // afterwards is never matched, leaving the Dart call awaiting + // forever. The link check shares the lock, so a disconnected + // autoConnect client cannot leave an entry the stack drops + // without a callback (#394). if (!subscriptionOperations.addIfLinkedUp(gatt, pending, ::isLinkUp)) { callback(Result.failure(deviceDisconnectedError())) return } - pendingFuture = pending - } - - /** Withdraws [pending] so a later callback cannot reply twice. */ - fun withdraw(): Boolean = removeSubscriptionFuture(pending) - - fun fail(error: FlutterError) { - if (!withdraw()) return - callback(Result.failure(error)) - } - - if (descriptor != null) { - // Some devices do not need CCCD to update - @Suppress("DEPRECATION") - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - val status = try { - gatt.writeDescriptor(descriptor, value) - } catch (e: Exception) { - // A callback or disconnect may already own the reply. - if (!withdraw()) return - throw e - } - if (status != BluetoothStatusCodes.SUCCESS) { - fail( - createFlutterError( - status.parseBluetoothStatusCodeError() - ?: UniversalBleErrorCode.FAILED, - "Failed to update descriptor" - ) - ) - return - } - } else { - descriptor.value = value - val started = try { - gatt.writeDescriptor(descriptor) - } catch (e: Exception) { - // A callback or disconnect may already own the reply. - if (!withdraw()) return - throw e - } - if (!started) { - fail( - createFlutterError( - UniversalBleErrorCode.FAILED, - "Failed to update descriptor" - ) + val status = writeCccdDescriptor(gatt, descriptor, value) + if (status != BluetoothGatt.GATT_SUCCESS) { + fail( + createFlutterError( + cccDescriptorErrorCode(status), + "Failed to update descriptor" ) - return - } + ) + return } } else { + // Some devices do not need CCCD to update. UniversalBleLogger.logDebug("CCCD Descriptor not found") } @@ -722,23 +680,63 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) ) } - } catch (e: FlutterError) { - if (removeSubscriptionFuture(pendingFuture)) callback(Result.failure(e)) } catch (e: Exception) { - if (removeSubscriptionFuture(pendingFuture)) { - callback( - Result.failure( - createFlutterError( - UniversalBleErrorCode.FAILED, - "Failed to update subscription state", - e.toString() - ) - ) + val error = if (e is FlutterError) { + e + } else { + createFlutterError( + UniversalBleErrorCode.FAILED, + "Failed to update subscription state", + e.toString() ) } + // A CCCD callback or a disconnect sweep may already have answered; + // withdrawing first keeps this path from replying twice. + if (pending == null || subscriptionOperations.remove(pending)) { + callback(Result.failure(error)) + } } } + /** + * Writes [value] to the CCCD, or to the descriptor that enables indications + * or notifications, and returns the status the stack reported. The API 33+ + * overload reports one; the deprecated one only a boolean, mapped here. + * A throwing call propagates to the caller's single error path. + * + * [value] is nullable because the values come from static arrays in the + * platform jar, which JVM tests see as null. The deprecated overload only + * stores the array, and the API 33+ overload — unreachable there, because + * the test JVM reports SDK_INT 0 — needs the non-null value a device has. + */ + @Suppress("DEPRECATION") + private fun writeCccdDescriptor( + gatt: BluetoothGatt, + descriptor: BluetoothGattDescriptor, + value: ByteArray?, + ): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + gatt.writeDescriptor(descriptor, checkNotNull(value)) + } else { + descriptor.value = value + if (gatt.writeDescriptor(descriptor)) { + BluetoothGatt.GATT_SUCCESS + } else { + BluetoothGatt.GATT_FAILURE + } + } + + /** + * The error a refused CCCD write reports. The pre-33 overload only says + * whether the request started, so it keeps the generic code; API 33+ + * carries a status that names the reason. + */ + private fun cccDescriptorErrorCode(status: Int): UniversalBleErrorCode = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + status.parseBluetoothStatusCodeError() ?: UniversalBleErrorCode.FAILED + } else { + UniversalBleErrorCode.FAILED + } + /** * Removes [future] while it is still registered. False means a callback (or * a device cleanup) already owns the reply, which must not be sent twice. diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt index ef5694a4..ea514c15 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt @@ -520,6 +520,71 @@ internal class GattCallbackCompletionTest { ) } + @Test + fun aThrowingCccdWriteFailsTheSubscriptionExactlyOnce() { + val plugin = plugin() + val results = mutableListOf>() + val characteristic = mockCharacteristic(serviceUuid, charUuid) + val cccd = mockDescriptor(characteristic, "00002902-0000-1000-8000-00805f9b34fb") + Mockito.`when`(characteristic.getDescriptor(ccdCharacteristic)).thenReturn(cccd) + val gatt = mockGattWithService(characteristic) + // A descriptor the framework has rebuilt out from under the call, or a + // closed client, throws instead of returning a status. + Mockito.`when`(gatt.writeDescriptor(cccd)) + .thenThrow(IllegalStateException("GATT client closed")) + plugin.attachConnectedGatt(gatt) + + plugin.setNotifiable( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + BleInputProperty.NOTIFICATION, + ) { results.add(it) } + drainMainLooper() + + assertEquals(1, results.size, "a throwing CCCD write must answer the call once") + assertTrue(results.single().isFailure) + assertTrue( + plugin.pendingSubscriptions().isEmpty(), + "the withdraw happens before the reply, not instead of it" + ) + } + + @Test + fun aWriteSweptWhileTheStackRefusesItIsNotAnsweredTwice() { + val plugin = plugin() + val writes = mutableListOf>() + val characteristic = mockCharacteristic(serviceUuid, charUuid) + Mockito.`when`(characteristic.properties).thenReturn( + BluetoothGattCharacteristic.PROPERTY_WRITE, + ) + val gatt = mockGattWithService(characteristic) + // A binder-thread disconnect can sweep the write before the synchronous + // refusal is handled. The sweep owns the reply from then on. + Mockito.`when`(gatt.writeCharacteristic(characteristic)).thenAnswer { + plugin.onConnectionStateChange( + gatt, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_DISCONNECTED + ) + false + } + plugin.attachConnectedGatt(gatt) + + plugin.writeValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + ByteArray(4), + BleOutputProperty.WITH_RESPONSE, + ) { writes.add(it) } + + drainMainLooper() + assertEquals(1, writes.size, "one write must send exactly one reply") + assertEquals( + UniversalBleErrorCode.DEVICE_DISCONNECTED.raw.toString(), + (writes.single().exceptionOrNull() as FlutterError).code, + ) + } + @Test fun rejectedSubscriptionLeavesNoPendingFuture() { val plugin = plugin() From 482f6a4ff6ee6896ff8dbfb4c88cd2c15970917a Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:41:59 +0100 Subject: [PATCH 11/13] Keep the link check and the disconnect report correct through a teardown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit STATE_DISCONNECTED took the client's link down only after sweeping the pending collections, so a request submitted while the sweep ran passed the link check, registered in a list that had already been swept, and then reached a dead link — the #394 hang the ordering was meant to prevent. Settle the client's state (AWAITING_RECONNECT or CLOSING) before the sweep, as the old connected-set did, and keep the client in the active slot until it is done so a replacement published meanwhile is still told apart from it. The disconnect report read `wasConnected` from the client's state, which disconnect() has already moved to CLOSING, so a locally initiated teardown that carries a non-zero status reported connectionFailed instead of the status-specific code. GattClient now remembers that the link came up and hands it out once per STATE_DISCONNECTED. cleanConnection() no longer publishes an untracked client: a teardown racing the fallback timer could evict a newer connection from the active slot. And connect() now tears down the client it replaces — a client left waiting for autoConnect to reconnect it was dropped from the registry but never closed, so it kept an open GATT and an autoConnect attempt next to the new link. --- CHANGELOG.md | 1 + .../navideck/universal_ble/GattRegistry.kt | 38 ++++++---- .../universal_ble/UniversalBlePlugin.kt | 49 +++++++++---- .../universal_ble/DisconnectCloseTest.kt | 70 ++++++++++++++++++- .../universal_ble/LinkLossOperationTest.kt | 31 ++++++++ 5 files changed, 160 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c37f019..6a28ce49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## 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. +* Android: `connect()` now closes the GATT client it replaces instead of leaving it open. A client left waiting for `autoConnect` to reconnect it — or one whose own `STATE_CONNECTED` had not arrived yet — was dropped from the registry but never closed, so it kept an autoConnect attempt (and the radio) alive next to the new connection. * Linux: a read, write, descriptor read/write or subscription submitted while the device is disconnected now fails with `deviceDisconnected` instead of `characteristicNotFound` or a generic `readFailed`/`writeFailed`. BlueZ drops the GATT object tree together with the link, so the lookup used to report the characteristic as unknown — as if the device had changed its services — and a request that reached D-Bus failed with `NotConnected` under a generic code (#394). * Web: the same requests now fail with `deviceDisconnected` instead of surfacing the browser's `NetworkError` as an unclassified error, and an unknown device reports `deviceNotFound` instead of a missing characteristic. The service cache is cleared on disconnection, so the lookup previously failed before the browser could say the link was gone (#394). * Windows: the same requests now fail with `deviceDisconnected` when the link is down but the connection-status callback has not removed the client yet. The operation used to be submitted anyway and completed with `Unreachable`, which surfaced as `failed` (#394). diff --git a/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt b/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt index 853c5859..5aca6bd0 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt @@ -2,6 +2,7 @@ package com.navideck.universal_ble import android.bluetooth.BluetoothGatt import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference /** @@ -33,6 +34,15 @@ internal class GattClient(val gatt: BluetoothGatt) { private val stateRef = AtomicReference(State.CONNECTING) + /** + * Whether the link came up since the previous disconnect. Android reports a + * failed connection attempt and a peer disconnect the same way, so the + * disconnect report reads this to tell them apart. [state] cannot answer it: + * a `disconnect()` has already moved the client to [State.CLOSING], and the + * `STATE_DISCONNECTED` that follows belongs to a link that was up. + */ + private val linkCameUp = AtomicBoolean(false) + /** Whether Android may reconnect this client after a link loss. */ @Volatile var autoConnect: Boolean = false @@ -45,9 +55,17 @@ internal class GattClient(val gatt: BluetoothGatt) { val isLinkUp: Boolean get() = state == State.CONNECTED fun setState(next: State) { + if (next == State.CONNECTED) linkCameUp.set(true) stateRef.set(next) } + /** + * Reads and clears whether the link had come up, i.e. whether the disconnect + * being reported ended a live link rather than a failed attempt. Called once + * per `STATE_DISCONNECTED`. + */ + fun takeLinkWasUp(): Boolean = linkCameUp.getAndSet(false) + /** * Moves the client from [expected] to [next], returning false when another * thread got there first. Used where two paths race to finish a teardown @@ -67,11 +85,13 @@ internal class GattClient(val gatt: BluetoothGatt) { * * [active] maps an address to the client its callbacks and API calls currently * belong to. [clients] tracks every client the plugin still owes a teardown, - * including ones that were replaced or are closing, so a late callback can - * still be attributed (and ignored) and its close is still driven. A connect() - * can publish a replacement only after the previous client's link is gone, and - * that client may still be waiting for its own STATE_DISCONNECTED — the reason - * the two maps exist. + * including ones that are closing, so a late callback can still be attributed + * (and ignored) and its close is still driven. A connect() can publish a + * replacement only after the previous client's link is gone, and that client + * may still be waiting for its own STATE_DISCONNECTED — the reason the two maps + * exist. `connect()` tears the client it replaces down, so [clients] does not + * accumulate replaced entries: everything it holds besides the active client is + * on its way to [GattClient.State.CLOSED]. */ internal class GattRegistry { private val active = ConcurrentHashMap() @@ -104,14 +124,6 @@ internal class GattRegistry { return client } - /** - * Every client tracked for [deviceId], in any state. Used by `disconnect()` - * and detach to withdraw autoConnect from clients that a replacement has - * already taken out of the active slot. - */ - fun forAddress(deviceId: String): List = - clients.values.filter { it.address == deviceId } - /** * Starts closing [client]: it leaves the active slot immediately, so API * calls for the address fail with `deviceNotFound`, while [clients] keeps diff --git a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt index 5d460b26..acb536c3 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePlugin.kt @@ -338,7 +338,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // Note: platformConfig carries platform-specific connection options // If already connected, send connected message, // if connecting, do nothing - gattRegistry.find(deviceId)?.let { existing -> + val replaced = gattRegistry.find(deviceId) + replaced?.let { existing -> val currentState = bluetoothManager.getConnectionState(existing.gatt.device, BluetoothProfile.GATT) if (currentState == BluetoothGatt.STATE_CONNECTED) { @@ -353,10 +354,6 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), "Connection already in progress" ) } - // The client below replaces this one: it inherits the address's - // reconnect decision, and is no longer the client that can report - // the reconnect. - existing.autoConnect = shouldAutoConnect } val remoteDevice = bluetoothManager.adapter.getRemoteDevice(deviceId) @@ -371,12 +368,15 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), remoteDevice.connectGatt(context, shouldAutoConnect, this) } gattRegistry.put(gatt, shouldAutoConnect) + // The client this one replaces cannot report the new link, and its own + // link is down (a connected or connecting one returned above), so tear + // it down here. Leaving it open would keep a tracked client — and an + // autoConnect attempt Android never stops — that nothing would ever + // close. + if (replaced != null && replaced.gatt !== gatt) cleanConnection(replaced.gatt) } override fun disconnect(deviceId: String) { - // An explicit disconnect cancels the address's autoConnect, for the - // active client and for any client a replacement left behind. - gattRegistry.forAddress(deviceId).forEach { it.autoConnect = false } val client = gattRegistry.find(deviceId) if (client == null) { cleanUpConnection(deviceId) @@ -384,6 +384,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), callbackChannel?.onConnectionChanged(deviceId, false, null, null, null) {} } } else { + // cleanConnection() also cancels the client's autoConnect, so an + // explicit disconnect is not followed by an automatic reconnect. cleanConnection(client.gatt) } } @@ -1768,7 +1770,12 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), private fun cleanConnection(gatt: BluetoothGatt) { val deviceId = gatt.device.address - val client = gattRegistry.find(gatt) ?: gattRegistry.put(gatt) + // A client the registry no longer tracks was closed already (a late + // STATE_DISCONNECTED, after the fallback timer or another path ran). It + // still gets a client so the teardown below stays idempotent, but that + // client is never published: doing so would evict a newer connection + // from the active slot and make a live link look superseded. + val client = gattRegistry.find(gatt) ?: GattClient(gatt) client.autoConnect = false gattRegistry.beginClose(client) cleanUpConnection(deviceId, gatt) @@ -1952,9 +1959,14 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), val deviceId = gatt.device.address val client = gattRegistry.find(gatt) // Android reports a failed connection attempt the same way, so only - // a client that reached CONNECTED owes a disconnect report. - val wasConnected = client?.state == GattClient.State.CONNECTED + // a client whose link came up owes a disconnect report. Read before + // the state below changes: disconnect() has already moved it to + // CLOSING by the time this callback arrives. + val wasConnected = client?.takeLinkWasUp() == true val closingByRequest = client?.state == GattClient.State.CLOSING + // Only a client that still reads autoConnect keeps its link open for + // Android to reconnect it. + val keepOpen = !closingByRequest && client?.autoConnect == true // A client the registry no longer holds as active was replaced, // whether by a newer connect() or by disconnect(): its requests and // its connection state are not the current connection's to fail or @@ -1962,6 +1974,17 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), val active = gattRegistry.find(deviceId) val superseded = active != null && active.gatt !== gatt + // Take the link down before the sweep, as the old connected-set based + // code did: a request submitted while the sweep runs must be refused + // with `deviceDisconnected`, not registered in a list that was + // already swept and then dropped by the stack without a callback + // (#394). The client stays in the active slot until the sweep is + // done, so `owns` can still tell its requests apart from a + // replacement published meanwhile. + client?.setState( + if (keepOpen) GattClient.State.AWAITING_RECONNECT else GattClient.State.CLOSING + ) + if (!superseded) { // Always clean up internal state (futures, etc.) cleanUpConnection(deviceId, gatt) @@ -1980,9 +2003,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // Only keep the client open when autoConnect should let Android // reconnect it; its next STATE_CONNECTED starts a new link. - if (!closingByRequest && client?.autoConnect == true) { - client.setState(GattClient.State.AWAITING_RECONNECT) - } else if (client == null || gattRegistry.finishClose(client)) { + if (!keepOpen && (client == null || gattRegistry.finishClose(client))) { gatt.disconnect() UniversalBleLogger.logDebug("Closing gatt for $deviceId") gatt.close() diff --git a/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt index 2fd38b4c..35472252 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt @@ -42,8 +42,6 @@ internal class DisconnectCloseTest { private fun plugin(): UniversalBlePlugin = pluginWithInlineLooper().also { it.setField("callbackChannel", callbackChannel) } - - @Test fun closingClientIsClosedAndReportedOnDisconnect() { val plugin = plugin() @@ -87,6 +85,74 @@ internal class DisconnectCloseTest { ) } + @Test + fun explicitDisconnectAfterConnectReportsDeviceDisconnected() { + val plugin = plugin() + val gatt = mockGatt(deviceAddress) + plugin.gattRegistry().put(gatt) + plugin.onConnectionStateChange( + gatt, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_CONNECTED + ) + + // disconnect() moves the client to CLOSING before the stack answers, and + // a locally initiated teardown can still carry a non-zero status. The + // report belongs to a link that was up, so it keeps its specific code. + plugin.disconnect(deviceAddress) + plugin.onConnectionStateChange( + gatt, BluetoothGatt.GATT_FAILURE, BluetoothGatt.STATE_DISCONNECTED + ) + + assertEquals( + listOf( + listOf(deviceAddress, true, null, null, null), + listOf( + deviceAddress, + false, + "Unknown Error 257", + UniversalBleErrorCode.DEVICE_DISCONNECTED, + 257L, + ), + ), + connectionChanges, + ) + } + + @Test + fun connectClosesTheClientItReplaces() { + val plugin = plugin() + val previous = mockGatt(deviceAddress) + val replacement = mockGatt(deviceAddress) + // A link loss left this client open for autoConnect to reconnect it: it + // is no longer connected, and nothing will ever report on it again. + plugin.gattRegistry().put(previous, autoConnect = true) + + val device = Mockito.mock(BluetoothDevice::class.java) + Mockito.`when`(device.address).thenReturn(deviceAddress) + Mockito.`when`( + device.connectGatt( + Mockito.any(Context::class.java), + Mockito.anyBoolean(), + Mockito.any(BluetoothGattCallback::class.java), + ) + ).thenReturn(replacement) + val adapter = Mockito.mock(BluetoothAdapter::class.java) + Mockito.`when`(adapter.getRemoteDevice(deviceAddress)).thenReturn(device) + val manager = Mockito.mock(BluetoothManager::class.java) + Mockito.`when`(manager.adapter).thenReturn(adapter) + plugin.setField("bluetoothManager", manager) + plugin.setField("context", Mockito.mock(Context::class.java)) + + plugin.connect(deviceAddress, null, null) + + assertSame(replacement, plugin.gattRegistry().find(deviceAddress)?.gatt) + Mockito.verify(previous).disconnect() + plugin.onConnectionStateChange( + previous, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_DISCONNECTED + ) + Mockito.verify(previous).close() + assertNull(plugin.gattRegistry().find(previous), "the replaced client is released") + } + @Test fun disconnectBeforeConnectReportsConnectionFailed() { val plugin = plugin() diff --git a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt index 4f19cd5b..8e7dfaa0 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/LinkLossOperationTest.kt @@ -154,6 +154,37 @@ internal class LinkLossOperationTest { assertTrue(acks.single().isSuccess) } + @Test + fun aRequestSubmittedDuringTheDisconnectSweepIsRefused() { + // The disconnect report is posted after the sweep and before the client + // leaves the active slot, so a request submitted from it lands in the + // middle of the teardown. The link is already gone: the request must be + // refused with deviceDisconnected, not handed to the stack where it can + // be dropped without a callback (#394). + lateinit var plugin: UniversalBlePlugin + val reads = mutableListOf>() + val channel = Mockito.mock(UniversalBleCallbackChannel::class.java) { invocation -> + if (invocation.method.name == "onConnectionChanged") { + plugin.readValue( + deviceAddress, + serviceUuid.toString(), + charUuid.toString(), + ) { reads.add(it) } + } + null + } + plugin = pluginWithInlineLooper().also { it.setField("callbackChannel", channel) } + plugin.gattRegistry().put(gatt).setState(GattClient.State.CONNECTED) + + report(plugin, BluetoothGatt.STATE_DISCONNECTED) + + assertEquals(1, reads.size, "the request must be answered, not left to its timeout") + assertDeviceDisconnected(reads.single()) + assertTrue(plugin.pendingReads().isEmpty()) + Mockito.verify(gatt, Mockito.never()) + .readCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java)) + } + @Test fun theBackstopTouchesOnlyTheReconnectingClient() { val plugin = pluginWithInlineLooper() From 3b93df7379a7c1402eaa06fd0fa7d45ef6f97787 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:42:03 +0100 Subject: [PATCH 12/13] Drop the test-only drain hook from PendingOperations beforeDrain ran inside the collection's lock on every drain and existed for one test. Completions are already delivered while the sweep is still running, so that test can publish the replacement from a completion instead and exercise the same ordering without a hook in production code. --- .../universal_ble/PendingOperations.kt | 14 +++----- .../GattCallbackCompletionTest.kt | 33 ++++++++++++------- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt b/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt index 3712fb5b..c5952035 100644 --- a/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt +++ b/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt @@ -37,13 +37,6 @@ internal class PendingOperations( ) { private val pending = mutableListOf() - /** - * Runs immediately before a drain, inside the collection's lock. Unit tests - * use it to publish a state change mid-sweep (a `connect()` completing - * while a disconnect cleans up); production never sets it. - */ - internal var beforeDrain: (() -> Unit)? = null - /** Adds [future] under the lock. */ fun add(future: T) { synchronized(this) { pending.add(future) } @@ -88,9 +81,12 @@ internal class PendingOperations( match } - /** Removes and returns every operation matching [predicate]. */ + /** + * Removes and returns every operation matching [predicate], read under the + * lock. Callers must evaluate the predicate against current state: the + * registry can change between the sweep of one collection and the next. + */ fun drainMatching(predicate: (T) -> Boolean): List = synchronized(this) { - beforeDrain?.invoke() val matches = pending.filter(predicate) pending.removeAll(matches) matches diff --git a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt index ea514c15..6c788c84 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/GattCallbackCompletionTest.kt @@ -670,28 +670,39 @@ internal class GattCallbackCompletionTest { @Test fun cleanupKeepsARequestWhoseClientIsRegisteredWhileItIsSwept() { - val plugin = plugin() + // Completions run inline, so the read fails while the sweep is still + // going. Its callback publishes the replacement, and the write that + // client owns is swept afterwards: the registry has to be read at match + // time rather than once when the sweep starts. + val plugin = pluginWithInlineLooper() val old = mockGatt(deviceAddress) val current = mockGatt(deviceAddress) - val results = mutableListOf>() - val reads = plugin.pendingReads() - reads.add( + val oldReads = mutableListOf>() + val currentWrites = mutableListOf>() + plugin.pendingReads().add( ReadResultFuture( + old, deviceAddress, charUuid.toString(), serviceUuid.toString() + ) { result -> + oldReads.add(result) + // A connect() publishes the replacement mid-sweep. + plugin.gattRegistry().put(current) + } + ) + plugin.pendingWrites().add( + WriteResultFuture( current, deviceAddress, charUuid.toString(), serviceUuid.toString() - ) { results.add(it) } + ) { currentWrites.add(it) } ) - // A connect() publishes the replacement while this sweep is running: - // the requests that client owns must survive, so the registry has to be - // read at match time rather than once when the sweep starts. - reads.beforeDrain = { plugin.gattRegistry().put(current) } val cleanup = UniversalBlePlugin::class.java.getDeclaredMethod( "cleanUpConnection", String::class.java, BluetoothGatt::class.java ).apply { isAccessible = true } cleanup.invoke(plugin, deviceAddress, old) - drainMainLooper() - assertTrue(results.isEmpty(), "the replacement's read is still in flight") + assertEquals(1, oldReads.size, "the old client's read is failed") + assertTrue(oldReads.single().isFailure) + assertTrue(currentWrites.isEmpty(), "the replacement's write is still in flight") + assertEquals(1, plugin.pendingWrites().size) assertSame(current, plugin.gattRegistry().find(deviceAddress)?.gatt) } From bd26ab3a7f2f7505acd32c4067920f071a3dd7cd Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Sun, 22 Nov 2026 21:38:31 +0100 Subject: [PATCH 13/13] Web: read the live GATT flag for the disconnect check (#394) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The seeded `connected` stream only learns about a drop once the browser dispatches `gattserverdisconnected`, which happens in a task, so a request issued right after `disconnect()` — or in the turn a drop is detected — still saw the device as connected. It then reached the dependency's discoverServices(), which throws "Cannot discover services if the device is not connected", so the caller got an unclassified error instead of deviceDisconnected. Read the browser's own `gatt.connected` flag instead. The getter is `@visibleForTesting`, so the read is scoped with an ignore. Also align the Linux and Web message with the "Device Disconnected" text Android, Windows and Apple emit, and document the behaviour under Error Handling in the README, including that Linux and Web report deviceDisconnected before the characteristic lookup. --- README.md | 8 +++++++- lib/src/universal_ble_linux/universal_ble_linux.dart | 2 +- lib/src/universal_ble_web/universal_ble_web.dart | 11 +++++++---- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 54a19ae3..5d245c84 100644 --- a/README.md +++ b/README.md @@ -348,7 +348,7 @@ You can enable automatic reconnection by setting the `autoConnect` parameter to await bleDevice.connect(autoConnect: true); ``` -While the link is down — after the plugin reports a disconnection and before the system reconnects the client — a read, write, descriptor access or subscription to that device fails right away with `UniversalBleErrorCode.deviceDisconnected` instead of waiting for the request timeout. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. +While the link is down — after the plugin reports a disconnection and before the system reconnects the client — a read, write, descriptor access or subscription to that device fails right away instead of waiting for the request timeout (see [Disconnected device](#disconnected-device)). #### Background connection events (iOS/macOS) @@ -996,6 +996,12 @@ The error parser automatically converts platform-specific error formats (strings When a peripheral refuses a characteristic or descriptor read/write, or a subscription, Android, Apple and Windows report the ATT error as the matching `UniversalBleErrorCode` (`insufficientEncryption`, `insufficientAuthentication`, `readNotPermitted`, ...) instead of a generic `failed`/`unknownError`. The raw native code is available in `UniversalBleException.details`. Service/characteristic discovery at connect time, and the Linux and Web backends, may still report a generic code. +### Disconnected device + +A read, write, descriptor access or subscription to a device whose link is down fails right away with `UniversalBleErrorCode.deviceDisconnected`, instead of waiting for the request timeout or reaching the stack. This holds whether or not the connection was made with `autoConnect`. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap. + +On Linux and Web the disconnect check runs before the characteristic lookup, because BlueZ drops a device's GATT object tree with the link and Web clears its service cache on disconnection. Those two platforms therefore report `deviceDisconnected` for a request on a disconnected device even when the characteristic no longer exists, while Android, Windows and Apple still report `characteristicNotFound` for an unknown characteristic. Do not rely on `characteristicNotFound` alone as a "services changed, re-discover" signal on Linux or Web. + ## Peripheral Mode `universal_ble` provides peripheral mode through `UniversalBlePeripheral`, so your app can advertise as a peripheral "server" in addition to client mode. diff --git a/lib/src/universal_ble_linux/universal_ble_linux.dart b/lib/src/universal_ble_linux/universal_ble_linux.dart index 8bcd979a..89f8dd63 100644 --- a/lib/src/universal_ble_linux/universal_ble_linux.dart +++ b/lib/src/universal_ble_linux/universal_ble_linux.dart @@ -579,7 +579,7 @@ class UniversalBleLinux extends UniversalBlePlatform { if (!device.connected) { throw UniversalBleException( code: UniversalBleErrorCode.deviceDisconnected, - message: 'Device not connected', + message: 'Device Disconnected', ); } return device; diff --git a/lib/src/universal_ble_web/universal_ble_web.dart b/lib/src/universal_ble_web/universal_ble_web.dart index 9663b556..a399465a 100644 --- a/lib/src/universal_ble_web/universal_ble_web.dart +++ b/lib/src/universal_ble_web/universal_ble_web.dart @@ -697,12 +697,15 @@ class UniversalBleWeb extends UniversalBlePlatform { message: '$deviceId Not Found', ); } - // `connected` is seeded with the current GATT state, so the first event is - // the live value (the same way getConnectionState reads it). - if (!await device.connected.first) { + // Read the browser's own GATT flag instead of the `connected` stream: the + // stream is seeded from it, but only updates once the browser dispatches + // `gattserverdisconnected`, which happens in a task — so it still reports + // `true` right after `disconnect()` or a drop detected in the same turn. + // ignore: invalid_use_of_visible_for_testing_member + if (device.gatt?.connected != true) { throw UniversalBleException( code: UniversalBleErrorCode.deviceDisconnected, - message: 'Device $deviceId is not connected', + message: 'Device Disconnected', ); } }