Diving in BLE development

xosrov


Overview:

Bluetooth is playing a very important role in term of short long communication .such an important role push developers to improve it better and faster for new requirement of the market ,the success of BLE is similar to success of USB and its fast versioning .The main focus on this topic is to introduce the steps to design a costum BLE solution or add BLE support to your current application . 
[In this document when I mention BLE , i refer to BLUETOOTH LOW ENERGY 4.X]

According to standard specification the new version of BlueTooth technology relayed on the concept of Low Energy It means using a single cell coin battery as power source, a BLE device's life could be extended to sevral years.there are many advantages and a few weakness of BLE 4 , It dosn’t support audio streaming , so if you’re planning to support an audio streming device ,BLE is not a good solution for you, the way it works is based on transfering small packet data throgh signal events , but the good latency of signals  with fast transaction 3ms from start to finish probably recompense this low data rate in communication, it  sleeps when no event or communication is on going, in sleep mode it  consume less than 1 µA , and wakeup if necessary.From many aspects BLE is different from a Classic BT ,more connectivity range, low energy consumption ,in the table below you see those difference,BLE is low cost and easy to implement ,don't be suprised if I say the battery will cost more than the electronics!

To wrap up this overview ,before starting your project you have to know, BLE is designed for sending small chunks of data that's why BLE is not advised for File Transfer operation specially when processing big files,it cannot handle it as we expect and as we get used with WIFI, once again notice BLE is perfect for kind of devices based on command with small packet data to carry out,with minimum time processing, BLE is not designed to execute heavy calculation and math processing ,those things should be delegated to Master device rather than slave BLE , this point is very important your BLE device is there to hand you the data you need and not to process  or execute them , any mathmatical operation and/or presentation of this data is to be implemented on Master side.Later when you write and download your codes into device's firmware be carreful to not implement huge routines which make  processor busy for a relative long time. 

Below a list of known Use Cases

1- Proximity  detection,presence detection  2-Time  3-Emergency 4- Network availability  5- Personal User Interface  6- Simple remote control  7-Browse over Bluetooth

8- Temperature Sensor  9- Humidity Sensor  10- Generic I/O (automation)   11- Battery status   12- Heart rate monitor   13-Physical activity monitor

14-Blood glucose monitor  15- Cycling sensors    16-Pulse Oximeter    17-Body thermometer



As you see the volum of data transfered in each transaction in BLE is less than a classic BT! however you notice that even if BLE perform a smaller data packet in a single transaction , the transactions occurancy in BLE is higher than a classic BT , this acceptable latency makes the difference and put it on top of the short range communication protocol. 
In this topic we're not going to discover all those details in every corner of this marvelous technology but we need a minimum knowledge to start a successful project around BLE,things like how BLE communicates to outside world is the first step to implement it in our solution.

Bluetooth devices currently available in market either they support BLE or not, are divided by 3 categories:
Classic Bluetooth (Legacy):
 
is classic generation from 1.x to 3.x
Bluetooth Smart :
is new generation known as BLE v4.x,they are not backward-compatible with previous Classic Bluetooth 
Bluetooth Smart Ready:
 indicates a dual-mode device compatible with both Classic and low energy peripherals.

Bluetooth Smart indicates a low energy-only device which requires either a Smart Ready or another Smart device in order to function.In IT  Jargon,sometimes professional use "Central" and "peripheral" Centeral refers to any smartphone,tablette,...and peripheral is the BLE device attatched to it.other term usually in this jargon are [Master] and [slave], Master refer to Smartdevice ,tablette,...which control the device , and Slave is the BLE device
[
notice : A Slave cannot have two Master at the same time]
Other interessting feature unique to BLE device is the ability to get enough information about device even before connecting ,this feature is exploited by professional to push advertizing over it.Advertising is the primary way a peripheral device make its presence via Bluetooth LE.
Advertising packets are very small ,broadcasted by BLE device to nearby , this feature allow master devices (smartdevice)to be able to retreive enough information before connecting.notice that in any case the connection is initiated by Master , so it’s up to master device to decide wether to connect or not.Advertising packets contain useful data, such as the peripheral’s name. It can also include some extra data related to what the peripheral collects. For example, in the case of a heart rate monitor, the packet also provides heartbeats per minute (BPM) data.The job of a central is to scan for those advertising packets, identify any peripherals it finds relevant, and connect to individual devices for more information.
During the  lifecycle of connection or advertizing all communications are  asynchronous.


