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
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
* Linux: a read, write, descriptor read/write or subscription submitted while the device is disconnected now fails with `deviceDisconnected` instead of `characteristicNotFound` or a generic `readFailed`/`writeFailed`. BlueZ drops the GATT object tree together with the link, so the lookup used to report the characteristic as unknown — as if the device had changed its services — and a request that reached D-Bus failed with `NotConnected` under a generic code (#394).
* Web: the same requests now fail with `deviceDisconnected` instead of surfacing the browser's `NetworkError` as an unclassified error, and an unknown device reports `deviceNotFound` instead of a missing characteristic. The service cache is cleared on disconnection, so the lookup previously failed before the browser could say the link was gone (#394).
* Windows: the same requests now fail with `deviceDisconnected` when the link is down but the connection-status callback has not removed the client yet. The operation used to be submitted anyway and completed with `Unreachable`, which surfaced as `failed` (#394).
* Apple: reads, descriptor reads and writes, and subscriptions now refuse a disconnected peripheral with `deviceDisconnected`, as `writeValue` already did since #378, instead of submitting a request the peripheral cannot serve (#394).
* Apple: reads, writes, descriptor reads and writes, and subscriptions now check `CBPeripheral.state` before the characteristic or descriptor lookup, so a request on a disconnected peripheral fails with `deviceDisconnected`. CoreBluetooth discards a peripheral's attribute tree when the link drops, so with the previous lookup-first order the caller got `characteristicNotFound` for a characteristic it had just used. The check now runs first, as it already did on Linux and Web; an unknown characteristic on a connected peripheral still reports `characteristicNotFound` (#394).
* Android and Windows: the link check now runs before the characteristic and descriptor lookup too, so a read, write, descriptor read/write or subscription on a known but disconnected device reports `deviceDisconnected` even when the cached attribute tree no longer holds the characteristic. Previously the lookup won and the answer depended on the platform. Android's submission gate keeps its lock-protected check as the authoritative one for the race described above (#394).
* Apple: MTU requests and RSSI reads now refuse a disconnected peripheral with `deviceDisconnected` instead of reaching CoreBluetooth, matching Android. Service discovery already refused one and now uses the same "Device Disconnected" message, so the set of gated calls is identical on both platforms (#394).
* Android: a read, write, descriptor read/write, notification subscription, MTU request, service discovery or RSSI read submitted to an `autoConnect` client after its link dropped now fails right away with `deviceDisconnected` instead of reaching the stack. The client stays open and keeps its cached services after the link loss, and below API 33 the stack accepts such a request and then drops it without a callback, leaving a pending entry that the first callback of the reconnected link completes — so every later write lagged by one and timed out after 10 s, giving about one write per timeout. The link check shares the lock with the disconnect cleanup, so a request submitted concurrently is either registered in time to be swept or refused; as a backstop, a client whose link comes back fails anything still pending from the previous link before the new link starts accepting requests. `readDescriptorValue`, `readRssi` and `discoverServices` register their pending result before issuing the operation, as `readValue` already did. A subscription to a characteristic without a CCCD is refused the same way. All of this needs the system to report the disconnection, which the plugin cannot infer on its own (#394).

## 3.4.0
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -998,9 +998,9 @@ When a peripheral refuses a characteristic or descriptor read/write, or a subscr

### Disconnected device

A read, write, descriptor access or subscription to a device whose link is down fails right away with `UniversalBleErrorCode.deviceDisconnected`, instead of waiting for the request timeout or reaching the stack. On Android the same applies to MTU requests, service discovery and RSSI reads. This holds whether or not the connection was made with `autoConnect`, and it relies on the system reporting the disconnection: if it never does, the plugin cannot tell the link is down. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap.
A read, write, descriptor access or subscription to a device whose link is down fails right away with `UniversalBleErrorCode.deviceDisconnected`, instead of waiting for the request timeout or reaching the stack. On Android and Apple the same applies to MTU requests, service discovery and RSSI reads. This holds whether or not the connection was made with `autoConnect`, and it relies on the system reporting the disconnection: if it never does, the plugin cannot tell the link is down. Wait for the next connected event on `connectionStream` before issuing requests again; requests are not queued across the gap.

On Linux and Web the disconnect check runs before the characteristic lookup, because BlueZ drops a device's GATT object tree with the link and Web clears its service cache on disconnection. Those two platforms therefore report `deviceDisconnected` for a request on a disconnected device even when the characteristic no longer exists, while Android, Windows and Apple still report `characteristicNotFound` for an unknown characteristic. Do not rely on `characteristicNotFound` alone as a "services changed, re-discover" signal on Linux or Web.
Every platform runs this check before the characteristic or descriptor lookup, so a known device whose link is down reports `deviceDisconnected` even when its cached attribute tree no longer holds the characteristic. On a live link an unknown characteristic or descriptor still reports `characteristicNotFound`. That code is not a reliable "services changed, re-discover" signal on Android: a read the stack refuses to start — because another operation is in flight on the same link (callers can run parallel queues with `queueId`), or because the link dropped between the check and the call — is reported as `characteristicNotFound` too. A device the plugin has already forgotten reports `deviceNotFound`: Android closes a client that `autoConnect` does not keep open, and Windows removes its device agent when the connection-status callback reports the drop.

## Peripheral Mode

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(),
try {
UniversalBleLogger.logDebug("SET_NOTIFY -> $deviceId $service $characteristic input=$bleInputProperty")
val gatt = gattRegistry.get(deviceId).gatt
// A disconnected device reports that, whatever the cache holds.
if (!isLinkUp(gatt)) {
callback(Result.failure(deviceDisconnectedError()))
return
}
val gattCharacteristic = gatt.getCharacteristic(service, characteristic)
if (gattCharacteristic == null) {
callback(
Expand Down Expand Up @@ -782,6 +787,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(),
try {
UniversalBleLogger.logDebug("READ -> $deviceId $service $characteristic")
val gatt = gattRegistry.get(deviceId).gatt
// A disconnected device reports that, whatever the cache holds.
if (!isLinkUp(gatt)) {
callback(Result.failure(deviceDisconnectedError()))
return
}
val gattCharacteristic = gatt.getCharacteristic(service, characteristic)
if (gattCharacteristic == null) {
callback(
Expand Down Expand Up @@ -906,6 +916,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(),
try {
UniversalBleLogger.logDebug("WRITE -> $deviceId $service $characteristic len=${value.size} property=$bleOutputProperty")
val gatt = gattRegistry.get(deviceId).gatt
// A disconnected device reports that, whatever the cache holds.
if (!isLinkUp(gatt)) {
callback(Result.failure(deviceDisconnectedError()))
return
}
val gattCharacteristic = gatt.getCharacteristic(service, characteristic)
if (gattCharacteristic == null) {
callback(
Expand Down Expand Up @@ -948,8 +963,8 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(),
writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
}

// Checked after the lookups so a caller still gets deviceNotFound,
// characteristicNotFound and the write-support errors it got before.
// Checked after the link check and the lookups so a wrong device,
// attribute or operation outranks a payload that is too long.
if (value.size > MAX_ATTRIBUTE_VALUE_SIZE) {
callback(
Result.failure(
Expand Down Expand Up @@ -1126,6 +1141,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(),
try {
UniversalBleLogger.logDebug("READ_DESCRIPTOR -> $deviceId $service $characteristic $descriptor")
val gatt = gattRegistry.get(deviceId).gatt
// A disconnected device reports that, whatever the cache holds.
if (!isLinkUp(gatt)) {
callback(Result.failure(deviceDisconnectedError()))
return
}
val gattCharacteristic = gatt.getCharacteristic(service, characteristic)
if (gattCharacteristic == null) {
callback(
Expand Down Expand Up @@ -1247,6 +1267,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(),
try {
UniversalBleLogger.logDebug("WRITE_DESCRIPTOR -> $deviceId $service $characteristic $descriptor len=${value.size}")
val gatt = gattRegistry.get(deviceId).gatt
// A disconnected device reports that, whatever the cache holds.
if (!isLinkUp(gatt)) {
callback(Result.failure(deviceDisconnectedError()))
return
}
val gattCharacteristic = gatt.getCharacteristic(service, characteristic)
if (gattCharacteristic == null) {
callback(
Expand All @@ -1272,9 +1297,10 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(),
return
}

// Checked after the lookups so a caller still gets deviceNotFound and
// the not-found errors it got before. writeDescriptor does not throw
// for a long value, but a value over the attribute cap cannot work.
// Checked after the link check and the lookups so a wrong device or
// attribute outranks a payload that is too long. writeDescriptor does
// not throw for a long value, but a value over the attribute cap
// cannot work.
if (value.size > MAX_ATTRIBUTE_VALUE_SIZE) {
callback(
Result.failure(
Expand Down Expand Up @@ -1511,6 +1537,11 @@ class UniversalBlePlugin : UniversalBlePlatformChannel, BluetoothGattCallback(),
* 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).
*
* Requests check it before the characteristic lookup: an autoConnect client
* keeps its cached services across a link loss, so a lookup-first order
* would report a missing characteristic for a device that is known and
* simply disconnected. The submission gate still re-checks under its lock.
*/
private fun isLinkUp(gatt: BluetoothGatt): Boolean =
gattRegistry.find(gatt)?.isLinkUp == true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -372,4 +372,136 @@ internal class LinkLossOperationTest {
Mockito.verify(gatt, Mockito.never()).readRemoteRssi()
Mockito.verify(gatt, Mockito.never()).discoverServices()
}

@Test
fun anUnknownCharacteristicOnADroppedLinkStillReportsDisconnected() {
// The client keeps its cached tree across the link loss, but the tree
// need not still hold the requested characteristic. The link check runs
// before the lookup, so the answer describes the connection the caller
// can act on rather than the cache.
val plugin = connectedAutoConnectPlugin()
report(plugin, BluetoothGatt.STATE_DISCONNECTED)

val unknown = UUID.randomUUID().toString()
val reads = mutableListOf<Result<ByteArray>>()
plugin.readValue(deviceAddress, serviceUuid.toString(), unknown) { reads.add(it) }
assertEquals(1, reads.size)
assertDeviceDisconnected(reads.single())

val writes = mutableListOf<Result<Unit>>()
plugin.writeValue(
deviceAddress,
serviceUuid.toString(),
unknown,
ByteArray(2),
BleOutputProperty.WITHOUT_RESPONSE,
) { writes.add(it) }
assertEquals(1, writes.size)
assertDeviceDisconnected(writes.single())

val subscriptions = mutableListOf<Result<Unit>>()
plugin.setNotifiable(
deviceAddress,
serviceUuid.toString(),
unknown,
BleInputProperty.NOTIFICATION,
) { subscriptions.add(it) }
assertEquals(1, subscriptions.size)
assertDeviceDisconnected(subscriptions.single())

Mockito.verify(gatt, Mockito.never())
.readCharacteristic(Mockito.any(BluetoothGattCharacteristic::class.java))
}

@Test
fun anUnknownCharacteristicOnALiveLinkStillReportsNotFound() {
val plugin = connectedAutoConnectPlugin()

val reads = mutableListOf<Result<ByteArray>>()
plugin.readValue(
deviceAddress,
serviceUuid.toString(),
UUID.randomUUID().toString(),
) { reads.add(it) }

assertEquals(1, reads.size)
assertEquals(
UniversalBleErrorCode.CHARACTERISTIC_NOT_FOUND.raw.toString(),
errorCode(reads.single()),
"a live link keeps reporting a missing characteristic as such",
)
}

@Test
fun anUnknownDescriptorOnADroppedLinkStillReportsDisconnected() {
// The descriptor paths check the link before the characteristic and
// descriptor lookups too, so an unknown attribute cannot shadow the
// connection the caller has to fix.
val plugin = connectedAutoConnectPlugin()
report(plugin, BluetoothGatt.STATE_DISCONNECTED)

val unknown = UUID.randomUUID().toString()
val descriptorReads = mutableListOf<Result<ByteArray>>()
plugin.readDescriptorValue(
deviceAddress,
serviceUuid.toString(),
charUuid.toString(),
unknown,
) { descriptorReads.add(it) }
assertEquals(1, descriptorReads.size)
assertDeviceDisconnected(descriptorReads.single())

val descriptorWrites = mutableListOf<Result<Unit>>()
plugin.writeDescriptorValue(
deviceAddress,
serviceUuid.toString(),
charUuid.toString(),
unknown,
ByteArray(2),
) { descriptorWrites.add(it) }
assertEquals(1, descriptorWrites.size)
assertDeviceDisconnected(descriptorWrites.single())

Mockito.verify(gatt, Mockito.never())
.readDescriptor(Mockito.any(BluetoothGattDescriptor::class.java))
Mockito.verify(gatt, Mockito.never())
.writeDescriptor(Mockito.any(BluetoothGattDescriptor::class.java))
}

@Test
fun anUnknownDescriptorOnALiveLinkStillReportsNotFound() {
val plugin = connectedAutoConnectPlugin()

val unknown = UUID.randomUUID().toString()
val descriptorReads = mutableListOf<Result<ByteArray>>()
plugin.readDescriptorValue(
deviceAddress,
serviceUuid.toString(),
charUuid.toString(),
unknown,
) { descriptorReads.add(it) }

assertEquals(1, descriptorReads.size)
assertEquals(
UniversalBleErrorCode.CHARACTERISTIC_NOT_FOUND.raw.toString(),
errorCode(descriptorReads.single()),
"a live link keeps reporting a missing descriptor as such",
)

val descriptorWrites = mutableListOf<Result<Unit>>()
plugin.writeDescriptorValue(
deviceAddress,
serviceUuid.toString(),
charUuid.toString(),
unknown,
ByteArray(2),
) { descriptorWrites.add(it) }

assertEquals(1, descriptorWrites.size)
assertEquals(
UniversalBleErrorCode.CHARACTERISTIC_NOT_FOUND.raw.toString(),
errorCode(descriptorWrites.single()),
"a live link keeps reporting a missing descriptor as such",
)
}
}
Loading
Loading