Tuesday, August 30, 2016

Now a simple iBeacon

As I wrote in the previous blog post, iBeacon are things born in Apple’s mind.

A simple way, based on BLE, to add Location Awareness to your things and Applications.

An iBeacon is a small thing, with a chip supporting BLE, powered by a “cell coin” battery”, that does only one thing: periodically transmits an advertising packet that contains some information:

  • UUID, major and minor number; These three values uniquely identify the iBeacon (for example they represent: the company, the room and something inside the room);
  • RSSI: Received Signal Strength Indicator; A value that indicate what should be the signal strength received by a detector at 1m distance

A device capable of BLE communication can scan the frequencies and detect the near presence of the iBeacon; For example you can use an iPhone, with an App like Locate (by Radius Network), to detect iBeacon and therefore provide you with information of value when you’re near the Thing the iBeacon is attached to.

Imagine: you’re walking along a Museum and you want to see on the screen of your Smartphone information relevant to the portrait you’re looking at.

You can easily buy today iBeacons for a small amount of money, for example from Amazon.

Now, as I told you in the previous post, there are some NodeJS modules that enable you to write application based on BLE and iBeacon.

With the BLENO module you can easily create an iBeacon. Try it on Linux or Mac OS, obviously with an HW supporting BLE:

//

// this code simulate an iBeacon in NodeJS

//

var bleno = require('bleno');

 

// you can change it 

var uuid = 'e2c56db5dffb48d2b060d0f5a71096e0';

 

var major =0; // 0x0000 - 0xffff

var minor =0xffff; // 0x0000 - 0xffff

 

var measuredPower = -57

 

bleno.on ('stateChange', function (state)

{

    console.log ( 'State change:' + state);

 

    if (state === 'poweredOn')

    {

 

        // What I want to advertise

        bleno.startAdvertisingIBeacon(uuid, major, minor, measuredPower);

 

        isAdvertising = true;

    } else

    {

        bleno.stopAdvertising ();

 

        isAdvertising = false;

    }

});

 

As we have pointed out, uuid, major and minor number should identify the iBeacon.

Another useful parameter is measuredPower. This parameter maps to the RSSI. It is an estimation, provided by the iBeacon vendor, of the RSSI that your detector (for example a smartphone) should measure at 1m of distance. Since the RSSI is approximately a linear function of the distance, your detector can compare the RSSI observed with the value provided by the iBeacon (measuredPower) and therefore calculate approximately the distance from the iBeacon.

It is not a very accurate estimate. The reason is that your iBeacon is positioned in an environment that can influence the actual BLE signal power observed. The estimate is more accurate as the distance is lower. But it is a useful indicator for proximity.

 

Bluetooth and Bluetooth Low Energy

Introduction.

In this blog post I want to highlight the main features of Bluetooth Low Energy and to show how it can be used on Intel Edison as a communication protocol.

Bluetooth is born, now almost twenty years ago, as a wireless communication technology, short-range: a technology to implement at low cost a Wireless Personal Area Network (WPAN).

Historically, the first and principal use of Bluetooth was voice and audio streaming, for example from a mobile phone or Smartphone, to a headset or a wireless loudspeaker. Today, all the cars provide connectivity from a smartphone or other devices to the speaker using Bluetooth.

In addition, many runner, like me, use Bluetooth wireless headset to listen to music stored on their Smartphone, when they run.

But the advent of Bluetooth Low-Energy (BLE) or Bluetooth Smart has broadened the range of possible solutions and enabled realization of low-power wireless connectivity between devices with limited resources (e.g. powered by a tiny "cell-coin " battery), fitted with sensors (heart rate, temperature) and a central device that receives, processes and displays data.

The center device often is a Smartphone or better today a Smart-watch.

In fact, today the BLE technology is the simplest wireless communication technology short-range that can be used to communicate with a smartphone (iOS, Android, Windows Phone).

BLE is a communication protocol that rightfully can be considered very important in the context of the Internet of Things. For this reason, it is increasingly supported, for example in boards used by so-called Makers: we find an out-of-the-box support for Intel Edison and even in the latest version of the Raspberry PI, version 3.

