Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Bluetooth characteristic read gives an error

Tags:

flutter

dart

Connection func: (Using Flutter_Blue)

connectDevice(BluetoothDevice device) async {
    flutterBlue.stopScan();
    try {
      print('waiting');
      await device.connect();
      print('ok');
    } catch (e) {
      print(e);
    } finally {
      _services = await device.discoverServices();
    }
    _connectedDevice = device;
    if (_connectedDevice != null) {
      for (BluetoothService bleservice in _services) {
        if (bleservice.uuid.toString().toLowerCase() == deviceUUID) {
          bleservice.characteristics.forEach((c) {
            if (c.uuid.toString().toLowerCase() == writeUUID) {
              _tx = c;
              print('TX found');
            } else if (c.uuid.toString().toLowerCase() == readUUID) {
              _rx = c;
              print('RX found');
            }
          });
        }
        await _tx.write(sourceSettings);
        notifyListeners();
      }
    } else {
      print("CANNOT START SERVICE ON THIS DEVICE");
    }
  }

I run this method to send a command. Then I wait for it to get finished. I also separated the functions to write and read, even that didn't work.

getBackgroundFunction(final List<int> writeBgCommand) async {
    await _tx.write(writeBgCommand, withoutResponse: false);
    List<int> value = await _rx.read();
    print(value);
  }

The value shows as null. It's supposed to read multiple packets of 20 bytes each which are received as a response to writing the characteristic. The device responds correctly when I use the nRF app from Play Store, but here value returns as null. What am I doing wrong here? The characteristics are setup correctly... (I think) Also, there is a certain delay to receive all the packets as they are sent one by one. MTU of device: 20.

like image 373
RealRK Avatar asked Apr 18 '26 04:04

RealRK


1 Answers

Turns out I had to listen to notify events and get the value:

await characteristic.setNotifyValue(true);
characteristic.value.listen((value) {
    // do something with new value
});
like image 172
RealRK Avatar answered Apr 20 '26 22:04

RealRK