0

我正在创建一个应用程序,我需要扫描所有 BLE 信标并连接到特定的信标,然后在该外围设备上执行其他操作。我能够扫描 android 设备上的外围设备,但我无法连接到它们中的任何一个。在下面的代码中,使用了 react-native-ble-plx API。

import React, { Component } from 'react';
import {PermissionsAndroid, Text, View} from 'react-native';
import { BleManager } from 'react-native-ble-plx';

export default class App extends Component{

    state = {
        permissionStatus:'denied', 
        bluetoothStatus: 'disabled',
        devices:[],
        info:''
    }

    constructor(){
        super();
        this.manager = new BleManager();
    }

    info(message) {
        this.setState({info: message})
    }

    error(message) {
        this.setState({info: "ERROR: " + message})
    }

    async requestPermission() {
        try {
          const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);

          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            this.setState({permissionStatus:'granted'});
          }else if(granted === PermissionsAndroid.RESULTS.DENIED) {
            this.setState({permissionStatus:'denied'});
          }else{
             //console.log('never-ask-again');
          }
        } catch (err) {
          console.error(err)
        }
      }

    scanAndConnect(){
            this.manager.startDeviceScan(null, null, (error, device) => {
            if(error){
                console.log('Error occurred while scanning');
                return;
            }

            if(device.id === MAC_ADDRESS){
                console.log(device);
                console.log(device.isConnectable);
                console.log(`info: ${this.state.info}`);
                this.manager.stopDeviceScan();

                this.manager.connectToDevice(MAC_ADDRESS, {autoConnect:true})
                .then((device) => {
                    this.info("Discovering services and characteristics")
                    console.log('device');
                    return device.discoverAllServicesAndCharacteristics();
                })
                .then((device) => {
                    this.info("Listening... ")
                })
                .catch((error) => {
                        this.manager.isDeviceConnected(device.id).then((res) => console.log(res))
                        .catch(err=>console.log(err));

                        this.error(error.message);
                        device.cancelConnection();
                        this.scanAndConnect();
                });
            }
        })
    }

    componentDidMount()
    {
        this.requestPermission();
        const subscription = this.manager.onStateChange((state) => {
            if(state === 'PoweredOn'){
                this.setState({bluetoothStatus:'enabled'});
                this.scanAndConnect();
                subscription.remove();
            }else{
                this.setState({bluetoothStatus:'disabled'});
            }
        }, true);
    }


    render(){
        return(
             <View style={{flex:1, padding:15, justifyContent:'center'}}>
                <Text style={{fontSize:20, alignSelf:'center', color:'steelblue'}}>
                    Location access is {this.state.permissionStatus}
                </Text>
                <Text style={{fontSize:20, alignSelf:'center', color:'blue'}}>
                    Bluetooth is {this.state.bluetoothStatus}
                </Text>
                <Text style={{fontSize:20, alignSelf:'center', color:'black'}}>
                    Info is {this.state.info}
                </Text>
             </View>
        );
    }
}

如果我从 connectToDevice() 函数中删除 autoConnect 选项,我会收到一个错误,即 ERROR: Device MAC_ADDRESS is disconnected。

4

0 回答 0