Main use cases for BLE.

BLE is a low-power wireless communication technology (low power).

It has a very low energy consumption compared to the WI-FI. In fact it is possible to fabricate devices (see the so-called iBeacons) that by using a "coin-cell battery" broadcast for years without having to change the battery.

It has a limited communication range (tens of meters) and the amount of data to be transmitted per second can not be high (say of the order of tens of bytes per second).

There are many scenarios in which you can think of adopting BLE.

Think of the case of use of the "Connected Car": we want to collect a lot of data, produced by the various car components in real-time, allowing you to analyze the behavior, for example to predict the need for maintenance (Predictive Maintenance).

In this case an effective topology provides a " field gateway", a central device that connects via 4G network (for example) with an IoT Cloud Service, and a series of "resource constrained" devices acquiring data from sensors and communicating with the gateway via BLE. The gateway performs local analysis of the data, aggregates the individual readings and sends messages to the Cloud Service.

NewImage

 

Another use case is in medical applications. You may think to measure vital signs such as heart rate (Heart Rate, HR) using a device with a sensor that transmits via BLE to a central monitoring.

iBeacon.

An iBeacon is a small low-power device, battery powered (e.g. CR2032), , which transmits periodically, every fraction of a second, a message that allows a detector (eg: an App on iPhone) to identify its presence and read the distance.

The specification of iBeacons was defined by Apple. An iBeacon transmits using BLE, using the advertising messages, with a custom usage of the optional data area advertising packet.

Each message contains a UUID, a Major and a Minor number, which allow you to uniquely distinguish the Beacon. 

NewImage

They are typically used as proximity indicators: to indicate that the detector is close to an iBeacon, and somehow identify the environment where it is located (example: I enter into a shop XXX and I’m in the section YYY of the shop).

Another example: we can assign a distinct beacon to each member of our family and place a detector at the entrance of the House, near the door. Thus, as soon as a person of the family enters in the House the Beacon assigned is detected and person recognized.

The main benefit from Beacons comes from their simplicity. The power consumption is extremely low (in the order of micro-amperes) and then the battery can last a year without having to be replaced.

A very well-made guide that explains how the technology of iBeacon works and how it can be used to add "Indoor Location Awareness" to applications is available on the Apple Developer website:

https://developer.apple.com/ibeacon/Getting-Started-with-iBeacon.pdf

It is interesting that even an Apple iPhone can behave as an iBeacon. Activating an application on your iPhone, you can enable its recognition as soon as you get into an environment that "reveals" the close iBeacon. 

Standard.

BLE from the point of view of standardization is a "lightweight" subset of the Bluetooth Core 4.0 specification.

For the specifications, see, for example, the site:

https://www.bluetooth.com

According to the specification, the main characteristics of BLE are:

  • Ultra-low peak, average and idle mode power consumption
  • Ability to run for years on standard coin-cell batteries
  • low cost
  • Multi-vendor interoperability
  • Enhanced range

Bluetooth Low Energy (BLE).

A device that uses the BLE makes its presence known through an  "advertising" mechanism.

As for the advertising and the connection to a central device, roles and actions are defined by the GAP (Generic Access Profile).

The GAP briefly defines how a BLE device can communicate broadcast to the rest of the world its presence, the services it offers and how you can establish a connection between the BLE device and a central device.

GAP defines two main roles:

  • Peripheral: a low-power device, resource constrained, which transmits data via BLE;
  • A Device Central, which collects data, for example from multiple devices.

The peripheral initially transmits in broadcast mode, by periodically sending an "advertising packet" that provides information on the device itself and can also carry data, if you want to transmit in broadcast mode, "connection-less."

The central device typically performs a scan of devices, capturing the "advertising packets", in order to identify devices with which to connect.

When the device is identified, the central device can establish a connection, thus enabling a bi-directional communication between the peripheral and the central device itself.

