0

我将数据作为 20 字节块发送到 BLE 设备。
我收到了很大的回复。但是onCharacteristicRead回电,我只得到最后一条数据。

byte[] messageBytes = characteristic.getValue();

if (messageBytes != null && messageBytes.length > 0) {
  for(byte byteChar : messageBytes) {
     stringBuilder.append((char)byteChar);
  }
}
  • 谁能帮助理解我哪里出错了?
  • 我应该也将数据作为块读回吗?
  • 如果是这样,怎么做?
4

1 回答 1

1

每次写入时,Characteristic 的值都会更新,这就是为什么当您读取时,它只反映最新的值(您写入的最后一个值)。

要连续读取数据,您应该首先启用有关特征的通知。

    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID_DESCRIPTOR);
    descriptor.setValue(enabled?BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                             :BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);

然后就可以开始写数据了

            byte[] data = <Your data here>;
            BluetoothGattService Service = mBluetoothGatt.getService(UUID_TARGET_SERVICE);

            BluetoothGattCharacteristic charac = Service
            .getCharacteristic(UUID_TARGET_CHARACTERISTIC);

            charac.setValue(data);
            mBluetoothGatt.writeCharacteristic(charac);

现在每次编写时,客户端都会收到一个onCharactersticChanged包含新更新值(data)的回调。您实际上不需要调用读取操作。

请记住,mBluetoothGatt 一次只能处理 1 个操作,如果在前一个未完成的情况下执行另一个操作,它不会放入队列,但会返回 false。

于 2020-05-08T08:26:12.163 回答