首页 > 解决方案 > 如何从缓冲区呈现数据?反应原生 Javascript

问题描述

我是 react-native 的新手,我正在使用库 react-native-ble-plx 将心脏传感器连接到我的应用程序并显示它的值。

此时,我设法通过蓝牙连接它并将信息存储在缓冲区中,我可以通过 console.log(buffer) 看到,如下图所示。

在此处输入图像描述

我的问题是如何将这些信息呈现给应用程序?我不知道如何从那个缓冲区处理它。

编辑:我特别想要那个缓冲区的第二个值(通常是 70 的那个)

这是代码:

scanAndConnect() {
      this.manager.startDeviceScan(null,
                                   null, (error, device) => {
          this.info("Scanning...");

          if (error) {
            this.error(error.message);
            return;
          }
          console.log(device.name)
          //if (device && device.name == 'Inspire HR') {
            if (device && device.name == 'HX-00043494') {
            this.manager.stopDeviceScan()
             device.connect()
               .then((device) => {
                 this.info("Discovering services and characteristics ")
                 return device.discoverAllServicesAndCharacteristics()
           }).then((device) => {
                 this.info("Setting notifications")
            ``return this.Async_setupNotifications(device);
          })
          .then(() => {
            this.info("Listening...")
           return this.setupNotifications(device)

          }, (error) => {
            this.error(error.message)
          })
      }
    })`
  }


async Async_setupNotifications(device) {
 this.manager.characteristic  = device.characteristicsForService("0000180d-0000-1000-8000-00805f9b34fb");
const buf = Buffer.from(characteristic.value, "base64");
console.log(buf);
console.log (buf[1]);


this.manager.characteristic.isNotifying = true;
this.manager.characteristic.isReadable = true;


 if (error) {
   this.error(error.message)
             }
return ;
}

非常感谢到目前为止的帮助

标签: javascriptandroidreact-nativebluetooth

解决方案


假设您在应用程序中执行 console.log,您需要通过 buffer.data[1] 访问数据,它应该为您提供第二个值。

如果buffer是一个全局变量,简单的例子如何在 React Native Component 中渲染:

import React from 'react';
import {View,Text} from 'react-native';

let buffer;
export default class YourComponent extends React.Component {

    Async_setupNotifications = async (device) => { // call this method from within your code
       this.manager.characteristic  = 
       device.characteristicsForService("0000180d-0000-1000-8000-00805f9b34fb");
       const buf = Buffer.from(characteristic.value, "base64");
       console.log(buf);
       console.log (buf[1]);
       this.setState({pulse: buf.data[1]}); // assign the needed data to state
    }
    render() {
       return(
          <View>
              <Text>{this.state.pulse}</Text>
          </View>
       )
    }
}

推荐阅读