diff --git a/CHANGELOG.md b/CHANGELOG.md index 60e1b36a..72e00570 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/GattRegistry.kt b/android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt index 4facfb02..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,38 +2,157 @@ 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 /** - * 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 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 + + 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) { + 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 + * (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 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 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 + } + + /** + * 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/PendingOperations.kt b/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt new file mode 100644 index 00000000..c5952035 --- /dev/null +++ b/android/src/main/kotlin/com/navideck/universal_ble/PendingOperations.kt @@ -0,0 +1,110 @@ +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() + + /** 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], 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) { + 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 fd6a7721..4bb568f4 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 @@ -28,10 +27,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 @@ -74,41 +71,33 @@ 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 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()) + private val rssiOperations = pendingOperations("RSSI") // 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 +105,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 +138,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 +333,15 @@ 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) + val replaced = gattRegistry.find(deviceId) + replaced?.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 +354,8 @@ 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 - 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 +367,26 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } else { remoteDevice.connectGatt(context, shouldAutoConnect, this) } - gattRegistry.put(gatt) + 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) { - autoConnectDevices.remove(deviceId) - val gatt = gattRegistry.find(deviceId) - if (gatt == null) { - awaitingReconnectGatts.removeAll { it.device.address == deviceId } + val client = gattRegistry.find(deviceId) + if (client == null) { cleanUpConnection(deviceId) mainThreadHandler?.post { callbackChannel?.onConnectionChanged(deviceId, false, null, null, null) {} } } else { - cleanConnection(gatt) + // cleanConnection() also cancels the client's autoConnect, so an + // explicit disconnect is not followed by an automatic reconnect. + cleanConnection(client.gatt) } } @@ -447,13 +434,13 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), override fun readRssi(deviceId: String, callback: (Result) -> Unit) { try { - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt // Register before readRemoteRssi, as readValue does: its callback // arrives on a binder thread, so the entry must already be in the - // list the disconnect cleanup sweeps — and only while the link is up - // (#394). + // collection the disconnect cleanup sweeps — and only while the link + // is up (#394). val future = RssiResultFuture(gatt, deviceId, callback) - if (!rssiResultFutureList.addIfLinkedUp(gatt, future)) { + if (!rssiOperations.addIfLinkedUp(gatt, future, ::isLinkUp)) { callback(Result.failure(deviceDisconnectedError())) return } @@ -461,15 +448,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), gatt.readRemoteRssi() } catch (e: Exception) { // A callback or disconnect may already own the reply. - synchronized(rssiResultFutureList) { - if (!rssiResultFutureList.remove(future)) return - } + if (!rssiOperations.remove(future)) return throw e } if (!started) { - synchronized(rssiResultFutureList) { - if (!rssiResultFutureList.remove(future)) return - } + if (!rssiOperations.remove(future)) return callback( Result.failure( createFlutterError( @@ -491,11 +474,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 } @@ -526,21 +505,19 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), callback: (Result>) -> Unit, ) { try { - val gatt = gattRegistry.get(deviceId) + val gatt = gattRegistry.get(deviceId).gatt // Register before discoverServices, as readValue does: the result // arrives on a binder thread, so the entry must already be in the - // list the disconnect cleanup sweeps — and only while the link is up - // (#394). + // collection the disconnect cleanup sweeps — and only while the link + // is up (#394). val future = DiscoverServicesFuture(gatt, deviceId, withDescriptors, callback) - if (!discoverServicesFutureList.addIfLinkedUp(gatt, future)) { + if (!discoveryOperations.addIfLinkedUp(gatt, future, ::isLinkUp)) { callback(Result.failure(deviceDisconnectedError())) return } if (platformConfig?.android?.clearGattCache == true && !gatt.refreshGattCache()) { // A callback or disconnect may already own the reply. - synchronized(discoverServicesFutureList) { - if (!discoverServicesFutureList.remove(future)) return - } + if (!discoveryOperations.remove(future)) return callback( Result.failure( createFlutterError( @@ -551,19 +528,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), ) return } - val started = try { - gatt.discoverServices() - } catch (e: Exception) { - // A callback or disconnect may already own the reply. - synchronized(discoverServicesFutureList) { - if (!discoverServicesFutureList.remove(future)) return - } - throw e - } - if (!started) { - synchronized(discoverServicesFutureList) { - if (!discoverServicesFutureList.remove(future)) return - } + if (!gatt.discoverServices()) { + if (!discoveryOperations.remove(future)) return callback( Result.failure( createFlutterError( @@ -585,12 +551,8 @@ 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) - } - if (services != null && gattRegistry.find(deviceId) === gatt) { + val pending = discoveryOperations.drainMatching { it.gatt === gatt } + if (services != null && gattRegistry.find(deviceId)?.gatt === gatt) { try { setCachedServices(deviceId, services.map { it.uuid.toString() }) } catch (e: Exception) { @@ -660,15 +622,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) - val gattCharacteristic: BluetoothGattCharacteristic? = - gatt.getCharacteristic(service, characteristic) - + val gatt = gattRegistry.get(deviceId).gatt + val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( Result.failure( @@ -680,38 +641,47 @@ 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). - if (!subscriptionResultFutureList.addIfLinkedUp(gatt, pending)) { + // 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 + val status = writeCccdDescriptor(gatt, descriptor, value) + if (status != BluetoothGatt.GATT_SUCCESS) { + fail( + createFlutterError( + cccDescriptorErrorCode(status), + "Failed to update descriptor" + ) + ) + return + } } else if (!isLinkUp(gatt)) { // No CCCD to write, so there is no pending result to sweep, but // setCharacteristicNotification() still succeeds locally on a @@ -719,57 +689,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // cannot deliver. Refuse it like any other request (#394). callback(Result.failure(deviceDisconnectedError())) return - } - - /** 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" - ) - ) - return - } - } } else { + // Some devices do not need CCCD to update. UniversalBleLogger.logDebug("CCCD Descriptor not found") } @@ -786,32 +707,70 @@ 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. */ private fun removeSubscriptionFuture(future: SubscriptionResultFuture?): Boolean { if (future == null) return true - synchronized(subscriptionResultFutureList) { - return subscriptionResultFutureList.remove(future) - } + return subscriptionOperations.remove(future) } override fun readValue( @@ -822,7 +781,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( @@ -841,39 +800,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 (!readResultFutureList.addIfLinkedUp(gatt, readFuture)) { - callback(Result.failure(deviceDisconnectedError())) - return - } - - val started = try { - gatt.readCharacteristic(gattCharacteristic) - } catch (e: Exception) { - // A callback or disconnect may already own the reply. - synchronized(readResultFutureList) { - if (!readResultFutureList.remove(readFuture)) return - } - throw e - } - if (!started) { - synchronized(readResultFutureList) { - if (!readResultFutureList.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)) @@ -908,15 +860,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( @@ -955,10 +903,9 @@ 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) + val gatt = gattRegistry.get(deviceId).gatt val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1015,63 +962,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 (!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) - } 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( @@ -1084,10 +1016,47 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } } - private fun withdrawWriteFuture(future: WriteResultFuture) { - synchronized(writeResultFutureList) { - writeResultFutureList.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, @@ -1113,15 +1082,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( @@ -1160,7 +1125,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( @@ -1185,43 +1150,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 (!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( - 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)) @@ -1244,16 +1201,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 { @@ -1291,10 +1244,9 @@ 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) + val gatt = gattRegistry.get(deviceId).gatt val gattCharacteristic = gatt.getCharacteristic(service, characteristic) if (gattCharacteristic == null) { callback( @@ -1335,52 +1287,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 (!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) - } 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( @@ -1393,16 +1339,10 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), } } - private fun withdrawWriteDescriptorFuture(future: WriteDescriptorResultFuture) { - synchronized(writeDescriptorResultFutureList) { - writeDescriptorResultFutureList.remove(future) - } - } - 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 @@ -1410,7 +1350,7 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), var reusedMtu: Int? = null var shouldRequest = false var linkUp = false - synchronized(mtuResultFutureList) { + mtuOperations.withLock { // Only serve or register while the link is up, under the lock the // disconnect cleanup takes (see writeValue): the stack accepts a // request on a linkless autoConnect client and then drops it @@ -1424,9 +1364,9 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), 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 } } @@ -1470,11 +1410,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. @@ -1487,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 @@ -1560,40 +1498,22 @@ 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. * - * `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 = 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 isLinkUp(gatt: BluetoothGatt): Boolean = + gattRegistry.find(gatt)?.isLinkUp == true private fun deviceDisconnectedError(): FlutterError = createFlutterError( UniversalBleErrorCode.DEVICE_DISCONNECTED, @@ -1762,7 +1682,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 @@ -1770,21 +1691,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 } } @@ -1849,13 +1768,13 @@ 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) // 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 { @@ -1876,147 +1795,34 @@ 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) { val deviceId = gatt.device.address - gattRegistry.remove(gatt) - awaitingReconnectGatts.remove(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) - 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)) { @@ -2160,12 +1966,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 } + 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 @@ -2175,12 +1985,14 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(), // to it (#394). // // Sweep before the link is marked up: the submission gate reads - // connectedGatts, so a request that lands in a pending list after - // this point belongs to the new link and must not be failed here. - if (awaitingReconnectGatts.remove(gatt)) { + // the client state, so a request that lands in a pending collection + // after this point belongs to the new link and must not be failed + // here. + val reconnected = client.state == GattClient.State.AWAITING_RECONNECT + if (reconnected) { failPendingOperations { futureGatt, _ -> futureGatt === gatt } } - connectedGatts.add(gatt) + client.setState(GattClient.State.CONNECTED) mainThreadHandler?.post { callbackChannel?.onConnectionChanged( gatt.device.address, true, status.parseHciErrorCode(), status.toConnectionErrorCode(), status.toGattErrorCode() @@ -2188,14 +2000,33 @@ 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 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 // 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 + + // 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.) @@ -2213,17 +2044,12 @@ 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 (!keepOpen && (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) } } } @@ -2267,16 +2093,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 { @@ -2310,21 +2132,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/DisconnectCloseTest.kt b/android/src/test/kotlin/com/navideck/universal_ble/DisconnectCloseTest.kt index 9faaf87d..35472252 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 @@ -38,35 +39,14 @@ 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 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 - } + private fun plugin(): UniversalBlePlugin = + pluginWithInlineLooper().also { it.setField("callbackChannel", callbackChannel) } @Test fun closingClientIsClosedAndReportedOnDisconnect() { val plugin = plugin() - val gatt = mockGatt() - closingGatts(plugin).add(gatt) + val gatt = mockGatt(deviceAddress) + plugin.gattRegistry().beginClose(plugin.gattRegistry().put(gatt)) plugin.onConnectionStateChange( gatt, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_DISCONNECTED @@ -74,13 +54,13 @@ 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 fun peerDisconnectAfterConnectReportsDeviceDisconnected() { val plugin = plugin() - val gatt = mockGatt() + val gatt = mockGatt(deviceAddress) plugin.gattRegistry().put(gatt) plugin.onConnectionStateChange( @@ -105,10 +85,78 @@ 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() - val gatt = mockGatt() + val gatt = mockGatt(deviceAddress) plugin.gattRegistry().put(gatt) plugin.onConnectionStateChange( @@ -132,8 +180,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,9 +194,9 @@ internal class DisconnectCloseTest { @Test fun supersededClientClosesWithoutTouchingTheNewOne() { val plugin = plugin() - val oldGatt = mockGatt() - val newGatt = mockGatt() - closingGatts(plugin).add(oldGatt) + val oldGatt = mockGatt(deviceAddress) + val newGatt = mockGatt(deviceAddress) + plugin.gattRegistry().beginClose(plugin.gattRegistry().put(oldGatt)) plugin.gattRegistry().put(newGatt) plugin.onConnectionStateChange( @@ -157,13 +205,13 @@ internal class DisconnectCloseTest { Mockito.verify(oldGatt).close() assertTrue(connectionChanges.isEmpty()) - assertSame(newGatt, plugin.gattRegistry().find(deviceAddress)) + assertSame(newGatt, plugin.gattRegistry().find(deviceAddress)?.gatt) } @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 @@ -195,16 +243,16 @@ 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 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) + plugin.gattRegistry().beginClose(plugin.gattRegistry().put(gatt)) plugin.onConnectionStateChange( gatt, BluetoothGatt.GATT_SUCCESS, BluetoothGatt.STATE_CONNECTED @@ -216,12 +264,12 @@ internal class DisconnectCloseTest { @Test fun replacedClientDisconnectDoesNotReportOrFailTheNewConnection() { val plugin = plugin() - // connect() replaced the client, so the old one is never in closingGatts. - val replaced = mockGatt() - val current = mockGatt() + // 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) val reads = mutableListOf>() - plugin.getField>("readResultFutureList").add( + plugin.pendingReads().add( ReadResultFuture(current, deviceAddress, charUuid.toString(), serviceUuid.toString()) { reads.add(it) } @@ -238,7 +286,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..6c788c84 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, @@ -561,11 +520,76 @@ 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() 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 +606,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 +615,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 +645,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() @@ -648,53 +670,60 @@ internal class GattCallbackCompletionTest { @Test fun cleanupKeepsARequestWhoseClientIsRegisteredWhileItIsSwept() { - val plugin = plugin() - val old = mockGatt() - val current = mockGatt() - val results = mutableListOf>() - val items = mutableListOf( + // 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 oldReads = mutableListOf>() + val currentWrites = mutableListOf>() + plugin.pendingReads().add( ReadResultFuture( - current, deviceAddress, charUuid.toString(), serviceUuid.toString() - ) { results.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. - plugin.setField("readResultFutureList", object : MutableList by items { - override fun iterator(): MutableIterator { + old, deviceAddress, charUuid.toString(), serviceUuid.toString() + ) { result -> + oldReads.add(result) + // A connect() publishes the replacement mid-sweep. plugin.gattRegistry().put(current) - return items.iterator() } - }) + ) + plugin.pendingWrites().add( + WriteResultFuture( + current, deviceAddress, charUuid.toString(), serviceUuid.toString() + ) { currentWrites.add(it) } + ) 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") - assertSame(current, plugin.gattRegistry().find(deviceAddress)) + 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) } @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 +736,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 +775,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 +798,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..bc7c6077 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,23 +41,17 @@ 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)) - assertSame(gatt, background.find(address)) + assertSame(gatt, background.find(address)?.gatt) assertFalse(ui.isKnown(address)) assertNull(ui.find(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,28 +72,28 @@ 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) - first.remove(firstGatt) + first.finishClose(first.find(firstGatt)!!) assertNull(first.find(address)) - assertSame(secondGatt, second.find(address)) + assertSame(secondGatt, second.find(address)?.gatt) } @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) - 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 8daf39e0..1c3a5205 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,72 +25,20 @@ 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() - plugin.autoConnectDevices().add(deviceAddress) - plugin.gattRegistry().put(gatt) + val plugin = pluginWithInlineLooper() + plugin.gattRegistry().put(gatt, autoConnect = true) report(plugin, BluetoothGatt.STATE_CONNECTED) return plugin } @@ -102,21 +47,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 @@ -160,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()) @@ -178,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>() @@ -222,20 +154,46 @@ 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 = 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) - plugin.autoConnectDevices().add(deviceAddress) - plugin.gattRegistry().put(other) - plugin.connectedGatts().add(other) - plugin.gattRegistry().put(reconnecting) - plugin.connectedGatts().add(reconnecting) + val otherAddress = GattIds.OTHER_ADDRESS + val other = mockGatt(otherAddress) + plugin.gattRegistry().put(other).setState(GattClient.State.CONNECTED) + plugin.gattRegistry().put(reconnecting, autoConnect = true) + .setState(GattClient.State.CONNECTED) val otherResult = mutableListOf>() plugin.pendingWrites().add( @@ -243,7 +201,6 @@ internal class LinkLossOperationTest { otherResult.add(it) } ) - report(plugin, BluetoothGatt.STATE_DISCONNECTED) // Registered after the disconnect sweep, so only the reconnect backstop @@ -270,29 +227,29 @@ internal class LinkLossOperationTest { val plugin = connectedAutoConnectPlugin() report(plugin, BluetoothGatt.STATE_DISCONNECTED) - // A request submitted while the sweep holds the list lock must still be - // refused: the link may only be marked up after the stale entries are - // gone, or the sweep would also fail a write the stack just accepted. - val stale = mutableListOf() - stale.add( - ReadResultFuture(gatt, deviceAddress, charUuid.toString(), serviceUuid.toString()) {} + // A request submitted while the sweep holds the collection's lock must + // still be refused: the link may only be marked up after the stale + // entries are gone, or the sweep would also fail an operation the stack + // just accepted. Delivery is inline here, so the failed future observes + // the state the backstop swept under. + val linkUpDuringSweep = mutableListOf() + plugin.pendingWrites().add( + WriteResultFuture( + gatt, deviceAddress, charUuid.toString(), serviceUuid.toString() + ) { linkUpDuringSweep.add(plugin.gattClient(gatt)?.isLinkUp) } ) - val linkUpDuringSweep = mutableListOf() - plugin.setField("readResultFutureList", object : MutableList by stale { - override fun iterator(): MutableIterator { - linkUpDuringSweep.add(plugin.connectedGatts().contains(gatt)) - return stale.iterator() - } - }) report(plugin, BluetoothGatt.STATE_CONNECTED) - assertTrue(linkUpDuringSweep.isNotEmpty(), "the reconnect must sweep the stale entry") - assertTrue( - linkUpDuringSweep.none { it }, + assertEquals( + listOf(false), + linkUpDuringSweep, "the backstop must sweep before marking the link up", ) - assertTrue(plugin.connectedGatts().contains(gatt), "the new link is up afterwards") + assertTrue( + plugin.gattClient(gatt)?.isLinkUp == true, + "the new link is up afterwards", + ) } @Test @@ -311,14 +268,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 0d1d4150..eb5e6683 100644 --- a/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt +++ b/android/src/test/kotlin/com/navideck/universal_ble/MtuCompletionTest.kt @@ -14,32 +14,19 @@ 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.attachConnectedGatt(it) } - } - private fun drainMain() { - while (true) (posted.poll() ?: return).run() - } + private fun drainMain() = drainPosts(posted) @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 3e78a462..54cfab1c 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,9 +107,8 @@ internal class NotificationOwnershipTest { @Test fun autoConnectClientKeepsDeliveringAcrossALinkLoss() { val plugin = plugin() - val gatt = mockGatt() - plugin.gattRegistry().put(gatt) - plugin.getField>("autoConnectDevices").add(address) + val gatt = mockGatt(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 882fe89f..5e970632 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,6 +32,32 @@ 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 +// key every time. They are the live lists, not copies. + +internal fun UniversalBlePlugin.pendingReads(): PendingOperations = + getField("readOperations") + +internal fun UniversalBlePlugin.pendingWrites(): PendingOperations = + getField("writeOperations") + +internal fun UniversalBlePlugin.pendingDescriptorReads(): PendingOperations = + getField("descriptorReadOperations") + +internal fun UniversalBlePlugin.pendingDescriptorWrites(): PendingOperations = + getField("descriptorWriteOperations") + +internal fun UniversalBlePlugin.pendingSubscriptions(): PendingOperations = + getField("subscriptionOperations") + +internal fun UniversalBlePlugin.pendingMtus(): PendingOperations = + getField("mtuOperations") + +internal fun UniversalBlePlugin.pendingRssis(): PendingOperations = + getField("rssiOperations") + +internal fun UniversalBlePlugin.pendingDiscoveries(): PendingOperations = + getField("discoveryOperations") 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..aac24f52 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 val requestGatt by lazy { mockGatt(deviceAddress) } - 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 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 - } + private fun pendingWrites(plugin: UniversalBlePlugin): PendingOperations = + 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(