Reputation: 329
I've been having some issues with how to best handle the device data of discovered peripherals and wanted to see if anyone can shine some light on this.
I am able to scan for devices perfectly fine, and my "success" callback works as well. What I want to do is create a list that displays the found devices and connects to the one that is selected. I have no problem with creating the list with ng repeat, however I am unsure as to how to proceed with the data that is returned by the success function. How can I go about saving each peripheral into an array so that I can access each individual peripheral's name, id , rssi, etc? I have tried something along the lines of creating an array outside the function to store the peripherals in, and this works perfectly fine inside the starScanning function, however I can't push them into an array from inside the success callback function. If I just store the scan results into an array from inside the startScanning function, is that sufficient?
startScanning = function() {
this.ble.startScan([], this.success).subscribe(device => {
console.log(JSON.stringify(device.name));
});
this.isScanning = true;
this.presentLoading();
setTimeout(() => {
this.ble.stopScan().then(() => {
console.log("Scanning has stopped");
this.isScanning = false;
});
}, 3000);
}
success = function(peripheral) {
console.log("Success Callback called");
console.log(peripheral.rssi);
}
Upvotes: 0
Views: 624
Reputation: 56
You can handle data returned from the scan in the subscribe
callback (the startScan
method is supposed to only take an array of services as the parameters according to the docs:
this.scanSubscription = this.ble.startScan([])
.subscribe( device => {
// device will have an id property that you can use to connect
this.devices.push(device); // devices is an array on your component
});
Now, you can use *ngFor
to loop over the devices
array and attach a click handler that passes the device's id:
<ion-list>
<ion-item *ngFor="let device of devices" (click)="connectToDevice(device.id)">{{device.id}}</ion-item>
</ion-list>
The connectToDevice()
takes a device id and connects:
connectToDevice(id: string) {
this.connectSubscription = this.ble.connect(id)
.subscribe((data) => {
console.log('Successfully connected!');
});
}
A couple of notes:
unsubscribe()
on them when a page/component is destroyed to prevent memory leaksstartScanWithOptions
function since you can pass the option reportDuplicates
with a value of false
to ignore duplicate devicesCheck out my Github repo (especially the page file bluetooth.ts
) for a working demo app (this uses the startScanWithOptions
function I mentioned above, but the functionality is the same)
Upvotes: 2