使用react-native-ble-plx API的android中的BLE外围设备连接问题

时间:2019-04-12 11:12:02

标签: javascript android react-native bluetooth-lowenergy react-native-ble-plx

我正在创建一个应用程序,在其中我需要扫描所有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选项,则会收到错误消息,即错误:设备MAC_ADDRESS已断开连接。

0 个答案:

没有答案