Connecting to a Bluetooth Smart Sensor with Ionic 2

You’d have to have been living in a box for the last couple of years not to have heard of the Internet Of Things and all the buzz  around it.  A big part of IoT is Bluetooth Smart technology which I started working with as a mobile developer a couple of years ago whilst working as a contractor for the Innovations department of a large corporation in London.

We began looking at Bluetooth Smart Beacons and investigating ways in which they could be used in an office environment.  To prove they could be useful we created FreeDesk, a native application for iOS and Android that used beacons to help people find free desks in the office (particularly contract staff requiring a hot desk). After that we did lots of stuff with Bluetooth Smart that I can’t talk about as it was under an NDA 🙂

Later I worked with Beacons again when I developed Open Day, an application for colleges and universities that uses beacons placed around campus buildings in order to provide a more engaging experience for visitors.  The Open Day  app was initially built natively in Android and iOS but I later developed a hybrid version of the application using Ionic.  I’ll probably write a blog post soon about using Beacons with Ionic 2.

For now I want to talk a little bit about how to get started with an Ionic 2 app that communicates with a a Bluetooth Smart device.   If you want to get serious about working with Bluetooth Smart communications you really need to head over to the Bluetooth SIG website where there is an abundance of resources to help you.  In particular you need to read up on the Bluetooth Generic Attributes protocol (GATT) which is what you need to understand if you want to connect and communicate with a Bluetooth Smart device.

When I started looking at Bluetooth Smart and wanted a device to connect to I ordered a Texas Instruments  SensorTag Development Kit. This is a very neat little device and has a number of sensors on it that you can read from – temperature, humidity, pressure etc.  Its a really great way to start and I’d recommend buying something like this if you want to have a play. Another similar piece of kit available is the Broadcom WICED Sense Kit and this is what I used recently to create a Bluetooth Smart app in Ionic 2.

Broadcom_BCM9WICED-SENSE

The following steps should help you on your way to creating an Ionic 2 application that can start communicating with a Bluetooth Smart device.  The application will use the new Ionic Native wrappers which are used in Ionic 2 (as a replacement for the ngCordova which was used in Ionic 1).  One of the Cordova plugins already provided by the Ionic Native wrapper is the ble-central plugin and its this one which we will use to handle our communications with the device.

Start by creating your Ionic 2 application:

ionic start ionic2-BLE-demo blank –v2

Move into the application folder

cd ionic2-BLE-demo

Install Ionic Native

npm install ionic-native –save

Add the ble-central Cordova plug-in

ionic plugin add cordova-plugin-ble-central

In your main view template (mine is called pages/home.html) provide a button (to start scanning for devices), a list (to display devices found) and a spinner to be displayed when we are scanning for devices and hidden when we’re done scanning:

<ion-navbar *navbar>

<ion-title>
Devices
</ion-title>

<ion-buttons end>
<button (click) = “startScanning()” >Scan</button>
</ion-buttons>

</ion-navbar>

<ion-content>
<ion-list inset>
<ion-item-sliding *ngFor=”#device of devices” #slidingItem>
<button ion-item (click)=”connectToDevice(device)”>
<h2>{{device.name}}</h2>
<p>{{device.id}}</p>
<p>{{device.rssi}}</p>
</button>

</ion-item-sliding>
</ion-list>
<ion-spinner *ngIf=”isScanning==true” name=”circles”></ion-spinner>
</ion-content>

In the associated component (pages/home.js) provide a startScanning function that is executed when the Scan button is pressed.  When this button is pressed a 3 second scan will be carried out and any Bluetooth Smart devices found will be displayed in a list.

import {Component,NavController} from ‘@angular/core’;
import {DevicePage} from ‘../device/device’;
import {BLE} from ‘ionic-native’;

@Component({
templateUrl: ‘build/pages/home/home.html’
})
export class HomePage {

constructor(public nav: NavController) {
this.devices = [];
this.isScanning = false;
}

startScanning() {
console.log(“Scanning Started”);
this.devices = [];
this.isScanning = true;
BLE.startScan([]).subscribe(device => {
this.devices.push(device);
});

setTimeout(() => {
BLE.stopScan().then(() => {
console.log(‘Scanning has stopped’);
console.log(JSON.stringify(this.devices))
this.isScanning = false;
});
}, 3000);

}

connectToDevice(device) {
console.log(‘Connect To Device’);
console.log(JSON.stringify(device))
this.nav.push(DevicePage, {
device: device
});
}

}

