ble-starter-android
ble-starter-android copied to clipboard
connection is not closed if there was a fail while establishing the connection
https://github.com/PunchThrough/ble-starter-android/blob/master/app/src/main/java/com/punchthrough/blestarterappandroid/ble/ConnectionManager.kt
It seems like if a connection fail event happens (for example, the status field is not success and there was a failure while establishing the connection) - the teardownConnection(...) will be called, but without any effect. The teardown function will check for is the device connected/not, and in this particular case the device won't be connected, so essentially "gatt.close()" won't be called.
I have the same issue. Does anyone have a solution ?
Fix?
`
fun teardownConnection(device: BluetoothDevice) {
if (device.isConnected()) {
enqueueOperation(Disconnect(device))
true
} else {
Timber.e("Not connected to ${device.address}, cannot teardown connection!")
signalEndOfOperation()
false
}
}
fun disconnect(gatt: BluetoothGatt) {
if (gatt.device.isConnected()) {
teardownConnection(gatt.device)
true
} else {
gatt.close()
deviceGattMap.remove(gatt.device)
Timber.e("Not connected to ${gatt.device.address}, cannot teardown connection!")
signalEndOfOperation()
false
}
}
. . .
private val callback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
val deviceAddress = gatt.device.address
if (status == BluetoothGatt.GATT_SUCCESS) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Timber.w("onConnectionStateChange: connected to $deviceAddress")
deviceGattMap[gatt.device] = gatt
Handler(Looper.getMainLooper()).post {
gatt.discoverServices()
}
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Timber.e("onConnectionStateChange: disconnected from $deviceAddress")
disconnect(gatt)
//teardownConnection(gatt.device)
}
} else {
Timber.e("onConnectionStateChange: status $status encountered for $deviceAddress!")
if (pendingOperation is Connect) {
signalEndOfOperation()
}
disconnect(gatt)
//teardownConnection(gatt.device)
}
}
`
It works in my case ...