Topology :

As design classic Bluetooth Master can be connected to up to 7 slave devices simultaneously , however according to SIG specification  this limit is not defined  for Blue tooth Low Energy(BLE) but  it seems to have a practical limitation  since in Advertizing phase BLE consume  energy and by higher number of devices that may  be a major challanging to the principal of Low Energy, so from topology state , A Slave can only be  connected to one Master at a time  but a Master can be connected to an unlimited (undefined) number of Slaves , A Master could be playing the role of Slave at the same time, there is no any  direct communication between two slaves  , no direct connection , therefore for such a scenario  , Slave must use a Master as a bridge to  achieve  that as shown here:

image324



Hardware design :

According to SIG (Special Interest Group ), BLE is using the same frequency range as Classic BT(and also WIFI) ,From 400 GHz to 2.4835 GHz ISM band=> delta =0.08GHz=80MH pass band , this 80MHZ is distributed as channels ,In BlueTooth classic this range is divided into 79*1MHz (79 channels) 
however In BLE this range is divided into 40*2MHz (40 channels) within these 2MHZ we can send or receive BLE data.channels (37,38,39) are used for advertizing & discovery service in different part of spectrs to ensure safety against interference, the rest are data channels , once connection established and initiated data channels are used instead.

image3001

BLE device communicates with smart devices (masters) trough events signals every transaction of data or advertizing occurs in the interval of around 3ms , data is dispatched on multiple channels  , advertizing are carried out by 3 channels  37,38,39, the following diagram taken by TI (Texas Instrument) show this communication

image3021



BLE device signals are transfered with GFSK modulation GAUSSIAN FREQUENCY SHIFT KEYING, I briefly describe the principal of GFSK modulation to better understand the signal pattern of a BLE device .GFSK is Gaussian FSK which mean it's derivation of FSK modulation by passing signals throgh a Low Pass Filter ,

image304

GFSK  modulation is generated by previously filtering signals before sending it to FSK Modulator
A Gaussian Low Pass Filter get input sigals before sending it to FSK Modulator so the Frequency Resonse Function in more detail is shown here

image306


The reason why GFSK has been adopted for BLE is the fact that it's well behaved in therm of usefull particularity of a Gaussian signal in which the frequency response impulse and time response both are Gaussian, by makin inverse Fourier we get what is shown below 

image3081

you see the result and comparaison of both modulation in Fig.As you see communication signal for a BLE

image310


The data packets transferring profiles[Services+Characteristics+descriptors+...] (known as ATT/GATT) are carried by this Gaussian signal in  Physic Layer ,remember that in physic layer Logic BLE data packets(Services) are encapsulated with additional data , headres and CRC added by other layers  as shown here

image312


This data is provided to physical support but we don't care about it , we should focus on data structure at Application level, at profile level, service retreiving ....etc our job is not to analyse the management of other layers such as Link ,Physic,.. , because each layer is managed separately by its own protocol manager , i wanted to show a full schema of what's going on in a real world just to let you figure out how is a real communication in action!


Logic layer:

In Networking & Communication ,stack of different layer to carry out data is represented as following figure:

image3151




GATT/ATT [Generic Attribute Profile/Attribute Protocol] 
This pair is the two main concept of BT4 transported data packet are named characteristics/services, Profils are a collection of services, a service a collection of Characteristics and a Characteristic a collection of descriptors and a value.BLE communication is based on exchange of atrributes between two devices through services, 

Services:
There services are kind of interfaces in form of data structures including profiles linked to a given function supported by the sensors A service contains one or more Charactersitics and each Charactersitic contains a value and one or more descriptors.Indeed Services are used to break data up into logic entities, and contain specific chunks of data called characteristics. A service can have one or more characteristics, and each service distinguishes itself from other services by means of a unique numeric ID called a UUID, which can be either 16-bit (for officially adopted BLE Services) or 128-bit (for custom services).

