React Native ble-plx OBDII Adapter 写入和读取/监控特性

问题描述 投票:0回答:1

我正在使用 EAS 构建一个 React Native Expo 应用程序,用于可视化 OBD2 数据。 为此,我使用具有 Buetooth Low Energy 的 ELM327 OBDII 适配器和react-native-ble-plx 库来连接到它。 我能够连接到适配器,但在编写命令和读取响应时遇到问题。

以下代码显示了我如何连接和发现适配器的服务和特征:

  const connectToDevice = async (device: Device) => {
    try {
      const connectedDevice = await bleManager.connectToDevice(device.id);
      setConnectedDevice(connectedDevice);
      await bleManager.discoverAllServicesAndCharacteristicsForDevice(
        device.id
      );
      const services = await bleManager.servicesForDevice(device.id);
      services.forEach(async (service) => {
        const characteristics = await device.characteristicsForService(
          service.uuid
        );
        // characteristics.forEach(console.log);
      });
      bleManager.stopDeviceScan();
      startStreamingData(device);
      console.log("Connection Successful!");
    } catch (e) {
      console.log("Connection Error", e);
    }
  };

函数 startstreamingdata 应该是神奇发生的地方。在这里,我首先尝试发送 OBDII PID(“010C”代表发动机转速),然后使用以下方法读取答案:

 const service = "0000fff0-0000-1000-8000-00805f9b34fb";
  const readAndNotifyChar = "0000fff1-0000-1000-8000-00805f9b34fb";
  const writeChar = "0000fff2-0000-1000-8000-00805f9b34fb";

  const startStreamingData = async (device: Device) => {
    if (device)
      try {
        await device.writeCharacteristicWithoutResponseForService(
          service,
          writeChar,
          "010C\r"
        );
        const currentRPM = await device.readCharacteristicForService(
          service,
          readAndNotifyChar
        );

        if (currentRPM.value) {
          console.log("Response: " + currentRPM.value);
        } else {
          console.log("No Value!");
        }
      } catch (error: any) {
        throw new Error(error);
      }
  };

遗憾的是,运行应用程序并连接到适配器时我的输出如下: 控制台输出

currentRPM.value 似乎保持为空。我做错了什么?

javascript react-native bluetooth-lowenergy obd-ii react-native-ble-plx
1个回答
0
投票

而不是使用“010C “您必须使用 base64 编码值。 另请验证您的设备特性是否支持 isWritableWithoutResponse。在我的设备中,它仅支持 isWritableWithResponse 因此我使用 writeCharacteristicWithResponseForService 而不是 writeCharacteristicWithoutResponseForService。对于实时详细信息,请使用通知而不是按顺序写入和读取

例如-

await bleService.current?.setupMonitor(
      UUID.service,
      UUID.readAndNotify,
      res => {
        if (res?.value) {
          const encodedValue = base64.decode(res.value);
          console.log('response from device:', encodedValue);
        }
      },
      err => {
        console.log(err);
      },
    );

    // await bleService.current?.writeCharacteristicWithResponseForDevice(
    //   UUID.service,
    //   UUID.write,
    //   base64.encode('AT SP 0' + '\r'),
    // );  
    // await delay(5);

    await bleService.current?.writeCharacteristicWithResponseForDevice(
      UUID.service,
      UUID.write,
      base64.encode('010C\r'),
    );
© www.soinside.com 2019 - 2024. All rights reserved.