Tag Archives: Bluetooth

Creating a Beacon application with Ionic

This is a very quick “get going with beacons and Ionic 2” post.

The code can be found in a github repository here.

First create an Ionic app:

ionic start –v2 beacon-starter blank

Now, from the newly created application directory add the cordova beacon plugin:

ionic plugin add cordova-plugin-ibeacon

Next, create a provider (beacon-provider.ts) in a providers folder:

import { Injectable } from ‘@angular/core’;
import { Platform, Events } from ‘ionic-angular’;
import { IBeacon } from ‘ionic-native’;
/*
Generated class for the BeaconProvider provider.

See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class BeaconProvider {

delegate: any;
region: any;

constructor(public platform: Platform, public events: Events) {
}

initialise(): any {
let promise = new Promise((resolve, reject) => {
// we need to be running on a device
if (this.platform.is(‘cordova’)) {

// Request permission to use location on iOS
IBeacon.requestAlwaysAuthorization();

// create a new delegate and register it with the native layer
this.delegate = IBeacon.Delegate();

// Subscribe to some of the delegate’s event handlers
this.delegate.didRangeBeaconsInRegion()
.subscribe(
data => {
this.events.publish(‘didRangeBeaconsInRegion’, data);
},
error => console.error()
);

// setup a beacon region – CHANGE THIS TO YOUR OWN UUID
this.region = IBeacon.BeaconRegion(‘deskBeacon’, ‘F7826DA6-4FA2-4E98-8024-BC5B71E0893E’);

// start ranging
IBeacon.startRangingBeaconsInRegion(this.region)
.then(
() => {
resolve(true);
},
error => {
console.error(‘Failed to begin monitoring: ‘, error);
resolve(false);
}
);
} else {
console.error(“This application needs to be running on a device”);
resolve(false);
}
});

return promise;
}
}

 

Now import this provider into app.module.ts and add it to the providers folder.  Your app.module.ts file should then look like this:

 

import { NgModule } from ‘@angular/core’;
import { IonicApp, IonicModule } from ‘ionic-angular’;
import { MyApp } from ‘./app.component’;
import { HomePage } from ‘../pages/home/home’;
import { BeaconProvider } from ‘../providers/beacon-provider’

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [BeaconProvider]
})
export class AppModule { }

 

Next, create a model called beacon-module.ts in a models folder:

export class BeaconModel {

uuid: string;
major: number;
minor: number;
rssi: number;

constructor(public beacon: any) {
this.uuid = beacon.uuid;
this.major = beacon.major;
this.minor = beacon.minor;
this.rssi = beacon.rssi;
}
}

(we don’t really need a model for this app but creating one makes me feel more grown up)

Now change home.ts so it looks like this:

// core stuff
import { Component } from ‘@angular/core’;
import { NavController, Platform, Events } from ‘ionic-angular’;
import { NgZone } from “@angular/core”;

// plugins
import { IBeacon } from ‘ionic-native’;

// providers
import { BeaconProvider } from ‘../../providers/beacon-provider’

// models
import { BeaconModel } from ‘../../models/beacon-model’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {

beacons: BeaconModel[] = [];
zone: any;

constructor(public navCtrl: NavController, public platform: Platform, public beaconProvider: BeaconProvider, public events: Events) {
// required for UI update
this.zone = new NgZone({ enableLongStackTrace: false });
}

ionViewDidLoad() {
this.platform.ready().then(() => {
this.beaconProvider.initialise().then((isInitialised) => {
if (isInitialised) {
this.listenToBeaconEvents();
}
});
});
}

listenToBeaconEvents() {
this.events.subscribe(‘didRangeBeaconsInRegion’, (data) => {

// update the UI with the beacon list
this.zone.run(() => {

this.beacons = [];

let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});

});

});
}

}

and change home.html so it looks like this:

<ion-header>
<ion-navbar>
<ion-title>
My Beacons
</ion-title>
</ion-navbar>
</ion-header>

<ion-content>
<ion-list no-lines>

<ion-item *ngFor=”let beacon of beacons”>
<ion-grid>
<ion-row>
<ion-col>Major</ion-col>
<ion-col>{{beacon.major}}</ion-col>
</ion-row>
<ion-row>
<ion-col>Minor</ion-col>
<ion-col>{{beacon.minor}}</ion-col>
</ion-row>
<ion-row>
<ion-col>RSSI</ion-col>
<ion-col>{{beacon.rssi}}</ion-col>
</ion-row>
</ion-grid>
</ion-item>

</ion-list>
</ion-content>

That’s all there is to it.  You will need to change the UUID in the beacon provider to the UUID of your own beacons.   If you run the app it should detect your beacons and display a list of them on screen (showing major, minor and RSSI):

image1-1

 

Hopefully, that will get you started!  Good luck.

 


I’m a mobile applications developer based in the UK, concentrating primarily on hybrid application development with Ionic 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 but also with other mobile frameworks and technologies.  Thanks for visiting.

 

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.