We also need a DevicePage which is displayed when the user clicks on a device.  Mine is called pages/device.js.  The template (pages/device.html) looks like this:

<ion-navbar *navbar>
<ion-title>{{device.name}}</ion-title>
</ion-navbar>
<ion-content>
<ion-list inset>
<ion-item-sliding *ngFor=”#characteristic of characteristics” #slidingItem>
<button ion-item (click)=”connectToCharacteristic(device.id,characteristic)”>
<h2>{{characteristic.characteristic}}</h2>
<p>{{characteristic.properties}}</p>
<p>{{characteristic.isNotifying}}</p>
<p>{{characteristic.service}}</p>
</button>
</ion-item-sliding>
</ion-list>
<ion-spinner *ngIf=”connecting==true” name=”circles”></ion-spinner>
</ion-content>

The component (pages/device.js) looks like this:

import {Component, NavController,NavParams} from ‘@angular/core’;
import {CharacteristicPage} from ‘../characteristic/characteristic’;
import {BLE} from ‘ionic-native’;

@Component({
templateUrl: ‘build/pages/device/device.html’
})

export class DevicePage {

constructor(public navParams: NavParams,public nav: NavController) {
this.device = this.navParams.get(‘device’);
this.connecting = true;
this.connect(this.device.id);
}

connect(deviceID) {
this.characteristics = [];

BLE.connect(deviceID).subscribe(peripheralData => {
console.log(peripheralData.characteristics);
this.characteristics = peripheralData.characteristics;
this.connecting = false;
},
peripheralData => {
console.log(‘disconnected’);
});
}

connectToCharacteristic(deviceID,characteristic) {
console.log(‘Connect To Characteristic’);
console.log(deviceID);
console.log(characteristic);
}

}

The component connects to the device and displays that device’s services and characteristics on screen.  If you read up on the GATT protocol and understand it you should be able to create the final component we need – a component that would be pushed on the navigation stack by the connectToCharacteristic function and which displays the value of that characteristic e.g a temperature value or humidity value etc.  I hope this has helped you get started on your journey into the IoT !

 


I’m a mobile applications developer based in the UK, concentrating primarily on hybrid application development with Ionic and Ionic 2 but also with native development skills. Please visit www.crossplatformsolutions.co.uk for more information about me and how I may be able to help you with mobile application development, particularly with Ionic 2 but also with other mobile frameworks and technologies.  Thanks for visiting.

15 thoughts on “Connecting to a Bluetooth Smart Sensor with Ionic 2

  1. Dora Chua

    Hi Richard

    Thanks for your tutorial.

    I tried to follow your tutorial, but was stuck at the portion where it needed a “CharacteristicPage” in device.js

    import {Page, NavController,NavParams} from ‘ionic-angular’;
    import {CharacteristicPage} from ‘../characteristic/characteristic’;
    import {BLE} from ‘ionic-native’;

    Are you able to show us the code for that too? Thank you! 🙂

    Reply
  2. Victor Rodriguez

    Hi Richard :
    Excelent tutorial, I already wrote the mobile app, with Ionic2, and its running, I have to made some modifications, I never understand how to configure Page, so I replace with import { Component } from ‘@angular/core’; and it works !
    Now I’m trying to understand how to get more paramenters from the BLE, I’m using a Beacon (from Kontack.io) . I only get the name, Id, and rssi and I would like to get the url . I take a look into GATT XML documentation. I undestand the url and other info of the Beacon, shoul be retrive by GATT Characteristics, I’m googleing but I can’t found a nice and simple example or tips.
    I know you are a busy genius, but can you give me some tips of how to work with characteristics. My idea is to wriite an app, like the guys from Physical Web, that the app read the url, configured in the Beacon, and take you to the websiite.
    Again, thank you for you tutorial, and hope you can give me some tips.

    Victor Rodriguez from Cancun

    Reply
      1. Victor Rodriguez

        Hi Richard, thank you very much for your quick response and your tip. One question, is this app written to work with iBeacons?, because I’m using Eddystone Beacons, and I think are different ?
        Best regards,
        Victor Rodriguez

      2. Victor Rodriguez

        Hi Richard :
        Again, thank you very much for your quick response and tips. I’m gonna try to integrate my Beacon app, with Evothings plug-in, and I’ll tell you later about my experience.
        Best regads,
        Victor Rodriguez

  3. Andy

    hi Richard,

    Great tutorials about connecting IONIC with different devices. But what about connecting IONIC with Raspberry Pi ?

    Do you have some example for that ?

    Thank you

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s