首页 > 解决方案 > 如何将从 ble 设备获取的字节数据转换为人类可读的字符串?

问题描述

我正在使用 react-native-ble-manager 将我的 ble 设备连接到我的 react native 应用程序。我在我的应用程序中连接并从 ble 设备获取数据。它是字节数组。我在下面尝试了解决方案,但没有运气。如何转换数据?

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]
                });

标签: javascriptandroidreact-nativebluetoothbluetooth-lowenergy

解决方案


使用 Buffer 包非常适合我。更多信息:https ://www.npmjs.com/package/buffer

这是我用来从字节字符串解码浮点数的示例代码:

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

在需要模块后,

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}`);
    };
);   

推荐阅读