admin 管理员组

文章数量: 1086019

I am trying to set up App.tsx to be able to discover nearby BLE devices. I followed docs, blogs and watched some videos but I can't get it to work (testing on iOS physical device).

Permissions are fine, I guess the listener is not working properly because it doesn't log anything after the 10 seconds scan timer expires (should log "Scan stopped").

Here is my code:

import "./i18n";
import BeaconButton from "@components/UI/BeaconButton";
import { handleAndroidPermissions } from "@utils/androidPermissions";
import { checkLocationPermissions } from "@utils/location";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  SafeAreaView,
  ScrollView,
  Text,
  View,
  Platform,
  Alert,
  NativeModules,
  NativeEventEmitter,
  DeviceEventEmitter,
  FlatList,
  EmitterSubscription,
} from "react-native";
import BleManager, {
  Peripheral as BlePeripheral,
} from "react-native-ble-manager";

interface Peripheral extends BlePeripheral {
  connected?: boolean;
}

export default function App() {
  const BleManagerModule = NativeModules.BleManager;
  const BleManagerEmitter = new NativeEventEmitter(BleManagerModule);

  const [isScanning, setIsScanning] = useState<boolean>(false);

  const { t } = useTranslation("location");


  const startScan = async () => {
    if (!isScanning) {
      try {
        console.log("Starting scan...");
        await BleManager.scan([], 10, false); 
        setIsScanning(true);
        console.log("Scan started");
      } catch (error) {
        console.error("Scan error:", error);
      }
    }
  };

  useEffect(() => {
    const initBle = async () => {
      try {
        // 1. Ask to enable Bluetooth
        if (Platform.OS === "android") {
          try {
            await BleManager.enableBluetooth();
            console.log("Bluetooth is turned on!");
          } catch {
            Alert.alert(
              "Bluetooth Required",
              "Please enable Bluetooth to continue."
            );
            throw new Error("Bluetooth not enabled");
          }
        }

        // 2. Request permissions
        await handleAndroidPermissions();
        await checkLocationPermissions(t);

        // 3. Start BLE manager
        await BleManager.start({ showAlert: false });
        console.log("BleManager started and ready.");
      } catch (err) {
        console.error("Error initializing BLE:", err);
      }
    };

    initBle();
  }, []);

 useEffect(() => {
    const discoverListener = BleManagerEmitter.addListener(
      "BleManagerDiscoverPeripheral",
      (peripheral) => {
        console.log("Discovered:", peripheral);
      }
    );

    return () => discoverListener.remove();
  }, []);

  useEffect(() => {
    let stopListener = BleManagerEmitter.addListener(
      "BleManagerStopScan",
      () => {
        setIsScanning(false);
        console.log("Scan stopped");
      }
    );

    return () => stopListener.remove();
  }, []);

  return (
    <SafeAreaView className="flex-1 bg-">
      <View className="flex-1 items-center px-5 pt-4">
        <ScrollView className="w-full p-5 mt-32 bg-red-100">
          {/* render devices here */}
        </ScrollView>
        <BeaconButton
          className="bg-blue-500 rounded-lg mt-8"
          textClassName="text-white"
          onPress={startScan}
        >
          {isScanning ? "Scanning..." : "Scan Bluetooth Devices"}
        </BeaconButton>
      </View>
    </SafeAreaView>
  );
}

I should see something when logging the peripheral. Then I know I have to use Map to be able to set the devices to be rendered later.

本文标签: bluetooth lowenergyreactnativeblemanager setup not workingStack Overflow