dotintent / react-native-ble-plx

React Native BLE library
Apache License 2.0
3.08k stars 515 forks source link

I'm getting an error when sending commands with WriteQuestion #1204

Closed avcismail closed 4 months ago

avcismail commented 6 months ago

Prerequisites

Question

Hi, I get the following error when sending a command with Write. What could be causing this? My device supports BLE.

Error: Write success: {"_manager": {"_activePromises": {}, "_activeSubscriptions": {}, "_errorCodesToMessagesMapping": {"0": "Unknown error occurred. This is probably a bug! Check reason property.", "1": "BleManager was destroyed", "100": "BluetoothLE is unsupported on this device", "101": "Device is not authorized to use BluetoothLE", "102": "BluetoothLE is powered off", "103": "BluetoothLE is in unknown state", "104": "BluetoothLE is resetting", "105": "Bluetooth state change failed", "2": "Operation was cancelled", "200": "Device {deviceID} connection failed", "201": "Device {deviceID} was disconnected", "202": "RSSI read failed for device {deviceID}", "203": "Device {deviceID} is already connected", "204": "Device {deviceID} not found", "205": "Device {deviceID} is not connected", "206": "Device {deviceID} could not change MTU size", "3": "Operation timed out", "300": "Services discovery failed for device {deviceID}", "301": "Included services discovery failed for device {deviceID} and service: {serviceUUID}", "302": "Service {serviceUUID} for device {deviceID} not found", "303": "Services not discovered for device {deviceID}", "4": "Operation was rejected", "400": "Characteristic discovery failed for device {deviceID} and service {serviceUUID}", "401": "Characteristic {characteristicUUID} write failed for device {deviceID} and service {serviceUUID}", "402": "Characteristic {characteristicUUID} read failed for device {deviceID} and service {serviceUUID}", "403": "Characteristic {characteristicUUID} notify change failed for device {deviceID} and service {serviceUUID}", "404": "Characteristic {characteristicUUID} not found", "405": "Characteristics not discovered for device {deviceID} and service {serviceUUID}", "406": "Cannot write to characteristic {characteristicUUID} with invalid data format: {internalMessage}", "5": "Invalid UUIDs or IDs were passed: {internalMessage}", "500": "Descriptor {descriptorUUID} discovery failed for device {deviceID}, service {serviceUUID} and characteristic {characteristicUUID}", "501": "Descriptor {descriptorUUID} write failed for device {deviceID}, service {serviceUUID} and characteristic {characteristicUUID}", "502": "Descriptor {descriptorUUID} read failed for device {deviceID}, service {serviceUUID} and characteristic {characteristicUUID}", "503": "Descriptor {descriptorUUID} not found", "504": "Descriptors not discovered for device {deviceID}, service {serviceUUID} and characteristic {characteristicUUID}", "505": "Cannot write to descriptor {descriptorUUID} with invalid data format: {internalMessage}", "506": "Cannot write to descriptor {descriptorUUID}. It's not allowed by iOS and therefore forbidden on Android as well.", "600": "Cannot start scanning operation", "601": "Location services are disabled"}, "_eventEmitter": {"_nativeModule": [Object]}, "_scanEventSubscription": null, "_uniqueId": 11}, "deviceID": "98:F4:AB:6A:FF:7A", "id": 11, "isIndicatable": false, "isNotifiable": false, "isNotifying": false, "isReadable": false, "isWritableWithResponse": true, "isWritableWithoutResponse": false, "serviceID": 8, "serviceUUID": "6e400001-b5a3-f393-e0a9-e50e24dcca9e", "uuid": "6e400002-b5a3-f393-e0a9-e50e24dcca9e", "value": "MTQ1M3Jlc2V0"}

My code is here:

import { StatusBar } from "expo-status-bar";
import React, { useEffect, useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  PermissionsAndroid,
  Button,
} from "react-native";
import { BleManager, State } from "react-native-ble-plx";
import { AppRegistry } from "react-native";
import { name as appName } from "./app.json";

const manager = new BleManager();

