简体   繁体   中英

how to send data using flutter_blue?

I am looking through the documentation at: https://pub.dev/documentation/flutter_blue/latest/ The following code is shown on the documentation:

// 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])

I understand that in order to read, we need to loop through all the characteristics, and read each one. What about write?

If the c is the iterator inside the loop, how can we call it outside the loop. I am assuming that the 1 by 2 matrix inside the write method is the location to write the characteristic inside the service. I doubt that the location should be hard coded. I am just a little confused., and would love a little clarification. Any explanation would be greatly appreciated! Thanks !

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM