[英]How to connect to a device BLE?
我正在嘗試使用 BLE 連接到設備。 我需要自動連接到特定設備。 我不明白如何直接連接到設備。 讓我更好地解釋一下,目前我可以掃描並獲得所有藍牙設備。 相反,我想直接連接到特定設備。 - 因此我應該只選擇一種類型的設備 - 直接連接我
你覺得我能做什么?
使用此代碼,我選擇名稱
return (
<View style={{borderBottomColor: 'lightgrey', borderBottomWidth: 1, alignItems: 'stretch'}}>
<View style={{flexDirection: 'row', alignItems: 'center', padding: 15}}>
<View style={{flex: 1}}>
<Text style={{fontSize: 20, color: '#888'}}>{`${peripheral.name}`}</Text>
</View>
<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
<Btn onPress={() => onConnect(peripheral)}>
{`Connect`}
</Btn>
</View>
</View>
</View>
)
使用此代碼我進行掃描
return (
<View style={{flex: 1 , paddingTop: Theme.navbarHeight }}>
<StatusBar
/* backgroundColor={Theme.color}*/
/* barStyle="light-content" */
/>
{
Object.keys(peripherals).length === 0 ? (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{ uiState === UiState.scanning && <ActivityIndicator size='large' color={Theme.color}/> }
<Text style={{marginBottom: 10, fontSize: 18, color: '#999'}}>
Nessun Risultato
</Text>
{ uiState === UiState.idle && <Btn onPress={this._doScan}>Scansione</Btn> }
</View>
) : (
<ScrollView style={{ flex: 1 }} contentContainerStyle={{ alignItems: 'stretch' }}>
{
Object.keys(peripherals).map(key => peripherals[key]).map(
peripheral => (
<Peripheral
key={peripheral.id}
peripheral={peripheral}
onConnect={onConnect}
/>
)
)
}
</ScrollView>
)
}
</View>
)
}
_renderScanButton = () => {
let {uiState} = this.state;
if (uiState === UiState.scanning) {
return <ActivityIndicator color='white'/>
}
return (
<TouchableOpacity onPress={this._doScan}>
<Text style={{color: 'white', width: 100, textAlign: 'right'}}>Scansione</Text>
</TouchableOpacity>
)
}
_doScan = () => {
if (this.state.uiState !== UiState.idle) {
return;
}
this.setState({ uiState: UiState.scanning, peripherals: {} });
BleManager.scan([], 5, true)
.then(results => {
console.log('Scansione in corso...');
})
.catch(() => {
this.setState({ uiState: UiState.idle })
})
}
}
您正在使用react-native-ble-manager
。 根據他們的文檔,您可以使用connect
方法連接到外圍設備:
BleManager.connect('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX')
.then(() => {
// Success code
console.log('Connected');
})
.catch((error) => {
// Failure code
console.log(error);
});
您應該從掃描方法results
獲取外圍 UID:
BleManager.scan([], 5, true)
.then(results => {
// Success code
console.log(results);
});
我個人不使用react-native-ble-manager
包,而是react-native-ble-plx
包,但過程非常相似。 這是我的方法:
manager.startDeviceScan(null, null, async (error, device) => {
console.log("scanning bluetooth...")
if (device.name === "MY_DEVICE_NAME") {
manager
.connectToDevice(device.id, {
autoconnect: true,
timeout: BLUETOOTH_TIMEOUT
})
// ............
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.