首页 > 解决方案 > 无法使用 react-native ble-manager 向 BLE 硬件写入或发送数据 [写入错误状态 3]

问题描述

我能够与硬件建立 BLE 连接。通过使用服务 UUID 和特性 UUID,我可以通过启动通知功能从硬件接收数据。但是当我尝试将数据发送到硬件时,它显示错误 [Write error status-3],如下面的代码所示。



BleManager.retrieveServices(peripheral.id).then((peripheralInfo) => {
              console.log(peripheralInfo);

              var service = '6e400001-b5a3-f393-e0a9-e50e24dcca9e';
              var WriteCharacteristic = '6e400002-b5a3-f393-e0a9-e50e24dcca9e';
              var ReadCharacteristic = '6e400003-b5a3-f393-e0a9-e50e24dcca9e';

              setTimeout(() => {

                // receiving data from hardware 
                BleManager.startNotification(peripheral.id, service, ReadCharacteristic).then(() => {
                  console.log('Started notification on ' + peripheral.id);
                  setTimeout(() => {
                      // sending data to the hardware
                    BleManager.write(peripheral.id, service, WriteCharacteristic, [1,95]).then(() => {
                      console.log('Writed NORMAL crust');
                    });

                  }, 500);
                }).catch((error) => {
                  console.log('Notification error', error);
                });

首先遇到了一些没有找到特征的问题。经过一些更改后,我收到错误消息

Write error Status - 3

我无法找到此错误的任何解决方案。先感谢您

标签: javascriptreact-nativebluetooth-lowenergyreact-native-androidreact-native-ios

解决方案


在使用 BleManager.write 时,您应该首先准备数据

资料准备:

如果您的数据不是字节数组格式,您应该先转换它。对于字符串,您可以使用 convert-string 或其他 npm 包来实现这一点。先安装包:

npm install convert-string

然后在您的应用程序中使用它:

// Import/require in the beginning of the file
import { stringToBytes } from "convert-string";
// Convert data to byte array before write/writeWithoutResponse
const data = stringToBytes(yourStringData);

就我而言,我将数据转换为字节格式,这样你也可以这样做。

const dataByte = convertString.UTF8.stringToBytes(data);

然后在我的代码中使用

BleManager.retrieveServices(currentDevice.PID).then((peripheralInfo) => {
      console.log(peripheralInfo);
      BleManager.write(
        currentDevice.PID,
        '0000ffe0-0000-1000-8000-00805f9b34fb',
        '0000ffe1-0000-1000-8000-00805f9b34fb',
        dataByte,
      )
        .then(() => {
          console.log(`Sent ${dataByte}`);
        })
        .catch((error) => {
          console.log(error);
        });
    });
  };

推荐阅读