ESPHome 2026.4.0
Loading...
Searching...
No Matches
bluetooth_proxy.cpp
Go to the documentation of this file.
1#include "bluetooth_proxy.h"
2
3#include "esphome/core/log.h"
6#include <algorithm>
7#include <cstring>
8#include <limits>
9
10#ifdef USE_ESP32
11
13
14static const char *const TAG = "bluetooth_proxy";
15
16// BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE is defined during code generation
17// It sets the batch size for BLE advertisements to maximize WiFi efficiency
18
19// Verify BLE advertisement data array size matches the BLE specification (31 bytes adv + 31 bytes scan response)
20static_assert(sizeof(((api::BluetoothLERawAdvertisement *) nullptr)->data) == 62,
21 "BLE advertisement data array size mismatch");
22
24
26 this->connections_free_response_.limit = BLUETOOTH_PROXY_MAX_CONNECTIONS;
27 this->connections_free_response_.free = BLUETOOTH_PROXY_MAX_CONNECTIONS;
28
29 // Capture the configured scan mode from YAML before any API changes
31
33
34 this->set_interval(100, [this]() {
35 if (api::global_api_server->is_connected() && this->api_connection_ != nullptr) {
37 return;
38 }
39 for (uint8_t i = 0; i < this->connection_count_; i++) {
40 auto *connection = this->connections_[i];
41 if (connection->get_address() != 0 && !connection->disconnect_pending()) {
42 connection->disconnect();
43 }
44 }
45 });
46}
47
53
64
66 ESP_LOGW(TAG, "[%d] [%s] Connection request ignored, state: %s", connection->get_connection_index(),
68}
69
71 ESP_LOGI(TAG, "[%d] [%s] Connecting %s", connection->get_connection_index(), connection->address_str(), message);
72}
73
74void BluetoothProxy::log_not_connected_gatt_(const char *action, const char *type) {
75 ESP_LOGW(TAG, "Cannot %s GATT %s, not connected", action, type);
76}
77
78void BluetoothProxy::handle_gatt_not_connected_(uint64_t address, uint16_t handle, const char *action,
79 const char *type) {
80 this->log_not_connected_gatt_(action, type);
81 this->send_gatt_error(address, handle, ESP_GATT_NOT_CONNECTED);
82}
83
84#ifdef USE_ESP32_BLE_DEVICE
86 // This method should never be called since bluetooth_proxy always uses raw advertisements
87 // but we need to provide an implementation to satisfy the virtual method requirement
88 return false;
89}
90#endif
91
92bool BluetoothProxy::parse_devices(const esp32_ble::BLEScanResult *scan_results, size_t count) {
93 if (!api::global_api_server->is_connected() || this->api_connection_ == nullptr)
94 return false;
95
96 auto &advertisements = this->response_.advertisements;
97
98 for (size_t i = 0; i < count; i++) {
99 auto &result = scan_results[i];
100 uint8_t length = result.adv_data_len + result.scan_rsp_len;
101
102 // Fill in the data directly at current position
103 auto &adv = advertisements[this->response_.advertisements_len];
104 adv.address = esp32_ble::ble_addr_to_uint64(result.bda);
105 adv.rssi = result.rssi;
106 adv.address_type = result.ble_addr_type;
107 adv.data_len = length;
108 std::memcpy(adv.data, result.ble_adv, length);
109
111
112 ESP_LOGV(TAG, "Queuing raw packet from %02X:%02X:%02X:%02X:%02X:%02X, length %d. RSSI: %d dB", result.bda[0],
113 result.bda[1], result.bda[2], result.bda[3], result.bda[4], result.bda[5], length, result.rssi);
114
115 // Flush if we have reached BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE
116 if (this->response_.advertisements_len >= BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE) {
118 }
119 }
120
121 return true;
122}
123
125 ESP_LOGV(TAG, "Sent batch of %u BLE advertisements", this->response_.advertisements_len);
126}
127
129 ESP_LOGCONFIG(TAG,
130 "Bluetooth Proxy:\n"
131 " Active: %s\n"
132 " Connections: %d",
133 YESNO(this->active_), this->connection_count_);
134}
135
139
141 for (uint8_t i = 0; i < this->connection_count_; i++) {
142 auto *connection = this->connections_[i];
143 uint64_t conn_addr = connection->get_address();
144
145 if (conn_addr == address)
146 return connection;
147
148 if (reserve && conn_addr == 0) {
149 connection->send_service_ = INIT_SENDING_SERVICES;
150 connection->set_address(address);
151 // All connections must start at INIT
152 // We only set the state if we allocate the connection
153 // to avoid a race where multiple connection attempts
154 // are made.
155 connection->set_state(espbt::ClientState::INIT);
156 return connection;
157 }
158 }
159 return nullptr;
160}
161
163 switch (msg.request_type) {
166 auto *connection = this->get_connection_(msg.address, true);
167 if (connection == nullptr) {
168 ESP_LOGW(TAG, "No free connections available");
169 this->send_device_connection(msg.address, false);
170 return;
171 }
172 if (!msg.has_address_type) {
173 ESP_LOGE(TAG, "[%d] [%s] Missing address type in connect request", connection->get_connection_index(),
174 connection->address_str());
175 this->send_device_connection(msg.address, false);
176 return;
177 }
178 if (connection->state() == espbt::ClientState::CONNECTED ||
179 connection->state() == espbt::ClientState::ESTABLISHED) {
180 this->log_connection_request_ignored_(connection, connection->state());
181 this->send_device_connection(msg.address, true);
182 this->send_connections_free();
183 return;
184 } else if (connection->state() == espbt::ClientState::CONNECTING) {
185 if (connection->disconnect_pending()) {
186 ESP_LOGW(TAG, "[%d] [%s] Connection request while pending disconnect, cancelling pending disconnect",
187 connection->get_connection_index(), connection->address_str());
188 connection->cancel_pending_disconnect();
189 return;
190 }
191 this->log_connection_request_ignored_(connection, connection->state());
192 return;
193 } else if (connection->state() != espbt::ClientState::INIT) {
194 this->log_connection_request_ignored_(connection, connection->state());
195 return;
196 }
198 connection->set_connection_type(espbt::ConnectionType::V3_WITH_CACHE);
199 this->log_connection_info_(connection, "v3 with cache");
200 } else { // BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITHOUT_CACHE
201 connection->set_connection_type(espbt::ConnectionType::V3_WITHOUT_CACHE);
202 this->log_connection_info_(connection, "v3 without cache");
203 }
204 uint64_to_bd_addr(msg.address, connection->remote_bda_);
205 connection->set_remote_addr_type(static_cast<esp_ble_addr_type_t>(msg.address_type));
206 connection->set_state(espbt::ClientState::DISCOVERED);
207 this->send_connections_free();
208 break;
209 }
211 auto *connection = this->get_connection_(msg.address, false);
212 if (connection == nullptr) {
213 this->send_device_connection(msg.address, false);
214 this->send_connections_free();
215 return;
216 }
217 if (connection->state() != espbt::ClientState::IDLE) {
218 connection->disconnect();
219 } else {
220 connection->set_address(0);
221 this->send_device_connection(msg.address, false);
222 this->send_connections_free();
223 }
224 break;
225 }
227 auto *connection = this->get_connection_(msg.address, false);
228 if (connection != nullptr) {
229 if (!connection->is_paired()) {
230 auto err = connection->pair();
231 if (err != ESP_OK) {
232 this->send_device_pairing(msg.address, false, err);
233 }
234 } else {
235 this->send_device_pairing(msg.address, true);
236 }
237 }
238 break;
239 }
241 esp_bd_addr_t address;
243 esp_err_t ret = esp_ble_remove_bond_device(address);
244 this->send_device_pairing(msg.address, ret == ESP_OK, ret);
245 break;
246 }
248 esp_bd_addr_t address;
250 esp_err_t ret = esp_ble_gattc_cache_clean(address);
252 call.address = msg.address;
253 call.success = ret == ESP_OK;
254 call.error = ret;
255
256 this->api_connection_->send_message(call);
257
258 break;
259 }
261 ESP_LOGE(TAG, "V1 connections removed");
262 this->send_device_connection(msg.address, false);
263 break;
264 }
265 }
266}
267
269 auto *connection = this->get_connection_(msg.address, false);
270 if (connection == nullptr) {
271 this->handle_gatt_not_connected_(msg.address, msg.handle, "read", "characteristic");
272 return;
273 }
274
275 auto err = connection->read_characteristic(msg.handle);
276 if (err != ESP_OK) {
277 this->send_gatt_error(msg.address, msg.handle, err);
278 }
279}
280
282 auto *connection = this->get_connection_(msg.address, false);
283 if (connection == nullptr) {
284 this->handle_gatt_not_connected_(msg.address, msg.handle, "write", "characteristic");
285 return;
286 }
287
288 auto err = connection->write_characteristic(msg.handle, msg.data, msg.data_len, msg.response);
289 if (err != ESP_OK) {
290 this->send_gatt_error(msg.address, msg.handle, err);
291 }
292}
293
295 auto *connection = this->get_connection_(msg.address, false);
296 if (connection == nullptr) {
297 this->handle_gatt_not_connected_(msg.address, msg.handle, "read", "descriptor");
298 return;
299 }
300
301 auto err = connection->read_descriptor(msg.handle);
302 if (err != ESP_OK) {
303 this->send_gatt_error(msg.address, msg.handle, err);
304 }
305}
306
308 auto *connection = this->get_connection_(msg.address, false);
309 if (connection == nullptr) {
310 this->handle_gatt_not_connected_(msg.address, msg.handle, "write", "descriptor");
311 return;
312 }
313
314 auto err = connection->write_descriptor(msg.handle, msg.data, msg.data_len, true);
315 if (err != ESP_OK) {
316 this->send_gatt_error(msg.address, msg.handle, err);
317 }
318}
319
321 auto *connection = this->get_connection_(msg.address, false);
322 if (connection == nullptr || !connection->connected()) {
323 this->handle_gatt_not_connected_(msg.address, 0, "get", "services");
324 return;
325 }
326 if (!connection->service_count_) {
327 ESP_LOGW(TAG, "[%d] [%s] No GATT services found", connection->connection_index_, connection->address_str());
329 return;
330 }
331 if (connection->send_service_ == INIT_SENDING_SERVICES) // Start sending services if not started yet
332 connection->send_service_ = 0;
333}
334
336 auto *connection = this->get_connection_(msg.address, false);
337 if (connection == nullptr) {
338 this->handle_gatt_not_connected_(msg.address, msg.handle, "notify", "characteristic");
339 return;
340 }
341
342 auto err = connection->notify_characteristic(msg.handle, msg.enable);
343 if (err != ESP_OK) {
344 this->send_gatt_error(msg.address, msg.handle, err);
345 }
346}
347
349 if (this->api_connection_ == nullptr)
350 return;
351
352 auto *connection = this->get_connection_(msg.address, false);
354 resp.address = msg.address;
355
356 if (connection == nullptr || !connection->connected()) {
357 ESP_LOGW(TAG, "[%d] [%s] Cannot set connection params, not connected",
358 connection ? static_cast<int>(connection->connection_index_) : -1,
359 connection ? connection->address_str() : "unknown");
360 resp.error = ESP_GATT_NOT_CONNECTED;
361 this->api_connection_->send_message(resp);
362 return;
363 }
364
365 // Protobuf fields are uint32_t to future-proof the API if BLE ever supports wider values;
366 // clamp to uint16_t since the current BLE spec defines these as 16-bit.
367 constexpr uint32_t max_val = std::numeric_limits<uint16_t>::max();
368 resp.error = connection->update_connection_params(static_cast<uint16_t>(std::min(msg.min_interval, max_val)),
369 static_cast<uint16_t>(std::min(msg.max_interval, max_val)),
370 static_cast<uint16_t>(std::min(msg.latency, max_val)),
371 static_cast<uint16_t>(std::min(msg.timeout, max_val)));
372 this->api_connection_->send_message(resp);
373}
374
376 if (this->api_connection_ != nullptr) {
377 ESP_LOGE(TAG, "Only one API subscription is allowed at a time");
378 return;
379 }
380 this->api_connection_ = api_connection;
382
384}
385
387 if (this->api_connection_ != api_connection) {
388 ESP_LOGV(TAG, "API connection is not subscribed");
389 return;
390 }
391 this->api_connection_ = nullptr;
393}
394
395void BluetoothProxy::send_device_connection(uint64_t address, bool connected, uint16_t mtu, esp_err_t error) {
396 if (this->api_connection_ == nullptr)
397 return;
400 call.connected = connected;
401 call.mtu = mtu;
402 call.error = error;
403 this->api_connection_->send_message(call);
404}
406 if (this->api_connection_ != nullptr) {
408 }
409}
410
414
422
423void BluetoothProxy::send_gatt_error(uint64_t address, uint16_t handle, esp_err_t error) {
424 if (this->api_connection_ == nullptr)
425 return;
428 call.handle = handle;
429 call.error = error;
430 this->api_connection_->send_message(call);
431}
432
433void BluetoothProxy::send_device_pairing(uint64_t address, bool paired, esp_err_t error) {
434 if (this->api_connection_ == nullptr)
435 return;
438 call.paired = paired;
439 call.error = error;
440
441 this->api_connection_->send_message(call);
442}
443
444void BluetoothProxy::send_device_unpairing(uint64_t address, bool success, esp_err_t error) {
445 if (this->api_connection_ == nullptr)
446 return;
449 call.success = success;
450 call.error = error;
451
452 this->api_connection_->send_message(call);
453}
454
456 if (this->parent_->get_scan_active() == active) {
457 return;
458 }
459 ESP_LOGD(TAG, "Setting scanner mode to %s", active ? "active" : "passive");
460 this->parent_->set_scan_active(active);
461 this->parent_->stop_scan();
463 true); // Set this to true to automatically start scanning again when it has cleaned up.
464}
465
466BluetoothProxy *global_bluetooth_proxy = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
467
468} // namespace esphome::bluetooth_proxy
469
470#endif // USE_ESP32
uint8_t address
Definition bl0906.h:4
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_interval(const std voi set_interval)(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a unique name.
Definition component.h:404
bool send_message(const T &msg)
enums::BluetoothDeviceRequestType request_type
Definition api_pb2.h:1922
std::array< BluetoothLERawAdvertisement, BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE > advertisements
Definition api_pb2.h:1904
enums::BluetoothScannerMode mode
Definition api_pb2.h:2307
enums::BluetoothScannerState state
Definition api_pb2.h:2306
enums::BluetoothScannerMode configured_mode
Definition api_pb2.h:2308
void bluetooth_gatt_read(const api::BluetoothGATTReadRequest &msg)
void bluetooth_gatt_send_services(const api::BluetoothGATTGetServicesRequest &msg)
void handle_gatt_not_connected_(uint64_t address, uint16_t handle, const char *action, const char *type)
esp32_ble_tracker::AdvertisementParserType get_advertisement_parser_type() override
void send_device_connection(uint64_t address, bool connected, uint16_t mtu=0, esp_err_t error=ESP_OK)
void send_device_unpairing(uint64_t address, bool success, esp_err_t error=ESP_OK)
void send_device_pairing(uint64_t address, bool paired, esp_err_t error=ESP_OK)
bool parse_devices(const esp32_ble::BLEScanResult *scan_results, size_t count) override
void log_not_connected_gatt_(const char *action, const char *type)
void bluetooth_device_request(const api::BluetoothDeviceRequest &msg)
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override
void bluetooth_gatt_write_descriptor(const api::BluetoothGATTWriteDescriptorRequest &msg)
void send_bluetooth_scanner_state_(esp32_ble_tracker::ScannerState state)
void subscribe_api_connection(api::APIConnection *api_connection, uint32_t flags)
void send_gatt_error(uint64_t address, uint16_t handle, esp_err_t error)
void unsubscribe_api_connection(api::APIConnection *api_connection)
api::BluetoothLERawAdvertisementsResponse response_
void log_connection_info_(BluetoothConnection *connection, const char *message)
BluetoothConnection * get_connection_(uint64_t address, bool reserve)
void bluetooth_set_connection_params(const api::BluetoothSetConnectionParamsRequest &msg)
void bluetooth_gatt_read_descriptor(const api::BluetoothGATTReadDescriptorRequest &msg)
void bluetooth_gatt_write(const api::BluetoothGATTWriteRequest &msg)
void bluetooth_gatt_notify(const api::BluetoothGATTNotifyRequest &msg)
void on_scanner_state(esp32_ble_tracker::ScannerState state) override
BLEScannerStateListener interface.
void flush_pending_advertisements_()
Caller must ensure api_connection_ is non-null and API server is connected.
static void uint64_to_bd_addr(uint64_t address, esp_bd_addr_t bd_addr)
std::array< BluetoothConnection *, BLUETOOTH_PROXY_MAX_CONNECTIONS > connections_
api::BluetoothConnectionsFreeResponse connections_free_response_
void log_connection_request_ignored_(BluetoothConnection *connection, espbt::ClientState state)
void add_scanner_state_listener(BLEScannerStateListener *listener)
Add a listener for scanner state changes.
const char * message
Definition component.cpp:35
uint16_t type
uint16_t flags
bool state
Definition fan.h:2
@ BLUETOOTH_DEVICE_REQUEST_TYPE_UNPAIR
Definition api_pb2.h:222
@ BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITH_CACHE
Definition api_pb2.h:223
@ BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT
Definition api_pb2.h:219
@ BLUETOOTH_DEVICE_REQUEST_TYPE_PAIR
Definition api_pb2.h:221
@ BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITHOUT_CACHE
Definition api_pb2.h:224
@ BLUETOOTH_DEVICE_REQUEST_TYPE_CLEAR_CACHE
Definition api_pb2.h:225
@ BLUETOOTH_DEVICE_REQUEST_TYPE_DISCONNECT
Definition api_pb2.h:220
@ BLUETOOTH_SCANNER_MODE_PASSIVE
Definition api_pb2.h:236
@ BLUETOOTH_SCANNER_MODE_ACTIVE
Definition api_pb2.h:237
APIServer * global_api_server
BluetoothProxy * global_bluetooth_proxy
const char * client_state_to_string(ClientState state)
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
Definition ble.h:38
static void uint32_t
uint16_t length
Definition tt21100.cpp:0