I use following code to enable notification on android device using kotlin: with this code notifications get enabled, but i am not recieving notification even when data changes on the device. I am not recieving any error, i am so confused as i am developing my first ble app. I don't know what more details i could include
is EnableNotifications -> with(operation) {
gatt.findCharacteristic(characteristicUuid)?.let { characteristic ->
val cccdUuid = UUID.fromString(CCC_DESCRIPTOR_UUID)
val payload = when {
characteristic.isIndicatable() ->
BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
characteristic.isNotifiable() ->
BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
else ->
error("${characteristic.uuid} doesn't support notifications/indications")
}
characteristic.getDescriptor(cccdUuid)?.let { cccDescriptor ->
if (!gatt.setCharacteristicNotification(characteristic, true)) {
Timber.e("setCharacteristicNotification failed for ${characteristic.uuid}")
signalEndOfOperation()
return
}
cccDescriptor.value = payload
gatt.writeDescriptor(cccDescriptor)
}}
//which is writing descriptor as follows:
override fun onDescriptorWrite(
gatt: BluetoothGatt,
descriptor: BluetoothGattDescriptor,
status: Int
) {
with(descriptor) {
when (status) {
BluetoothGatt.GATT_SUCCESS -> {
Timber.i("Wrote to descriptor $uuid | value: ${value.toHexString()}")
if (isCccd()) {
onCccdWrite(gatt, value, characteristic)
} else {
listeners.forEach {
it.get()?.onDescriptorWrite?.invoke(
gatt.device,
this
)
}
}
}
BluetoothGatt.GATT_WRITE_NOT_PERMITTED -> {
Timber.e("Write not permitted for $uuid!")
}
else -> {
Timber.e("Descriptor write failed for $uuid, error: $status")
}
and then on characteristic changed the following code get used:
override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic
) {
with(characteristic) {
super.onCharacteristicChanged(gatt, characteristic)
Timber.i("Characteristic $uuid changed | value: ${value.toHexString()}")
listeners.forEach {
it.get()?.onCharacteristicChanged?.invoke(gatt.device, this)
}
}
}
As above code is written in manager class, I am calling this with following code from activity which need to recieve notification:
val characteristicNotify = BluetoothGattCharacteristic(
char_uuid, BluetoothGattCharacteristic.PROPERTY_NOTIFY ,
1
)
Manager.enableNotifications(device, characteristicNotify)