Decode Ble data raw flutter

971 views Asked by At

I'm developing a flutter app using the flutter_blue library to interface a BlueNRG-tile from STMicroelectronics. I'm receiving the the raw data from the desired caracteristics then i'm note able ble to convert them to string using the utf8.decode() function.

This is the received data as a list and the issue.

I/flutter (32277): Teste conversion : [121, 85, 0, 0, 209, 133, 1, 0, 5, 10, 237, 0, 0, 0]
E/flutter (32277): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FormatException: Missing extension byte (at offset 11).

the code from the in the st board:

tBleStatus Environmental_Update(int32_t Press,int32_t Press2,uint16_t Hum, int16_t Temp,int16_t Temp2) {
    uint8_t BuffPos = 0;

    STORE_LE_16(buff, (getTimestamp()));
    BuffPos = 2;

    STORE_LE_32(buff + BuffPos, Press);
    BuffPos += 4;

    STORE_LE_16(buff + BuffPos, Hum);
    BuffPos += 2;

    STORE_LE_16(buff + BuffPos, Temp);
    BuffPos += 2;
    STORE_LE_16(buff + BuffPos, Temp2);
    

    return aci_gatt_update_char_value(HWServW2STHandle, EnvironmentalCharHandle, 0, EnvironmentalCharSize, buff);

}

Environmental_Update(PressToSend,PressToSend2, HumToSend, TempToSend,TempToSend2);

Thank You.

1

There are 1 answers

0
Michael Kotzjan On

You are not able to convert your RAW data to string because you are not sending it as string but in form of bytes.

Take your temperature for example: You receive the temperature as int16_t, a 16-bit number storing values from –32768 to 32767. This number needs two bytes to be stored, that's why you used BuffPos += 2; and increased the position by 2 bytes.

You need to extract the values from your received array the same way, bytewise. Have a look at this example:

import 'dart:typed_data';

int fromBytesToInt16(int b1, int b0) {
    final int8List = new Int8List(2)
      ..[1] = b1
      ..[0] = b0;
  
    return ByteData.sublistView(int8List).getInt16(0);
}

void main() {
    var received = [121, 85, 0, 0, 209, 133, 1, 0, 5, 10, 237, 0, 0, 0];
    var temp = fromBytesToInt16(received[8], received[9]) / 100;
    print('temperature: $temp');
}

The temperature was stored as a int16 at index 8 and 9 so I converted it the same way. This results in a temp value of 2565, which divided by 100 would give a pretty nice temperature of 25.65 degree