为了实现连接对象的项目。我需要在各种设备之间实现蓝牙连接。
这里的目标是在 React Native 中创建一个应用程序,然后将数据从该应用程序发送到我的 Raspberry。该 Raspberry 有一个连接的 HC-08 模块,负责蓝牙通信。
现在,我想使用react-native-ble-plx库通过蓝牙发送数据。我能够将我的 Android 连接到该模块。但我不明白如何发送数据......
这是我的代码:
constructor() {
super()
this.manager = new BleManager()
}
componentWillMount() {
console.log("mounted")
const subscription = this.manager.onStateChange((state) => {
if (state === 'PoweredOn') {
this.scanAndConnect();
subscription.remove();
}
}, true);
}
scanAndConnect() {
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
// Handle error (scanning will be stopped automatically)
return
}
console.log(device.name)
// Check if it is a device you are looking for based on advertisement data
// or other criteria.
if (device.name === 'SH-HC-08') {
// Stop scanning as it's not necessary if you are scanning for one device.
this.manager.stopDeviceScan();
console.log(`Found ${device.name}`)
this.setState({
device: device
})
// Proceed with connection.
device.connect()
.then((device) => {
console.log(device)
return device.discoverAllServicesAndCharacteristics()
})
.then((device) => {
console.log(device)
})
.then((result) => {
// Do work on device with services and characteristics
//console.log(this.manager.characteristicsForService("00001800-0000-1000-8000-00805f9b34fb"))
console.log(result)
console.log("connected")
})
.catch((error) => {
// Handle errors
console.log(error)
});
}
});
}
send() {
this.manager.writeCharacteristicWithResponseForDevice("58:7A:62:4F:EF:6D",
this.device.serviceUUIDs[0],
this.manager.characteristicsForDevice(this.device.id),
"ok")
.catch((error) => {
console.log('error in writing data');
console.log(error);
})
}
我想要一个发送方法,可以在我需要的时候发送数据。但我不太明白它是如何工作的:/
有人可以帮助我,甚至给我一个例子吗?我将非常感激。
致以诚挚的问候。
最佳答案
我成功实现了以下内容:
scanAndConnect() {
this.manager.startDeviceScan(null, null, (error, device) => {
this.info("Scanning...");
console.log(device);
if (error) {
this.error(error.message);
return
}
if (device.name ==='MyDevice') {
this.info("Connecting to Tappy");
this.manager.stopDeviceScan();
device.connect()
.then((device) => {
this.info("Discovering services and characteristics");
return device.discoverAllServicesAndCharacteristics()
})
.then((device) => {
this.info(device.id);
device.writeCharacteristicWithResponseForService('12ab', '34cd', 'aGVsbG8gbWlzcyB0YXBweQ==')
.then((characteristic) => {
this.info(characteristic.value);
return
})
})
.catch((error) => {
this.error(error.message)
})
}
});
在我使用 12ab
的地方,插入 BLE 服务的 UUID。同样,在我使用 34cd
的地方,插入 BLE 特征的 UUID。最后,请在我有 aGVsbG8gbWlzcyB0YXBweQ==
的地方添加您尝试发送的任何消息的 Base64 编码。
希望这有帮助。
关于javascript - 使用react-native-ble-plx包发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137867/