1.. _bluetooth_le_host:
2
3LE Host
4#######
5
6The Bluetooth Host implements all the higher-level protocols and
7profiles, and most importantly, provides a high-level API for
8applications. The following diagram depicts the main protocol & profile
9layers of the host.
10
11.. figure:: img/ble_host_layers.png
12   :align: center
13   :alt: Bluetooth Host protocol & profile layers
14
15   Bluetooth Host protocol & profile layers.
16
17Lowest down in the host stack sits a so-called HCI driver, which is
18responsible for abstracting away the details of the HCI transport. It
19provides a basic API for delivering data from the controller to the
20host, and vice-versa.
21
22Perhaps the most important block above the HCI handling is the Generic
23Access Profile (GAP). GAP simplifies Bluetooth LE access by defining
24four distinct roles of BLE usage:
25
26* Connection-oriented roles
27
28  * Peripheral (e.g. a smart sensor, often with a limited user interface)
29
30  * Central (typically a mobile phone or a PC)
31
32* Connection-less roles
33
34  * Broadcaster (sending out BLE advertisements, e.g. a smart beacon)
35
36  * Observer (scanning for BLE advertisements)
37
38Each role comes with its own build-time configuration option:
39:kconfig:option:`CONFIG_BT_PERIPHERAL`, :kconfig:option:`CONFIG_BT_CENTRAL`,
40:kconfig:option:`CONFIG_BT_BROADCASTER` & :kconfig:option:`CONFIG_BT_OBSERVER`. Of the
41connection-oriented roles central implicitly enables observer role, and
42peripheral implicitly enables broadcaster role. Usually the first step
43when creating an application is to decide which roles are needed and go
44from there. Bluetooth Mesh is a slightly special case, requiring at
45least the observer and broadcaster roles, and possibly also the
46Peripheral role. This will be described in more detail in a later
47section.
48
49Peripheral role
50===============
51
52Most Zephyr-based BLE devices will most likely be peripheral-role
53devices. This means that they perform connectable advertising and expose
54one or more GATT services. After registering services using the
55:c:func:`bt_gatt_service_register` API the application will typically
56start connectable advertising using the :c:func:`bt_le_adv_start` API.
57
58There are several peripheral sample applications available in the tree,
59such as :zephyr_file:`samples/bluetooth/peripheral_hr`.
60
61Central role
62============
63
64Central role may not be as common for Zephyr-based devices as peripheral
65role, but it is still a plausible one and equally well supported in
66Zephyr. Rather than accepting connections from other devices a central
67role device will scan for available peripheral device and choose one to
68connect to. Once connected, a central will typically act as a GATT
69client, first performing discovery of available services and then
70accessing one or more supported services.
71
72To initially discover a device to connect to the application will likely
73use the :c:func:`bt_le_scan_start` API, wait for an appropriate device
74to be found (using the scan callback), stop scanning using
75:c:func:`bt_le_scan_stop` and then connect to the device using
76:c:func:`bt_conn_le_create`.
77
78There are some sample applications for the central role available in the
79tree, such as :zephyr_file:`samples/bluetooth/central_hr`.
80
81Observer role
82=============
83
84An observer role device will use the :c:func:`bt_le_scan_start` API to
85scan for device, but it will not connect to any of them. Instead it will
86simply utilize the advertising data of found devices, combining it
87optionally with the received signal strength (RSSI).
88
89Broadcaster role
90================
91
92A broadcaster role device will use the :c:func:`bt_le_adv_start` API to
93advertise specific advertising data, but the type of advertising will be
94non-connectable, i.e. other device will not be able to connect to it.
95
96Connections
97===========
98
99Connection handling and the related APIs can be found in the
100:ref:`Connection Management <bluetooth_connection_mgmt>` section.
101
102Security
103========
104
105To achieve a secure relationship between two Bluetooth devices a process
106called pairing is used. This process can either be triggered implicitly
107through the security properties of GATT services, or explicitly using
108the :c:func:`bt_conn_security` API on a connection object.
109
110To achieve a higher security level, and protect against
111Man-In-The-Middle (MITM) attacks, it is recommended to use some
112out-of-band channel during the pairing. If the devices have a sufficient
113user interface this "channel" is the user itself. The capabilities of
114the device are registered using the :c:func:`bt_conn_auth_cb_register`
115API.  The :c:struct:`bt_conn_auth_cb` struct that's passed to this API has
116a set of optional callbacks that can be used during the pairing - if the
117device lacks some feature the corresponding callback may be set to NULL.
118For example, if the device does not have an input method but does have a
119display, the ``passkey_entry`` and ``passkey_confirm`` callbacks would
120be set to NULL, but the ``passkey_display`` would be set to a callback
121capable of displaying a passkey to the user.
122
123Depending on the local and remote security requirements & capabilities,
124there are four possible security levels that can be reached:
125
126    :c:enumerator:`BT_SECURITY_L1`
127        No encryption and no authentication.
128
129    :c:enumerator:`BT_SECURITY_L2`
130        Encryption but no authentication (no MITM protection).
131
132    :c:enumerator:`BT_SECURITY_L3`
133        Encryption and authentication using the legacy pairing method
134        from Bluetooth 4.0 and 4.1.
135
136    :c:enumerator:`BT_SECURITY_L4`
137        Encryption and authentication using the LE Secure Connections
138        feature available since Bluetooth 4.2.
139
140.. note::
141  Mesh has its own security solution through a process called
142  provisioning. It follows a similar procedure as pairing, but is done
143  using separate mesh-specific APIs.
144
145L2CAP
146=====
147
148L2CAP stands for the Logical Link Control and Adaptation Protocol. It is
149a common layer for all communication over Bluetooth connections, however
150an application comes in direct contact with it only when using it in the
151so-called Connection-oriented Channels (CoC) mode. More information on
152this can be found in the :ref:`L2CAP API section <bt_l2cap>`.
153
154Terminology
155-----------
156
157The definitions are from the Core Specification version 5.4, volume 3, part A
1581.4.
159
160.. list-table::
161  :header-rows: 1
162
163  * - Term
164    - Description
165
166  * - Upper layer
167    - Layer above L2CAP, it exchanges data in form of SDUs. It may be an
168      application or a higher level protocol.
169
170  * - Lower layer
171    - Layer below L2CAP, it exchanges data in form of PDUs (or fragments). It is
172      usually the HCI.
173
174  * - Service Data Unit (SDU)
175    - Packet of data that L2CAP exchanges with the upper layer.
176
177      This term is relevant only in Enhanced Retransmission mode, Streaming
178      mode, Retransmission mode and Flow Control Mode, not in Basic L2CAP mode.
179
180  * - Protocol Data Unit (PDU)
181    - Packet of data containing L2CAP data. PDUs always start with Basic L2CAP
182      header.
183
184      Types of PDUs for LE: :ref:`B-frames <bluetooth_l2cap_b_frame>` and
185      :ref:`K-frames <bluetooth_l2cap_k_frame>`.
186
187      Types of PDUs for BR/EDR: I-frames, S-frames, C-frames and G-frames.
188
189  * - Maximum Transmission Unit (MTU)
190    - Maximum size of an SDU that the upper layer is capable of accepting.
191
192  * - Maximum Payload Size (MPS)
193    - Maximum payload size that the L2CAP layer is capable of accepting.
194
195      In Basic L2CAP mode, the MTU size is equal to MPS. In credit-based
196      channels without segmentation, the MTU is MPS minus 2.
197
198  * - Basic L2CAP header
199    - Present at the beginning of each PDU. It contains two fields, the PDU
200      length and the Channel Identifier (CID).
201
202PDU Types
203---------
204
205.. _bluetooth_l2cap_b_frame:
206
207B-frame: Basic information frame
208^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
209
210PDU used in Basic L2CAP mode. It contains the payload received from the upper
211layer or delivered to the upper layer as its payload.
212
213.. image:: img/l2cap_b_frame.drawio.svg
214  :align: center
215  :width: 45%
216  :alt: Representation of a B-frame PDU. The PDU is split into two rectangles,
217        the first one being the L2CAP header, its size is 4 octets and its made
218        of the PDU length and the channel ID. The second rectangle represents
219        the information payload and its size is less or equal to MPS.
220
221.. _bluetooth_l2cap_k_frame:
222
223K-frame: Credit-based frame
224^^^^^^^^^^^^^^^^^^^^^^^^^^^
225
226PDU used in LE Credit Based Flow Control mode and Enhanced Credit Based Flow
227Control mode. It contains a SDU segment and additional protocol information.
228
229.. image:: img/l2cap_k_frame_1.drawio.svg
230  :width: 45%
231  :alt: Representation of a starting K-frame PDU. The PDU is split into three
232        rectangles, the first one being the L2CAP header, its size is 4 octets
233        and its made of the PDU length and the channel ID. The second rectangle
234        represents the L2CAP SDU length, its size is 2 octets. The third
235        rectangle represents the information payload and its size is less or
236        equal to MPS minus 2 octets. The information payload contains the L2CAP
237        SDU.
238
239.. image:: img/l2cap_k_frame.drawio.svg
240  :align: right
241  :width: 45%
242  :alt: Representation of K-frames PDUs after the starting one. The PDU is split
243        into two rectangles, the first one being the L2CAP header, its size is 4
244        octets and its made of the PDU length and the channel ID. The second
245        rectangle represents the information payload and its size is less or
246        equal to MPS. The information payload contains the L2CAP SDU.
247
248Relevant Kconfig
249----------------
250
251.. list-table::
252  :header-rows: 1
253
254  * - Kconfig symbol
255    - Description
256
257  * - :kconfig:option:`CONFIG_BT_BUF_ACL_RX_SIZE`
258    - Represents the MPS
259
260  * - :kconfig:option:`CONFIG_BT_L2CAP_TX_MTU`
261    - Represents the L2CAP MTU
262
263  * - :kconfig:option:`CONFIG_BT_L2CAP_DYNAMIC_CHANNEL`
264    - Enables LE Credit Based Flow Control and thus the stack may use
265      :ref:`K-frame <bluetooth_l2cap_k_frame>` PDUs
266
267GATT
268====
269
270The Generic Attribute Profile is the most common means of communication
271over LE connections. A more detailed description of this layer and the
272API reference can be found in the
273:ref:`GATT API reference section <bt_gatt>`.
274
275ATT timeout
276-----------
277
278If the peer device does not respond to an ATT request (such as read or write)
279within the ATT timeout, the host will automatically initiate a disconnect. This
280simplifies error handling by reducing rare failure conditions to a common
281disconnection, allowing developers to manage unexpected disconnects without
282special cases for ATT timeouts.
283
284.. image:: img/att_timeout.svg
285  :align: center
286  :alt: ATT timeout
287
288Mesh
289====
290
291Mesh is a little bit special when it comes to the needed GAP roles. By
292default, mesh requires both observer and broadcaster role to be enabled.
293If the optional GATT Proxy feature is desired, then peripheral role
294should also be enabled.
295
296The API reference for mesh can be found in the
297:ref:`Mesh API reference section <bluetooth_mesh>`.
298
299LE Audio
300========
301The LE audio is a set of profiles and services that utilizes GATT and
302Isochronous Channel to provide audio over Bluetooth Low Energy.
303The architecture and API references can be found in
304:ref:`Bluetooth Audio Architecture <bluetooth_le_audio_arch>`.
305
306
307.. _bluetooth-persistent-storage:
308
309Persistent storage
310==================
311
312The Bluetooth host stack uses the settings subsystem to implement
313persistent storage to flash. This requires the presence of a flash
314driver and a designated "storage" partition on flash. A typical set of
315configuration options needed will look something like the following:
316
317  .. code-block:: cfg
318
319    CONFIG_BT_SETTINGS=y
320    CONFIG_FLASH=y
321    CONFIG_FLASH_PAGE_LAYOUT=y
322    CONFIG_FLASH_MAP=y
323    CONFIG_NVS=y
324    CONFIG_SETTINGS=y
325
326Once enabled, it is the responsibility of the application to call
327settings_load() after having initialized Bluetooth (using the
328:c:func:`bt_enable` API).
329