I have been working on a Bluetooth based KaiOS mobile application in which the user interfaces have developed using React.js and I had created a simple javascript class to manage the Bluetooth based operations such as scanning, connect/disconnect, data transfer, etc. I have been trying to send data or object to the react component from the Blemanager.js class when the devices are scanned.
The following code has been used to check for a device with a particular address and if found, resolve the promise so that the object has been sent to the React component. Now, I do want to send the scanned devices object to the react component and check the notified device object is the required one, and stop scanning. How this can be achieved in Javascript.
I am an iOS developer and with respect to iOS, I am looking for a delegation or observable pattern.
startLeScan = () => {
return new Promise((resolve, reject) => {
navigator.mozBluetooth.defaultAdapter.startLeScan([])
.then(function(handlerLE) {
handlerLE.ondevicefound = function(eventLE) {
if (eventLE.device.address === "ed:ec:90:87:5d:86") {
navigator.mozBluetooth.defaultAdapter.stopLeScan(eventLE.target);
console.log('FOUND:', 'Address:', eventLE.device.address, 'Name:', eventLE.device.name, 'Type:', eventLE.device.type);
resolve({"eventLE":eventLE})
}
}
})
.catch(function(e) {
console.log(e);
reject({error: e })
});
})
}
I would refer to this documentation on the Bluetooth spec including good examples on how to use it.
https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web
There is a
characteristics
object onto which you can attach event handlers. These can in turn fire your class methods as pleased.Also there is an
onDisconnected
method that can also fire your methods.