image317



Charactersitics :
are generally the properties of the sensors, measured and reported by sensors , a Characteristic has many readable/writtable attributs but a single value, this value represents a real human physical value measured by a device's sensor , when an attribut of Characteristic is writtable it can be used both server or client in order to setup a handler,enable a notification or configuration or even to set a feature on device.Evry attribute has a UUID which is formated as a 16bit or 128 bits unique numbers, 16 bits are reserved and defined by Bluetooth SIG, however 128bits,are custom and free to be used for any purpose! if you're planning to provide a custom BLE device ,use 128 bits values ,  you will see later how to download a custom firmare on a BLE module.The lowest level concept in GATT transactions is the Characteristic, which encapsulates a single data point (though it may contain an array of related data, such as X/Y/Z values from a 3-axis accelerometer, etc.).

Descriptors:
desriptors are informations related to characteristics value for example if this value is a tempreture, descriptors tell us a description of the value Ex:"Temperature"  another descriptor may return us the unity of this value Ex"°C" or "°F"

In Psudo code we can represent a Value as this data structure

struct values{
propertyA;
propertyB;
....
config cfg;
}


image319




UUID:
uuid are unique identifiers for every single Service or Characteristic implemented on the device,as I said they are either Custom or defined by the chip maker/provider , when a Master device or an application is connected to a BLE device , the first thing should be performed is to reteive all services and characteristics of BLE device , informations provided by BLE device at this time includes UUIDs of all services & characteristics, if later Application needs to communicate to a specific characteristic, it will do it by previously provided uuid of that specific Characteristics.Here an example from Nordic SemiConductor the following uuids are defined for measure of "Battery Level" , "Glucose" and "Heart rate" [by a medical device sensor] , "Temperature"

#define    BLE_UUID_BATTERY_LEVEL_STATE_CHAR   0x2A1B
#define    BLE_UUID_GLUCOSE_MEASUREMENT_CHAR   0x2A18
#define    BLE_UUID_HEART_RATE_MEASUREMENT_CHAR   0x2A37
#define    BLE_UUID_TEMPERATURE_MEASUREMENT_CHAR   0x2A1C

Suppose your device is a Medical smart sencor from Nordic SemiConductor ,and your application  is a smartphone application to read and display and probably calculate data As I mentioned 
Once you are connected to your medical device , to read GLUCOSE value or Heart rate value
you perform a READ request to related Service (which in turn linked by its own UUID) and you provide uuid of such a characteristic in your READ request (Refer to programming section). 

The concept of Servuice & Characteristics & Attributes are very similar to USB communication
In USB the channel of communication are based on Interface ,Endpoints … 

One of the most likely feature supported by some BLE devices chipsets is OTA downloading,OTA stands for Over_The_Air , so we can upgrade the BLE device's firmware wirelessly through the Bluetooth connection.generally the update is done by an application installed on a smartdevices (smartphone Android or IOS)

Notice:

You can only scan for Bluetooth LE devices or scan for Classic Bluetooth devices, as described in Bluetooth. You cannot scan for both Bluetooth LE and classic devices at the same time.

 

Development:

When we are planning to support BLE in our products ,since a BLE device is used in a Client-Server environment , before making any decision we have to make things clear , are we going to develop a Client or A Server?,a Master device or a Slave device?
In both case we have  at least one of  3 scenarios as mentioned below:

1) We are a vendor of BLE modules so we are going to design a custom BLE module from scratch.

2) Our device is a BLE device we purchase an already existant module then we customize it by flashing Firmware

3)we purchase an already existant device then we support it on our own products, without any customization.