The specification defines a few simple rules:

  1. A device can be connected only to a single central device;
  2. Generally, after establishing a connection, the device ceases to send advertising packets.

The GAP defines an additional mechanism: a central device can send a BLE Scan Request to a device, to which the device responds with a Scan Response: it is a mechanism that allows an additional sending of descriptive information on the peripheral, required from Device Central.

After having implemented the connection, the communication is ruled by GATT mechanisms (Generic Attribute Profile).

GATT defines how should be the communication between two devices where a connection has been made. It defines how a client can identify the services offered by a server (discovery), how information offered can be read and write, and how receive notifications about state’s changes.

GATT defines two roles:

  • Client Device; the device requesting the connection and performing Read and Write Request;
  • Server Device: the device that responds to requests.

The communication between the two devices is governed by GATT  Transactions’ mechanism.

The exchange of data takes place using logical data structures. It is based on the concepts of:

  • Profile;
  • Service;
  • Characteristics.

Typically, a device defines (or supports) one or more profiles. A profile includes N services and each service provides M characteristics.

NewImage 

An example of profile.

The specification defines, to ensure the maximum possible interoperability between devices and device, a whole set of profiles.

An example of a profile is the Heart Rate Profile (HRP) that is the recommended profile, for example, for the heart rate monitors that use BLE. As indicated in the specification, this profile "enables a Collector Device to connect and interact with Cardio sensors for use in fitness applications."

The profile defines two services, as shown below:

  • Heart Rate Service;
  • Device Information Service.

NewImageBLE and NodeJS.

If you have hardware that can communicate using BLE, you can quickly build applications that exchange information through BLE using the NodeJS platform and the programming language JavaScript.

As previously mentioned, in general (see GAP) BLE will provide for two distinct roles: in other words, our device can be a peripheral device or a central device.

NodeJS provides a modular extension mechanism, based on modules. There is a very broad set of modules, many OpenSource, which can be downloaded from the Internet and installed.

Modules supporting BLE are all "wrapper" of C libraries provided by the underlying hardware platform.

Two Open Source modules can be usefully employed to carry out experiments based on BLE:

Both modules can be installed using NPM.

As we will see below, the code that uses the two modules can be tested on a device like the Intel Edison board and a MacBook. 

An experiment: the environment.

To get a better feeling of BLE and how to set up communication with devices based on this protocol we will use the following working environment:

  • Intel Edison board, connected to the sensors, which will act as peripheral device;
  • A PC that will act as a central device; in my case I used a MacBook Pro (I’m a proud Mac user for years now).

On Mac you can easily install tools that allow you to connect with BLE devices and to analyze and diagnose what is happening during the communication.

In our case we use Developer Tools (Bluetooth Explorer, etc) that are integrated into Xcode.

These tools must be pre-installed by downloading from the Apple website.

In the illustration below, the Bluetooth Explorer is shown, after he has discovered my Intel Edison with BLE activated and initiated a connection (the hostname is thunder10 card and exposes a service of UUID AAA1):

NewImage

Bluetooth and Intel Edison.

In our experiments we will use as a Peripheral Device an Intel Edison board. It natively supports the BLE protocol and requires no additional hardware. Bluetooth management is implemented at hardware level by the chipset Broadcom BCM43340.

A very complete and updated guide on these subjects has been published by Intel and is available at the following URL:

http://www.intel.com/content/www/us/en/support/boards-and-kits/000005743.html

For further details regarding the use of Bluetooth BLE with Edison the reading of the guide is definitely to be recommended.

Intel Edison is a powerful card and probably its best use is in the role of central device, but being small size and with low-power consumption it can be also effectively used in the role of peripheral device.

The stack of Bluetooth protocol in Edison is implemented using BlueZ, the official "protocol stack" of Linux 1 . BlueZ is an OpenSource project.

For more details on BlueZ you can visit their site:

http://www.bluez.com

Intel in the article linked above lists all the commands available at O.S. level, to enable/disable BT and perform most common Bluetooth operations (e.g. scan of visible devices).

The main command-line utility is bluetoothctl.

