【问题标题】:Connect to a device with BLE Android连接到具有 BLE Android 的设备
【发布时间】:2023-04-03 05:55:01
【问题描述】:

我正在尝试使用 Android 设备上 react-Native 中的 BLE 连接连接到设备。 我需要连接到具有特定名称的设备:例如“deviceName”。 我正在使用 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,
    },
})

目前我收到此错误:“未定义不是对象(正在评估'b.default.startDeviceScan')。

如何解决此错误?你认为代码可以直接连接到设备吗?谢谢

【问题讨论】:

    标签: android react-native bluetooth-lowenergy


    【解决方案1】:

    您正在导出 BleManager 错误。你必须像这样把它放在大括号之间:

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

    您也使用了错误的 BleManager。你必须在某个地方实例化它,我习惯在状态下使用它,以确保我只有 1 个 BleManager 并像这样创建一个 BleManager 的新对象:

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

    然后使用 this.state.bleManager 代替你之前使用的 BleManager:

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

    【讨论】:

    • 感谢您的回复!我已经用你的建议更新了我的帖子。我不断收到“未定义不是对象(评估'this.state.bleManager')错误但是,您认为此代码可以直接连接到设备吗?
    • 你不必把'const { bleManager } = this.state;'课外的发言者。相反,您应该将它放在使用 .startDeviceScan 的函数中。如果您的 BleDevive 被称为“Proximity”,那应该可以工作。无论如何,您可能会遇到更多错误
    • 你说得对,我把它带进来,它告诉我它没有找到变量 bleManager。
    • 我发现了我的错误!现在唯一的问题是我不知道它是否有效xD感谢您的帮助
    • 祝你好运,不要放弃! Ble 可能是一个艰难的世界,非常无证,专门用于 react native。但是,一旦您掌握了信息,您就会发现这很容易!
    猜你喜欢
    • 2015-05-07
    • 1970-01-01
    • 2016-05-25
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多