====== IoT8: BLE Communication with characteristics =====
This scenario presents how to create the Bluetooth Low Energy server device and corresponding client device. The server can be the sensor device which responds to the client with the results of the measurements. This can also be the output device, which we can control writing the data to. The client connects to a server and reads the data. This scenario presents the use of the concept of services and characteristics.
===== Prerequisites =====
It is necessary to understand the principles of the Bluetooth Low Energy protocol with concepts of services, characteristics and descriptors. We will use in this scenario the knowledge of the advertising process so making the [[en:iot-open:practical:hardware:sut:esp32:IoT_7]] exercise is recommended.
===== Suggested Readings and Knowledge Resources =====
* [[en:iot-open:introductiontoembeddedprogramming2:cppfundamentals]]
* [[en:iot-open:hardware2:esp32|]]
* [[en:iot-open:practical:hardware:sut:esp32|]]
===== Hands-on Lab Scenario =====
This scenario is intended to be implemented using two BLE laboratory nodes. One of them is a server, while the second is a client. Here we will present the simplest implementation to be extended in further scenarios.
==== Task to be implemented ====
**Task 1.** Implement a program that operates as the BLE server which advertises itself and allows us to connect to.
\\
**Task 2.** Implement a client device, to read the exemplary data from a server.
==== Start ====
You can use the beacon and simple client programs from [[en:iot-open:practical:hardware:sut:esp32:IoT_7]] as the starting point.
==== Steps ====
We will present the lab in a few steps. We begin with a simple program which advertises the device with a single service containing a single characteristic. It allows us to establish a connection with a client and, if successfully connected, responds with simple text data. The program returns automatically to the advertisement procedure after disconnecting.
=== Step 1 ===
Let's begin with a simple program which advertises a single service. The code should start with including Arduino and BLE libraries.
#include
#include "BLEDevice.h"
#include "BLEUtils.h"
#include "BLEServer.h"
We need variables to hold the class pointers for advertising, the server instance, service, and characteristics.
BLEAdvertising *pAdvertising; //class for the advertising data
BLEServer *pServer; //class for the BLE Server device
BLEService *pService; //class for the BLE Service in the Server
BLECharacteristic *pCharacteristic; //class for the characteristic
We will also need two boolean variables to control the restarting of the advertising. In case of establishing the connection from the remote client, the server device stops advertising, so it will not be searchable anymore. If we lose the connection with the client we need to restart advertising.
bool deviceConnected = false;
bool advStarted = true;
Any service or characteristic is identified with a unique UUID. If you use the standard service, like eg. Health Thermometer or Binary Sensor Service you can use a 16-bit UUID defined by Bluetooth SIG in the document ((https://www.bluetooth.com/specifications/assigned-numbers/)). The same document defines the UUIDs for characteristics.
Example of the standard UUIDs for service and characteristic:
Health Thermometer Service - 0x1809
Temperature Measurement Characteristic - 0x2A1C
While none of the standard UUIDs fits your device you need to define your own UUID. It must be 128-bit long and can be randomly generated with the tool available on the website https://www.uuidgenerator.net/((https://www.uuidgenerator.net/)).
The service UUID and characteristic UUID must differ. Although they can be completely different in many implementations the UUIDs of characteristics grouped under one service differ on one digit.
#define SERVICE_UUID "6e9b7b26-ca96-4774-b056-8ec5b759fd86"
#define CHARACTERISTIC_UUID "6e9b7b27-ca96-4774-b056-8ec5b759fd86"
Before we implement the setup() function, we have to create the callback function executed in case of connection and disconnection events. It allows us to control the advertising process with the deviceConnected flag.
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
The setup() function creates and initialises the BLE device instance with the name "SUT BLE device", and creates the server and sets the callback function. It also creates the service within the server.
// Initialise the BLE device
BLEDevice::init("SUT BLE device");
// Create BLE Server instance
pServer = BLEDevice::createServer();
// Set callback function for handling server events
pServer->setCallbacks(new MyServerCallbacks());
// Create the service in the server
pService = pServer->createService(SERVICE_UUID);
Data for reading or writing is organised using characteristics. In this example, we create one characteristic with reading and writing enabled, and the initial data as the "BLE onboard" text.
// Create the characteristic in the service
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
// Set the initial value of the characteristic.
// We will be able to read it by client
pCharacteristic->setValue("BLE onboard");
In the advertising packet, we can add the service UUID.
// Get the pointer to the advertising object
pAdvertising = BLEDevice::getAdvertising();
// Add the service UUID to the advertising
pAdvertising->addServiceUUID(SERVICE_UUID);
// Enable reading extended information with scan response packet
pAdvertising->setScanResponse(true);
Due to the limited size of the advertisement packet, not all service UUIDs can be broadcast. Even more, service UUID does not have to appear in the advertising frame, but its presence makes it possible to scan nearby devices by their functionality, not by names only.
After preparing all the elements we can close the setup() function by starting the service and beginning advertising.
// Starting the service and advertising process
pService->start();
pAdvertising->start();
In the loop function, we need to handle the restarting of advertising in case of disconnection of the client.
void loop(){
if (!deviceConnected && !advStarted) {
pServer->startAdvertising(); // restart advertising
advStarted = true;
}
if (deviceConnected){
advStarted = false;
}
delay(500);
};
=== Step 2 ===
In this step, we will analyse the behaviour of the client. The client software is much more complex than the server. It is because the server, called also the central device, in many circumstances is a more powerful device than the peripheral. Some parts of the software are implemented as callback functions because they handle reactions on the data coming asynchronously from the server. The diagram presents the algorithm of the client and data coming from the server.
{{ en:iot-open:practical:hardware:sut:esp32:ble_client_char.drawio.svg?500 |The client algorithm}}
=== Step 3 ===
While we have analysed the client's behaviour we can start implementation. Let's begin with the libraries needed.
#include "Arduino.h"
#include "BLEDevice.h"
#include "Adafruit_LiquidCrystal.h"
Next, we define the UUIDs for remote service and a characteristic. Notice they must match the ones defined in the server.
// The remote service we wish to connect to.
#define SERVICE_UUID "6e9b7b26-ca96-4774-b056-8ec5b759fd86"
// The characteristic of the remote service we are interested in.
#define REMOTE_CHARACTERISTIC_UUID "6e9b7b27-ca96-4774-b056-8ec5b759fd86"
Some global variables will be needed for our software.
// Variables
static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;
We need to add and configure the LCD to be able to observe the results.
// LCD display pins and class declaration
#define LCD_RS 2
#define LCD_ENABLE 1
#define LCD_D4 39
#define LCD_D5 40
#define LCD_D6 41
#define LCD_D7 42
static Adafruit_LiquidCrystal lcd(LCD_RS, LCD_ENABLE, LCD_D4, LCD_D5, LCD_D6, LCD_D7);
Two callback functions will be defined. The first callback is for advertising. It is called whenever the advertising frame is received, no matter which device sends it. Inside the callback, we search for the device nearby which presents the service we would like to use. If we find one, we can create the instance of the remote device class and pass the signal to the main program to establish the connection.
// Scan for BLE servers and find the first one that advertises
// the service we are looking for.
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
// We will print the asterix for every device found
lcd.print("*");
// We have found a device, let's see if it contains the service we are looking for.
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(BLEUUID(SERVICE_UUID))) {
// Our device has the service we need. We can stop scanning.
BLEDevice::getScan()->stop();
// Create the instance of remote device
myDevice = new BLEAdvertisedDevice(advertisedDevice);
// Pass information to other part of the program to connect to the device
doConnect = true;
doScan = true;
} // Found our server
} // onResult
}; // MyAdvertisedDeviceCallbacks
The second callback class helps to inform the other parts of the program about the connection close. It will additionally inform us about the current state of the program.
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {
lcd.setCursor(0,0);
lcd.print("Connected ");
}
void onDisconnect(BLEClient* pclient) {
lcd.setCursor(0,0);
lcd.print("Disconnected ");
lcd.setCursor(0,1);
connected = false;
}
};
The setup function initialises the Bluetooth, registers the advertising callback function, and starts the scan to look for nearby devices.
void setup() {
// Initialise the LCD and print the welcome message
lcd.begin(16, 2);
delay(1000);
lcd.setCursor(0,0);
lcd.print("BLE Client ");
// Initialise the Bluetooth
BLEDevice::init("");
// Retrieve the pointer to the scan module
BLEScan* pBLEScan = BLEDevice::getScan();
// Register callback for incoming advertising
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
// Start scan parameters with active scan mode
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
// Print the message on the LCD
lcd.setCursor(0,0);
lcd.print("Scanning ");
lcd.setCursor(0,1);
// Start the scan for 30 seconds
pBLEScan->start(30, false);
}
In the loop() function, we wait for the information that the server with the service UUID we were interested in was found. It is signalled with the use of "doConnect" flag. If it's true we can connect to this server. Once we are connected the "connected" flag is set to be true in the connectToServer() function. We will show this function in a while.
\\
In a loop() function we will periodically read the characteristic value. It is a good practice to check if the characteristic is properly retrieved and readable before reading the value.
void loop() {
if (doConnect == true) {
// Establish the connection to the server
connectToServer();
doConnect = false;
}
if (!connected) {
if(doScan){
// Start scan again after disconnect
BLEDevice::getScan()->start(0);
}
}
if (connected) {
lcd.setCursor(0,1);
// Is the characteristic properly retrieved?
if(pRemoteCharacteristic != nullptr)
// Is the characteristic readable?
if(pRemoteCharacteristic->canRead())
// We can safely read the value
lcd.print(pRemoteCharacteristic->readValue().c_str());
}
delay(1000); // Delay a second between loops.
}
The connection to the server is executed in some steps:
- Creation of the client object.
- Setting the callback class for handling disconnection.
- Connection to the remote device.
- Setting parameters of the connection.
- Getting the reference to the service.
- Getting the reference to the characteristic.
- Informing the main program with the "connected" flag.
bool connectToServer() {
BLEClient* pClient = BLEDevice::createClient();
pClient->setClientCallbacks(new MyClientCallback());
// Connect to the remote BLE Server.
pClient->connect(myDevice);
// Obtain a reference to the service in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(BLEUUID(SERVICE_UUID));
// Obtain a reference to the characteristic of the chosen service.
pRemoteCharacteristic = pRemoteService->getCharacteristic(BLEUUID(REMOTE_CHARACTERISTIC_UUID));
connected = true;
return true;
}
==== Result validation ====
You should be able to observe messages describing the process of searching for the server on the first line of LCD and during scanning asterisks appearing on the second line. After establishing the connection, the characteristic value should appear on the display's second line.
===== FAQ =====
**What types of data can be sent with the characteristics?**: The BLE characteristics can send any value as a single byte or a sequence of bytes. BLE does not interpret the data in characteristic in any way. Interpretation lies on the side of the application.
\\
**What if I need to read or write more data than a single text?**: It is possible to implement many services in one device and add many characteristics to one service. Theoretically, the maximum number of characteristics in one service is 512, but the implementation and the memory available for the BLE library limit it.
\\
**What is the maximum length of the data in the characteristics?**: The maximum length of the data in the characteristics in the BLE specification is 512 bytes.
\\
===== Project information =====
{{:en:iot-open:logo_iot_200_px.png?200|}}\\
This Intellectual Output was implemented under the Erasmus+ KA2.\\
Project IOT-OPEN.EU Reloaded – Education-based strengthening of the European universities, companies and labour force in the global IoT market.\\
Project number: 2022-1-PL01-KA220-HED-000085090.
**__Erasmus+ Disclaimer__**\\
This project has been funded with support from the European Commission. \\
This publication reflects the views of only the author, and the Commission cannot be held responsible for any use that may be made of the information contained therein.
**__Copyright Notice__**\\
This content was created by the IOT-OPEN.EU Reloaded consortium, 2022,2024.\\
The content is Copyrighted and distributed under CC BY-NC [[https://en.wikipedia.org/wiki/Creative_Commons_license|Creative Commons Licence]], free for Non-Commercial use.