javascript - 如何将从 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]
});
解决方案
使用 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}`);
};
);
推荐阅读
- c - 套接字是否允许在 C 中是全局的?
- java - 弹簧靴。如何将 Optional<> 传递给实体类
- java - 在名称为“dispatcher”的 DispatcherServlet 中找不到带有 URI [/ecommerce.mvc/] 的 HTTP 请求的映射
- webpack-4 - React+Typescript+Webpack4:找不到模块“***.json”
- angular - Angular 6 / AngularFire 迁移
- botframework - 与多个机器人共享相同的对话
- php - 登录后使用php重定向到索引
- jquery - 使用 excel-bootstrap-table-filter jQuery 插件时如何对日期进行排序
- c# - c#: GUID 指定的值超出范围
- android - 如何在安卓应用中访问谷歌开发者API