首页 > 解决方案 > 如何使用flutter_blue发送数据?

问题描述

我正在查看文档:https ://pub.dev/documentation/flutter_blue/latest/ 文档 中显示了以下代码:

// Reads all characteristics
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
    List<int> value = await c.read();
    print(value);
}

// Writes to a characteristic
await c.write([0x12, 0x34])

我知道为了阅读,我们需要遍历所有特征,并阅读每一个特征。写呢?

如果 c 是循环内的迭代器,我们如何在循环外调用它。我假设 write 方法中的 1 x 2 矩阵是在服务中写入特征的位置。我怀疑该位置应该是硬编码的。我只是有点困惑。,并希望得到一点澄清。任何解释将不胜感激!谢谢 !

标签: flutterbluetoothbluetooth-lowenergy

解决方案


There are several types of characteristics for BLE:

  1. Read - this characteristic will allow you only to read from it.
  2. Write - this characteristic will allow you to only write to it. Side note, there are two types of writes: with response where the write will be confirmed (by the os usually) and this will make sure that all the data is written correctly, write without response where there will be no confirmation of the write.
  3. Notify - this characteristic will trigger a callback on your code when an event is sent by the opposing device.

Now in your case, and in my opinion, in general, it's a good practice to keep a hard reference to your characteristics since the characteristics won't change during the app run. You can query them whenever you need them, but I think it's better to query them after you connect to the device, check the characteristic type (read, write, notify) and based on the device specs you can decide which characteristics to use for: read, write, notify.

Another note on the write, BLE doesn't allow you to write an chunk of data, the value that indicates the packet size is called MTU, based on MTU, you will have to split your raw data in packets of that same length. The MTU differs from device to device and OS and BLE version, so it's a good practice to check it out before any write (also you can store it for later use).

Last note, you don't have to write/read to/from all characteristics, you should always use the characteristics described in the BLE device specs.


推荐阅读