connectivity/bluetooth/bluetooth-le-host.html · connectivity/bluetooth/bluetooth-le-host.rst 공식 원문 ↗

Zephyr 3.7.0 · Connectivity · Bluetooth

Bluetooth LE Host

Application API에서 HCI 경계까지 Bluetooth LE Host의 역할과 data unit을 읽습니다.

Official pathconnectivity/bluetooth/bluetooth-le-host.html
Source fileconnectivity/bluetooth/bluetooth-le-host.rst
Source versionZephyr 3.7.0
TranslationFull · reviewed

Part 1

요약·해설

GAP의 Peripheral·Central·Observer·Broadcaster 역할, pairing 보안 단계, L2CAP SDU/PDU와 B/K-frame, GATT·Mesh·LE Audio·persistent storage를 공식 도식과 표로 정리합니다.

GAP Roles

Peripheral · Central · Observer · Broadcaster

Security

L1 · L2 · L3 · L4

L2CAP

SDU · PDU · MTU · MPS

Part 2

접을 수 있는 영어 원문 전체

영어 원문 전체 펼치기
원문 SHA-256 9F7EDABA7BFC29F57179D98FA03683D2135386F03BCB3342B816C8535D7B9D0C
.. _bluetooth_le_host:

LE Host
#######

The Bluetooth Host implements all the higher-level protocols and
profiles, and most importantly, provides a high-level API for
applications. The following diagram depicts the main protocol & profile
layers of the host.

.. figure:: ../../../../connectivity/bluetooth/img/ble_host_layers.png
   :align: center
   :alt: Bluetooth Host protocol & profile layers

   Bluetooth Host protocol & profile layers.

Lowest down in the host stack sits a so-called HCI driver, which is
responsible for abstracting away the details of the HCI transport. It
provides a basic API for delivering data from the controller to the
host, and vice-versa.

Perhaps the most important block above the HCI handling is the Generic
Access Profile (GAP). GAP simplifies Bluetooth LE access by defining
four distinct roles of BLE usage:

* Connection-oriented roles

  * Peripheral (e.g. a smart sensor, often with a limited user interface)

  * Central (typically a mobile phone or a PC)

* Connection-less roles

  * Broadcaster (sending out BLE advertisements, e.g. a smart beacon)

  * Observer (scanning for BLE advertisements)

Each role comes with its own build-time configuration option:
:kconfig:option:`CONFIG_BT_PERIPHERAL`, :kconfig:option:`CONFIG_BT_CENTRAL`,
:kconfig:option:`CONFIG_BT_BROADCASTER` & :kconfig:option:`CONFIG_BT_OBSERVER`. Of the
connection-oriented roles central implicitly enables observer role, and
peripheral implicitly enables broadcaster role. Usually the first step
when creating an application is to decide which roles are needed and go
from there. Bluetooth Mesh is a slightly special case, requiring at
least the observer and broadcaster roles, and possibly also the
Peripheral role. This will be described in more detail in a later
section.

Peripheral role
===============

Most Zephyr-based BLE devices will most likely be peripheral-role
devices. This means that they perform connectable advertising and expose
one or more GATT services. After registering services using the
:c:func:`bt_gatt_service_register` API the application will typically
start connectable advertising using the :c:func:`bt_le_adv_start` API.

There are several peripheral sample applications available in the tree,
such as :zephyr_file:`samples/bluetooth/peripheral_hr`.

Central role
============

Central role may not be as common for Zephyr-based devices as peripheral
role, but it is still a plausible one and equally well supported in
Zephyr. Rather than accepting connections from other devices a central
role device will scan for available peripheral device and choose one to
connect to. Once connected, a central will typically act as a GATT
client, first performing discovery of available services and then
accessing one or more supported services.

To initially discover a device to connect to the application will likely
use the :c:func:`bt_le_scan_start` API, wait for an appropriate device
to be found (using the scan callback), stop scanning using
:c:func:`bt_le_scan_stop` and then connect to the device using
:c:func:`bt_conn_le_create`. If the central wants to keep
automatically reconnecting to the peripheral it should use the
:c:func:`bt_le_set_auto_conn` API.

There are some sample applications for the central role available in the
tree, such as :zephyr_file:`samples/bluetooth/central_hr`.

Observer role
=============

An observer role device will use the :c:func:`bt_le_scan_start` API to
scan for device, but it will not connect to any of them. Instead it will
simply utilize the advertising data of found devices, combining it
optionally with the received signal strength (RSSI).

Broadcaster role
================

