Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
en:iot-open:practical:hardware:sut:esp32:iot_7 [2024/04/14 09:32] ktokarzen:iot-open:practical:hardware:sut:esp32:iot_7 [2024/05/02 11:11] (current) – [IOT7: BLE Beacon] ktokarz
Line 1: Line 1:
-====== IoT_7Setting-up BLE Beacon =====+====== IoT7: BLE Beacon =====
 This scenario presents how to create the Bluetooth Low Energy beacon device which periodically broadcasts a small amount of information, and the client device which can receive packets sent by the beacon. Beacons are usually used for sending useful information (eg. the web address of the owner, a link to the page with tourist information). In some cases, they simply send the identification number recognised by a dedicated mobile application allowing the users to localise themselves. This scenario presents how to create the Bluetooth Low Energy beacon device which periodically broadcasts a small amount of information, and the client device which can receive packets sent by the beacon. Beacons are usually used for sending useful information (eg. the web address of the owner, a link to the page with tourist information). In some cases, they simply send the identification number recognised by a dedicated mobile application allowing the users to localise themselves.
  
Line 20: Line 20:
 This scenario is intended to be implemented using two laboratory nodes. One node will work as the beacon device, while the second will receive the beacon's packets and display information on the LCD. This scenario is intended to be implemented using two laboratory nodes. One node will work as the beacon device, while the second will receive the beacon's packets and display information on the LCD.
 ==== Task to be implemented ==== ==== Task to be implemented ====
-**Task 1** Implement a program that operates as the BLE beacon which advertises itself with the link to the SUT website. This can be done with the Eddystone beacon format.+**Task 1** Implement a program that operates as the BLE beacon which advertises itself with the link to the website. This can be done with the Eddystone beacon format.
 **Task 2** Implement the receiver of advertising frames broadcasted by the beacon device capable of displaying information on the LCD screen. **Task 2** Implement the receiver of advertising frames broadcasted by the beacon device capable of displaying information on the LCD screen.
  
 ==== Start ==== ==== Start ====
-We need to implement both software to be able to observe the results.  +We need to implement both parts of the software to be able to observe the results (steps 1-4). **The Task 1** we implement in steps 1 and 2. **The Task 2** we implement in steps 3 and 4. At the end, we return to **Task 1** with step 5
- +
  
 ==== Steps ==== ==== Steps ====
Line 34: Line 32:
 Let's begin with including Arduino and BLE libraries. Let's begin with including Arduino and BLE libraries.
 <code c> <code c>
-#include <Arduino.h>+#include "Arduino.h"
 #include "BLEDevice.h" #include "BLEDevice.h"
 #include "BLEAdvertising.h" #include "BLEAdvertising.h"
 </code> </code>
 We need one variable only which holds the pointer to the advertising class. We need one variable only which holds the pointer to the advertising class.
-<code>+<code c>
 BLEAdvertising *pAdvertising; BLEAdvertising *pAdvertising;
 </code> </code>
 The setup function creates and initialises the BLE device instance with a chosen name. If we add our text in the BLEDevice::init() function we will see this text as the device name in the advertising frame. It will also appear as the value of the Device Name characteristic in the Generic Access service. If we don't define the name it will use the default "ESP32". While the device is ready we can get the pointer to its class using it to configure the advertising packet. After configuration, we can start the advertising process. The setup function creates and initialises the BLE device instance with a chosen name. If we add our text in the BLEDevice::init() function we will see this text as the device name in the advertising frame. It will also appear as the value of the Device Name characteristic in the Generic Access service. If we don't define the name it will use the default "ESP32". While the device is ready we can get the pointer to its class using it to configure the advertising packet. After configuration, we can start the advertising process.
