连续通知和写入差异特征

时间:2020-09-20 15:06:50

标签: android bluetooth-lowenergy bluetooth-gatt

我试图接收某个特性中的通知,然后在同一BLE设备的另一个特性中编写文本。但是在大多数情况下,当写入设备时,它会断开我的连接,因为我想不到某些事情会进展顺利。这是代码。

BluetoothGatt gatt = null;
    BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                gatt.close();
            }
        }
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        BluetoothGattCharacteristic characteristic = null;

        if (BLOODGLUCOSE_MODEL.equals(GlobalNames.ADF_B27)) {
            characteristic = gatt.getService(BLOODGLUCOSE_SERVICEUDID).getCharacteristic(BLOODGLUCOSE_NOTIFY_CHARACTERISTICSUDID);
            gatt.setCharacteristicNotification(characteristic, true);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID);
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);
        }
    }

    @Override
    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        super.onDescriptorWrite(gatt, descriptor, status);
        BluetoothGattCharacteristic characteristic = null;

        try {
            if (BLOODGLUCOSE_MODEL.equals(GlobalNames.ADF_B27)) {
                characteristic =
                        gatt.getService(BLOODGLUCOSE_SERVICEUDID)
                                .getCharacteristic(BLOODGLUCOSE_WRITE_CHARACTERISTICSUDID);
                byte[] byteValue = new byte[10];
                byteValue[0] = (byte)0x5A;
                byteValue[1] = (byte)0x0A;
                byteValue[2] = (byte)0x00;
                byteValue[3] = (byte)0x14;
                byteValue[4] = (byte)0x09;
                byteValue[5] = (byte)0x14;
                byteValue[6] = (byte)0x0A;
                byteValue[7] = (byte)0x05;
                byteValue[8] = (byte)0x09;
                byteValue[9] = (byte)0xAF;
                characteristic.setValue(byteValue);
                (gatt.writeCharacteristic(characteristic);
            }
        } catch (NullPointerException e) {  }
    }
}

我可以看到writeDescriptor()和writeCharacteristic始终返回true。 有人看到任何错误吗?

谢谢。

0 个答案:

没有答案