Introduction
Bluetooth low energy (BLE) is a wireless technology standard for personal area networks. BLE is targeted for very low power devices, devices that can run on a coin cell battery for months or years. Typical applications that uses BLE are Health care (fitness trackers), beacons, smart home, security, entertainment, proximity sensors, Industrial and automotive. BLE ecosystem is centered around Smart phones, tablets and PCs.
BLE_API is a very thin and lightweight layer of C++ interfaces to abstract the architectural building blocks of Bluetooth Smart. Portable applications may then be written on the basis of these high-level constructs and interfaces, and remain compatible with all mbed-supported underlying Bluetooth Smart platforms and components. Using BLE_API also implies that developers implicitly benefit from all the low-power optimizations offered by the supported hardware. In addition, we offer support for firmware-over-the-air (FOTA) for Nordic targets.
FOTA is currently available only for the Nordic nRF51822 platform, owing to it being a single-chip-solution. It requires a host-specific bootloader to be installed initially, and thereafter can be used to update the BLE application as long as the BLE stack on the system remains operational. Android apps (released by Nordic) may be used to drive FOTA for now; we'll be releasing our own iOS and Android supplementary apps shortly.
BLE_API comes with reference implementations for some of the Bluetooth-SIG specified GATT profiles and services, which can serve as a useful starting point for prototyping. In we offer several reasonably documented demo applications to get the user up to speed quickly.
Harnessing Bluetooth Smart for embedded applications will require the user to familiarize herself with several basic concepts, but we hope that using BLE_API together with the demo applications as reference will ease and support such efforts.
BLE services supported on mbed¶
- Battery Service
- Device Firmware Update Service
- Device Information Service
- Health Thermometer Service
- Heart Rate Service
- UART Service
- URI Beacon Configuration Service
Additional documentation specific to each services is provided in the code section below. Here is our BLE development roadmap.
Hardware Platforms supported with BLE¶
More Technical Information¶
- Bluetooth Low Energy on Wikipedia
- Bluetooth Smart (Low Energy) Technology
- The Low Energy Technology Behind Bluetooth Smart
BLE Specifications¶
Development Resources¶
Link to Videos¶
<<Placeholder...>>
What's special about the technology?¶
<<Placeholder...>>
What applications is it suited for?¶
<<Placeholder...>>
Architecture of an mbed-BLE solution¶
For most developers, one of the big hurdles in getting started with Bluetooth smart is familiarizing oneself with the low-level details of the underlying controller and APIs for the accompanying BLE-stack. Mbed attempts to abstract these details in the form of BLE_API. Applications may then be written to take advantage of the high-level constructs and interfaces offered by BLE_API and remain compatible with all supported underlying Bluetooth smart platforms. This makes for portable programs, which can easily be moved from one supported platform to another during development. Using BLE_API also implies that developers implicitly benefit from all the low-power optimizations offered by the hardware.
BLE_API is a very thin and lightweight layer of C++ interfaces and abstractions allowing users to develop portable applications for Bluetooth Smart. It needs to be combined with some 'bridge software' specific to each vendor platform. This bridge software provides the instantiations for the interfaces offered by BLE_API, and helps drive the underlying controller and Bluetooth stack.
A Bluetooth Smart application is composed of BLE_API, bridge software, and controller-specific Bluetooth stack.
BLE_API is developed on Github (https://github.com/mbedmicro/BLE_API/) and mirrored on mbed.org (http://developer.mbed.org/teams/Bluetooth-Low-Energy/code/BLE_API/).
Inside BLE_API¶
BLE_API offers building blocks to help construct applications. These fall into two broad categories: interfaces under 'public/' to express BLE constructs such as GAP, GATT, Service, Characteristics, etc. and classes under 'services/' to offer reference implementations for many of the commonly used GATT profiles. The code under 'services/' isn't essential, but offers a useful reference and a good starting point for prototyping. Code under 'common/' encapsulates headers which need to be shared between the public interfaces and underlying bridge code.
Over time, we expect to keep adding more reference implementations for the standard GATT profiles under 'services/'.
Example mbed BLE apps¶
<<Placeholder..., and please include a walk-through of the sample apps below>>
iBeacon¶
Import programBLE_iBeacon
Beacon demo for the BLE API using the nRF51822 native mode drivers
Physical Web: a variation on the same theme¶
Import programBLE_URIBeacon
The Uniform Resource Identifier Beacon (UriBeacon) defines Bluetooth 4.0 Advertisement Data that contain Web URIs. URIBeacon provides a way for Bluetooth Low Energy devices to discover nearby URIs, for example, provides a way for a user to discover a short URL and then download it on their smartphone.
Heart rate sensor. [connection oriented]¶
Import programBLE_HeartRate
Heart Rate Monitor example for the BLE API using nRF51822 native mode drivers
Getting started with BLE on mbed¶
<<Placeholder...>>
Supported platforms¶
Mbed currently supports several platforms based on Nordic's nRF51822, and CSR's CSR1010 as an add-on component.
<<Please add more here>>
Build and run a demo¶
<<Placeholder...>>
Low Power Credentials¶
This is a topic of considerable importance to BLE; and we target the best that the radio controller has to offer. It is our goal that the power consumed by the BLE stack (together with BLE API) will be dwarfed by the overhead of driving the radio, or running externals sensors.
While the BLE stack is idling the baseline currents are around 6-10uAmps; and this sets the theoretical limit for battery life. Consumption jumps to 10-15mAmps (note: milli-amps) when the radio is used. These peaks are affected by the quality of the radio, antenna, and various factors around RF tuning; it is reasonable to expect that RF vendors will reduce the cost of these peaks over time.
Getting Measurements¶
Measuring power can be tricky with BLE because of the large dynamic range involved. There is a variance of 3 orders of magnitude between sleep-mode and active-mode currents. Traditional methods such as measuring the voltage drop across a sense resistor don't have enough of a dynamic range to cover this, and so don't work very well. In some cases useful measurements can be obtained as averages (some multi-meters offer reasonably accurate estimates of average currents through the use of min-max-avg modes). The use of fast auto-ranging oscilloscopes can also help.
We've had some success with the Power Monitor from Monsoon Solutions.
Some of the BLE dev boards (such as the mkit and the nRF-DK) pose a further challenge for power measurements in the form of introducing the mbed interface-chip into the equation. Measuring power by observing what's fed into the USB input to the board gives misleading numbers due to the overheads of the supporting circuitry. In those cases, it becomes necessary to isolate the extraneous components through appropriate jumpers and schematic-study; or by switching to battery supply instead of USB. Measuring from a custom board with minimal components (or through the use of something like the smart-beacon kit) is another successful strategy.
Profile of the iBeacon example¶
The results shown in the following discussion were obtained using the smart beacon kit. With this board, the BLE_Beacon example program on mbed consumes 35uA of average current. Here's a power profile for that use-case measured using the 'Power Monitor' from Monsoon Solutions.
The vertical axis in this figure is the current consumption (in milli-amps), and the horizontal axis shows time. This picture captures nearly 1 second of activity. The power profile is periodic and repeats every 1 second.
The major peak is an advertising event where a beacon is broadcast; the minor peak comes from periodic housekeeping activities of the bluetooth stack. Outside the peaks, current consumption is around 6uAmps (when measured using instruments with 0.1uA precision); as can be seen from the instantaneous current value of 0.01mA.
The primary contribution to power consumption comes from the use of the radio. Please note that the radio peaks at 12-15mA of current for around 2ms during every advertisement event (this is when an advertising payload must be sent out over the three advertising channels and then the radio is run a little longer to look for scan-requests or connection requests). In the default beacon example, advertisements are sent out at 1Hz (once every second) and at a power level of 0dB; both of these factors are under the control of the developer. This should give you an idea of what's possible.
The average current, highlighted with a red underline on the left panel, is around 35uAmps; and with a coin cell battery the system may be expected to last around 7000 hours (which is nearly a year).
What we've done to lower energy consumption¶
Here are some of the strategies we've employed on the Nordic nRF51822 to lower baseline power consumption:
- The system now starts with low-frequency clock by default (instead of using the external 16MHz clock). The high frequency clock is still kicked into action automatically by the soft-device when needed; but now it doesn't remain active all the time. This by itself lowers the baseline consumption significantly. It also means that if an application needs the high- frequency clock (such as for any high-speed serial communication), then it must enable the external clock source explicitly; and hopefully the external clock will be managed in a power-conscious manner, which means that clocks will be turned off when not needed.
- We make an effort to avoid using wait() API from mbed. This API is currently synchronous and wastes a lot of power. The mbed team will be coming out with asynchronous APIs very shortly; and then hopefully this problem would vanish silently.
- We've also re-implemented the Ticker APIs to use the RTC instead of a high- frequency timer. This makes a trade-off between precision and power; and we believe power trumps over precision in the context of BLE.
Steps recommended for users¶
It's worth re-emphasizing this. Users are free to enable high-frequency timers explicitly if needed. If an application requires the use of high-frequency clock (for instance to do serial communication at high baud rates), then it must enable the high-frequency clock by writing into the appropriate control registers (please refer to the datasheets of the nRF51822). It would help to turn off high-frequency clocks at the earliest opportunity.
Users may also experiment with reducing the transmit power of their radio; there's an API for this.
Connection intervals and connection latency are also available for modification, and play a very important role in power consumption.
Please try using the following API once a connection is made in order to request the central to update the settings:
BLEDevice::updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params)
It is ultimately up to the central/master to choose the connection parameters. Your requested settings may not be honored.
Please take notice of the following comment from ble_gap.h (under nrf- sdk/s110) and also pay attention to the constraint mentioned mentioned at the end:
/**@brief Update connection parameters. * * @details In the central role this will initiate a Link Layer connection parameter update procedure, * otherwise in the peripheral role, this will send the corresponding L2CAP request and wait for * the central to perform the procedure. In both cases, and regardless of success or failure, the application * will be informed of the result with a @ref BLE_GAP_EVT_CONN_PARAM_UPDATE event. * * @note If both a connection supervision timeout and a maximum connection interval are specified, then the following constraint * applies: (conn_sup_timeout * 8) >= (max_conn_interval * (slave_latency + 1)) ...
Here's one user's attempt to reduce connection intervals for the heart-rate demo after a connection has been established:
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(379, UNIT_1_25_MS) /**< Minimum connection interval (379 ms) */ #define MAX_CONN_INTERVAL MSEC_TO_UNITS(399, UNIT_1_25_MS) /**< Maximum connection interval (399 ms). */ #define SLAVE_LATENCY 4 /**< Slave latency. */ #define CONN_SUP_TIMEOUT MSEC_TO_UNITS(6000, UNIT_10_MS) /**< Connection supervisory timeout (6 seconds). */ void onConnectionCallback(Gap::Handle_t handle, const Gap::ConnectionParams_t *p_conn_param) { Gap::ConnectionParams_t gap_conn_params; gap_conn_params.minConnectionInterval = MIN_CONN_INTERVAL; gap_conn_params.maxConnectionInterval = MAX_CONN_INTERVAL; gap_conn_params.slaveLatency = SLAVE_LATENCY; gap_conn_params.connectionSupervisionTimeout = CONN_SUP_TIMEOUT; ble.updateConnectionParams(handle, &gap_conn_params); } ...
The mbed team is also working towards asynchronous (non-blocking, interrupt- driven) APIs; automatic, smart management of clocks; and the use of DMA. Once these are in place, even non-trivial applications should be able to exhibit excellent power profiles.
FOTA¶
We've got over-the-air firmware updates (FOTA) working for the platforms based on Nordic's nRF51822. This means that it is possible to update the firmware of an nRF51822 based device from a BLE-enabled smartphone (and hopefully soon from a development PC over a BLE dongle).
Presently, there is very little security or safety in this firmware-update process, but this is being worked upon.
We're also working on standardization of the FOTA protocol; and for defining a security model for validating/authenticating firmwares.
FOTA requires the use of a (Nordic-specific) DFU-bootloader to provide the functionality for firmware download and reprogramming. Once the DFU-bootloader is resident, any BLE application may be updated as long as the operation of the BLE stack isn't impaired.
Components Involved¶
The following image shows the layout of the main software components which go into a FOTA capable system. These include:
- Softdevice: this is Nordic's encapsulation of the bluetooth stack.
- Application: the user's BLE application.
- Bootloader: which is responsible for firmware updates.
Upon power-up, the softdevice initializes the system and forwards control to the bootloader. Unless it has been triggered to do firmware-updates, the bootloader forwards control to the application right-away.
The bootloader image needs to be installed initially; and thereafter the FOTA mechanism can update any DFU-service enabled application as long as it doesn't crash. The softdevice and the bootloader components don't change during FOTA updates; and therefore don't need to be combined with the firmware sent over the air.
Mbed platforms typically come with an interface chip, called CMSIS- DAP<<@pratul LINK>>, which offers drag-n-drop based programming over USB. CMSIS-DAP does a complete chip-erase before programming new firmware, so binaries meant for USB drag-n-drop need to combine the softdevice with the application. FOTA offers a complementary programming facility where once the initial bootloader image is installed (possibly using CMSIS-DAP), further programming involves only updating the application while keeping the softdevice and the bootloader unchanged.
We'd like to re-emphasize that FOTA applications don't need to be combined with the softdevice (as is needed for stand-alone applications used with CMSIS-DAP). For this reason, FOTA applications need a separate (virtual) build target for each Nordic platform. be generated by building for 'shadow' platforms meant for FOTA.
Here are some links to these alternate/virtual platforms:
Please be sure to add these platforms to your online compiler; and build for them when generating FOTA binaries.
Default Bootloader¶
Here's an initial image for the Nordic mKit to install the bootloader.
Here's the corresponding initial image for the nRF-DK platform.
Please unpack the appropriate .zip archive into a .hex file for programmed onto the target.
Together with the bootloader, these images come with a default application offering Device-Information and Console Output services.
You can find more information about the internals of the DFU bootloader at: http://developer.mbed.org/forum/team-63-Bluetooth-Low-Energy- community/topic/5201/.
DFU Service¶
FOTA enabled applications work by offering a DFUService. This service contains a 'control' characteristic which when written to forwards program control to the resident bootloader in preparation for FOTA. This division of responsibility implies that FOTA applications need bear only a small overhead while keeping most of the FOTA heavy-lifting in the bootloader.
When building for a FOTA-enabled platform (see discussion on virtual/shadow
platforms above), an instance of the DFUService gets added to an application
implicitly during the call to ble.init()
; the assumption being that
for such a platform an application will always want to enable FOTA.
If an application built for a non-FOTA platform wishes to introduce the DFUService explicitly, it takes a single line of code to do so:
code changes needed to add DFU-Service
/* Enable over-the-air firmware updates. Instantiating DFUSservice introduces a * control characteristic which can be used to trigger the application to * handover control to a resident bootloader. */ DFUService dfu(ble);
In that case you will also need to include DFUService.h
. An example of
such use would be the creation of the initial application which goes with the
bootloader.
Driving FOTA¶
Updating a FOTA-capable application is a two stage process. It involves triggering the application to hand over control to the bootloader, and then letting the bootloader receive and apply the udpate safely.
Sequence Diagram for Firmware Over The Air¶
This process can currently be driven from an external BLE agent such as an Android phone. We'll soon be releasing our own reference apps for iOS and Android; together with SDKs to build custom apps for FOTA. For the moment, we recommend using Nordic's nRF Master Control Panel as a generic tool to drive FOTA. https://play.google.com/store/apps/details?id=no.nordicsemi.android.mcp
Here's a video showing FOTA (starting at around 2:00).
The following sections provide snapshots of the process as driven by the Master Control Panel.
Lising the device with DFU Service¶
The following images (taken using Nordic's master-control-panel Android-app) expand on the capabilities of the defaultApp bundled into the initial bootloader image (mentioned above). Among other services, this application offers a DFU-Service which allows FOTA. All DFU-capable applications should offer this service.
Triggering FOTA¶
The DFUService contains a single 'control-point' characteristic, which when written forces the application to enter DFU mode; internally it causes the application to forward control to the resident bootloader which takes over the firmware transfer.
The following set of images shows how Nordic's Master Control Panel can be used to cause a DFU capable application to forward control to the bootloader:
Driving FOTA¶
And these images show the main FOTA sequence using the bootloader:
At the end of this process, the new application is handed control automatically, and you can see it appear on the master-control-panel.
Attribute/Service Caching¶
You should be aware that to save energy a GATT client often caches the results from a service discovery. Changing/updating an application (especially when replacing it with a different application) may require the client to re- attempt service discovery. After a FOTA update, you may want to restart your client application, if this doesn't happen automatically; or restart the Bluetooth service on the client's system.
UART access over BLE¶
If you want to receive console output from an updated app, it is possible to do so over the BLE UART Service. For instance, the default app which comes bundled with the bootloader generates regular pings on the rx-characteristic of the UARTService. These pings can be received using one of several UART apps, such as Nordic's nRF UART.
Please be aware that presently it is possible to have only a single active connection to a BLE device; so let's say you're working with a heart-rate application and if you've connected to it using nRF UART for console output, then you cannot simultaneously connect to it from another heart-rate phone app.
Please also note that console messages are sent across in notification packets of up to 20 bytes in size; this limit is imposed by Bluetooth standard. So longer messages need to be cropped into a sequence of 20-byte packets. Output buffers internal to the UARTService are flushed upon encountering a newline character. The receiving UART application should be able to stitch together cropped portions of longer messages.
Using the UART service¶
The following program illustrates the use of UARTService to redirect something like printf() to use the BLE transport.
Import programBLE_UARTConsole
A console service.
code changes needed to redirect console output to UART Service
#if NEED_CONSOLE_OUTPUT #define DEBUG(STR) { if (uart) uart->write(STR, strlen(STR)); } #else #define DEBUG(...) /* nothing */ #endif /* #if NEED_CONSOLE_OUTPUT */ uart = new UARTService(ble); DEBUG("ping\r\n");
You will also need to include UARTService.h
.
Limitations of our current implementation¶
- There is no security or safety built into the process yet. Anyone with the right tools can update a FOTA capable target. Resolving this is very high on our priorities.
- Building FOTA binaries currently requires using a 'shadow' build platform for every target. We shouldn't be cloning build platforms for FOTA; ideally this should be a selectable option.
- FOTA requires installing an initial image containing the bootloader. For non-official mbed platforms, that would mean that a user would need to understand the internals well enough to be able to build an initial image, and also find a programming interface to transfer it to the target. We're working on releasing a USB->SWD adaptor which can target nRF51822 boards which don't have an mbed CMSIS-DAP interface.
- The two stage FOTA process is cumbersome and error-prone. We're working on creating a simple reference app to drive FOTA. Eventually we hope to release an SDK to allow users to create their own FOTA driver applications.
Roadmap¶
In addition to adding support for BLE solutions from more vendors, we've got the following on our roadmap for the next near.
Switching to Bluetooth 4.1 and eventually to 4.2¶
Top on our list of priorities for the coming releases would be to extend our BLE APIs to support Bluetooth 4.1 and 4.2. This is expected to bring several desirable improvements:
- Low-power IP connectivity.
- Support for multiple concurrent connections at the peripheral; and being able to act as a peripheral and central at the same time.
- Being able to advertise while still being in a connection.
- Being able to scan for advertisements from nearby peripherals.
To execute this, we'll move to support the S130 softdevice or whatever else Nordic's going to release to become compatible with BLE-4.2; and the same for CSR.
Firmware Over The Air¶
Firmware over the air (or FOTA for short) has been supported on our Nordic platforms for a while. We'd like to enhance our FOTA functionality with the following:
- Adding safety to FOTA; this means it should be possible to ensure firmware updates are not applied unless they are built for the correct MCU/platform target.
- Adding security to FOTA; which means that it should be possible to authenticate and validate the update before applying it.
- We want to develop standardization around the FOTA protocol.
- We would also like to create a generic bootloader to allow FOTA on platforms other than Nordic.
- An 'mbed' iOS/Android reference application to drive FOTA seamlessly; offering a conduit between an online/offline build system and mbed targets. It should also be possible to target multiple devices concurrently.
- Core FOTA functionality of the 'mbed' app should be extracted as an SDK to allow other user-specific implementations.
- Being able to drive FOTA from a desktop (over a BLE dongle).
- We're working on releasing a USB->SWD adaptor which can target nRF51822 boards which don't have an mbed CMSIS-DAP interface.
Peripherals as GATT clients¶
Some services/applications, such as ANCS, are designed keeping the Central as a GATT server, and expecting the peripherals to act as Clients (in the case of ANCS as Notification Consumers). This requires GATT client extensions to be added to BLE_API, covering at the very least service and characteristic discovery together with reads, writes, and notifications/indications.
Connection Handles in all relevant API calls¶
Even when acting as a peripheral, version 4.1 of the specification allows connections to multiple centrals. A connection handle is therefore required in most of the API calls that deal with link-specific things: disconnecting, data transfer, etc.
GAP: Security¶
Bonding and other security features to be enabled.
API extensions to support Read/Write Authorization¶
- Extend BLE API to allow setting up of read and write authorization on every attribute access operation.
Unit testing¶
Create a unit-test framework to automate testing of BLE_API. This should be able to verify protocol correctness (to some reasonable degree), and also track any regressions in energy consumption when driving the BLE stacks. This validation suite could then be the basis for
GATT standard Services¶
Add implementation for more SIG-defined GATT services; and create demos for them.
PTS Qualification¶
We'll invest in getting our services approved by the Profile Tuning Suite to assist our users in getting their devices certified by Bluetooth-SIG.
Interoperation with an RTOS¶
We'd like to create a few demos where our BLE framework lives alongside an RTOS.