A broadcaster role device will use the :c:func:`bt_le_adv_start` API to
advertise specific advertising data, but the type of advertising will be
non-connectable, i.e. other device will not be able to connect to it.

Connections
===========

Connection handling and the related APIs can be found in the
:ref:`Connection Management <bluetooth_connection_mgmt>` section.

Security
========

To achieve a secure relationship between two Bluetooth devices a process
called pairing is used. This process can either be triggered implicitly
through the security properties of GATT services, or explicitly using
the :c:func:`bt_conn_security` API on a connection object.

To achieve a higher security level, and protect against
Man-In-The-Middle (MITM) attacks, it is recommended to use some
out-of-band channel during the pairing. If the devices have a sufficient
user interface this "channel" is the user itself. The capabilities of
the device are registered using the :c:func:`bt_conn_auth_cb_register`
API.  The :c:struct:`bt_conn_auth_cb` struct that's passed to this API has
a set of optional callbacks that can be used during the pairing - if the
device lacks some feature the corresponding callback may be set to NULL.
For example, if the device does not have an input method but does have a
display, the ``passkey_entry`` and ``passkey_confirm`` callbacks would
be set to NULL, but the ``passkey_display`` would be set to a callback
capable of displaying a passkey to the user.

Depending on the local and remote security requirements & capabilities,
there are four possible security levels that can be reached:

    :c:enumerator:`BT_SECURITY_L1`
        No encryption and no authentication.

    :c:enumerator:`BT_SECURITY_L2`
        Encryption but no authentication (no MITM protection).

    :c:enumerator:`BT_SECURITY_L3`
        Encryption and authentication using the legacy pairing method
        from Bluetooth 4.0 and 4.1.

    :c:enumerator:`BT_SECURITY_L4`
        Encryption and authentication using the LE Secure Connections
        feature available since Bluetooth 4.2.

.. note::
  Mesh has its own security solution through a process called
  provisioning. It follows a similar procedure as pairing, but is done
  using separate mesh-specific APIs.

L2CAP
=====

L2CAP stands for the Logical Link Control and Adaptation Protocol. It is
a common layer for all communication over Bluetooth connections, however
an application comes in direct contact with it only when using it in the
so-called Connection-oriented Channels (CoC) mode. More information on
this can be found in the :ref:`L2CAP API section <bt_l2cap>`.

Terminology
-----------

The definitions are from the Core Specification version 5.4, volume 3, part A
1.4.

.. list-table::
  :header-rows: 1

  * - Term
    - Description

  * - Upper layer
    - Layer above L2CAP, it exchanges data in form of SDUs. It may be an
      application or a higher level protocol.

  * - Lower layer
    - Layer below L2CAP, it exchanges data in form of PDUs (or fragments). It is
      usually the HCI.

  * - Service Data Unit (SDU)
    - Packet of data that L2CAP exchanges with the upper layer.

      This term is relevant only in Enhanced Retransmission mode, Streaming
      mode, Retransmission mode and Flow Control Mode, not in Basic L2CAP mode.

  * - Protocol Data Unit (PDU)
    - Packet of data containing L2CAP data. PDUs always start with Basic L2CAP
      header.

      Types of PDUs for LE: :ref:`B-frames <bluetooth_l2cap_b_frame>` and
      :ref:`K-frames <bluetooth_l2cap_k_frame>`.

      Types of PDUs for BR/EDR: I-frames, S-frames, C-frames and G-frames.

  * - Maximum Transmission Unit (MTU)
    - Maximum size of an SDU that the upper layer is capable of accepting.

  * - Maximum Payload Size (MPS)
    - Maximum payload size that the L2CAP layer is capable of accepting.

      In Basic L2CAP mode, the MTU size is equal to MPS. In credit-based
      channels without segmentation, the MTU is MPS minus 2.

  * - Basic L2CAP header
    - Present at the beginning of each PDU. It contains two fields, the PDU
      length and the Channel Identifier (CID).

PDU Types
---------

.. _bluetooth_l2cap_b_frame:

B-frame: Basic information frame
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

PDU used in Basic L2CAP mode. It contains the payload received from the upper
layer or delivered to the upper layer as its payload.

.. image:: ../../../../connectivity/bluetooth/img/l2cap_b_frame.drawio.svg
  :align: center
  :width: 45%
  :alt: Representation of a B-frame PDU. The PDU is split into two rectangles,
        the first one being the L2CAP header, its size is 4 octets and its made
        of the PDU length and the channel ID. The second rectangle represents
        the information payload and its size is less or equal to MPS.

.. _bluetooth_l2cap_k_frame:

