ionic 4 bluetooth low energy - example code - Read Data from BLE Devices

January 24, 2020 8 comments
Please refer two articles, for better understanding of BLE and IONIC connectivity and how to implement ionic 4 Bluetooth low energy devices communication.


In this article we shall communicate with BLE (Bluetooth Low energy) device with IONIC4.

To start BLE device we need to send some Command in my case it is ST (start + enter). 
Note: BLE takes one character at a time and also in HEX 
Hex code for S - 53 
Hex code for T - 54
Hex code for LF (Line feed) - 0A 

Also BLE device has their own Services and Characteristics, in previous article we had listed all the services associated with selected device. ref following code in previous article in details page (details.page.html)



<ion-list>
<ion-item ngfor="let service of peripheral.services">
  {{service}}
</ion-item>
</ion-list>


Standard BLE service is FFE0 and BLE characteristic with WriteWithoutResponse is FFE1

After connecting to BLE devices; we need to do following tasks to start reading data

  1. WriteWithoutResponse (Service FFE0 and Characteristic FFE1)
  2. Then Subscribe  to start getting value change notification  for Service FFE0 and Characteristic FFE1
Check following two snippets one for WriteWithoutResponse and another for StartGettingNotification


BleWrite() {

        // Subscribe for notifications when the resitance changes
        var inputdata = new Uint8Array(3);
        inputdata[0] = 0x53; // S
        inputdata[1] = 0x54; // T
        inputdata[2] = 0x0a; // LF

        this.ble
            .writeWithoutResponse(
                this.peripheral.id,
                BLE_SERVICE,
                BLE_CHARACTERISTIC,
                inputdata.buffer
            )
            .then(
                data => {
                    debugger;   
                    
                    console.log(data);
                    this.subscribe();
                },
                err => {
                    console.log(err);
                }
            );
    }

And for reading values from BLE device

subscribe() {
        this.ble
            .startNotification(this.peripheral.id,
 BLE_SERVICE, BLE_CHARACTERISTIC)
            .subscribe(
                data => {
                    console.log(data);
                    this.onValueChange(data);
                },
                () =>
               
        this.showAlert(
                 "Unexpected Error",
                 "Failed to subscribe for changes, please try to re-connect."
               )
            );
    }

In above function we are capturing data and passing it to onValueChange function. You can handle your data in onValueChange function. Data which we send and receive from BLE devices is always an ArrayBuffer. In above functions we have passed ST + LineFeed as array buffer input.buffer

So we need two more functions one to convert array buffer into plain character string and another function to capture valuechange




onValueChange(buffer: ArrayBuffer) {
        this.ngZone.run(() => {
            try {
                if (this.dataFromDevice == undefined)
 this.dataFromDevice = this.bytesToString(buffer).replace(/\s+/g, " ");
                else this.dataFromDevice += '
' + this.bytesToString(buffer).replace(/\s+/g, " ");

//Simply assign data to variable dataFromDevice and string concat
            } catch (e) {
                console.log(e);
            }
        });
    }

    bytesToString(buffer) {
        return String.fromCharCode.apply(null, new Uint8Array(buffer));
    }

This is how we read data from BLE devices using IONIC4. Ionic4 Ble example.

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.

ionic 4 bluetooth low energy - sample code - List BLE Devices

January 16, 2020 12 comments
This article will demonstrate usage of cordova-plugin-ble-central with IONIC 4. i.e. Mobile application connectivity with BlueTooth Low Energy Devices.

Before we start I assume that you already have ionic4 blank project working.

When you run ionic server command following screen should open in browser
ionic4 ble example code
Ionic4 BLE (Bluetooth Low energy sample/example code)

On command line or in visual studio terminal use following commands to install BLE  Ionic plugin


$ ionic cordova plugin add cordova-plugin-ble-central
$ npm install @ionic-native/ble
Above commands will add required cordova plugin and ionic4 wrapper for Bluetooth low energy devices communication. I am using default Home page to display list of available BLE Devices, on TAP of device it will be redirected to details page for further operations. We shall add following line of code to import BLE Home.page.ts file looks as follows


import { BLE } from '@ionic-native/ble/ngx';
import { Component, NgZone } from '@angular/core';
import { NavController, ToastController } from '@ionic/angular';


@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(
    public navCtrl: NavController,
    private toastCtrl: ToastController,
    private ble: BLE,
    private ngZone: NgZone
  ) {}

}


After this make sure BLE provider is added in app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { BLE } from '@ionic-native/ble/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen, BLE,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}



Now we shall add following functions for Bluetooth low energy (BLE) device discovery and listing BLE devices.

  • scan - scan for ble devices for 5 seconds.
  • onDeviceDiscovered - this function will execute if any BLE device is discovered.
  • scanError - this function will be called if any error occurs in scan function
  • setStatus - simple function to set message 
Above functions we are adding in home.page.ts file. Location setting should be on while scanning devices, else you will see error message


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);
    let 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;
    });
  }


Please check HTML of home.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      BLE Connect
    </ion-title>
    <ion-buttons slot="end">
      <ion-button click="" scan="">
        Scan
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list> 
    <ion-item click="" device="" deviceselected=""
 ngfor="let device of devices">
      <ion-label>
      <h2>
{{ device.name || 'Unnamed' }}</h2>
{{ device.id }}
     RSSI: {{ device.rssi }}


      </ion-label> 
    </ion-item>
   
   </ion-list> 
</ion-content>

<ion-footer>
  <ion-toolbar>
    <ion-item>
    <ion-label>{{ statusMessage }}</ion-label>
    </ion-item>
  </ion-toolbar>
</ion-footer>

 


Now build app using following command
ionic cordova build android 

This will create an APK file which will list BLE devices after scan. You can click on scan button or can add scan() function in ionViewDidEnter()


ionViewDidEnter() {
    console.log('ionViewDidEnter');
    this.scan();
  }



Now we are able to build Bluetooth low energy device listing app in ionic4

Mobile application connectivity with BlueTooth Low Energy Devices


In next Article ionic 4 bluetooth low energy - sample code - Connect to BLE Devices we shall connect to BLE devices.