In the first case as a vendor our development consists of  design a new Hardware ,implements electronic components in full adequation with all communication protocols and compatible with major known OS in market.the vendor generally make thier own Bluetooth stack ex:Toshiba,Broadcom,TI,Microsoft....
In second case we're dealing with a device to be reprogrammed for a specific purpose.In this case we are on Slave mode or Server side ,our job consists of define our interface on the device ,those interface are  profile, Services and Characteristics which expose device functions to end user.The next step will be compiling and downloading those information to device.A compiler is required to customize the firmware , a Downloader is also required to download new firmware so called image to device.since OTA (over-the-Air) feature is available on the majority of BLE devices , even a smartphone could be playing this role to download codes to device. BLE devices generally have two memory location dedicated to firmware images used by Device Boot Loader,one location for current running version of firmware , the second one is for new version image.Once downloader sent new version , boot loader pick it up in the next time device restarts .The best Compiler in the market so far is 
IAR embedded workbench , expensive but very powerful with a rich IDE software allowing you write your firmware in C/C++  .
In the third scenario you are going to develop an application to handle communication with a specific BLE device.in this case developer is in Master mode or Clien side,here you're dealing mostly with a software  rather than a hardware, if your target OS is supposed to support BLE ,so the only task in your charge is how to use BLE API in order to perform Read/Write/Control operation . I've prepared a few basic operation you need to write your code in such a scenario at the end of this document. 
For Master side development there are two well known development kits available,one from 
Texas Instrument CC2541 SensorTag featured by 6 built-in censors :IR temperature Sensor,Humidity Sensor,Pressure Sensor,Accelerometer,Gyroscope,Magnetometer.

If you're planing to have at least of those features on your device this kit could help you to master the feature by explore all services and characteristics exposed by device,it would be a good starting point in your projectbut currently all demo and library provided by the company are only available for IOS , so if ios is not your host OS for your application, stay tuned to future update from Texas Instrument.
Notice TI solution allow you to compile  code for Master side , if your project is about a customized device with your own profile & services
You should purchase a third party compiler such as  
IAR embedded workbench  to write and download codes to firmware. 

The second one is WICED SMART from Broadcom ,also with the same built-in censors as TI,the good point with WICED SMART is they provide not only a kit to develop master side but also an IDE to develop Slave side and download codes on firmware after defining your services and characteristics of a customizable dongle device, this IDE automatically generates codes based on defined profile information you provide through wizard pages, so you don't need any additional compiler to customize your device.Broadcom IDE integrate to Eclipse and their sdk supports C/C++/Java for Android 

Both Broadcom and TI kit support OTA (Over-The Air) upgrade

image328


Basic Steps in programming:

The codes i ‘ve prepared have been developed and tested under Android OS 4.4 using Java language , but if you’re targetting IOS ,Windows or any other OS the basic steps remain the same.I’ve also provided an example of a complet project attached to this document.
To start this section I present you few basic BLE API functions recently added to Android SDK 4.4  

BluetoothGattService : return the list of services included in devices

BluetoothGattCharacteristic :return the list of characteristics included in GATT(service)?

BluetoothGattDescriptor:return the list of descriptors in this characteristics

 

 1)first get a bluetooth adapter

 public static BluetoothAdapter getBluetoothAdapter(Context context) {

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to

        // BluetoothAdapter through BluetoothManager.

        final BluetoothManager bluetoothManager =

                (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);

        if (bluetoothManager == null)

            return null;

        return bluetoothManager.getAdapter();

    }

2) checkout BLE

    public static int getBleStatus(Context context) {

        // Use this check to determine whether BLE is supported on the device.  Then you can

        // selectively disable BLE-related features.

        if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {            return STATUS_BLE_NOT_AVAILABLE;    }

        final BluetoothAdapter adapter = getBluetoothAdapter(context);
        // Checks if Bluetooth is supported on the device.
       if (adapter == null) {
            return STATUS_BLUETOOTH_NOT_AVAILABLE;
        }

 

        if (adapter.isEnabled())

            return STATUS_BLUETOOTH_DISABLED;

        return STATUS_BLE_ENABLED;

    }

 

you can also enable BT on your device using :
 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);


                 

Then for proceesing here is the step you should perform:

1)Starting a device discovery /scan as below

 

