Skip to content

Commit

Permalink
fix(android): wait for onDescriptorWrite when setting notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
pwespi committed Mar 20, 2021
1 parent b763247 commit 06d05bc
Showing 1 changed file with 18 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class Device(
private var bluetoothGatt: BluetoothGatt? = null
private var callbackMap = HashMap<String, ((CallbackResponse) -> Unit)>()
private var timeoutMap = HashMap<String, Handler>()
private var setNotificationsKey = ""

private val gattCallback: BluetoothGattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(
Expand Down Expand Up @@ -125,6 +126,21 @@ class Device(
callbackMap[notifyKey]?.invoke(CallbackResponse(true, value))
}
}

override fun onDescriptorWrite(
gatt: BluetoothGatt,
descriptor: BluetoothGattDescriptor,
status: Int
) {
super.onDescriptorWrite(gatt, descriptor, status)
if (status == BluetoothGatt.GATT_SUCCESS) {
resolve(setNotificationsKey, "Setting notification succeeded.")
} else {
reject(setNotificationsKey, "Setting notification failed.")
}
setNotificationsKey = ""

}
}

fun getId(): String {
Expand Down Expand Up @@ -219,6 +235,7 @@ class Device(
callback: (CallbackResponse) -> Unit,
) {
val key = "setNotifications|$serviceUUID|$characteristicUUID"
setNotificationsKey = key
val notifyKey = "notification|$serviceUUID|$characteristicUUID"
callbackMap[key] = callback
if (notifyCallback != null) {
Expand All @@ -240,11 +257,7 @@ class Device(
}
val resultDesc = bluetoothGatt?.writeDescriptor(descriptor)
if (result == true && resultDesc == true) {
if (enable) {
resolve(key, "Notification enabled.")
} else {
resolve(key, "Notification disabled.")
}
// wait for onDescriptorWrite
} else {
reject(key, "Setting notification failed.")
}
Expand Down

0 comments on commit 06d05bc

Please sign in to comment.