const App = () => {
  const [isConnected, setIsConnected] = useState(false);
  const serviceUUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
  const characteristicUUIDRX = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E";
  const characteristicUUIDTX = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E";
  //var deviceID = "0C:B8:15:75:71:6A";
  const deviceID = "98:F4:AB:6A:FF:7A";

  const requestLocationPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          title: "BLE App Location Permission",
          message: "BLE App needs access to your location ",
          buttonNeutral: "Ask Me Later",
          buttonNegative: "Cancel",
          buttonPositive: "OK",
        }
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the location");
      } else {
        console.log("Location permission denied");
      }
    } catch (err) {
      console.warn(err);
    }
  };

  useEffect(() => {
    const subscription = manager.onStateChange((state) => {
      if (state === "PoweredOn") {
        scan();
        subscription.remove();
      }
    }, true);
    return () => subscription.remove();
  }, [manager]);

  const writeCharacteristic = async () => {
    await manager

      .writeCharacteristicWithResponseForDevice(
        deviceID,
        serviceUUID,
        characteristicUUIDRX,
        "MTQ1M3Jlc2V0" 
      )
      .then((value) => {
        console.log("Write success: ", value);
      })
      .catch((error) => {
        console.log("Write Failed: ", error);
      });
  };

  const monitorCharacteristicData = async () => {
    try {
      const device = await manager.isDeviceConnected(deviceID);
      if (device) {
        console.log("test1");
        const monitorCharateristicData = async () => {
          await manager
            .monitorCharacteristicForDevice(
              deviceID,
              serviceUUID,
              characteristicUUIDTX
            )
            .then((value) => {
              console.log("Monitor success: ", value);
            })
            .catch((error) => {
              console.log(" Monitor Failed: ", error);
            });
        };
      } else {
        console.log("Device is not connected");
      }
    } catch (error) {
      console.log("Error: ", error);
    }
  };

  const scan = () => {
    manager.startDeviceScan(null, null, (error, device) => {
      if (error) {
        console.log(error);
        return;
      }
      if (device.name === "YDUART") {
        console.log("Device is found!");
        manager.stopDeviceScan();
        //deviceID = device.id;
        //console.log('DeviceID : ' + deviceID);
        connect();
      }
    });
  };

  const connect = async () => {
    try {
      await manager
        .connectToDevice(deviceID)
        .then((device) => {
          console.log("Connected to device:", device.name);
          setIsConnected(true);
          console.log("Services and characteristics discovered");
          console.log(device.discoverAllServicesAndCharacteristics());
          return device.discoverAllServicesAndCharacteristics();
        })
        .catch((error) => {
          console.error("Error connecting to device:", error);
        });
    } catch (error) {
      console.error("Error connecting to device:", error);
    }
  };

  const disconnectFromDevice = async () => {
    try {
      const device = await manager.isDeviceConnected(deviceID);
      if (device) {
        await manager
          .cancelDeviceConnection(deviceID)
          .then((device) => {
            console.log("Disconnect success: ", device);
            setIsConnected(false);
          })
          .catch((error) => {
            console.log("Disconnect Failed: ", error);
          });
      } else {
        console.log("Device is not connected");
      }
    } catch (error) {
      console.log("Error: ", error);
    }
  };

  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
      <Button title="Connect to Device" onPress={connect} />
      <Button title="Read to Device" onPress={writeCharacteristic} />
      <Button title="Disconnect from Device" onPress={disconnectFromDevice} />
    </View>
  );
};

AppRegistry.registerComponent(appName, () => App);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

export default App;
intent-kacper-cyranowski commented 5 months ago

Hi, the log you provided is no error. The console.log is placed in then method so everything should be fine. I think the logged value might be confusing as it contains _manager object. If you ignore it, your value looks like that:

{
  "deviceID": "98:F4:AB:6A:FF:7A",
  "id": 11,
  "isIndicatable": false,
  "isNotifiable": false,
  "isNotifying": false,
  "isReadable": false,
  "isWritableWithResponse": true,
  "isWritableWithoutResponse": false,
  "serviceID": 8,
  "serviceUUID": "6e400001-b5a3-f393-e0a9-e50e24dcca9e",
  "uuid": "6e400002-b5a3-f393-e0a9-e50e24dcca9e",
  "value": "MTQ1M3Jlc2V0"
}

If it’s not an expected behaviour please provide more details on what is the problem.

intent-kacper-cyranowski commented 5 months ago

Hi, did you manage to solve your issue?

intent-kacper-cyranowski commented 4 months ago

Closing due to inactivity