In the previous article I had mentioned how to list BLE (Bluetooth Low energy devices), Please refer to Ionic-4 Bluetooth Low Energy Devices - List BLE Devices article.
Please note we have added one function named deviceSelected(device: any) This function take device information and sends it to details page.
We get BLE (Blue tooth low energy) device info as follows (This is log)
After we select device, we are navigated to details.page.html .
In details.page.ts file, there three main activities
In next Article ionic 4 Bluetooth low energy - example code - Read Data from BLE Devices we shall read data from BLE devices.
In last article we had page Home, we had displayed BLE devices as follows.
List BLE Devices - IONIC 4 |
Now on click of Device, we shall redirect to Detail page, we shall pass BLE device information to Detail page. Thus we have modified our code of home.page.ts file as follows
import { BLE } from '@ionic-native/ble/ngx';
import { Component, NgZone } from '@angular/core';
import { ToastController } from '@ionic/angular';
import { Router, NavigationExtras } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
devices: any[] = [];
statusMessage: string;
deviceMode = true;
constructor(
public router: Router,
private toastCtrl: ToastController,
private ble: BLE,
private ngZone: NgZone
) {}
ionViewDidEnter() {
console.log('ionViewDidEnter');
this.scan();
}
scan() {
this.setStatus('Scanning for Bluetooth LE Devices');
this.devices = []; // clear list
this.ble.scan([], 5).subscribe(
device => this.onDeviceDiscovered(device),
error => this.scanError(error)
);
setTimeout(this.setStatus.bind(this), 5000, 'Scan complete');
}
onDeviceDiscovered(device) {
console.log('Discovered ' + JSON.stringify(device, null, 2));
this.ngZone.run(() => {
this.devices.push(device);
});
}
// If location permission is denied, you'll end up here
async scanError(error) {
this.setStatus('Error ' + error);
const toast = await this.toastCtrl.create({
message: 'Error scanning for Bluetooth low energy devices',
position: 'middle',
duration: 5000
});
toast.present();
}
setStatus(message) {
console.log(message);
this.ngZone.run(() => {
this.statusMessage = message;
});
}
deviceSelected(device: any) {
console.log(JSON.stringify(device) + ' selected');
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(device)
}
};
this.router.navigate(['detail'], navigationExtras);
}
}
Please note we have added one function named deviceSelected(device: any) This function take device information and sends it to details page.
We get BLE (Blue tooth low energy) device info as follows (This is log)
After we select device, we are navigated to details.page.html .
In details.page.ts file, there three main activities
- Read device information sent from home page - we are doing it in constructor
- Ble Connect function
- Ble Disconnect function
Check details.page.ts code carefully to understand how BLE (Bluetooth low energy) devices is connected and disconnected.
import { Component, OnInit, NgZone } from '@angular/core';
import { ToastController } from '@ionic/angular';
import { ActivatedRoute, Router } from '@angular/router';
import { BLE } from '@ionic-native/ble/ngx';
@Component({
selector: 'app-detail',
templateUrl: './detail.page.html',
styleUrls: ['./detail.page.scss']
})
export class DetailPage implements OnInit {
peripheral: any = {};
statusMessage: string;
constructor(public route: ActivatedRoute, public router: Router,
private ble: BLE,
private toastCtrl: ToastController, private ngZone: NgZone) {
this.route.queryParams.subscribe(params => {
if (params && params.special) {
const device = JSON.parse(params.special);
this.setStatus('Connecting to ' + device.name || device.id);
//Call BLE Connect - Connect to BLE Device
this.BleConnect(device);
}
});
}
ngOnInit() {
}
BleConnect(device) {
this.ble.connect(device.id).subscribe(
peripheral => this.onConnected(peripheral),
peripheral => this.onDeviceDisconnected(peripheral)
);
}
BleDisconnect() {
this.ble.disconnect(this.peripheral.id).then(
() => console.log('Disconnected ' + JSON.stringify(this.peripheral)),
() => console.log('ERROR disconnecting ' + JSON.stringify(this.peripheral)));
}
onConnected(peripheral) {
this.ngZone.run(() => {
this.setStatus('');
this.peripheral = peripheral;
});
}
async onDeviceDisconnected(peripheral) {
const toast = await this.toastCtrl.create({
message: 'The peripheral unexpectedly disconnected',
duration: 3000,
position: 'middle'
});
toast.present();
}
// Disconnect peripheral when leaving the page
ionViewWillLeave() {
console.log('ionViewWillLeave disconnecting Bluetooth');
this.BleDisconnect();
}
setStatus(message) {
console.log(message);
this.ngZone.run(() => {
this.statusMessage = message;
});
}
}
In detail.page.html, we are simply displaying Device information, Devices services
This is how we can connect to BLE Devices, using IONIC4.
<ion-header>
<ion-toolbar>
<ion-title>{{ peripheral.name || 'Device' }}</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="padding">
<ion-card>
<ion-card-header>
{{ peripheral.name || 'Unnamed' }}
</ion-card-header>
<ion-card-content>
{{ peripheral.id }}
</ion-card-content>
</ion-card>
<ion-card>
<ion-card-header>
Services
</ion-card-header>
<ion-list>
<ion-item ngfor="let service of peripheral.services">
{{service}}
</ion-item>
</ion-list>
</ion-card>
<ion-card>
<ion-card-header>
Details
</ion-card-header>
<ion-card-content>
<pre>{{peripheral | json }}</pre>
</ion-card-content>
</ion-card>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-item>
<ion-label>{{ statusMessage }}</ion-label>
</ion-item>
</ion-toolbar>
</ion-footer>
In next Article ionic 4 Bluetooth low energy - example code - Read Data from BLE Devices we shall read data from BLE devices.
0 thoughts on " ionic 4 bluetooth low energy - sample code - Connect to BLE Devices"