Issue
I'm creating an Ionic react (TypeScript) app which uses the Community Bluetooth-le plugin.
When I try to connect to a device using requestDevice this shows the available devices and I can then pair/connect with that device and all is good.
await BleClient.initialize();
if (isAndroid) {
await BleClient.disconnect(devices.deviceId);
}
const device = await BleClient.requestDevice({
services: services ? services : [],
optionalServices: optionalServices ? optionalServices : [],
namePrefix: prefixFilter ? prefixFilter : "",
});
await BleClient.connect(device.deviceId, (deviceId) => onDisconnect(deviceId));
await BleClient.getServices(device.deviceId).then(
(services) => {
if (services[0]) {
//....
} else {
//....
}
}
)
However, if I save the device ID and then try to directly connect with that device using getDevices (rather than scanning and manually connecting) it always fails with the following console output:
Uncaught (in promise) Error: Device not found. Call "requestDevice", "requestLEScan" or "getDevices" first.
The code I use is this:
await BleClient.initialize();
if (isAndroid) {
await BleClient.disconnect(devices.deviceId);
}
await BleClient.getDevices(devices.deviceId);
await BleClient.connect(devices.deviceId, (deviceId) => onDisconnect(deviceId));
For clarification: I want to be able to search for available devices and connect to the device the first time the app is opened. Then, save the device ID and use this ID to connect to the device directly using getDevices from that point onwards. Likewise if the app is closed and re-opened I need to be able to take the stored device data and connect with that device directly without the whole scan and manual selection process.
I don't understand what I'm missing.
Solution
I assume Device-1 (app) is scanning and Device-2 is advertising. Try to bond the devices after first time connection. This allow you to connect it automatically without scanning next time.
Make sure the Device-2 is in connectable mode after getting disconnected from Device-1.
EDIT-1
For example I am using a generic app called nRF connect and a smart watch. In this app we can scan and connect with any BLE device. I am following below steps:
- Scan
- Connect
- Bond (option available under 3 dots at top right corner, refer image)
After third step, device get bonded and later whenever the device is in vicinity you can connect with it, without advertising and scanning. PFA image.
This is the overview of process to be followed, in regards to code you can get many ready examples related to android or iOS. Hope this is helpful!!
Answered By - Nitin Jadhav
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.