0

我正在尝试使用 react-native-ble-plx 将网关与 React 本机应用程序配对。下面的源代码在 Android 中运行良好,而在 iOS 中,bleManager.startDeviceScan() 没有被触发。这一步之后没有任何反应。

任何帮助深表感谢!

源代码:

const connectBLE = () => {
    const subscription = bleManager.onStateChange(async (state) => {
      if (state === 'PoweredOn') {
          subscription.remove();
          scanAndConnect();
      } 
  };
}
  const scanAndConnect = () => {
    bleManager.startDeviceScan(null, null, async (error, device) => {
      if (error) {
        showToast(error, 'error');
        console.log('Handle error - scanning will be stopped automatically');
        return;
      }
      console.log('Devices');
      console.log(device.name);
      // Check if it is a device you are looking for based on device name
      if (device.name === "BLE_0006") {
        // Stop scanning as we have found the device.
        bleManager.stopDeviceScan();
        // Establish Device connection.
        device
          .connect()
          .then((deviceData) => {
            /** Show Toast on Device disconnect */
            bleManager.onDeviceDisconnected(
              deviceData.id,
              (connectionError, connectionData) => {
                if (connectionError) {
                  console.log(connectionError);
                }
                console.log('Device is disconnected');
                console.log(connectionData);
              },
            );
            /** Discover All Services and Characteristics */
            return device.discoverAllServicesAndCharacteristics();
          })
          .then(async (deviceObject) => {
            console.log('deviceObject');
            console.log(deviceObject);
            /** Subscribe for the Readable service */
            device.monitorCharacteristicForService(
              Enum.bleConnectionInfo.customServiceUUID,
              Enum.bleConnectionInfo.readCharacteristicUUID,
              (error, characteristic) => {
                if (error) {
                  console.log('Error in monitorCharacteristicForService');
                  console.log(error.message);
                  return;
                }
                console.log(characteristic.uuid, characteristic.value);
                ]);
              },
            );
          })
          .catch((error) => {
            console.warn(error);
            showToast(error, 'error');
          });
      }
    });
  }
4

1 回答 1

0

这可能对某人有帮助!

该问题已通过将 bleManager() 初始化移到功能组件之外得到解决。

于 2021-06-14T11:27:52.653 回答