Repository navigation
Description
Library version
3.4.0 (also present on main: writeValue has no connection check)
Reproducible with the example app
Not tested
OS
Android
OS version
Android 11 (API 30), Samsung SC-02M. Likely affects API ≤ 32 only
Device connecting to
A commercial BLE peripheral driven by write-without-response to a vendor characteristic
BLE version of connecting device
Unknown
What happened?
With connect(autoConnect: true) on Android, the BluetoothGatt client stays open
after a link loss so that Android can reconnect it. If a write is submitted in the
few milliseconds after STATE_DISCONNECTED (for example, a periodic write from a
timer that has not yet seen the disconnect), that write is never completed, and
after the auto-reconnect every write times out:
onConnectionStateChange(STATE_DISCONNECTED)removes the client from
connectedGattsand runscleanUpConnection(deviceId, gatt), which fails every
pending write.close()is skipped because the device is inautoConnectDevices.- 30 ms later
writeValueis called.gattRegistry.get(deviceId)still returns the
open client andgetCharacteristic()still finds the cached characteristic. The
WriteResultFutureis registered. Below API 33 the plugin uses the deprecated
writeCharacteristic(characteristic), which returnstrueonce the request is
handed toGattService. So the plugin counts it as success and keeps the future. GattServicethen drops the request. The system logs
E/BtGatt.GattService: writeCharacteristic() - No connection for …
6 ms later, andonCharacteristicWriteis never called. Nothing removes the future
afterwards: cleanup already ran,STATE_CONNECTEDsweeps nothing, and the Dart
timeout (10 s) does not withdraw the native entry.- Android reconnects the same client (
clientIfunchanged), and services are
discovered again. From then on, the stack reports every write as successful within
3–5 ms (onWriteCharacteristic() status=0), yet every Dartwritetimes out after
exactly 10 s.onCharacteristicWritecompletes the oldest matching
WriteResultFuture(firstOrNull,it.gatt === gatt), which is the stale one
from step 2, so each write is completed by the next one's callback. With the
per-device queue the peripheral gets about one write per 10 s until the
device is disconnected.
This is the "lags by one" failure from #387 / #390, with a different trigger. Here
the stale entry comes from a write the stack accepted and then dropped, not one
that threw, so the #390 withdrawal does not apply. #376 does not help either, because
the reconnect reuses the same BluetoothGatt instance, so the ownership check matches.
Scope: likely API ≤ 32 only. On API 33+ the plugin calls
writeCharacteristic(characteristic, value, writeType), which returns a status code.
As far as I can tell from AOSP, GattService returns ERROR_DEVICE_NOT_CONNECTED
there, so the existing result != GATT_SUCCESS branch should fail the write right
away. I could not test this on API 33+.
Expected: a write submitted while the client is not connected fails right away with
deviceDisconnected, as Apple already does since #378. Writes after the auto-reconnect
complete normally.
For comparison: flutter_blue_plus (Android 7.0.x) keeps the client in a separate
autoConnect map but refuses a write unless the device is in its connected-devices map
(mConnectedDevices.get(remoteId) == null → "device is disconnected"). It removes
the device from that map on STATE_DISCONNECTED even when autoConnect keeps the
client open. So the same race fails fast there.
Possible fix (Android)
- In
writeValue, checkconnectedGatts.contains(gatt)inside
synchronized(writeResultFutureList), right before the future is added, and fail with
DEVICE_DISCONNECTEDif it is missing. A check before taking the lock still leaves a
gap: the check passes, thenSTATE_DISCONNECTEDruns cleanup on the binder thread,
and only then is the future added. Inside the lock it is safe, because
onConnectionStateChangeremoves the client fromconnectedGattsbefore
cleanUpConnectiontakes that lock. Either the check fails, or the future is added
in time to be swept. The same likely applies towriteDescriptorValueand the read
paths. - As a backstop, on
STATE_CONNECTEDfail any pending operations whose
it.gatt === gatt, that is, ones left over from that client's previous link. Only
that client's operations, not every operation for the address.
Workaround (app side, verified)
As soon as an unexpected disconnect is reported, call
UniversalBle.disconnect(deviceId), then connect(deviceId, autoConnect: true)
again, instead of letting Android reconnect the old client. disconnect() runs
cleanConnection → cleanUpConnection, which fails anything still pending on the old
client, and removes it from the registry. The new client starts with no stale
entries. Doing it straight away matters: if Android relinks the old client first, the
reset tears down a link that has just come back.
Verified on three power cycles:
- With the reset delayed by about 1 s, the racing write reached the stack
(No connection for …) and was then failed by the reset with
deviceDisconnected. - With the reset started 25–85 ms after the link loss, the racing write arrived after
the old client had left the registry and failed at once withdeviceNotFound. It
never reached the stack. - In every case, writes after the reconnect completed in 1–3 ms with no timeouts, the
old client was closed by the plugin's fallback timer, and the peripheral was still
discoverable after an intended disconnect.
The workaround costs a fresh connectGatt per link loss, and app code that relies on
the plugin's in-place autoConnect reconnect has to manage the reconnect itself.
Notes on logs
UniversalBle.setLogLevel(BleLogLevel.debug) plus the system BtGatt.GattService
lines. MAC and vendor UUIDs are redacted.
Before the power cycle, the same writes completed in about 10–25 ms each. The behaviour
reproduced on two separate power cycles. With the workaround above it did not occur
in three more power cycles (see Workaround).
Sample code
// Android ≤ 12, a peripheral with a write-without-response characteristic.
await UniversalBle.connect(deviceId, autoConnect: true);
await UniversalBle.discoverServices(deviceId);
// Write periodically, like a vibration pattern.
Timer.periodic(const Duration(milliseconds: 250), (_) {
UniversalBle.write(deviceId, serviceId, charId, payload, withoutResponse: true)
.catchError((e) => print(e));
});
// Power the peripheral off for about 5 s, then back on. Android reconnects the
// autoConnect client and discoverServices runs again on CONNECTED. From then on,
// every write fails with TimeoutException after 10 s.Logs / stack trace
07:14:49.851 D/UniversalBle: WRITE -> XX:XX:XX:XX:87:96 <svc> <chr> len=12 property=WITHOUT_RESPONSE
07:14:49.857 D/BtGatt.GattService: onWriteCharacteristic() - address=…, status=0
07:14:49.918 D/BtGatt.GattService: onDisconnected() - clientIf=10, connId=10, status=19
07:14:49.928 D/UniversalBle: onConnectionStateChange-> Status: 19 Remote User Terminated Connection, NewState: 0
07:14:49.957 D/UniversalBle: WRITE -> XX:XX:XX:XX:87:96 <svc> <chr> len=12 property=WITHOUT_RESPONSE <-- after cleanup
07:14:49.963 E/BtGatt.GattService: writeCharacteristic() - No connection for … <-- dropped, no callback
07:14:59.979 I/flutter: TimeoutException after 0:00:10.000000: Future not completed
07:15:00.427 D/UniversalBle: onConnectionStateChange-> Status: 0 null, NewState: 2 <-- same clientIf=10
07:15:01.186 D/BluetoothGatt: onSearchComplete() Status=0
07:15:02.036 D/UniversalBle: WRITE -> …
07:15:02.040 D/BtGatt.GattService: onWriteCharacteristic() - address=…, status=0 <-- stack completes in 4 ms
07:15:12.042 I/flutter: TimeoutException after 0:00:10.000000: Future not completed <-- Dart still times out
07:15:12.044 D/UniversalBle: WRITE -> …
07:15:12.055 D/BtGatt.GattService: onWriteCharacteristic() - address=…, status=0
07:15:22.048 I/flutter: TimeoutException after 0:00:10.000000: Future not completed
… continues, one write per 10 s
Activity
fotiDim commentedon Nov 22, 2026
@vienvudev please try #395
Android: gate every GATT request on a live link, sweep before reconne…
Web: read the live GATT flag for the disconnect check (#394)
Keep the link check and the disconnect report correct through a teardown
Web: read the live GATT flag for the disconnect check (#394)
Android: refuse requests on a disconnected autoConnect client (#394) (#…
Linux/Web: name a disconnected device in GATT request failures (#394)
Windows: refuse GATT requests on a link that is already down (#394)
Apple: refuse GATT requests on a disconnected peripheral (#394)
Web: read the live GATT flag for the disconnect check (#394)
Linux/Web/Windows/Apple: name a disconnected device in GATT request f…
Android: one state field per GATT client, one pending-operation regis…
CI: typecheck the Apple sources on every pull request
CI: typecheck the Apple sources on every pull request (#398)
Android/Windows/Apple: check the link before the GATT lookup (#399)