React Native BLE PLX Demo:无线通信的新境界
以下是React Native BLE PLX Demo中的核心函数,展示了如何初始化蓝牙适配器,以及如何扫描和连接到BLE设备。
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import bleplx from 'react-native-ble-plx';
const App = () => {
const [scanning, setScanning] = useState(false);
const [devices, setDevices] = useState([]);
const ble = bleplx.default;
useEffect(() => {
const initBle = async () => {
await ble.initialize();
console.log('BLE Initialized');
};
initBle();
}, []);
const startScan = async () => {
setScanning(true);
const scan = await ble.scan([], true);
scan.on('discover', device => {
console.log(device);
setDevices(devices => [...devices, device]);
});
scan.on('end', () => {
console.log('Scan end');
setScanning(false);
});
};
const stopScan = async () => {
setScanning(false);
await ble.stopScan();
};
return (
<View style={styles.container}>
<Text>Bluetooth Low Energy Plugin Example</Text>
<Button title="Scan" onPress={startScan} disabled={scanning} />
<Button title="Stop" onPress={stopScan} disabled={!scanning} />
<Text>Devices found: {devices.length}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
export default App;
这段代码展示了如何在React Native应用中使用react-native-ble-plx
库进行蓝牙低能耗(BLE)扫描和设备发现。代码中定义了一个React组件,其中包含初始化蓝牙适配器、开始和停止扫描的逻辑,以及如何处理扫描到的设备信息。这为开发者提供了一个实践的蓝牙低能耗通信的例子。
评论已关闭