-<code>+<code c>
 void setup(){ void setup(){
 BLEDevice::init("SUT BLE device"); BLEDevice::init("SUT BLE device");
Line 55: Line 53:
  
 The loop function can remain empty or call the delay() function. The loop function can remain empty or call the delay() function.
-<code>+<code c>
 void loop(){ void loop(){
  delay(5000);  delay(5000);
Line 69: Line 67:
 | 0x02 | 0x0A        | Tx Power Level                        | 0x09           | | 0x02 | 0x0A        | Tx Power Level                        | 0x09           |
  
-Except for the text information as the device name, it is possible to send other data such as the web address which directs us to additional information. There are some formats defined for use in beacon devices. One of them is Eddystone invented by Google. It is used in the advertisement frames for simplification of the URL encoding. It requires the presence of the field (code 0x03) which shows the list of 16-bit UUIDs with 0xAAFE value, and the service data field (code 0x16) compatible with Eddystone format. These additional fields are shown in the table below. +Except for the text information as the device name, it is possible to send other data such as the web address which directs us to additional information. There are some formats defined for use in beacon devices. One of them is Eddystone invented by Google. It is used in the advertisement frames for simplification of the URL encoding. It requires the presence of the field "List of 16-bit UUIDs" (code 0x03) which shows the UUIDs of the Eddystobe service (0xAAFE value), and the service data field (code 0x16) compatible with Eddystone format. These additional fields are shown in the table below. 
-^ Field length  ^ Field code  ^ Field type                             Default value  ^+^ Field length  ^ Field code  ^ Field type                             Value  ^
 | 3             | 0x03        | Complete list of 16-bit service UUIDs  | 0xAAFE         | | 3             | 0x03        | Complete list of 16-bit service UUIDs  | 0xAAFE         |
 | 14            | 0x16        | Service data                           | Eddystone format               | | 14            | 0x16        | Service data                           | Eddystone format               |
-The Eddystone field starts with service UUID (0xAAFE), next specifies the content type (0x10 for URL), then the transmitting power in [dBm], and then the compressed URL. To compress URLs some default prefixes and suffixes were defined as non-ASCII characters. They are presented in the tables below.+The Eddystone field starts with service UUID (0xAAFE), next specifies the content type (0x10 for URL), then the transmitting power in [dBm], and then the compressed URL.  
 +<note> 
 +The UUID of Eddystone appears twice. Once as the element of the list of available services, the second time as the identifier of the service field. 
 +</note> 
 +To compress URLs some default prefixes and suffixes were defined as non-ASCII characters. They are presented in the tables below.
  
 ^ Decimal ^ Hex ^ Prefix ^ ^ Decimal ^ Hex ^ Prefix ^
Line 102: Line 104:
 </code> </code>
 In the setup() function, we need to fill in the empty spaces with details of the advertising packet. In the setup() function, we need to fill in the empty spaces with details of the advertising packet.
-<code>+<code c>
 eddystone_content[0]  = 0x02;   //Length of FLags field eddystone_content[0]  = 0x02;   //Length of FLags field
 eddystone_content[1]  = 0x01;   //Flags ID eddystone_content[1]  = 0x01;   //Flags ID
Line 124: Line 126:
 </note> </note>
 The created payload can be used as the payload data of the advertising packet. The created payload can be used as the payload data of the advertising packet.
-<code>+<code c>
 oAdvertisementData.addData(eddystone_content); oAdvertisementData.addData(eddystone_content);
 pAdvertising->setAdvertisementData(oAdvertisementData); pAdvertising->setAdvertisementData(oAdvertisementData);
Line 130: Line 132:
  
 === Step 3 === === Step 3 ===
-It is the time to receive the advertising packet. We will do it with another device.+It is the time to receive the advertising packet. We will do it with another device starting with including the libraries required. 
 +<code c> 
 +#include "Arduino.h" 
 +#include "BLEDevice.h" 
 +#include "Adafruit_LiquidCrystal.h" 
 +</code> 
 +There can be a lot of BLE devices in the range of our receiver. We should find the one that we are interested in so we define the UUID of the Eddystone service. 
 +<code c> 
 +#define SERVICE_UUID "feaa" 
 +</code> 
 + 
 +Our program will use objects of two classes and some variables: 
 +<code c> 
 +static BLEAdvertisedDevice* myDevice; // Class for remote BLE device 
 +BLEScan* pBLEScan;                    // Class for local scanner device 
 + 
 +uint8_t * advPayload;     // Pointer to the payload of incoming adv packet 
 +char eddystoneUrl[20];    // Buffer for text to display 
 +String advName;           // Remote device name 
 +int advLength;            // Length of payload of adv. packet 
 +int advIndex;             // Index of the byte we proceed 
 +int advEddystoneLength;   // Length of the Eddystone field 
 +int i; 
 +</code> 
 + 
 +The received information will be displayed on the LCD, so we need to configure it (similar to the scenario EMB5) 
 +<code c> 
 +// 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); 
 +</code> 
 + 
 +The setup function initialises the display and the Bluetooth, sets up and starts the scanning process. An important step is registering the callback function. The callback function is called every time the scanner receives the advertising frame.  
 +<code c> 
 +void setup() { 
 +  // Initialise LCD 
 +  lcd.begin(16, 2); 
 +  delay(1000); 
 +  lcd.print("BLE CLient"); 
 +   
 +  // Initialise the Bluetooth 
 +  BLEDevice::init(""); 
 +   
 +  // Retrieve the pointer to the scan module 
 +  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); 
 +   
 +  // Start the scan for 5 seconds 
 +  pBLEScan->start(5, false); 
 +
 +</code> 
 + 
 +In the loop function, we restart scanning every 5 seconds with 1 second delay. 
 +<note> 
 +The start function of the BLEScan class is blocking, so it stops program execution for the time of scanning. 
 +</note> 
 +<code c> 
 +void loop() { 
 +  delay(1000); 
 +  // Repeat scanning 
 +  pBLEScan->start(5,false); 
 +}  
 +</code> 
 +=== Step 4 === 
 +The callback function checks if the device which sent the advertising frame implements the Eddystone service. This is how we filter out all other BLE devices available in the range. 
 +<note> 
 +if we have more than one Eddystone device nearby we would have to implement additional filtering. 
 +</note> 
 + 
 +After a successful search for a device with Eddystone service, we can display its name and proceed with displaying the content of the Eddystone field. Because the code is quite complex we present the whole callback function below. Notice that we decode chosen compressed fields only (prefix = 0x00, suffice = 0x07). You would need to decode other values for compatibility with the Eddystone format. 
 +<code c> 
 +class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { 
 +  void onResult(BLEAdvertisedDevice advertisedDevice) { 
 +    // 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))) { 
 +     
 +      // Display the name of the remote device 
 +      lcd.setCursor(0,0); 
 +      lcd.print(advertisedDevice.getName().c_str()); 
 +     
 +      // Get the length of the payload and the pointer to it 
 +      advLength = advertisedDevice.getPayloadLength(); 
 +      advPayload = advertisedDevice.getPayload(); 
 +     
 +      // Search for the Eddystone field (field ID = 0x16) 
 +      advIndex = 0; 
 +      while (advIndex<=advLength) 
 +      { 
 +        if (advPayload[advIndex+1]==0x16) { 
 +         
 +          // Eddystone field found, get the length of it 
 +          advEddystoneLength = advPayload[advIndex]; 
 +     
 +          // Display the Eddystone field 
 +          lcd.setCursor(0,1); 
 + 
 +          // Prefix decoding 
 +          if (advPayload[advIndex+6]==0x00) { 
 +            lcd.print("http://www."); 
 +          } 
 + 
 +          // ULR name 
 +          for(i=0; i<advEddystoneLength-7; i++){ 
 +            eddystoneUrl[i]=(char)advPayload[advIndex+7+i]; 
 +          } 
 +          eddystoneUrl[i]=(char)NULL; // Terminate the string 
 +          lcd.print(eddystoneUrl); 
 + 
 +          // Suffix decoding 
 +          if (advPayload[advIndex+advEddystoneLength]==0x07){ 
 +            lcd.print(".com"); 
 +          } 
 +        } // Eddystone field found 
 +        advIndex ++; 
 +      } // Search for Eddystone 
 +    } // Found our server 
 +  } // onResult 
 +}; // MyAdvertisedDeviceCallbacks 
 +</code> 
 +Additional filtering of remote devices can be done with their names. We can add in the "MyAdvertisedDeviceCallbacks()" function the comparison of the remote device name with the constant string. It should be done if the Eddystone service was found. 
 +<code c> 
 +String name; 
 +name = advertisedDevice.getName().c_str(); 
 +if (name.equals("SUT BLE device")) 
 +  { 
 +    // here the internal code of the MyAdvertisedDeviceCallbacks() 
 +  } 
 +</code>
  
 === Step 5 === === Step 5 ===
 Let's return to the beacon device. The advertisement frame is quite short so normally additional information is sent upon Scan Request with Scan Response frame. It can contain the device name which can differ from the name we specified in step 1 (in the case of normal operation we can read it as the value of the Generic Access Service). To specify different names in advertising frame and service characteristics we can use the setScanResponseData() function from BLEAdvertising class. Let's return to the beacon device. The advertisement frame is quite short so normally additional information is sent upon Scan Request with Scan Response frame. It can contain the device name which can differ from the name we specified in step 1 (in the case of normal operation we can read it as the value of the Generic Access Service). To specify different names in advertising frame and service characteristics we can use the setScanResponseData() function from BLEAdvertising class.
-<code>+<code c>
 oScanResponseData.setName("SUT Beacon"); oScanResponseData.setName("SUT Beacon");
 pAdvertising->setScanResponseData(oScanResponseData); pAdvertising->setScanResponseData(oScanResponseData);
Line 140: Line 281:
  
 ==== Result validation ==== ==== Result validation ====
-You should be able to observe the content of the advertising frame in nRF Connect or a similar application. You should be able to navigate to the URL sent in the advertising.+After the implementation of steps 1-4, you should be able to see the name of the beacon device in the first line of LCD and the URL from the Eddystone field in the second line of LCD. Implementation of step 5 should result in a change of the device name.
  
 ==== Further work ==== ==== Further work ====
-You can try the example software for the beacon device which is available in the examples at the path: +You can try to implement the beacon device compatible with iBeacon. The description can be found on the website ((https://www.silabs.com/whitepapers/developing-beacons-with-bluetooth-low-energy-technology)).
-<code> +
-C:\..\.platformio\packages\framework-arduinoespressif32\libraries\BLE\examples\BLE_EddystoneURL_Beacon +
-</code> +
-It is more complex but enables automatic determination of packet length depending on the URL provided. +
-\\ +
-You can also try to implement the beacon device compatible with iBeacon. The description can be found on the website ((https://www.silabs.com/whitepapers/developing-beacons-with-bluetooth-low-energy-technology)).+
  
 ===== FAQ ===== ===== FAQ =====
en/iot-open/practical/hardware/sut/esp32/iot_7.1713087158.txt.gz · Last modified: 2024/04/14 09:32 by ktokarz
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0