For example, the following sequence of commands shows how you can make "discoverable" by a Smartphone an Intel Edison board, as seen from the output of the console (obtained through an SSH connection via WIFI to Edison board):

bluetoothctl

[NEW] Controller 58: A8: 39: 00: 18: 94 thunder10 [default]

[Bluetooth] # discoverable on

Changing discoverable on succeeded

[CHG] Controller 58: A8: 39: 00: 18: 94 Discoverable: yes

[NEW] Device F0: DB: F8: 8B: BE: 28 iPhone Louis

[CHG] Device F0: DB: F8: 8B: BE: 28 Connected: no

[DEL] Device F0: DB: F8: 8B: BE: 28 iPhone Louis

[NEW] Device F0: DB: F8: 8B: BE: 28 iPhone Louis

In the second part of the log you see the interaction with a Smartphone (iPhone) who made the discovery of the device and attempted to connect.

Sample code to implement a BLE device.

We are going to explore the JavaScript code, based on BLENO, to implement a simple BLE peripheral device.

The total HW is made by an Intel Edison board, with an Arduino Breakout Board kit. The board is equipped with a Grove Shield to which a Grove Temperature Sensor is connected.

  

First, to handle a bug in BLENO, tied to a conflict with the daemon bluetoothd, before executing the JavaScript code you must run the following sequence of commands:

# Command needed to solve problems with bluez on Linux

# To enable Bluetooth

rfkill unblock bluetooth

 

killall bluetoothd 

hciconfig hci0 up

 

Now let's see together the key elements of Javascript code.

To manage in a simple manner sensors you can use  the UPM library and UPM_GROVE module (JSUPM_GROVE).

In order to use the modules (BLENO, JSUPM_GROVE) and the temperature sensor:

// Using the bleno BLE module for communication

 

var bleno = require ( 'bleno');

 

// Using UPM for Grove Temp Sensor

 

var groveSensor = require ( 'jsupm_grove');

 

var tempSensor = new groveSensor.GroveTemp(0);

The sensor is connected to the pin A0.

 

The first operation the code must carry on is to start the Advertising process, with the periodic emission of the relevant packet, as soon as the BLE module is poweredOn

// When BLENO starts, begin the advertising

bleno.on ( 'stateChange', function (state)

{

    console.log ( 'State change:' + state);

 

    if (state === 'poweredOn')

    {

 

        // What I want to advertise

 

        bleno.startAdvertising ( 'Thunder10', [ 'FFF1']);

 

        isAdvertising = true;

    } else

    {

        bleno.stopAdvertising ();

 

        isAdvertising = false;

    }

 

});

At this point the events that the JS code must manage are:

  1. ACCEPT of a connection;
  2. DISCONNECT, by the Central Device;
  3. STOP ADVERTISING of the process;
  4. START of the ADVERTISING process;
  5. READ request, by the Central Device.

ACCEPT:

// Accepted a connection from a central device

bleno.on ('accept', function (clientAddress)

{

    console.log ( "Connection ACCEPTED from address:" + clientAddress);

 

    // Stop advertising

 

    bleno.stopAdvertising ();

 

    isAdvertising = false;

 

    console.log ( 'Stop advertising ...');

 

});

DISCONNECT:

// Disconnected from a client

bleno.on ('disconnect', function (clientAddress)

{

    console.log ( "Disconnected from address:" + clientAddress);

 

    // restart advertising ...

 

    bleno.startAdvertising ();

 

    isAdvertising = true;

 

    console.log ( 'Start advertising ...');

 

});

In our case we decided to implement the rule that when a connection is established with a Device Central, our device (Edison) stops sending the Advertising Package (thus, it is no longer discoverable).

STOP ADVERTISING:

bleno.on ( 'advertisingStop', function (error)

{

 

    console.log ( 'Advertising Stopped ...');

 

});

 

