ionic 4 bluetooth low energy - sample code - Connect to BLE Devices

January 20, 2020 0 comments
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.

In last article we had page Home, we had displayed BLE devices as follows. 
Ionic 4 - Ble - Bluetoothe low energy devices listing
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)
Ionic 4 bluetooth low energy - Connect BLE Devices - debugger screen

After we select device, we are navigated to details.page.html . 

In details.page.ts file, there three main activities

  1.   Read device information sent from home page - we are doing it in constructor
  2. Ble Connect function
  3. 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
 
<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>

This is how we can connect to BLE Devices, using IONIC4.

 In next Article ionic 4 Bluetooth low energy - example code - Read Data from BLE Devices we shall read data from BLE devices.
Share Share Tweet Share

0 thoughts on " ionic 4 bluetooth low energy - sample code - Connect to BLE Devices"

LEAVE A REPLY