Esp32 Bluetooth Architecture en
Esp32 Bluetooth Architecture en
Bluetooth Architecture
Version 1.2
Espressif Systems
Copyright © 2024
About This Guide
This document introduces the ESP32 Bluetooth® architecture, namely Bluetooth, Classic
Bluetooth, and Bluetooth Low Energy. Note that this user guide is only applicable to ESP-
IDF v5.0 and later.
Release Notes
Certi cation
Download certi cates for Espressif products from https://www.espressif.com/en/
certi cates.
fi
fi
fi
fi
fi
Table of Contents
1. Bluetooth ................................................................................................................................1
1.1. Overview ....................................................................................................................................1
1.1.1. Bluetooth Application Structure ...................................................................................1
1.1.2. Bluetooth Operating Environment ................................................................................2
1.2. Architecture ................................................................................................................................2
1.2.1. Controller ......................................................................................................................2
1.2.2. BLUEDROID .................................................................................................................3
1.2.2.1. Overall Architecture ...............................................................................................3
1.2.2.2. OS-Related Adaptation .........................................................................................5
1.2.3. Bluedroid Directory Introduction...................................................................................5
2. Classic Bluetooth ...................................................................................................................7
2.1. Overview ....................................................................................................................................7
2.2. Pro les and Protocols ................................................................................................................8
2.2.1. L2CAP ...........................................................................................................................8
2.2.2. SDP ...............................................................................................................................8
2.2.3. GAP...............................................................................................................................8
2.2.4. A2DP and AVRCP .........................................................................................................9
3. Bluetooth Low Energy .........................................................................................................12
3.1. GAP ..........................................................................................................................................12
3.1.1. Overview .....................................................................................................................12
3.1.2. Status Transitions Among GAP Roles ........................................................................12
3.1.3. BLE Broadcast Procedure ..........................................................................................13
3.1.3.1. Broadcast Using a Public Address ....................................................................13
3.1.3.2. Broadcast Using a Resolvable Address .............................................................13
3.1.3.3. Broadcast Using a Static Random Address ......................................................14
3.1.4. BLE Modes .................................................................................................................16
3.1.4.1. Connectable Scannable Undirected Mode ........................................................16
3.1.4.2. High Duty Cycle Directed Mode and Connectable Low Duty Cycle Directed
Mode .........................................................................................................................................16
3.1.4.3. Scannable Undirected Mode .............................................................................16
3.1.4.4. Non-Connectable Undirected Mode ..................................................................17
3.1.5. BLE Broadcast Filtering Policy ...................................................................................17
3.1.6. BLE Scanning Procedure............................................................................................17
fi
3.1.7. BLE GAP Implementation Mechanism .......................................................................18
3.2. GATT ........................................................................................................................................18
3.2.1. ATT ..............................................................................................................................18
3.2.2. GATT Pro le ................................................................................................................20
3.2.3. Add Gatt Services in ESP32 IDF Environment ...........................................................22
3.2.4. Discover a Peer Device’s Services in ESP32 IDF (GATT Client) .................................23
3.3. SMP .........................................................................................................................................24
3.3.1. Overview .....................................................................................................................24
3.3.2. Safety Management Controller ...................................................................................25
3.3.2.1.BLE Encryption ....................................................................................................25
3.3.2.2.BLE Bonding ........................................................................................................26
3.3.3. The Implementation of SMP .......................................................................................27
fi
1. Bluetooth
1. Bluetooth
This chapter describes the basic Bluetooth architecture of ESP32.
1.1. Overview
1.1.1. Bluetooth Application Structure
Bluetooth is a wireless technology standard for exchanging data over short distances, with
advantages including robustness, low power consumption, and low cost. The Bluetooth
system can be divided into two different categories: Classic Bluetooth and Bluetooth Low
Energy (BLE). ESP32 supports dual-mode Bluetooth, meaning that both Classic Bluetooth
and Bluetooth LE are supported by ESP32.
The Bluetooth protocol stack can be split into two parts: a “controller stack” and a “host
stack”. The controller stack contains the PHY, Baseband, Link Controller, Link Manager,
Device Manager, HCI, and other modules, and is used for the hardware interface
management and link management. The host stack contains L2CAP, SMP, SDP, ATT, GATT,
GAP, and various pro les, and functions as an interface to the application layer, thus
facilitating the application layer to access the Bluetooth system. The Bluetooth Host can be
implemented on the same device as the Controller, or on different devices. Both
approaches are supported by ESP32. Figure 1-1 describes some typical application
structures:
ESP32
PC
Bluedroid Linux/Android
IO
SD
RT/
UA
VHCI
PC
Bluetooth
Test Tool(BQB)
Controller UART
1/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
1. Bluetooth
the Controller are implemented on the same device (i.e., the ESP32 chip), eliminating
the need for an extra PC or other host devices running the Bluetooth Host.
• Scenario 2: The ESP32 system is used only as a Bluetooth Controller, and an extra
device running the Bluetooth Host is required (such as a Linux PC running BlueZ or
an Android device running BLUEDROID, etc). In this scenario, Controller and Host are
implemented on different devices, which is quite similar to the case of mobile phones,
PADs or PCs.
• Scenario 3: This scenario is similar to Scenario 2. The difference lies in that, in the
BQB controller test (or other certi cations), ESP32 can be tested by connecting it to
the test tools, with the UART being enabled as the IO interface.
1.2. Architecture
1.2.1. Controller
The Bluetooth Controller of ESP32 supports both the Classic BT and Bluetooth LE (V4.2).
The Controller has integrated a variety of functions, including H4 protocol, HCI, Link
Manager, Link Controller, Device Manager, and HW Interface. These functions are provided
to the developers in the form of libraries, while some APIs that can access the Controller
are also provided. For details, see API Reference.
2/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
1. Bluetooth
Figure 1-2. The Architecture of Classic BT & Bluetooth LE Controller (from the SIG BT CORE 4.2)
1.2.2. BLUEDROID
3/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
1. Bluetooth
Espressif Bluedroid
Coarse Architecture
V1.1
USER
TASK
USER APP
PROCEDURE
BTC
TASK
L2C
BAT SPP 6
BLE BLU … AP … A2D …
TER LIK Low D-
SPP
HID FI … … P …
Y E Pan Chan
BTA_API BLE BT
GAP GAP SDP
PROFILES PROFILES
BTU
TASK
VHCI_API VHCI
Contr
oller
TASK
Controller
H4
HCI
LM/LC
HW Interface
📖 Note:
This diagram mainly describes the hierarchy of the BLUEDROID, rather than details, such as the HCI
TASK. The detailed information about each layer can be seen below.
4/28
Espressif Systems Submit Documentation Feedback 2024.04
1. Bluetooth
As shown in the gure above, the BLUEDROID can be divided into two layers mainly, which
are the BTU layer and the BTC layer (except for HCI). Each layer is responsible for its
corresponding tasks. More speci cally, the BTU layer is mainly responsible for processing
the bottom layer protocol stacks of the Bluetooth Host, including L2CAP, GATT/ATT, SMP,
GAP, and other pro les. The BTU layer provides an interface pre xed with "bta". The BTC
layer is mainly responsible for providing a supported interface, pre xed with “esp”, to the
application layer, processing GATT-based pro les and handling miscellaneous tasks. All the
APIs are located in the ESP_API layer. Developers should use the Bluetooth APIs pre xed
with “esp".
The gure above does not describe the HCI layer in detail. In fact, the HCI layer has one
task that processes the downward and upward data.
The design logic behind this architecture is to minimize the load on the User Tasks and
streamline the Bluetooth structure by handing over the Bluetooth-related tasks to the BTC
layer.
Due to legacy reasons and actual demand, some of the Classic Bluetooth pro les, such as
RFCOMM and A2DP, as well as other lower layer protocols are implemented in the BTU
layer, while some of the protocols that are related to procedural controls, or require the
ESP-API, are implemented in the BTC layer.
Some of the pro les and lower layer functions of the Bluetooth Low Energy, such as the
6LowPan or Dynamic L2CAP Channel, will be implemented in the BTU layer, thus providing
the application layer with the ESP-API through the BTC.
1.2.2.2. OS-Related Adaptation
Some interfaces that are related to the system in BLUEDROID require OSI adaptation. The
functions involved include Timer (Alarm), Task (Thread), Future Await/Ready
(Semphore), and Allocator(malloc/free).
The FreeRTOS Timer in BLUEDROID has been packaged as an Alarm, and is used to start
the timer which triggers certain tasks.
In BLUEDROID, the POSIX Thread has been replaced with the FreeRTOS tasks, and uses
the FreeRTOS Queue to trigger tasks (i.e., wake up).
In BLUEDROID, the Future Await/Ready function is used to achieve Blocking. Future Lock
packages the xSemphoreTake of FreeRTOS as the future_await function, and packages
the xSemphoreGive as the future_ready function. It is worth noting that the future_await
and future_ready functions cannot be called in the same task context.
In BLUEDROID, malloc/free in the standard library is packaged as the Allocator function
that reserves (mallocs) or frees memory.
5/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
1. Bluetooth
The detailed description of each sub-folder can be found in the table below:
Sub-folder Description
The API directory, which includes all the APIs (except for those that are
api
related to the Controller)
The Bluetooth adaptation layer, which is suitable for the interface of some
bta
bottom layer protocols in the host.
Related to the device control of the Controller, e.g., the basic set of HCI
device
CMD controller processes.
Codes that are not directly related to the Bluetooth, but are still usable, e.g.,
external
the SBC codec software programs.
6/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
2. Classic Bluetooth
2. Classic Bluetooth
This chapter introduces the Classic Bluetooth in ESP-IDF.
2.1. Overview
The Bluetooth Host Stack in ESP-IDF originates from BLUEDROID and has been adapted
to embedded applications. At the lower layer, the Bluetooth Host Stack communicates with
the Bluetooth dual-mode Controller via the virtual HCI interface. At the upper layer, the
Bluetooth Host stack provides the pro les and APIs for stack management to the user
applications.
Protocols de ne the message formats and the procedures aimed to accomplish speci c
functions, e.g., data transportation, link control, security service, and service information
exchange. Bluetooth pro les, on the other hand, de ne the functions and features required
of each layer in the Bluetooth system, from PHY to L2CAP, and any other protocols outside
the core speci cation.
Below are the Classic BT pro les and protocols currently supported in the Host Stack.
• Pro les: GAP, A2DP, AVRCP, SPP, HFP
• Protocols: L2CAP, SDP, AVDTP, AVCTP, RFCOMM
The protocol model is depicted in Figure 2-1.
7/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
fi
fi
fi
2. Classic Bluetooth
In Figure 2-1, L2CAP and SDP are necessary in a minimal Host Stack for Classic Bluetooth.
AVDTP, AV/C, and AVCTP are outside the core speci cation and are used by speci c
pro les.
• Retransmission Mode
• Streaming Mode
For ACL-U logical links, the supported operation modes are the Basic L2CAP Mode,
Enhanced Retransmission Mode and Streaming Mode. For other features, the L2CAP
Signaling channel is the supported xed channel, while the Frame Check Sequence (FCS)
is also a supported option.
2.2.2. SDP
The Service Discovery Protocol (SDP) provides a means for applications to discover
services offered by a peer Bluetooth device, as well as to determine the characteristics of
the available services. The SDP involves communication between an SDP server and an
SDP client. A server maintains a list of service records that describe the characteristics of
services associated with the server. A client can retrieve this information by issuing an SDP
request.
2.2.3. GAP
The Generic Access Pro le (GAP) provides a description of the modes and procedures in
device discoverability, connection and security.
8/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
fi
2. Classic Bluetooth
For the time being, only a limited number of GAP APIs are provided to the Classic
Bluetooth Host Stack. An application can make use of these APIs, as if they were a
"passive device" which could be discovered by and connected to peer Bluetooth devices.
More GAP APIs for Classic Bluetooth are coming up next. API for link policy settings will be
provided at a later stage.
📖 Note:
As indicated in Figure 2-2, the A2DP is dependent upon the GAP, as well as the Generic
Audio/Video Distribution Pro le (GAVDP), which de nes procedures required to set up an
audio/video streaming.
Two roles are de ned in A2DP: Source (SRC) and Sink (SNK). SRC functions as a source of
a digital audio stream and SNK functions as a sink of a digital audio stream delivered from
the SRC.
Two roles de ned in AVRCP are Controller (CT) and Target (TG). CT is a device that initiates
a transaction by sending a command frame to a target. Examples of CT include personal
9/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
2. Classic Bluetooth
computers, PDAs, and mobile phones. TG is a device that receives a command frame and
accordingly generates a response frame. Audio players or headphones are examples of
TG.
In the current A2DP solution, the only audio codec supported is SBC, which is mandated in
the A2DP speci cation. A2DP Version 1.4 and AVDTP Version 1.3 are implemented.
Audio/Video Distribution Transport Protocol (AVDTP) de nes the binary transactions
between Bluetooth devices for a streaming set-up, and media streaming for audio and
video using L2CAP. As the basic transport protocol for A2DP, AVDTP is built upon the
L2CAP layer and consists of a signaling entity for negotiating streaming parameters and a
transport entity that handles the streaming itself.
The basic service of AVDTP transport capabilities is mandated by the A2DP speci cation.
According to the con guration of current service capabilities, Media Transport and Media
Codec in the basic service capability are provided.
AVRCP de nes the requirements necessary for the support of the Audio/Video remote
control use case.
The commands used in AVRCP fall into three main categories. The rst one is the AV/C
Digital Interface Command Set, which is applied only on certain occasions and is
transported with the Audio/Video Control Transport Protocol (AVCTP). Browsing
commands are included in the second category, which provides browsing functionality over
another transport channel called the AVCTP browsing channel. The third category, Cover
Art Commands, is used to transmit images associated with media items, and is provided
through the protocol de ned in the Bluetooth Basic Imaging Pro le (BIP) with the OBEX
protocol.
Two sets of AV/C commands are used in AVRCP. The rst one includes the PASS
THROUGH command, UNIT INFO command, and SUBUNIT INFO command, which are
de ned in the AV/C speci cation. The second set includes AVRCP-speci c AV/C
commands which are de ned as a Bluetooth SIG Vendor-Dependent extension. AV/C
commands are sent over the AVCTP control channel. A PASS THROUGH command is
used to transfer a user operation via a button from the Controller to the panel subunit,
which provides a simple and common mechanism to control the target. For example, the
operation IDs in PASS THROUGH include common instructions such as Play, Pause, Stop,
Volume Up, and Volume down.
AVRCP arranges the A/V functions in four categories to ensure interoperability:
• Player/Recorder
• Monitor/Ampli er
• Tuner
• Menu
In the current implementation, AVRCP Version 1.5 and AVCTP Version 1.4 are provided.
The default con guration for AVRCP-supported features is Category 2: Monitor/Ampli er.
Also, APIs for sending PASS THROUGH commands are provided.
10/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
2. Classic Bluetooth
A2DP and AVRCP are often used together. In the current solution, the lower Host stack
implements AVDTP and the AVCTP logic, while providing interfaces for A2DP and AVRCP
independently. In the upper layer of the stack, however, the two pro les combined make up
the "AV" module. The BTA layer, for example, provides a uni ed "AV" interface, and in BTC
layer there is a state machine that handles the events for both pro les. The APIs, however,
are provided separately for A2DP and AVRCP.
11/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
3. Bluetooth Low Energy
3.1. GAP
3.1.1. Overview
This section mainly introduces the implementation and use of the Bluetooth LE GAP APIs in
ESP32. The GAP (the Generic Access Pro le) de nes the discovery process, device
management and the establishment of device connection between Bluetooth LE devices.
The Bluetooth LE GAP is implemented in the form of API calls and Event returns. The
processing result of API calls in the protocol stack is returned by Events. When a peer
device initiates a request, the status of that peer device is also returned by an Event.
There are four GAP roles de ned for a Bluetooth LE device:
• Broadcaster: A broadcaster is a device that sends advertising packets, so it can be
discovered by the observers. This device can only advertise, but cannot be
connected.
• Observer: An observer is a device that scans for broadcasters and reports this
information to an application. This device can only send scan requests, but cannot be
connected.
• Peripheral: A peripheral is a device that advertises by using connectable advertising
packets and becomes a slave once it gets connected.
• Central: A central is a device that initiates connections to peripherals and becomes a
master once a physical link is established.
Scanning
Connection
12/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
3. Bluetooth Low Energy
API LLM
API LLM
API API
calls
esp_ble_gap_set_device_name
calls
esp_ble_gap_set_device_name
calls
esp_ble_gap_config_adv_data
sends config adv data HCI
command to LL layer
returns
esp_gap_ble_adv_data_set_co
mplete_evt
calls
esp_ble_gap_start_advertising
to start broadcast;
sets the own_addr_type
parameter to
ble_addr_type_public
sends start adv HCI command
to LL layer
advertising event
returns
esp_gap_ble_adv_start_comple advertising event
te_evt
esp_gap_ble_scan_result_evt
13/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fl
fi
fl
3. Bluetooth Low Energy
⚠ Note:
When a resolvable address is used for broadcasting, the broadcast only starts after the
esp_ble_gap_config_local_privacy event is returned, and the own_addr_type type, a broadcast
parameter, must be set to BLE_ADDR_TYPE_RPA_PUBLIC or BLE_ADDR_TYPE_RPA_RANDOM.
To use the BLE_ADDR_TYPE_RPA_RANDOM address type, it is necessary to rst set a Static Random Address
through the API esp_ble_gap_set_rand_addr. If BLE_ADDR_TYPE_RPA_PUBLIC is used, setting the address
is not required.
For BLE_ADDR_TYPE_RPA_RANDOM, if there is no matching entry in the resolving list, Static Random Address
is used instead.
14/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
3. Bluetooth Low Energy
Advertiser Scanner
API LLM
API LLM
API API
calls
esp_ble_gap_set_device_name
calls
esp_ble_gap_set_rand_addr sends set rand address HCI
command to LL layer
calls
esp_ble_gap_start_advertising
to start broadcast;
sets the own_addr_type
parameter to
ble_addr_type_random
sends start adv HCI command
to LL layer
advertising event
15/28
Espressif Systems Submit Documentation Feedback 2024.04
fl
3. Bluetooth Low Energy
Payload
Payload
The IP directed broadcasts can only be discovered by and connected to the designated
devices.
As shown in the table above, the High Duty Cycle Directed Broadcast packet includes 6
bytes of the broadcasting device’s address and 6 bytes of the receiving device’s address. In
this mode, the broadcast parameters adv_int_min and adv_int_max are ignored.
In the Connectable Low Duty Cycle Directed mode, the broadcast parameters adv_int_min
and adv_int_max must be greater than 100 ms (0xA0).
📖 Note:
16/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
3. Bluetooth Low Energy
Payload
Payload
17/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
3. Bluetooth Low Energy
⚠ Notice:
When the value of the duration is 0, the device will be scanned permanently without timeout.
3.2. GATT
3.2.1. ATT
The data inside the Bluetooth LE architecture exists in the form of Attributes that consist of
four basic elements:
• Attribute Handle: an Attribute Handle can help us locate any Attribute, which is similar
to using an address to locate data in the memory. For example, the Handle of the rst
attribute is 0x0001 and the second one is 0x0002, and so on, up to 0xFFFF.
• Attribute Type: Each data set exposes a certain type of information, such as
temperature, transmit power, battery level and so on. The type of the data that is
exposed is called attribute type. Given the different possible types of data that can be
exposed, a 16-bit or 128-bit number, also known as UUID, is used to identify the type
of the attribute. For example, UUID 0x2A09 is for Battery Level and UUID 0x2A6E is
for Temperature.
• Attribute value: the attribute value is the key information of each attribute, while the
other three elements (handle, type and permission) are added so the attribute value
can be better understood. The length of the attribute value for different attribute types
can be xed or variable. For example, the length of the attribute value in Battery Level
is only 1 byte, which is enough to cover all the possible values of a Battery Level
attribute, i.e. 0-100, while the attribute length of a BLE-enabled pass-through module
is variable.
• Attribute Permission: Each attribute contains information that can only be read or
written. To facilitate these restrictions upon access, every attribute has its attribute
permissions. The party that owns the data can control the read/write access of its
local data through attribute permissions.
0x0001 - - -
0x0002 - - -
18/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
3. Bluetooth Low Energy
……… - - -
0xFFFE - - -
0xFFFF - - -
The device that holds the data (i.e. the attributes) is de ned as a server, and the device that
obtains the data from the server is de ned as a client. The common operations between a
server and a client are listed below:
• A client sends data to a server by writing data into the server. Both the Write
Request and Write Command can be used to write an attribute value. However, a
Write Response is only prompted when a Write Request is used.
• A server sends data to a client by sending an Indication or Noti cation to the
client. The only difference between an Indication and a Noti cation is that a
Con rmation is prompted only when an Indication is used. This is similar to the
difference between a Write Request and a Write Command.
• A client can also obtain data from the server by initiating a Read Request.
⚠ Notice:
For detailed information regarding the common operations between a server and a client, please refer to
Core_V4.2, Vol3. Part F, Chapter 3.4 “Attribute Protocol PDUs”.
The common operations between a server and a client are achieved by using ATT PDU.
Each device can specify its supported MTU, which is the maximum length of an ATT
message. In ESP32 IDF, the MTU can be 23 - 517 bytes, and the total length of an attribute
value is not limited.
19/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
3. Bluetooth Low Energy
If the length of the user’s packet is greater than (MTU-3), a Prepare Write Request is
required to write data. Similarly, if the length of the packet is greater than (MTU-1), a Read
Blob Request is required to read the remaining data.
⚠ *Notice:
The difference between the MTU and the LE Packet Length of a single physical packet should be
highlighted here. The MTU, which is about the Host ATT layer in this case, determines whether all the
“data to be sent” can t into a single ATT Request and also whether a Prepare Write Request is required
to send the data. Meanwhile, the LE Packet Length, which is about the PHY layer, determines whether
the packet needs to be divided and transmitted in several packages. For example, if (MTU + 4) is greater
than the LE Packet Length, this ATT packet needs to be divided and transmitted in more than one
physical packets. On the contrary, if (MTU+4) is shorter than the LE Packet Length, only one physical
packet is required to send the whole ATT packet. The reason we add 4 bytes to the MTU is because a 4-
byte L2CAP header will be added during the transmission.
20/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
fi
3. Bluetooth Low Energy
the handles between two declarations compose a complete characteristic. The write
and read properties are also included in a declaration.
• Characteristic Value: a characteristic value is the main part of a characteristic, which
carries the most important information of a characteristic.
• Descriptor: Descriptors can further describe characteristics (e.g. providing
con guration information) and a characteristic can have multiple or no descriptors.
In BLE, the GAP groups similar functions together in the form of Services. For example, all
of the characteristics and behaviors related to the battery can be de ned as a Battery
Service; all of the characteristics and behaviors related to the heart rate can be de ned as a
Heart Rate Service; and all of the characteristics and behaviors related to the weight scale
can be de ned as a Weight Scale Service.
A Service typically includes one or more characteristics and each characteristic includes
zero or many descriptors. Users can select the required services based on their own
application requirements, and form the nal application.
A completed service de nition table is shown below:
0x0001 Service 1
0x0004 Descriptor 1
0x0007 Descriptor 2
0x0008 Descriptor 3
0x0009 Service 2
……… ………
21/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
fi
3. Bluetooth Low Energy
⚠ *Notices:
For other de nitions of services, characteristics and descriptors, please refer to:
• Core_V4.2, Vol3., Part G, Chapter 3 “Service Interoperability Requirements”
• https://www.bluetooth.com/zh-cn/speci cations/gatt
⚠ *Notice:
The interface and examples of adding services and characteristics manually are still reserved in ESP IDF.
For more information, please refer to the gatt_service example.
In this context, adding services and characteristics with an attribute table is introduced in
ESP32 IDF Release 2.0. Users can add new services and characteristics by simply entering
them in an attribute table and, then, calling esp_ble_gatts_create_attr_tab. Additionally,
a lower layer response is also supported in this case, meaning the lower layer is able to
respond to some requests and identify errors automatically, so the users can focus on
receiving and sending data.
In this way, users can port pro les to the ESP32 platform from other platforms easily,
without the need to implement the Bluetooth LE speci cations all over again.
⚠ *Notice:
We recommend that users add services and characteristics through the attribute table, which is much
easier, less error-prone, and supports low-layer responses. For details, please refer to the
gatt_server_service_table examples.
The structure of an attribute table de nes all of the parameters that require initialization to
describe an attribute through esp_gatts_attr_db_t:
Parameter Description
Indicates that the length of UUID is 16 bits, 32 bits or 128 bits. Since the
uint16_t uuid_length attribute UUID is transmitted by pointers, the length of the UUID has to
be speci ed.
22/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
fi
fi
3. Bluetooth Low Energy
Parameter Description
Indicates the pointer of the UUID of the current attribute. Users can read
uint8_t *uuid_p a certain length of the UUID value, based on the length information
speci ed in the uuid_lenght parameter.
Indicates the write and read permissions of the current attribute. This
parameter is bitwise-operated. Each bit represents a speci c write and
uint16_t perm read permission. Operating a certain bit can change the write and read
permission of the corresponding attribute. For example, PERM_READ |
PERM_WRITE means an attribute that can be read and written.
Indicates the maximum length of the current attribute value. The protocol
stack allocates memory to the attribute, based on this parameter. If the
length of the attribute value that a peer device has written exceeds the
uint16_t max_length
maximum length de ned in this parameter, a write error is returned,
indicating that the error is due to the length of the write operation
exceeding the maximum length of the data.
Indicates the actual length of the current attribute. For example, in case
the maximum length of the attribute is 512 bits and a peer device wants
to write “0x1122” into this attribute, we will set the current length of the
uint16_t length
attribute to 2. When a peer device, then, reads this attribute, we can
obtain the actual length of this attribute from the memory, sending only
the part with the actual values, instead of the whole 512 bits.
Indicates the initialized values of the current attribute value. Since the
format of this parameter is a pointer, the actual length of this parameter
uint8_t *value
should be obtained rst by the length parameter, in order to get the
correct value from the pointer.
23/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
3. Bluetooth Low Energy
• Given that the handles of a GATT Service lie in the range of 0x0001~0x0005,
0x0003, for example, should be followed by the corresponding descriptor. All
descriptors, then, should be sought from 0x0004 onwards.
- 0x0004 represents the descriptor of the Client Characteristic Con guration
- 0x0005 does not have any information at the moment, and could be a handle
reserved for this service.
• At this point, the discovery procedure of GATT Service is complete.
3.3. SMP
This chapter mainly introduces the implementation and use of the ESP32 Bluetooth LE
SMP (Security Management Protocol).
3.3.1. Overview
The SMP-related APIs have been packaged in ESP32 BLE’s GAP module.
The SMP generates encryption keys and identity keys, de nes a convenient protocol for
pairing and key distribution, and allows the other layers in the protocol stack to connect
and exchange data with other devices safely. A connection in the data link layer and certain
security standards are required in this process. The GAP SMP allows two devices
encrypting their connection in the data link layer by setting such security levels as those in
the SMP chapter of the Bluetooth Core Speci cation version. Before introducing the
implementation of the GAP SMP, we should clarify the following concepts:
• Pairing indicates that two devices have agreed to establish a connection with certain
security levels.
• Bonding indicates that at least one device has sent some kind of indication or
security information, which could be an LTK, CSRK, or IRK, to another device for
future connections. If these two devices can bond with each other, the key
distribution occurs after the pairing, otherwise, no bonding information will be
exchanged. Bonding is not a prerequisite for pairing. However, during pairing the two
devices exchange their characteristics to determine whether the peer device is open
for bonding. If neither of these two devices is open for bonding, no security
information of the peer devices should be stored.
• Authentication is de ned as a method to verify that the device you are connecting
with is indeed the device it claims to be, ensuring it is not a third-party attacker.
However, a de-authentication link does not necessarily mean this link is not secure at
all. When the key for the link encryption has the security attributes that have been
con rmed by both devices, these two devices are considered authenticated. When
STK is used for the authentication, a keyword is generated during the pairing. For
devices with input/output and OOB functions, all the keys generated and exchanged
have the MITM attributes (PIN/larger OOB keys are used, which enforces security). If
Just Works is used, all the keys generated and exchanged have the No MITM
attributes.
24/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fi
fi
fi
3. Bluetooth Low Energy
3.3.2.1.BLE Encryption
The encryption of a Bluetooth LE device can be achieved with two basic methods:
• When no bonding is established between two Bluetooth LE devices, these devices
are encrypted through the pairing procedure, while bonding (or not bonding) is
determined according to the speci c pairing information of these Bluetooth LE
devices.
• Two bonded devices: initiate the encryption through the bonding procedure. When
two devices have already bonded, encryption is initiated with one device resorting to
the original bonding process.
How a master initiates an encryption request in Just Works mode can be seen in the ow
chart below:
Master Slave
esp_ble_set_encryption
smp_pair_req
esp_gap_ble_sec_req_evt
esp_ble_gap_security_rsp
smp_pair_rsp
Encrypt
esp_gap_ble_auth_cmpl_evt
esp_gap_ble_auth_cmpl_evt
25/28
Espressif Systems Submit Documentation Feedback 2024.04
fi
fi
fl
3. Bluetooth Low Energy
How a master initiates an encryption request in Passkey Notify mode can be seen in the
ow chart below:
Master Slave
esp_ble_set_encryption
smp_pair_req
esp_gap_ble_sec_req_evt
esp_ble_gap_security_rsp
esp_gap_ble_passkey_notify_evt
displays the passkey to the user,
smp_pair_rsp esp_ble_passkey_reply
the peer device should enter this
sends the passkey to the
key and sent it to the SMP stack
SMP stack which is
displayed in the peer device
Encrypt
esp_gap_ble_auth_cmpl_evt esp_gap_ble_auth_cmpl_evt
3.3.2.2.BLE Bonding
The bonding between two Bluetooth LE devices is achieved by calling a GAP API.
According to the description in the Bluetooth Core Speci cation, the purpose of bonding is
that two Bluetooth LE devices, which have been encrypted by SMP, are able to use the
same keys to encrypt a link when they reconnect with each other, thus simplifying the
reconnection process. These two Bluetooth LE devices exchange encryption keys during
their pairing, and store them for long-term use. The bonding process can be seen in the
ow chart below:
26/28
Espressif Systems Submit Documentation Feedback 2024.04
fl
fl
fi
3. Bluetooth Low Energy
Master Slave
llc_start_enc_cmd
llc_ltk_req_evt
llc_ltk_req_reply_cmd
Encrypt
llc_enc_change_evt
llc_enc_change_evt
esp_gap_ble_auth_cmpl_evt
esp_gap_ble_auth_cmpl_evt
⚠ Notice:
The bonding process must be initiated by a master device during the connection.
27/28
Espressif Systems Submit Documentation Feedback 2024.04
Disclaimer and Copyright Notice
Information in this document, including URL references, is subject to change without
notice.
THIS DOCUMENT IS PROVIDED AS IS WITH NO WARRANTIES WHATSOEVER,
INCLUDING ANY WARRANTY OF MERCHANTABILITY, NON-INFRINGEMENT, FITNESS
FOR ANY PARTICULAR PURPOSE, OR ANY WARRANTY OTHERWISE ARISING OUT
OF ANY PROPOSAL, SPECIFICATION OR SAMPLE.
All liability, including liability for infringement of any proprietary rights, relating to use of
information in this document is disclaimed. No licenses express or implied, by estoppel or
otherwise, to any intellectual property rights are granted herein.
The Wi-Fi Alliance Member logo is a trademark of the Wi-Fi Alliance. The Bluetooth logo is
a registered trademark of Bluetooth SIG.
All trade names, trademarks and registered trademarks mentioned in this document are
Espressif IoT Team
property of their respective owners, and are hereby acknowledged.
www.espressif.com Copyright © 2024 Espressif Inc. All rights reserved.