K-frame: Credit-based frame
^^^^^^^^^^^^^^^^^^^^^^^^^^^

PDU used in LE Credit Based Flow Control mode and Enhanced Credit Based Flow
Control mode. It contains a SDU segment and additional protocol information.

.. image:: ../../../../connectivity/bluetooth/img/l2cap_k_frame_1.drawio.svg
  :width: 45%
  :alt: Representation of a starting K-frame PDU. The PDU is split into three
        rectangles, the first one being the L2CAP header, its size is 4 octets
        and its made of the PDU length and the channel ID. The second rectangle
        represents the L2CAP SDU length, its size is 2 octets. The third
        rectangle represents the information payload and its size is less or
        equal to MPS minus 2 octets. The information payload contains the L2CAP
        SDU.

.. image:: ../../../../connectivity/bluetooth/img/l2cap_k_frame.drawio.svg
  :align: right
  :width: 45%
  :alt: Representation of K-frames PDUs after the starting one. The PDU is split
        into two rectangles, the first one being the L2CAP header, its size is 4
        octets and its made of the PDU length and the channel ID. The second
        rectangle represents the information payload and its size is less or
        equal to MPS. The information payload contains the L2CAP SDU.

Relevant Kconfig
----------------

.. list-table::
  :header-rows: 1

  * - Kconfig symbol
    - Description

  * - :kconfig:option:`CONFIG_BT_BUF_ACL_RX_SIZE`
    - Represents the MPS

  * - :kconfig:option:`CONFIG_BT_L2CAP_TX_MTU`
    - Represents the L2CAP MTU

  * - :kconfig:option:`CONFIG_BT_L2CAP_DYNAMIC_CHANNEL`
    - Enables LE Credit Based Flow Control and thus the stack may use
      :ref:`K-frame <bluetooth_l2cap_k_frame>` PDUs

GATT
====

The Generic Attribute Profile is the most common means of communication
over LE connections. A more detailed description of this layer and the
API reference can be found in the
:ref:`GATT API reference section <bt_gatt>`.

Mesh
====

Mesh is a little bit special when it comes to the needed GAP roles. By
default, mesh requires both observer and broadcaster role to be enabled.
If the optional GATT Proxy feature is desired, then peripheral role
should also be enabled.

The API reference for mesh can be found in the
:ref:`Mesh API reference section <bluetooth_mesh>`.

LE Audio
========
The LE audio is a set of profiles and services that utilizes GATT and
Isochronous Channel to provide audio over Bluetooth Low Energy.
The architecture and API references can be found in
:ref:`Bluetooth Audio Architecture <bluetooth_le_audio_arch>`.


.. _bluetooth-persistent-storage:

Persistent storage
==================

The Bluetooth host stack uses the settings subsystem to implement
persistent storage to flash. This requires the presence of a flash
driver and a designated "storage" partition on flash. A typical set of
configuration options needed will look something like the following:

  .. code-block:: cfg

    CONFIG_BT_SETTINGS=y
    CONFIG_FLASH=y
    CONFIG_FLASH_PAGE_LAYOUT=y
    CONFIG_FLASH_MAP=y
    CONFIG_NVS=y
    CONFIG_SETTINGS=y

Once enabled, it is the responsibility of the application to call
settings_load() after having initialized Bluetooth (using the
:c:func:`bt_enable` API).

Part 3

한국어 전문 번역

LE Host

Bluetooth Host는 상위 protocol과 profile을 모두 구현하고, 무엇보다 application에 high-level API를 제공합니다. 다음 그림은 Host의 주요 protocol·profile layer를 보여 줍니다.

Bluetooth Host protocol and profile layers
Bluetooth Host protocol·profile layer.

Host stack의 가장 아래에는 HCI driver가 있습니다. 이 driver는 HCI transport의 구체적인 차이를 숨기고, Controller에서 Host로 또는 Host에서 Controller로 data를 전달하는 기본 API를 제공합니다.

Generic Access Profile과 역할

HCI 처리 위에서 가장 중요한 block 중 하나는 Generic Access Profile(GAP)입니다. GAP은 Bluetooth LE를 사용하는 방식을 네 가지 역할로 나눠 접근을 단순화합니다.

  • Connection-oriented roles
    • Peripheral: smart sensor처럼 보통 user interface가 제한된 장치
    • Central: 일반적으로 mobile phone이나 PC
  • Connection-less roles
    • Broadcaster: smart beacon처럼 BLE advertisement를 내보내는 장치
    • Observer: BLE advertisement를 scan하는 장치

