Mr Robinson
Mr Robinson

Reputation: 71

Connect to a device with BLE Android

I'm trying to connect to a device using BLE connection in react-Native on Android Device. I need to connect to a device with a with a specific name: for example "deviceName". I'm using react-native-ble-plx.

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ScrollView,
  FlatList,
  TextInput,
  Platform,
  Alert
} from 'react-native';
import { BleManager } from 'react-native-ble-plx';


export default class Main extends Component {
  constructor(props) {
          super(props);
          this.state={
              scaning:false,
              isConnected:false,
              text:'',
              writeData:'',
              receiveData:'',
              readData:'',
              bleManager: new BleManager(),
              data:[],
              isMonitoring:false,

          }
          this.bluetoothReceiveData = [];
          this.deviceMap = new Map();

  }



scan() {
  if(!this.state.scaning) {
    this.setState({scaning:true});
    this.deviceMap.clear();
    const { bleManager } = this.state;
    bleManager.startDeviceScan(null, null, async (error, device) => {
    console.log("scanning bluetooth...")

    if (device.name === "Proximity") {
        bleManager.connectToDevice(device.id, {
                autoconnect: true,
                timeout: BLUETOOTH_TIMEOUT,
                isConnected: true
            })
        // ............
    }
})
  }
}

disconnect(){
        bleManager.disconnect()
            .then(res=>{
                this.setState({data:[...this.deviceMap.values()],isConnected:false});
            })
            .catch(err=>{
                this.setState({data:[...this.deviceMap.values()],isConnected:false});
            })
}

render(){
  return(
    <View>
    <TouchableOpacity
                  activeOpacity={0.7}
                  style={[styles.buttonView,{marginHorizontal:10,height:40,alignItems:'center'}]}
                  onPress={this.state.isConnected?this.disconnect.bind(this):this.scan.bind(this)}>
                  <Text style={styles.buttonText}>{this.state.scaning?'Search':this.state.isConnected?'Disconnect Bluetooth':'Search Bluetooth'}</Text>
</TouchableOpacity>
    </View>
  );
}


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'white',
        marginTop:Platform.OS == 'ios'?20:0,
    },
    item:{
        flexDirection:'column',
        borderColor:'rgb(235,235,235)',
        borderStyle:'solid',
        borderBottomWidth:StyleSheet.hairlineWidth,
        paddingLeft:10,
        paddingVertical:8,
    },
    buttonView:{
        height:30,
        backgroundColor:'rgb(33, 150, 243)',
        paddingHorizontal:10,
        borderRadius:5,
        justifyContent:"center",
        alignItems:'center',
        alignItems:'flex-start',
        marginTop:10
    },
    buttonText:{
        color:"white",
        fontSize:12,
    },
    content:{
        marginTop:5,
        marginBottom:15,
    },
    textInput:{
        paddingLeft:5,
        paddingRight:5,
        backgroundColor:'white',
        height:50,
        fontSize:16,
        flex:1,
    },
})

At the moment I receive this error: "undefined is not an object (evaluating 'b.default.startDeviceScan').

How can I fix this error? and do you think the code can work to connect directly to a device? thank you

Upvotes: 2

Views: 2149

Answers (1)

SmoggeR_js
SmoggeR_js

Reputation: 3150

You are exporting BleManager wrong. You have to put it between braces like this:

import { BleManager } from 'react-native-ble-plx';

You are using BleManager wrong too. You have to instantiate it in some place, I use to use it in the state, to ensure that I have only 1 BleManager and make a new Object of BleManager like this:

 constructor {
    ....
    this.state = {
      ....
      bleManager: new BleManager(),
      ....
    };

And then use this.state.bleManager instead of BleManager you was using like this:

const { bleManager } = this.state;
bleManager.startDeviceScan(...)

Upvotes: 1

Related Questions