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.
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.
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:
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:
- A device can be connected only to a single central device;
- 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.
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.
BLE 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:
- BLENO, which can be used to implement a Device; https://github.com/sandeepmistry/bleno
- NOBLE, to implement a central device; https://github.com/sandeepmistry/noble
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):
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:
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:
- ACCEPT of a connection;
- DISCONNECT, by the Central Device;
- STOP ADVERTISING of the process;
- START of the ADVERTISING process;
- 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:
- enter_exit.js, who simply writes a line each time a visible BLE device connects or disconnects;
- advertisement_discovery.js, performing a scan of the visible devices and displays the list of advertised services.
- 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/
What connectivity to the existing car's audio equipment is optimal in your situation? You also might consider using your speakerphone in other places than your car. Rugged Bluetooth Speakers
ReplyDelete