Write data to BLE device and read its response flutter?

Issue

I am facing issues with writing the commands to BLE device and receiving the data. I am writing ASCII encoded string to the Characteristic. The problem arises when its time to decode the data back. Exact data is received as it’s received in iOS but when I try to decode it just gets blank. I tried decoding via UTF8 decoder and ASCII decoder but no result was obtained.

This is how I discover the devices.

@override
  void initState() {
    // TODO: implement initState
    widget.flutterBlue.scanResults.listen((List<ScanResult> results) {
      for (ScanResult result in results) {
        _addDeviceTolist(result.device);
      }
    });
    widget.flutterBlue.startScan();
  }

Connect Device:-

void _connectDevice() async {
    widget.flutterBlue.stopScan();
    print(_deviceToConnect);
    try {
      await _deviceToConnect.connect();
    } catch (e) {
      if (e.code != 'already_connected') {
        throw e;
      }
    } finally {
      _services = await _deviceToConnect.discoverServices();
    }
    _discoverDeviceServices();
    setState(() {
      _connectedDevice = _deviceToConnect;
    });
  }

Discovering the services:-

When commenting TAG-1 & TAG-2 lines the values get printed. I tried both ASCII and UTF8 decoding.

While scrolling through various issues I found out to read values from all the characteristics.

void _discoverDeviceServices() async {
    for (BluetoothService service in _services){
      for (BluetoothCharacteristic characteristic in service.characteristics){
        var value = await characteristic.read();
        print(value);
        // print(AsciiDecoder().convert(value)); /*** TAG-1***/
        // print(utf8.decode(value)); /*** TAG-2***/
        if (characteristic.properties.write){
          if (characteristic.properties.notify){
            _rx_Write_Characteristic = characteristic;
            _sendCommandToDevice();
          }
        }
      }
    }
  }

Writing commands to device:-

void _sendCommandToDevice() async {
    final command = "AT Z\r";
    final convertedCommand = AsciiEncoder().convert(command);
    await _rx_Write_Characteristic.write(convertedCommand);
    _connectedDevice.disconnect();
  }

Please help me out pointing where I got wrong in reading the response of the data written to BLE device and how exactly writing and reading of values is to be done?

Thanks!

Solution

It is probably String.fromCharCode you are looking for.

It seemed to give the right answer when I tested it with your values on https://dartpad.dev/

enter image description here

The 13s are \r escape characters that represent carriage return

Answered By – ukBaz

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.