Tuesday, 28 August 2018

Multiple BluetoothGattCharacteristic not being notified

I am working on a BLE device and am not able to get onCharacteristicChanged to ever be called. I have 8 BluetoothGattCharacteristic that I need to be subscribed to.

After I find the device onServicesDiscovered I start a process to subscribe to each characteristic.

private fun requestCharacteristics(gatt: BluetoothGatt, char: BluetoothGattCharacteristic){
        subscribeToCharacteristic(gatt, char, true)
        (charList).getOrNull(0)?.let {
            charList.removeAt(0)
        }
    }

Then in subscribeToCharacteristic I do all checking for the descriptor.

private val CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")

private fun subscribeToCharacteristic(gatt: BluetoothGatt, char: BluetoothGattCharacteristic, enable: Boolean) {
        if (gatt.setCharacteristicNotification(char, enable)){
            val descriptor = char.getDescriptor(CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID)
            if (descriptor != null){
                if (BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0 && char.properties != 0) {
                    descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                } else if (BluetoothGattCharacteristic.PROPERTY_INDICATE != 0 && char.properties != 0) {
                    descriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
                } else {
                    println("The characteristic does not have NOTIFY or INDICATE property set")

                }
                if (gatt.writeDescriptor(descriptor)){
                    println("this worked")
                } else {
                    println("This did not work")
                }
            } else {
                println("Failed to set client characteristic notification")
            }
        } else {
            println("Failed to register notification")
        }

    }

I then get a call for each characteristic in onDescriptorWrite and check if I need to subscribe to another characteristic.

override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor?, status: Int) {
        super.onDescriptorWrite(gatt, descriptor, status)
        if (signalsChars.isNotEmpty()) {
            requestCharacteristics(gatt, signalsChars.first())
        } 
    }

All of this works but I never get any calls from onCharacteristicChanged. Also, if I call gatt.readCharacteristic(char) before I subscribe, onDescriptorWrite will not be called. Again I have 8 characteristics I need to subscribe to. Please help!



from Multiple BluetoothGattCharacteristic not being notified

No comments:

Post a Comment