2  The big picture of BLE: roles, advertising, connections

In this chapter and the next, we sort out how BLE works before writing code. The terms that appear here (GAP, advertising, connection interval, ATT, GATT, CCCD…) show up directly in NimBLE’s API names.

2.1 BLE and Bluetooth Classic

Bluetooth has two major variants.

Bluetooth Classic (BR/EDR) Bluetooth Low Energy (BLE)
Main uses Wireless earphones, speakers (audio streaming) Sensors, wearables, beacons, smart locks
Communication style Stays connected and streams large amounts of data Exchanges short data, occasionally
Power consumption High Low (months to years on a coin cell is possible)
Channels 79 × 1 MHz wide 40 × 2 MHz wide

Both use the same 2.4 GHz band, but they are not compatible. The ESP32-C3 supports BLE only.

2.2 The protocol stack

BLE consists of a protocol stack made of layers with different roles.

flowchart TB
  subgraph Host["Host (NimBLE in ESP-IDF)"]
    direction TB
    GAP["GAP<br/>discover, connect, roles"]
    GATT["GATT<br/>services and characteristics"]
    SM["SM (Security Manager)<br/>pairing, keys"]
    ATT["ATT<br/>reading/writing attributes"]
    L2CAP["L2CAP<br/>multiplexing, segmentation"]
    GATT --> ATT --> L2CAP
    SM --> L2CAP
    GAP -.-> L2CAP
  end
  HCI["HCI (boundary between host and controller)"]
  subgraph Ctrl["Controller (binary provided by Espressif)"]
    direction TB
    LL["Link Layer<br/>advertising, connections, retransmission, encryption"]
    PHY["PHY<br/>2.4 GHz radio"]
    LL --> PHY
  end
  L2CAP --> HCI --> LL

Layer Role API touched in this hands-on
PHY Radio transmission/reception (1 Mbps basic; BLE 5 adds 2 Mbps and Coded) —
Link Layer (LL) Advertising, maintaining connections, retransmitting packets, encryption (AES-CCM) —
HCI The rules for commands and events between host and controller —
L2CAP Carries data of upper protocols (ATT, SM) multiplexed over one link —
ATT Protocol for reading/writing “attributes” Error codes BLE_ATT_ERR_*
GATT Defines the “service / characteristic” structure on top of ATT ble_gatts_*, struct ble_gatt_svc_def
SM Pairing; generation, distribution and storage of keys ble_hs_cfg.sm_*, ble_sm_inject_io()
GAP Device discovery, connections, roles, connection parameters ble_gap_*, BLE_GAP_EVENT_*

The bottom layers (PHY, LL) are called the controller, and the upper ones (L2CAP and above) the host. On the ESP32-C3, the controller is a binary provided by Espressif, and you choose NimBLE (or Bluedroid) as the host (Chapter 4).

2.3 GAP roles

GAP (Generic Access Profile) determines roles: “who broadcasts, who searches, who initiates the connection”.

Role Behaviour Example
Broadcaster Only sends advertisements (does not accept connections) Beacon
Observer Only receives advertisements Beacon scanner
Peripheral Sends advertisements and accepts connections Sensors, wearables (the ESP32-C3 in this hands-on)
Central Scans and initiates connections Smartphone, PC
NoteGAP roles and GATT roles are different things

GAP Peripheral / Central are “connection roles”; GATT Server / Client are the roles of “data owner and data user” (Chapter 3). In most cases Peripheral = GATT Server, Central = GATT Client, but in the specification they are independent. For example, a configuration where the smartphone (Central) has a time service and a wearable (Peripheral) reads it as a GATT Client is also possible.

2.4 Advertising

2.4.1 Three advertising channels

BLE divides the 2.4 GHz band into 40 channels. Of these, 3 (37, 38, 39) are dedicated to advertising, and the remaining 37 are for data communication after connecting.

flowchart LR
  A37["ch 37<br/>2402 MHz"] --- D["data ch 0–10"] --- A38["ch 38<br/>2426 MHz"] --- D2["data ch 11–36"] --- A39["ch 39<br/>2480 MHz"]

The three advertising channels are placed away from the centres of commonly used Wi-Fi channels (1, 6, 11) (at the band edges and in the gaps), making them less susceptible to Wi-Fi. A peripheral sends the same packet on the 3 channels in turn every advertising interval.

2.4.2 Advertising interval

Interval Pros Cons
Short (20–100 ms) Found quickly, connects fast High power consumption
Long (1–10 s) Low power consumption Takes time to be found

The specification allows 20 ms to about 10.24 s, specified in units of 0.625 ms. A random delay of 0–10 ms is added to the actual transmission interval so that devices don’t keep colliding. This hands-on uses 100–150 ms.

2.4.3 Contents of an advertising packet

Legacy advertising can carry at most 31 bytes of data. Inside it you line up “length, type, data” groups called AD structures.

| Len | Type | Data ...      | Len | Type | Data ...         | ...
| 02  | 01   | 06            | 11  | 07   | (128bit UUID 16B) |
  └ Flags: general discoverable + BR/EDR not supported   └ complete list of 128-bit service UUIDs

Commonly used AD types:

Type Name Contents
0x01 Flags Discovery mode (0x02 = general discoverable), BR/EDR not supported (0x04), etc.
0x03 / 0x02 16-bit service UUIDs (complete / incomplete) Standard services (Heart Rate 0x180D, etc.)
0x07 / 0x06 128-bit service UUIDs (complete / incomplete) Custom services
0x09 / 0x08 Name (complete / shortened) Device name
0x0A TX Power Level Transmit power [dBm] (used to estimate distance)
0xFF Manufacturer Specific Data First 2 bytes are the company ID. Used by beacons etc.

31 bytes fill up quickly. Flags (3 bytes) + a 128-bit UUID (18 bytes) is 21 bytes, leaving 10 bytes, so HANDSON-C3-XXXX (15 characters + 2 = 17 bytes) does not fit. So we use the following mechanism.

2.4.4 Scan response

When the Central is doing an active scan, after receiving an advertisement it sends a Scan Request. The peripheral answers with a Scan Response (up to another 31 bytes).

sequenceDiagram
  participant P as ESP32-C3 (Peripheral)
  participant C as Phone (Central)
  P->>C: ADV_IND (Flags + service UUID) ch 37/38/39
  C->>P: SCAN_REQ (during active scan)
  P->>C: SCAN_RSP (device name)
  Note over C: Name and UUID appear in the list
  C->>P: CONNECT_IND (connection request)
  Note over P,C: Connected from here. Move to data channels

In this hands-on, we put the service UUID in the advertisement and the name in the scan response (Step 3 onward). Putting the service UUID in the advertisement lets the Central filter its search to “only devices that have this service” (used with Web Bluetooth in Chapter 11).

2.4.5 Advertising types

PDU Connectable? Scan response? Use
ADV_IND Yes Yes Typical peripheral (this hands-on)
ADV_DIRECT_IND Only a specific peer No Quick reconnection to a known peer
ADV_SCAN_IND No Yes Not connectable but provides extra info
ADV_NONCONN_IND No No Beacon

In NimBLE, this is determined by the combination of conn_mode (connectable or not) and disc_mode (discovery mode) in ble_gap_adv_params.

2.5 Connections

2.5.1 Connection events and the connection interval

Once connected, the Central and Peripheral wake up at fixed timings every connection interval and exchange data. Each such exchange is called a connection event. The data channel used changes with every connection event (frequency hopping), which makes it robust against interference.

sequenceDiagram
  participant C as Central
  participant P as Peripheral
  Note over C,P: Connection event #1 (ch 12)
  C->>P: packet (may be empty)
  P->>C: packet (Notify etc.)
  Note over C,P: … sleep for the connection interval (e.g. 30 ms) …
  Note over C,P: Connection event #2 (ch 31)
  C->>P: packet
  P->>C: packet

Parameter Range Meaning
Connection interval 7.5 ms – 4 s (units of 1.25 ms) Shorter means faster response and more data, but uses more power
Peripheral Latency 0 – 499 Number of consecutive connection events the Peripheral may skip “if it has nothing to send”
Supervision Timeout 100 ms – 32 s (units of 10 ms) If no packet arrives for this long, the link is considered disconnected

The connection interval is decided by the Central (phone/PC). The Peripheral can request “please use this range” via a connection parameter update, but whether it is accepted is up to the Central. iOS and Android choose values according to OS policy (power saving, balancing with other connections).

Tip“Notify every second” and the connection interval

This hands-on notifies every second, but the packet actually goes out at the next connection event. With a 30 ms connection interval, it is delayed by up to 30 ms. Conversely, if you notify a lot at a period shorter than the connection interval, the number of packets that can be sent in one connection event is limited, so pending transmissions pile up.

2.5.2 Disconnect reasons

When disconnected, a code indicating the reason arrives (in NimBLE, reason of BLE_GAP_EVENT_DISCONNECT). NimBLE reports the HCI error code plus 0x200.

reason HCI error Common cause
0x208 Connection Timeout (0x08) Radio could no longer reach (Supervision Timeout)
0x213 Remote User Terminated (0x13) The peer (phone) disconnected
0x216 Local Host Terminated (0x16) We disconnected ourselves
0x23e Failed to be Established (0x3E) Failed to establish the connection

2.6 Addresses

BLE devices are identified by a 48-bit Bluetooth device address.

Kind Details
Public A fixed address assigned by IEEE (same idea as a Wi-Fi MAC address)
Random Static A fixed random address decided per boot or per product
Resolvable Private (RPA) An address that changes periodically. Only peers who know the IRK (key) can identify the original device
Non-resolvable Private An address that keeps changing. Nobody can identify it

Smartphones use RPAs for privacy protection. So from the peripheral’s point of view, the phone’s address looks different each time. If you exchange IRKs during pairing, you can tell “it’s that phone I paired with before” even if the address changes (Chapter 8).

The ESP32-C3 has a public address written in eFuse. In this hands-on, its lower 2 bytes are appended to the device name so that you can tell boards apart even if there are many in the same room.

ImportantKey points
  • BLE is split into the host (GAP/GATT/ATT/SM) and the controller (LL/PHY)
  • A peripheral advertises on 3 channels and the central initiates the connection
  • Advertisements are 31 bytes. Information that does not fit goes into the scan response
  • After connecting, data is exchanged every connection interval, which is decided by the central