0

I am using react-native-ble-manager for connecting my ble device to my react native app. I was connect and got data from ble device in my app. It is byte array. I was tried solutions below but no luck. How do I convert data?

bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic',
                ({ value, peripheral, characteristic, service }) => {

                    const data = bytesToString(value);
                    //value = 255,82,3,252,252,127,32,29,252,255
                    //data = ÿRüü üÿ (this returns non readable string)

                    let bytesView = new Uint8Array([value]);
                    // bytesView = [0]

                    const str = new TextDecoder().decode(bytesView)
                    //str = '' (no value to show here)

                    const bytes2 = new TextEncoder(
                        'windows-1252', { NONSTANDARD_allowLegacyEncoding: true })
                        .encode(str)
                    //bytes2 =  [0]
                });
Sid009
  • 421
  • 5
  • 16
  • Does this answer your question? [Converting byte array to string in javascript](https://stackoverflow.com/questions/3195865/converting-byte-array-to-string-in-javascript) – David784 Apr 19 '20 at 14:57
  • @David784 this solution tried before but not works. – Sid009 Apr 19 '20 at 14:59
  • Since you've already tried some things, perhaps you might consider editing your question to include your code, explaining what you have tried so far and why it didn't work? For example what error messages you got, or showing the output you got and why it's different than what you expected? A [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) is almost always helpful, and makes it much more likely that you'll get a useful answer. – David784 Apr 19 '20 at 15:48
  • But what type of data is it you try to show? If it's pure binary data, you could convert it to a hexadecimal string. – Emil Apr 20 '20 at 12:55

1 Answers1

0

using Buffer package perfectly worked for me. More info here: https://www.npmjs.com/package/buffer

This is an example code I'm using to decode a float from a byte string:

var Buffer = require('buffer/').Buffer  // note: the trailing slash is important!

After requiring the module,

bleManagerEmitter.addListener(
   'BleManagerDidUpdateValueForCharacteristic', 
    ({ value, peripheral, characteristic, service }) => {

        // value is an encoded Byte Array
        const buffer = Buffer.from(value);
        
        const decodedValue = buffer.readFloatLE(0, true);

        console.log(`Received ${decodedValue} for characteristic ${characteristic}`);
    };
);