각 역할에는 build-time Kconfig option이 있습니다. Peripheral은 CONFIG_BT_PERIPHERAL, Central은 CONFIG_BT_CENTRAL, Broadcaster는 CONFIG_BT_BROADCASTER, Observer는 CONFIG_BT_OBSERVER입니다. Connection-oriented 역할 중 Central을 켜면 Observer가 암시적으로 활성화되고 Peripheral을 켜면 Broadcaster가 암시적으로 활성화됩니다.

Application을 만들 때는 보통 필요한 역할부터 결정하고 나머지 설계를 이어 갑니다. Bluetooth Mesh는 조금 특수해서 최소한 Observer와 Broadcaster가 필요하고, 경우에 따라 Peripheral도 필요합니다. Mesh 절에서 자세히 설명합니다.

Peripheral role

Zephyr 기반 BLE 장치 대부분은 Peripheral 역할일 가능성이 큽니다. Connectable advertising을 수행하고 GATT service 하나 이상을 노출합니다. bt_gatt_service_register() API로 service를 등록한 뒤 보통 bt_le_adv_start() API로 connectable advertising을 시작합니다.

Peripheral sample은 source tree에 여러 개 있으며 samples/bluetooth/peripheral_hr가 대표적입니다.

Central role

Zephyr 장치에서는 Peripheral보다 흔하지 않을 수 있지만 Central도 충분히 가능한 역할이며 동일하게 지원됩니다. 다른 장치의 connection을 받아들이는 대신 주변 Peripheral을 scan하고 연결할 장치를 선택합니다. 연결한 뒤에는 보통 GATT client로 동작해 먼저 service를 discovery하고 지원 service 하나 이상에 접근합니다.

처음 연결할 장치를 찾을 때는 bt_le_scan_start()로 scan을 시작하고 scan callback에서 적절한 장치를 기다립니다. 장치를 찾으면 bt_le_scan_stop()으로 scan을 멈춘 뒤 bt_conn_le_create()로 연결합니다. Central이 Peripheral에 자동으로 계속 재연결하려면 bt_le_set_auto_conn()을 사용합니다.

Central sample로 samples/bluetooth/central_hr 등이 있습니다.

Observer role

Observer 장치는 bt_le_scan_start()로 장치를 scan하지만 연결하지 않습니다. 발견한 장치의 advertising data를 이용하고, 필요하면 수신 신호 세기 RSSI와 결합합니다.

Broadcaster role

Broadcaster 장치는 bt_le_adv_start()로 특정 advertising data를 내보냅니다. 다만 advertising type은 non-connectable이므로 다른 장치가 Broadcaster에 연결할 수 없습니다.

Connections

Connection 처리와 관련 API는 Bluetooth Connection Management 절에 있습니다.

Security

두 Bluetooth 장치가 안전한 관계를 맺으려면 pairing이라는 과정을 사용합니다. GATT service의 security property 때문에 암시적으로 시작될 수도 있고, connection object에 bt_conn_security() API를 호출해 명시적으로 시작할 수도 있습니다.

더 높은 security level을 얻고 Man-In-The-Middle(MITM) attack을 막으려면 pairing 중 out-of-band channel을 사용하는 것이 좋습니다. 장치에 충분한 user interface가 있으면 사용자가 바로 그 channel입니다. 장치 capability는 bt_conn_auth_cb_register() API로 등록합니다.

bt_conn_auth_cb 구조체에는 pairing 중 사용할 수 있는 optional callback 집합이 있습니다. 장치에 어떤 기능이 없으면 해당 callback을 NULL로 둡니다. 예를 들어 입력 장치는 없고 display만 있다면 passkey_entry와 passkey_confirm은 NULL로 두고, passkey_display에는 사용자에게 passkey를 보여 주는 callback을 설정합니다.

Local·remote 장치의 security requirement와 capability에 따라 다음 네 level 중 하나에 도달합니다.

BT_SECURITY_L1
Encryption과 authentication이 모두 없습니다.
BT_SECURITY_L2
Encryption은 있지만 authentication이 없어 MITM protection이 없습니다.
BT_SECURITY_L3
Bluetooth 4.0·4.1의 legacy pairing method를 사용한 encryption과 authentication입니다.
BT_SECURITY_L4
Bluetooth 4.2부터 제공하는 LE Secure Connections를 사용한 encryption과 authentication입니다.

L2CAP

L2CAP은 Logical Link Control and Adaptation Protocol의 약자입니다. 모든 Bluetooth connection 통신이 공통으로 거치는 layer이지만 application이 직접 접하는 경우는 Connection-oriented Channels(CoC) mode로 사용할 때뿐입니다. 자세한 API는 L2CAP API 절을 봅니다.

