ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
bluetooth_connection.h
Go to the documentation of this file.
1// Shared types and helpers for the per-platform GATT connection backends and
2// the Bluetooth proxy that drives them.
3
4#pragma once
5
8
11
12#include <array>
13#include <cstddef>
14#include <cstdint>
15#include <cstring>
16
17#ifdef USE_ESP32
18#include <esp_err.h>
19#endif
20
21// USE_BLUETOOTH_PROXY_CONNECTIONS is the single spelling of "this build has
22// proxy connection slots": codegen emits it per configured slot, and each
23// slot brings a GATT backend, so it also implies USE_BLE_GATT_CLIENT (not
24// the converse: a backend can exist without proxy slots). The hub
25// wrapper, the proxy's connection surface and the API's connection messages
26// all gate on it. The address-scoped maintenance functions below are only
27// reached from that gated surface; the #else stubs just keep this header
28// parsing on arms without a backend.
29
30namespace esphome::api {
31class BluetoothGATTGetServicesResponse;
32} // namespace esphome::api
33
35
36// Connection-owned error type for the API error fields, which are plain
37// integers on the wire. Aliases esp_err_t on esp32 (where the values come from
38// IDF calls); a bare int elsewhere. Owning the name instead of probing for
39// esp_err_t keeps the header independent of how a platform's SDK spells its
40// error type.
41#ifdef USE_ESP32
42using conn_err_t = esp_err_t;
43static constexpr conn_err_t CONN_OK = ESP_OK;
44#else
45using conn_err_t = int;
46static constexpr conn_err_t CONN_OK = 0;
47#endif
48
49// The ESPHome-private "not connected" wire value, shared with the neutral
50// GATT contract so backend and wrapper cannot drift.
51static constexpr conn_err_t GATT_NOT_CONNECTED = ble_device_base::GATT_ERR_NOT_CONNECTED;
52
53// What the platform's connection backend supports beyond GATT operations;
54// the proxy derives its feature flags and legacy version from these.
55#if defined(USE_ESP32)
56static constexpr bool SUPPORTS_PAIRING = true;
57static constexpr bool SUPPORTS_CACHE_CLEARING = true;
58#elif defined(USE_RP2040_BLE) && defined(USE_BLE_GATT_CLIENT)
59// The rp2 BTstack backend pairs (just works + bonding); it has no service
60// cache to clear. Keyed on the backend, not the generic client define, so a
61// future backend without pairing keeps the stub arm below.
62static constexpr bool SUPPORTS_PAIRING = true;
63static constexpr bool SUPPORTS_CACHE_CLEARING = false;
64#else
65static constexpr bool SUPPORTS_PAIRING = false;
66static constexpr bool SUPPORTS_CACHE_CLEARING = false;
67#endif
68
69// Address-scoped (not connection-scoped) maintenance requests.
70#if (defined(USE_ESP32) || defined(USE_RP2040_BLE)) && defined(USE_BLE_GATT_CLIENT)
72#else
73inline conn_err_t unpair_device(uint64_t) { return GATT_NOT_CONNECTED; }
74#endif
75#if defined(USE_ESP32) && defined(USE_BLE_GATT_CLIENT)
77#else
78inline conn_err_t clear_gatt_cache(uint64_t) { return GATT_NOT_CONNECTED; }
79#endif
80
81// send_service_ cursor states; >= 0 is the next service index to stream.
82static constexpr int DONE_SENDING_SERVICES = -2;
83static constexpr int INIT_SENDING_SERVICES = -3;
84static constexpr int SERVICES_DONE_PENDING = -4; // all batches delivered, done-message still owed
85// Every sentinel must stay below the >= 0 streaming gate and clear of
86// GATT_NOT_CONNECTED (-1) so cursor and error values can never be confused.
87static_assert(DONE_SENDING_SERVICES < 0 && INIT_SENDING_SERVICES < 0 && SERVICES_DONE_PENDING < 0);
88static_assert(DONE_SENDING_SERVICES != GATT_NOT_CONNECTED && INIT_SENDING_SERVICES != GATT_NOT_CONNECTED &&
89 SERVICES_DONE_PENDING != GATT_NOT_CONNECTED);
90// Owed-done retries stop here (~3 s at the 100 ms drain cadence): a done
91// delivered near the client's 30 s timeout could land on a fresh request's
92// empty accumulator and cache as an empty database.
93static constexpr uint8_t SERVICES_DONE_RETRY_LIMIT = 30;
94// Owed-ack retries stop after ~25 s of subscribed drain time from the first
95// refusal, keeping most of the client's 30 s GATT window for congestion to
96// clear while still bounding how stale a delivered reply can be.
97static constexpr uint16_t PENDING_ACK_RETRY_LIMIT = 250;
98
99// ---- Service-streaming size budget, shared by every platform's streamer ----
100
101// Conservative MTU limit for API messages (accounts for WPA3 overhead)
102static constexpr size_t MAX_PACKET_SIZE = 1360;
103
104// Constants for size estimation
105static constexpr uint8_t SERVICE_OVERHEAD_LEGACY = 25; // UUID(20) + handle(4) + overhead(1)
106static constexpr uint8_t SERVICE_OVERHEAD_EFFICIENT = 10; // UUID(6) + handle(4)
107static constexpr uint8_t CHAR_SIZE_128BIT = 35; // UUID(20) + handle(4) + props(4) + overhead(7)
108static constexpr uint8_t DESC_SIZE_128BIT = 25; // UUID(20) + handle(4) + overhead(1)
109static constexpr uint8_t DESC_PER_CHAR = 1; // Assume 1 descriptor per characteristic
110
114inline size_t estimate_service_size(uint16_t char_count, bool use_efficient_uuids) {
115 size_t service_overhead = use_efficient_uuids ? SERVICE_OVERHEAD_EFFICIENT : SERVICE_OVERHEAD_LEGACY;
116 return service_overhead + (CHAR_SIZE_128BIT + DESC_SIZE_128BIT * DESC_PER_CHAR) * char_count;
117}
118
119// ---- UUID wire packing, shared by every platform's streamer ----
120
121// This function is allocation-free and directly packs UUIDs into the output
122// array using precalculated constants for the Bluetooth base UUID. ESPBTUUID
123// stores its 128-bit form little-endian (same as Bluedroid).
124inline void fill_128bit_uuid_array(std::array<uint64_t, 2> &out, const ble_device_base::ESPBTUUID &uuid) {
126 if (uuid.type() == ESPBTUUID::Type::UUID128) {
127 const uint8_t *u = uuid.uuid128();
128 // out[0] = bytes 8-15 (big-endian), out[1] = bytes 0-7 (big-endian)
129 out[0] = encode_value_le<uint64_t>(&u[8]);
131 return;
132 }
133 // 16/32-bit UUID inserted into the Bluetooth base UUID:
134 // 00000000-0000-1000-8000-00805F9B34FB
135 uint32_t value = uuid.type() == ESPBTUUID::Type::UUID16 ? uuid.uuid16() : uuid.uuid32();
136 out[0] = ((uint64_t) value << 32) | 0x00001000ULL; // Base UUID bytes 8-11
137 out[1] = 0x800000805F9B34FBULL; // Base UUID bytes 0-7
138}
139
141inline ble_device_base::ESPBTUUID uuid_from_be128(const uint8_t *uuid128) {
143 // 0000xxxx-0000-1000-8000-00805F9B34FB without its first 4 bytes
144 static constexpr uint8_t BASE_UUID_TAIL[12] = {0x00, 0x00, 0x10, 0x00, 0x80, 0x00,
145 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
146 if (memcmp(uuid128 + 4, BASE_UUID_TAIL, sizeof(BASE_UUID_TAIL)) != 0)
147 return ESPBTUUID::from_raw_reversed(uuid128);
148 const uint32_t value = encode_uint32(uuid128[0], uuid128[1], uuid128[2], uuid128[3]);
149 return value <= UINT16_MAX ? ESPBTUUID::from_uint16(value) : ESPBTUUID::from_uint32(value);
150}
151
155inline void fill_gatt_uuid(std::array<uint64_t, 2> &uuid_128, uint32_t &short_uuid,
156 const ble_device_base::ESPBTUUID &uuid, bool use_efficient_uuids) {
158 if (!use_efficient_uuids || uuid.type() == ESPBTUUID::Type::UUID128) {
159 fill_128bit_uuid_array(uuid_128, uuid);
160 } else if (uuid.type() == ESPBTUUID::Type::UUID16) {
161 short_uuid = uuid.uuid16();
162 } else {
163 short_uuid = uuid.uuid32();
164 }
165}
166
167#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
171enum class BatchClose : uint8_t { CONTINUE, SEND };
172
177BatchClose close_service_batch(api::BluetoothGATTGetServicesResponse &resp, size_t &current_size, int16_t &send_service,
178 uint8_t connection_index, const char *address_str);
179#endif // USE_BLUETOOTH_PROXY_CONNECTIONS
180
181} // namespace esphome::bluetooth_connection
std::vector< uint8_t > & out
Definition gif.cpp:49
conn_err_t unpair_device(uint64_t address)
size_t estimate_service_size(uint16_t char_count, bool use_efficient_uuids)
Estimate the wire size of a service (service overhead + its characteristics, assuming 128-bit UUIDs a...
void fill_128bit_uuid_array(std::array< uint64_t, 2 > &out, const ble_device_base::ESPBTUUID &uuid)
BatchClose
Result of close_service_batch: keep filling the batch or send it now.
BatchClose close_service_batch(api::BluetoothGATTGetServicesResponse &resp, size_t &current_size, int16_t &send_service, uint8_t connection_index, const char *address_str)
Close out the service just packed into resp (account its actual wire size, advance the cursor) and de...
ble_device_base::ESPBTUUID uuid_from_be128(const uint8_t *uuid128)
A 128-bit UUID in big-endian (printable) order, as its 16 or 32-bit form when it is on the Bluetooth ...
void fill_gatt_uuid(std::array< uint64_t, 2 > &uuid_128, uint32_t &short_uuid, const ble_device_base::ESPBTUUID &uuid, bool use_efficient_uuids)
Fill the UUID in the appropriate wire format based on client support and UUID type (128-bit array for...
conn_err_t clear_gatt_cache(uint64_t address)
uint32_t value
Definition hal.cpp:41
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
Definition helpers.h:1084
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:1051
static void uint32_t