I am developing an app that needs to connect to a ble peripheral automatically.
I have a sticky service that does the following:
- looks for the required device in bonded devices
- if it doesn't fine the device (first time), scans for it and bonds to it by using
device.createBond()
, waits for the bond to finish by listening to the ACTION_BOND_STATE_CHANGED broadcast - connects to it using
device.connectGatt(ctx,true,callback)
- waits for
onConnectionStateChange
callback with connected state - starts service discovery by using
gatt.discoverServices()
- waits for
onServicesDiscoverd
callback - enables notifications on a characteristic by writing a descriptor using
gatt.writeDescriptor
- waits for onDescriptorWrite callback with success status
BluetoothGatt.GATT_SUCCESS (0)
- does stuff with the notifications it receives
This all works fine for the first time. When the device disconnects (becomes out of range for instance, or turned off) the sticky service callbacks gatt.disconnect()
and gatt.close()
, restarts and does all this again, this time it uses the bonded device to connect.
Everything works fine until step 7, meaning I get a callback to onDescriptorWrite
with status 133 sometimes followed by a connection state change callback with state 0 and status 22.
I could not find any info online for what status 133 or 22 mean.
Any idea why this is happening?
I am sort of working around it now by reacting to the bad onDescriptorWrite
callback by removing the bond (reflection) an doing everything again with the freshly scanned device.
So basically I am using the bond just to wait for the device connection and then restart the whole thing.
This means a gatt connection for a bonded device is useless for writing the descriptor I need.
It feels like I am missing something, would love to know what.
EDIT: some relavant logcat output
08-18 16:06:31.363 12765-12835/? W/bt-att﹕ gatt_rsp_timeout disconnecting...
08-18 16:06:31.363 12765-12835/? W/bt-btif﹕ bta_gattc_conn_cback() - cif=3 connected=0 conn_id=3 reason=0x0016
08-18 16:06:31.363 12765-12835/? W/bt-btif﹕ bta_gattc_conn_cback() - cif=4 connected=0 conn_id=4 reason=0x0016
08-18 16:06:31.363 12765-12835/? W/bt-btif﹕ bta_gattc_conn_cback() - cif=5 connected=0 conn_id=5 reason=0x0016
08-18 16:06:31.366 12765-12807/? D/BtGatt.GattService﹕ onDisconnected() - clientIf=5, connId=5, address=C1:D1:22:BA:F5:13
here im getting onDescriptorWrite with status 133
D/BluetoothGatt﹕ onClientConnectionState() - status=22 clientIf=5 device=C1:D1:22:BA:F5:13
by the looks of this:
https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/idea133/bta/include/bta_gatt_api.h#169
16 means BTA_GATT_CONN_TERMINATE_LOCAL_HOST
22 means BTA_GATT_CONN_LMP_TIMEOUT
asked this on nordics github:https://github.com/NordicSemiconductor/Android-nRF-Toolbox/issues/9#issuecomment-132191406