Read/Write 来自 BLE 设备的自定义特征

Read/Write custom characteristic from BLE device

我正在尝试使用 Android Studio 作为 IDE 和 Java 作为编程语言与温度计 BLE 设备进行交互。在我的智能手机上使用一个应用程序,我发现了这个设备在其运行期间公开的服务:有很多通用 services/characteristic 和一个自定义服务。

首先我尝试阅读

从服务列表中恢复特征并访问其描述符:

BluetoothGattCharacteristic temp_char = mBluetoothGattServiceList.get(2).getCharacteristics().get(0); 
for (BluetoothGattDescriptor descriptor : temp_char.getDescriptors()) {
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);
}
mBluetoothGatt.setCharacteristicNotification(temp_char, true);

在这种情况下,我可以在 onCharacteristicChanged 回调中看到测量结果:

public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
float char_float_value = characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_FLOAT, 1);
}

但是,在设备随附的文档中提示按照 GATT 连接到仪表:

并列出几个 8 字节的命令发送到仪表等待 8 字节的响应。使用此格式的帧发送命令

[0x51 CMD Data_0 Data_1 Data_2 Data_3 0xA3 CHK-SUM]

并且响应与响应相同,但有一些细微差别。

我可以使用 gatt.writeCharacteristic 发送帧,但我无法接收到响应帧,始终将 0x01 0x00 作为仪表的唯一答案(2 字节而不是 8)。

我就是这样做的:

    BluetoothGattCharacteristic custom_char = mBluetoothGattServiceList.get(5).getCharacteristics().get(0);                mBluetoothGatt.setCharacteristicNotification(custom_char, true);
    for (BluetoothGattDescriptor descriptor : custom_char.getDescriptors()) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
    byte[] req_frame = new byte[8];
    req_frame[0] = (byte) 0x51;
    req_frame[1] = (byte) 0x24;
    req_frame[2] = (byte) 0x0;
    req_frame[3] = (byte) 0x0;
    req_frame[4] = (byte) 0x0;
    req_frame[5] = (byte) 0x0;
    req_frame[6] = (byte) 0xA3;
    req_frame[7] = (byte) 0x18;
    custom_char.setValue(req_frame);
    mBluetoothGatt.writeCharacteristic(custom_char);

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS {
    mBluetoothGatt.readCharacteristic(characteristic);
        }
    }

@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    System.out.println("[onCharacteristicRead] status : " + status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG, "[onCharacteristicChanged] " + ByteArrayToString(characteristic.getValue()));
    }
}

@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    byte[] response = characteristic.getValue();
    Log.d(TAG, "[onCharacteristicChanged] " + ByteArrayToString(response));
    }
}

唯一未触发的回调是 OnCharacteristicRead,我想我会在其中找到帧响应。

我在通信协议中犯了一些错误?我怎样才能收到 8 字节的响应帧?

提前致谢!

您的错误是您一次只能进行一项未完成的 Gatt 操作。在发送下一个之前,您必须等待回调。有关详细信息,请参阅