The most complex part of the code is the following:

 bleno.on('advertisingStart', function(error) 

    if (error) 

    {

        console.log("Advertising start error:" + error);

    } else 

    {

 

        console.log("Advertising start success");

 

        bleno.setServices([

 

            // Define a new service

            new bleno.PrimaryService({

 

                uuid : 'aaa1',

 

                characteristics : [

 

                    // Define a new characteristic within that service

 

                    new bleno.Characteristic({

 

                        value : null,

 

                        uuid : 'ccc1',

 

                        // the value can ONLY be READ

 

                        properties : ['read'],

 

                        // Send a message back to the client with the      

                        //characteristic's value

 

                        onReadRequest : function(offset, callback) 

                        {

 

                            console.log("READ request received");

 

                            // read the temperature value from the sensor

 

                            this.value = tempSensor.value();

 

                            console.log('Temperature Value: ' + this.value);

 

                            callback(this.RESULT_SUCCESS, new Buffer(

 

                                (this.value ? this.value.toString() : "")));

                        }

                    })

                ]

            })

     ]);

    }

});

The choice made here, that is not the only one possible, is to define the service at the time of the start of advertising.

The code defines a service, identified by the UUID AAA1. Within this service you define a single characteristic, with UUID CCC 1. The feature has a value that can only be read (Read) and it is associated with the onReadRequest callback which is invoked by BLENO stack when it receives the READ request. The onReadRequest invokes the code to read the current value of temperature, which is returned by BLE.

In the code we only manage the events (1 to 5) listed above. In general, it should also provide for other events, such as: WRITE Request, Notify. But in our case the value exposed by the service (room temperature) can only be read and we assume that you do not want to provide notification of value changes, from the device to the Device Central.

Each event is run by a suitable callback, as usual in NodeJS.

Using the NOBLE module for the implementation of a BLE Central Device.

Another module that can be used to implement in NodeJS the other side of the connection (the Central Device) is Noble.

I have personally tested Noble on my MacBook, but it also runs on Intel Edison (which can then act as Device Central, as aggregator node).

If you install Noble, in the directory

node_modules / examples

There are three useful sample programs that show how to use the module API:

  1. enter_exit.js, who simply writes a line each time a visible BLE device connects or disconnects;
  1. advertisement_discovery.js, performing a scan of the visible devices and displays the list of advertised services.
  1. Finally peripheral_explorer, to be launched with the <device address> parameter, which shows the services and features exposed by the specified device address.

Finally, a last module that can be used to implement a Beacon is:

Node-bleacon

Some final thoughts.

Writing JavaScript code based on the two mentioned modules is not complex and, starting from the examples, with adequate experience, it is possible to create in a short time applications.

However, in tests carried out by me not always everything worked. In some cases I had to reboot the Edison board to resume the tests correctly, which shows that the two modules and the underlying stack have not, yet, totally free of bugs.

Moreover, the daily experience with the Bluetooth protocol, by users, showed us situations where, for example, the coupling between the two devices is not successful end and attempts must be repeated.

Suggestions for further reading.

A collection of short but very clear and useful pages on BLE is available on the Adafruit website:

https://learn.adafruit.com/introduction-to-bluetooth-low-energy

 

To learn more about using the iBeacon technology a very useful site is Apple site:

https://developer.apple.com/ibeacon/

 

Friday, August 19, 2016

Intel Edison and BLE

BLE stands for Bluetooth Low Energy.

Intel Edison supports out-of-the-box (no additional shields required) two communication ways:

  • WIFI
  • BLE

One scenario where you can think to adopt an Intel Edison board is where you want to use Edison as a Field Gateway. Sensors are connected to small, low-power, resource constrained boards like Arduino 101 (https://www.arduino.cc/en/Main/ArduinoBoard101).

They read the data from sensors and communicate these data to the Edison Gateway using BLE.

Then Edison aggregates and sends out these data using WIFI. For example using MQTT messages to an IoT Cloud Service.

BLE is low power, is easily supported by constrained resources boards, but can be employed only for short range communications (for example in the use case of the “Connected Car”).

I’ll cover BLE and BLE on Edison in next blog posts. Stay tuned.