given an adapter use API startLeScan to start discovery process something like that: 

 

 private void scanLeDevice(final boolean enable) {

        if (enable) {

            // Stops scanning after a pre-defined scan period.

            mHandler.postDelayed(new Runnable() {

                @Override

                public void run() {

                    mScanning = false;

                    mBluetoothAdapter.stopLeScan(mLeScanCallback);

                    invalidateOptionsMenu();

                }

            }, SCAN_PERIOD);

 

            mScanning = true;

            mBluetoothAdapter.startLeScan(mLeScanCallback);

        } else {

            mScanning = false;

            mBluetoothAdapter.stopLeScan(mLeScanCallback);

        }

        

    }

                 

                 as you see there is a callback which is request answer back from your device, there you generaly retreive information back from BLE device 

                 

                 // Device scan callback.

    private BluetoothAdapter.LeScanCallback mLeScanCallback =

            new BluetoothAdapter.LeScanCallback() {

 

        @Override

        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {

            runOnUiThread(new Runnable() {

                @Override

                public void run() {

                    mLeDeviceListAdapter.addDevice(device);

                    mLeDeviceListAdapter.notifyDataSetChanged();

                }

            });

        }

    };

                 

                 As you see this callback bring to you an object of BluetoothDevice class which inturn store whatever you need to know about all discovered devices including the one you want to connect to

                 BluetoothDevice object gives you " Name + Address" ,from the list of discovered deviced you select the one you're interesting to then 

                 the next step is to forward these two parameters (its name and address) to another activity through extra values in Intent like that:

                  

                  final Intent intent = new Intent(this, DeviceControlActivity.class);

        intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());

        intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());

                                  

                                  now it's the time of connection , from this new activity , 

                                  you're gonna to use ServiceConnection API to start a service which is in charge of connection

                                  ServiceConnection

                                  

                 

                  // Code to manage Service lifecycle.

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

 

        @Override

        public void onServiceConnected(ComponentName componentName, IBinder service) {

            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();

            if (!mBluetoothLeService.initialize()) {

                Log.e(TAG, "Unable to initialize Bluetooth");

                finish();

            }

            // Automatically connects to the device upon successful start-up initialization.

            mBluetoothLeService.connect(mDeviceAddress);

        }

 

        @Override

        public void onServiceDisconnected(ComponentName componentName) {

            mBluetoothLeService = null;

        }

    };

                 

         then using mBluetoothLeService.getSupportedGattServices() we get a list of all services within the selected device

         mBluetoothLeService is an instance of BluetoothLeService which manage connection , states, read/write operations....

        when a device founf wde can call connectGatt API by passing a callback in which we get all information of a service like that:

                 device.connectGatt(this, false, mGattCallback); 

                 in mGattCallback we perform onCharacteristicRead+....

                 

                 

                 private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

        @Override

        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

            String intentAction;

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                intentAction = ACTION_GATT_CONNECTED;

                mConnectionState = STATE_CONNECTED;

                broadcastUpdate(intentAction);

                Log.i(TAG, "Connected to GATT server.");

                // Attempts to discover services after successful connection.

                Log.i(TAG, "Attempting to start service discovery:" +

                        mBluetoothGatt.discoverServices());

 

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                intentAction = ACTION_GATT_DISCONNECTED;

                mConnectionState = STATE_DISCONNECTED;

                Log.i(TAG, "Disconnected from GATT server.");

                broadcastUpdate(intentAction);

            }

        }

 

        @Override

        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);

            } else {

                Log.w(TAG, "onServicesDiscovered received: " + status);

            }

        }

 

        @Override

        public void onCharacteristicRead(BluetoothGatt gatt,

                                         BluetoothGattCharacteristic characteristic,

                                         int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);

            }

        }

 

        @Override

        public void onCharacteristicChanged(BluetoothGatt gatt,

                                            BluetoothGattCharacteristic characteristic) {

            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);

        }

    };


Khosrov Boloorian – 2014

REFERENCES:

https://www.bluetooth.org/

http://www.ti.com/

http://www.broadcom.com/products/wiced/smart/

https://developer.android.com

 © Xosrov 2016