NordicSemiconductor / Android-BLE-Library

A library that makes working with Bluetooth LE on Android a pleasure. Seriously.
BSD 3-Clause "New" or "Revised" License
1.98k stars 413 forks source link

Connection state is not updated when cancelled during the thread sleep time #524

Closed krioru closed 10 months ago

krioru commented 10 months ago

This is the continuation of https://github.com/NordicSemiconductor/Android-BLE-Library/issues/514, which wasn't fully fixed in 2.7.0.

If connection is cancelled during Thread.sleep(200), connection state forever stays as Connecting. After 2.7.0. it got worse, because calling BleManager.getConnectionState() also always returns Connecting.

How it was before (2.6.1): If disconnect is cancelled during the Thread.sleep(200), connection state and BleManager.stateAsFlow() didn't get updated with the ConnectionState.Disconnected, so the main app didn't know what happened. However the connection itself was eventually cancelled/timed out after the first retry:

D  Attempting to connect to 58:8E:81:66:A5:DD
D  Disconnect reason: UNKNOWN
V  Connecting...
D  gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE, LE 1M)
D  [Callback] Connection state changed with status: 133 and new state: 0 (DISCONNECTED)
W  Error: (0x85): GATT ERROR
D  wait(300)
D  gatt.close()
D  wait(200)
D  Attempting to manually disconnect. Physical state = 1
W  Request cancelled
V  Retrying...
D  gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE, LE 1M)
D  [Callback] Connection state changed with status: 133 and new state: 0 (DISCONNECTED)
W  Error: (0x85): GATT ERROR
W  Connection attempt timed out
D  gatt.close()
D  onServicesInvalidated()

How it is now (2.7.0):

D  Attempting to connect to 58:8E:81:66:A5:DD
D  Disconnect reason: UNKNOWN
V  Connecting...
D  gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE, LE 1M)
D  [Callback] Connection state changed with status: 133 and new state: 0 (DISCONNECTED)
W  Error: (0x85): GATT ERROR
D  wait(300)
D  gatt.close()
D  wait(200)
D  Attempting to manually disconnect. Physical state = 1
W  Request cancelled

Nothing happens after Request cancelled. No retry, no connection state update, no onServicesInvalidated() call. Connection state forever equals to Connecting.

So when request is cancelled this way, the BleManager.state should be updated with Disconnected and BleManager.stateAsFlow() also should emit Disconnected state.

philips77 commented 10 months ago

OK, I'm on it now.