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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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).
Expand Down
145 changes: 132 additions & 13 deletions android/src/main/kotlin/com/navideck/universal_ble/GattRegistry.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, BluetoothGatt>()
private val active = ConcurrentHashMap<String, GattClient>()
private val clients = ConcurrentHashMap<BluetoothGatt, GattClient>()

/** 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<BluetoothGatt> = clients.values.toList()
/** The active clients, safe to iterate while releasing them. */
fun snapshot(): List<GattClient> = active.values.toList()
}
Original file line number Diff line number Diff line change
@@ -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<T : PendingOperation>(
/** 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<T>()

/** 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<T> = 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 <R> withLock(action: () -> R): R = synchronized(this, action)
}
Loading
Loading