Terminology

다음 정의는 Bluetooth Core Specification 5.4, Volume 3, Part A, 1.4를 기준으로 합니다.

TermDescription
Upper layerL2CAP 위의 layer입니다. SDU 형태로 data를 교환하며 application 또는 더 높은 level의 protocol일 수 있습니다.
Lower layerL2CAP 아래의 layer입니다. PDU 또는 PDU fragment 형태로 data를 교환하며 보통 HCI입니다.
Service Data Unit (SDU)L2CAP이 upper layer와 교환하는 data packet입니다. 이 용어는 Enhanced Retransmission, Streaming, Retransmission, Flow Control mode에서만 의미가 있으며 Basic L2CAP mode에는 적용하지 않습니다.
Protocol Data Unit (PDU)L2CAP data를 담는 packet이며 항상 Basic L2CAP header로 시작합니다. LE PDU는 B-frame과 K-frame, BR/EDR PDU는 I-frame·S-frame·C-frame·G-frame입니다.
Maximum Transmission Unit (MTU)Upper layer가 받아들일 수 있는 SDU의 최대 크기입니다.
Maximum Payload Size (MPS)L2CAP layer가 받아들일 수 있는 payload의 최대 크기입니다. Basic L2CAP mode에서는 MTU와 MPS가 같고, segmentation이 없는 credit-based channel에서는 MTU가 MPS보다 2 작습니다.
Basic L2CAP header모든 PDU 앞에 있으며 PDU length와 Channel Identifier(CID) 두 field를 담습니다.

PDU Types

B-frame: Basic information frame

Basic L2CAP mode에서 쓰는 PDU입니다. Upper layer에서 받은 payload 또는 upper layer에 전달할 payload를 그대로 담습니다.

B-frame with a four-octet L2CAP header and an information payload no larger than MPS
B-frame은 4-octet Basic L2CAP header와 MPS 이하의 information payload로 구성됩니다.

K-frame: Credit-based frame

LE Credit Based Flow Control mode와 Enhanced Credit Based Flow Control mode에서 쓰는 PDU입니다. SDU segment와 추가 protocol information을 담습니다.

Starting K-frame with L2CAP header, two-octet SDU length and payload no larger than MPS minus two
첫 K-frame은 4-octet header, 2-octet L2CAP SDU length와 MPS-2 이하의 information payload를 담습니다.
Subsequent K-frame with L2CAP header and payload no larger than MPS
이어지는 K-frame은 4-octet header와 MPS 이하의 SDU segment를 담습니다.

Relevant Kconfig

Kconfig symbolDescription
CONFIG_BT_BUF_ACL_RX_SIZEMPS를 나타냅니다.
CONFIG_BT_L2CAP_TX_MTUL2CAP MTU를 나타냅니다.
CONFIG_BT_L2CAP_DYNAMIC_CHANNELLE Credit Based Flow Control을 활성화하므로 stack이 K-frame PDU를 사용할 수 있습니다.

GATT

Generic Attribute Profile은 LE connection에서 가장 일반적인 통신 수단입니다. Layer의 자세한 설명과 API reference는 GATT API 절에 있습니다.

Mesh

Mesh가 요구하는 GAP role은 조금 특별합니다. 기본적으로 Observer와 Broadcaster를 모두 활성화해야 합니다. Optional GATT Proxy 기능도 필요하면 Peripheral까지 활성화해야 합니다. Mesh API reference는 Bluetooth Mesh API 절에 있습니다.

LE Audio

LE Audio는 GATT와 Isochronous Channel을 이용해 Bluetooth Low Energy로 audio를 제공하는 profile·service 집합입니다. Architecture와 API reference는 Bluetooth Audio Architecture 절에 있습니다.

Persistent storage

Bluetooth Host stack은 settings subsystem으로 flash persistent storage를 구현합니다. Flash driver가 있어야 하고 flash에 `storage` partition이 지정되어 있어야 합니다. 일반적으로 필요한 configuration은 다음과 같습니다.

CONFIG_BT_SETTINGS=y
CONFIG_FLASH=y
CONFIG_FLASH_PAGE_LAYOUT=y
CONFIG_FLASH_MAP=y
CONFIG_NVS=y
CONFIG_SETTINGS=y

활성화한 뒤에는 application이 bt_enable()로 Bluetooth를 초기화한 다음 settings_load()를 호출해야 합니다.

Source

출처

영어 원문에는 문단, 문서 지시문, 표, 코드, 코드 심벌, 경로를 그대로 보존했습니다.