flutter - 如何使用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 矩阵是在服务中写入特征的位置。我怀疑该位置应该是硬编码的。我只是有点困惑。,并希望得到一点澄清。任何解释将不胜感激!谢谢 !
解决方案
There are several types of characteristics for BLE:
- Read - this characteristic will allow you only to read from it.
- 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.
- 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.
推荐阅读
- javascript - JavaScript:如何为对象的键和值使用单独的数组索引变量?
- javascript - 在 ionic 3 中的 websql mock 中获取查询 ID(以在其他查询中重用)
- android - Gradle 构建失败,不同产品的字符串名称相同
- node.js - NodeJS sequelize 和 sqlite 错误:无法读取未定义的属性“findAll”
- c - 地址作为 sizeof() 运算符中的操作数
- java - 无法在 HotSpot 中创建 2³¹-1 大小的字节 []
- c# - 向另一个文本框应用程序发送消息
- vba - 自动排列数据
- kubernetes - Kubernetes 的艰难之路 - 如何将节点设置为不可调度
- javascript - TinyMCE - 包装选择的按钮不选择周围的标签