ESPHome 2026.8.0b4
Loading...
Searching...
No Matches
bluetooth_proxy.cpp
Go to the documentation of this file.
1#include "bluetooth_proxy.h"
2
3#ifdef USE_BLUETOOTH_PROXY
4
7#include "esphome/core/log.h"
10#include <algorithm>
11#include <cinttypes>
12#include <cstring>
13#include <limits>
14
16
17static const char *const TAG = "bluetooth_proxy";
18
19// BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE is defined during code generation
20// It sets the batch size for BLE advertisements to maximize WiFi efficiency
21
22// Verify BLE advertisement data array size matches the BLE specification (31 bytes adv + 31 bytes scan response)
23static_assert(sizeof(((api::BluetoothLERawAdvertisement *) nullptr)->data) == 62,
24 "BLE advertisement data array size mismatch");
25
27
28// The neutral enum's values are the wire values.
30static_assert(static_cast<uint32_t>(ble_device_base::ScannerState::STARTING) ==
32static_assert(static_cast<uint32_t>(ble_device_base::ScannerState::RUNNING) ==
34static_assert(static_cast<uint32_t>(ble_device_base::ScannerState::FAILED) ==
36static_assert(static_cast<uint32_t>(ble_device_base::ScannerState::STOPPING) ==
38static_assert(static_cast<uint32_t>(ble_device_base::ScannerState::STOPPED) ==
40
53
54#ifdef USE_BLE_SCANNER_STATE_CALLBACK
56 // False only on a refused frame, so the latch arms only when a retry is owed.
58}
59#else
61 // One read feeds both the frame and the change detector; the detector only
62 // advances if the frame was accepted, so a dropped send (WOULD_BLOCK on a
63 // full TX buffer) is retried from loop() instead of leaving a stale state.
64 const bool running = this->hub_->scan_running();
67 this->last_scan_running_ = running;
68 }
69}
70#endif // USE_BLE_SCANNER_STATE_CALLBACK
71
73#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
74 this->connections_free_response_.limit = BLUETOOTH_PROXY_MAX_CONNECTIONS;
75 this->connections_free_response_.free = BLUETOOTH_PROXY_MAX_CONNECTIONS;
76#endif
77
78 // Capture the configured scan mode from YAML before any API changes
79 this->configured_scan_active_ = this->hub_->scan_active();
80
81 this->hub_->set_raw_advertisement_callback({this, [](void *self, const ble_device_base::RawAdvertisement &adv) {
82 static_cast<BluetoothProxy *>(self)->on_raw_advertisement_(adv);
83 }});
84#ifdef USE_BLE_SCANNER_STATE_CALLBACK
85 // Only push hubs compile the slot; elsewhere loop() polls scan_running().
86 this->hub_->set_scanner_state_callback({this, [](void *self, ble_device_base::ScannerState state) {
87 static_cast<BluetoothProxy *>(self)->send_scanner_state_(state);
88 }});
89#endif
90}
91
92// The hub delivers raw advertisements on the ESPHome main loop.
94 if (!api::global_api_server->is_connected() || this->api_connection_ == nullptr)
95 return;
96
98 adv.address = raw.address;
99 adv.rssi = raw.rssi;
100 adv.address_type = raw.addr_type;
101 uint8_t length = raw.data_len > sizeof(adv.data) ? sizeof(adv.data) : static_cast<uint8_t>(raw.data_len);
102 adv.data_len = length;
103 std::memcpy(adv.data, raw.data, length);
104
106
107 ESP_LOGVV(TAG, "Queuing raw packet from %012" PRIX64 ", length %d. RSSI: %d dB", raw.address, length, raw.rssi);
108
109 // Flush if we have reached BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE
110 if (this->response_.advertisements_len >= BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE) {
112 }
113}
114
115#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
117 ESP_LOGW(TAG, "[%d] [%s] Connection request ignored, state: %s", connection->get_connection_index(),
119}
120
122 ESP_LOGI(TAG, "[%d] [%s] Connecting %s", connection->get_connection_index(), connection->address_str(), message);
123}
124#endif // USE_BLUETOOTH_PROXY_CONNECTIONS
125
126#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
127void BluetoothProxy::log_reply_dropped_(const char *what, uint64_t address) {
128 ESP_LOGW(TAG, "%s reply for %012" PRIX64 " dropped, TCP buffer full", what, address);
129}
130
131void BluetoothProxy::log_reply_deferred_(const char *what, uint64_t address) {
132 ESP_LOGW(TAG, "%s reply for %012" PRIX64 " deferred, TCP buffer full", what, address);
133}
134
135void BluetoothProxy::log_reply_displaced_(const char *what, uint64_t owed, uint64_t address) {
136 ESP_LOGW(TAG, "%s reply for %012" PRIX64 " dropped, displaced by %012" PRIX64, what, owed, address);
137}
138
139void BluetoothProxy::log_not_connected_gatt_(const char *action, const char *type) {
140 ESP_LOGW(TAG, "Cannot %s GATT %s, not connected", action, type);
141}
142
143void BluetoothProxy::handle_gatt_not_connected_(uint64_t address, uint16_t handle, const char *action,
144 const char *type) {
145 this->log_not_connected_gatt_(action, type);
146 if (!this->send_gatt_error(address, handle, GATT_NOT_CONNECTED)) {
147 // No connection, so nothing to latch against; the client's timeout arbitrates.
148 this->log_reply_dropped_("Not-connected", address);
149 }
150}
151#endif
152
154 if (sent) {
155 // VV: one line per flush drowns a verbose log in any busy environment.
156 ESP_LOGVV(TAG, "Sent batch of %u BLE advertisements", this->response_.advertisements_len);
157 } else {
158 // The rare congestion signal stays at V.
159 ESP_LOGV(TAG, "Batch of %u BLE advertisements dropped, TCP buffer full", this->response_.advertisements_len);
160 }
161}
162
164 // Print configured facts. dump_config runs right after setup, before the
165 // radio is up, so live scan state would always read "stopped" here — the
166 // loop's BluetoothScannerStateResponse carries the changing value instead.
167 char mac_str[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
169 const char *mac_out = mac_str[0] != '\0' ? mac_str : "unavailable (adapter not up yet)";
170 const char *scan_mode = this->configured_scan_active_ ? "active" : "passive";
171#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
172 ESP_LOGCONFIG(TAG,
173 "Bluetooth Proxy:\n"
174 " Active: %s\n"
175 " Connections: %d\n"
176 " Configured scan: %s\n"
177 " Adapter MAC: %s",
178 YESNO(this->active_), this->connection_count_, scan_mode, mac_out);
179#else
180 ESP_LOGCONFIG(TAG,
181 "Bluetooth Proxy:\n"
182 " Mode: advertisement-only (no GATT connections)\n"
183 " Configured scan: %s\n"
184 " Adapter MAC: %s",
185 scan_mode, mac_out);
186#endif
187}
188
189#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
190
192 if (this->connection_count_ >= BLUETOOTH_PROXY_MAX_CONNECTIONS) {
193 // Cannot happen with codegen-sized registration; a silent drop would
194 // surface later as a null proxy_ dereference, so refuse loudly.
195 ESP_LOGE(TAG, "Connection registry full, dropping registration");
196 return;
197 }
198 // The hub wrapper has no Component lifecycle, so the index is assigned here.
199 connection->connection_index_ = this->connection_count_;
200 this->connections_[this->connection_count_++] = connection;
201 connection->proxy_ = this;
202}
203
204void BluetoothProxy::log_slot_accounting_mismatch_() { ESP_LOGW(TAG, "Connection slot free-count mismatch, clamped"); }
205
206void BluetoothProxy::replace_allocated_slot_(uint64_t find_value, uint64_t set_value) {
207 for (auto &slot : this->connections_free_response_.allocated) {
208 if (slot == find_value) {
209 slot = set_value;
210 return;
211 }
212 }
213 // The accounting arrays are only mutated here and sized to the slot count,
214 // so a miss means the bookkeeping already drifted — say so.
215 ESP_LOGW(TAG, "Connection slot accounting mismatch (find 0x%llx)", (unsigned long long) find_value);
216}
217
219 // Match before free entry so one address never occupies two pool slots.
220 PendingReply *free_entry = nullptr;
221 for (uint8_t i = 0; i < this->connection_count_; i++) {
222 auto &owed = this->pending_disconnections_[i];
223 if (owed.matches(address)) {
224 owed.set(address, error);
225 return;
226 }
227 if (free_entry == nullptr && owed.empty()) {
228 free_entry = &owed;
229 }
230 }
231 if (free_entry != nullptr) {
232 this->log_reply_deferred_("Disconnect", address);
233 free_entry->set(address, error);
234 return;
235 }
236 // Every entry is owed: evict the first so the newest loss is not silent too.
237 this->log_reply_displaced_("Disconnect", this->pending_disconnections_[0].address(), address);
238 this->pending_disconnections_[0].set(address, error);
239}
240
242 // A reconnect supersedes the owed disconnect; a late resend would shadow
243 // the new connection.
244 for (uint8_t i = 0; i < this->connection_count_; i++) {
245 if (this->pending_disconnections_[i].matches(address)) {
246 this->pending_disconnections_[i].clear();
247 return; // latch_pending_disconnection_ keeps at most one entry per address
248 }
249 }
250}
251
253 if (this->send_device_connection(address, false)) {
254 // A landed answer satisfies any owed notification for the address; a
255 // drained duplicate would follow it otherwise.
256 this->clear_pending_disconnection_(address);
257 return;
258 }
259 // Not latched: the client's own request timeout arbitrates, and pooling
260 // these would let a request retry loop displace an unsolicited disconnect.
261 this->log_reply_dropped_("Disconnect", address);
262}
263
265 if (this->send_device_connection(address, false, 0, error)) {
266 // A later disconnect landing for an address that still has one owed would
267 // otherwise have the drain repeat it.
268 this->clear_pending_disconnection_(address);
269 return;
270 }
271 // A dropped disconnect leaves the client believing the link is live, so
272 // every GATT operation on it times out until something else corrects it.
273 // latch_pending_disconnection_() reports the leading edge.
274 this->latch_pending_disconnection_(address, error);
275}
276
278 // The client has no other way to learn of an unsolicited disconnect.
279 this->send_device_disconnected_(connection->get_address(), reason);
280 connection->set_address(0);
281 connection->send_service_ = INIT_SENDING_SERVICES;
282 this->send_connections_free();
283}
284
286 // Finish the scan before reserving: a free slot earlier in the array must
287 // not win over a later slot that already holds the address, or one device
288 // ends up on two slots with a second connection attempt racing the first.
289 BluetoothConnection *free_slot = nullptr;
290 for (uint8_t i = 0; i < this->connection_count_; i++) {
291 auto *connection = this->connections_[i];
292 uint64_t conn_addr = connection->get_address();
293
294 if (conn_addr == address) {
295 // A connect request supersedes an owed disconnect.
296 if (reserve) {
297 this->clear_pending_disconnection_(address);
298 }
299 return connection;
300 }
301
302 if (free_slot == nullptr && conn_addr == 0)
303 free_slot = connection;
304 }
305 if (!reserve || free_slot == nullptr)
306 return nullptr;
307 this->clear_pending_disconnection_(address);
308 free_slot->send_service_ = INIT_SENDING_SERVICES;
309 free_slot->set_address(address);
310 // All connections must start at INIT
311 // We only set the state if we allocate the connection
312 // to avoid a race where multiple connection attempts
313 // are made.
314 free_slot->set_state(ClientState::INIT);
315 return free_slot;
316}
317
319 switch (msg.request_type) {
322 auto *connection = this->get_connection_(msg.address, true);
323 if (connection == nullptr) {
324 ESP_LOGW(TAG, "No free connections available");
326 return;
327 }
328 if (!msg.has_address_type) {
329 ESP_LOGE(TAG, "[%d] [%s] Missing address type in connect request", connection->get_connection_index(),
330 connection->address_str());
332 return;
333 }
334 if (connection->state() == ClientState::CONNECTED || connection->state() == ClientState::ESTABLISHED) {
335 this->log_connection_request_ignored_(connection, connection->state());
336 connection->send_connected_reply_();
337 this->send_connections_free();
338 return;
339 } else if (connection->state() == ClientState::DISCONNECTING && connection->cancel_teardown()) {
340 ESP_LOGW(TAG, "[%d] [%s] Connection request while pending disconnect, cancelling pending disconnect",
341 connection->get_connection_index(), connection->address_str());
342 return;
343 } else if (connection->state() != ClientState::INIT) {
344 // Covers CONNECTING too: a repeat request during a connect attempt is
345 // ignored the same way.
346 this->log_connection_request_ignored_(connection, connection->state());
347 return;
348 }
350 connection->set_connection_type(ble_device_base::ConnectionType::V3_WITH_CACHE);
351 this->log_connection_info_(connection, "v3 with cache");
352 } else { // BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITHOUT_CACHE
353 connection->set_connection_type(ble_device_base::ConnectionType::V3_WITHOUT_CACHE);
354 this->log_connection_info_(connection, "v3 without cache");
355 }
356 connection->initiate_connection(static_cast<uint8_t>(msg.address_type));
357 this->send_connections_free();
358 break;
359 }
361 auto *connection = this->get_connection_(msg.address, false);
362 if (connection == nullptr) {
364 this->send_connections_free();
365 return;
366 }
367 if (connection->state() != ClientState::IDLE) {
368 connection->disconnect();
369 } else {
370 connection->set_address(0);
372 this->send_connections_free();
373 }
374 break;
375 }
377 // The connection wrapper exposes the pairing surface; success is
378 // reported when the platform's pairing completion arrives.
379 auto *connection = this->get_connection_(msg.address, false);
380 if (connection != nullptr) {
381 if (!connection->is_paired()) {
382 auto err = connection->pair();
383 if (err != CONN_OK) {
384 this->send_device_pairing(msg.address, false, err);
385 }
386 } else {
387 this->send_device_pairing(msg.address, true);
388 }
389 } else {
390 // Answer instead of leaving the client to time out.
391 this->send_device_pairing(msg.address, false, GATT_NOT_CONNECTED);
392 }
393 break;
394 }
397 if (ret == CONN_OK) {
398 // The bond is gone; a live connection must not short-circuit the
399 // next PAIR as already paired.
400 auto *connection = this->get_connection_(msg.address, false);
401 if (connection != nullptr) {
402 connection->set_unpaired();
403 }
404 }
405 this->send_device_unpairing(msg.address, ret == CONN_OK, ret);
406 break;
407 }
410 this->send_device_clear_cache(msg.address, ret == CONN_OK, ret);
411 break;
412 }
414 ESP_LOGE(TAG, "V1 connections removed");
416 break;
417 }
418 }
419}
420
422 auto *connection = this->get_connection_(msg.address, false);
423 if (connection == nullptr) {
424 this->handle_gatt_not_connected_(msg.address, msg.handle, "read", "characteristic");
425 return;
426 }
427
428 auto err = connection->read_characteristic(msg.handle);
429 if (err != CONN_OK) {
430 connection->send_gatt_error_(msg.handle, err);
431 }
432}
433
435 auto *connection = this->get_connection_(msg.address, false);
436 if (connection == nullptr) {
437 this->handle_gatt_not_connected_(msg.address, msg.handle, "write", "characteristic");
438 return;
439 }
440
441 auto err = connection->write_characteristic(msg.handle, msg.data, msg.data_len, msg.response);
442 if (err != CONN_OK) {
443 connection->send_gatt_error_(msg.handle, err);
444 }
445}
446
448 auto *connection = this->get_connection_(msg.address, false);
449 if (connection == nullptr) {
450 this->handle_gatt_not_connected_(msg.address, msg.handle, "read", "descriptor");
451 return;
452 }
453
454 auto err = connection->read_descriptor(msg.handle);
455 if (err != CONN_OK) {
456 connection->send_gatt_error_(msg.handle, err);
457 }
458}
459
461 auto *connection = this->get_connection_(msg.address, false);
462 if (connection == nullptr) {
463 this->handle_gatt_not_connected_(msg.address, msg.handle, "write", "descriptor");
464 return;
465 }
466
467 auto err = connection->write_descriptor(msg.handle, msg.data, msg.data_len, true);
468 if (err != CONN_OK) {
469 connection->send_gatt_error_(msg.handle, err);
470 }
471}
472
474 auto *connection = this->get_connection_(msg.address, false);
475 if (connection == nullptr || !connection->connected()) {
476 this->handle_gatt_not_connected_(msg.address, 0, "get", "services");
477 return;
478 }
479 if (!connection->has_gatt_services()) {
480 ESP_LOGW(TAG, "[%d] [%s] No GATT services found", connection->get_connection_index(), connection->address_str());
481 // Through the retrying sender: a drop must not leave discovery hanging.
482 // Re-entry does not depend on the cursor - this branch is gated on
483 // has_gatt_services() alone, so no restore is needed.
484 connection->send_services_done_();
485 return;
486 }
487 if (connection->send_service_ > 0) {
488 // A request mid-stream restarts from the top so the requester always
489 // gets the full list. No duplicate risk: the client accumulates batches
490 // per request, and a same-session re-request only happens after the
491 // previous request timed out and discarded its partial list.
492 ESP_LOGD(TAG, "[%d] [%s] GetServices mid-stream, restarting", connection->get_connection_index(),
493 connection->address_str());
494 connection->send_service_ = 0;
495 return;
496 }
497 if (connection->send_service_ == SERVICES_DONE_PENDING) {
498 // A new request supersedes an owed done: the client accumulates batches
499 // per request, so its fresh, empty accumulator plus a bare done would
500 // cache as an empty database. The table is freed; the client's timeout
501 // arbitrates.
502 ESP_LOGW(TAG, "[%d] [%s] GetServices superseded an undelivered done; client timeout will retry",
503 connection->get_connection_index(), connection->address_str());
504 connection->send_service_ = DONE_SENDING_SERVICES;
505 return;
506 }
507 if (connection->send_service_ == INIT_SENDING_SERVICES) // Start sending services if not started yet
508 connection->send_service_ = 0;
509}
510
512 auto *connection = this->get_connection_(msg.address, false);
513 if (connection == nullptr) {
514 this->handle_gatt_not_connected_(msg.address, msg.handle, "notify", "characteristic");
515 return;
516 }
517
518 auto err = connection->notify_characteristic(msg.handle, msg.enable);
519 if (err != CONN_OK) {
520 connection->send_gatt_error_(msg.handle, err);
521 }
522}
523
525 if (this->api_connection_ == nullptr)
526 return;
527 // Not latched (esp32 parity): the request is idempotent, so a drop resolves
528 // via the client timeout and a retry gives the same answer. Still reported.
529
530 auto *connection = this->get_connection_(msg.address, false);
532 resp.address = msg.address;
533
534 if (connection == nullptr || !connection->connected()) {
535 ESP_LOGW(TAG, "[%d] [%s] Cannot set connection params, not connected",
536 connection ? static_cast<int>(connection->get_connection_index()) : -1,
537 connection ? connection->address_str() : "unknown");
538 resp.error = GATT_NOT_CONNECTED;
539 if (!this->api_connection_->send_message(resp)) {
540 this->log_reply_dropped_("Connection-params", msg.address);
541 }
542 return;
543 }
544
545 // Protobuf fields are uint32_t to future-proof the API if BLE ever supports wider values;
546 // clamp to uint16_t since the current BLE spec defines these as 16-bit.
547 constexpr uint32_t max_val = std::numeric_limits<uint16_t>::max();
548 resp.error = connection->update_connection_params(static_cast<uint16_t>(std::min(msg.min_interval, max_val)),
549 static_cast<uint16_t>(std::min(msg.max_interval, max_val)),
550 static_cast<uint16_t>(std::min(msg.latency, max_val)),
551 static_cast<uint16_t>(std::min(msg.timeout, max_val)));
552 if (!this->api_connection_->send_message(resp)) {
553 this->log_reply_dropped_("Connection-params", msg.address);
554 }
555}
556
557#endif // USE_BLUETOOTH_PROXY_CONNECTIONS
558
559#ifdef USE_ESP32
560
562 // esp32 only: BLEHub is the concrete tracker here, so these calls reach
563 // tracker-native methods beyond the neutral contract.
564 if (this->hub_->get_scan_active() == active) {
565 return;
566 }
567 ESP_LOGD(TAG, "Setting scanner mode to %s", active ? "active" : "passive");
568 this->hub_->set_scan_active(active);
569 this->hub_->stop_scan();
570 this->hub_->set_scan_continuous(
571 true); // Set this to true to automatically start scanning again when it has cleaned up.
572}
573
574#else // !USE_ESP32
575
577 if (this->hub_->scan_active() != active) {
578 ESP_LOGD(TAG, "Setting scanner mode to %s", active ? "active" : "passive");
579 if (!this->hub_->request_scan_mode(active)) {
580 // Passive-only controller asked for active scanning; the state report
581 // below carries the real, unchanged mode so the subscriber does not
582 // assume the change happened.
583 ESP_LOGW(TAG, "Scanner mode %s not supported by this tracker", active ? "active" : "passive");
584 }
585 }
586#ifndef USE_BLE_SCANNER_STATE_CALLBACK
587 if (this->api_connection_ != nullptr) {
588 // Reports the mode change; the sender also refreshes last_scan_running_, so
589 // a failed restart (scan_running_ dropped by the tracker) is not reported
590 // again by loop() on the next tick. A push hub reports the restart's
591 // transitions (mode rides along) instead.
593 }
594#endif
595}
596
597#endif // USE_ESP32
598
600#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
601 // Stream pending service-discovery batches every iteration; the streamer
602 // handles a vanished API connection itself.
603 for (uint8_t i = 0; i < this->connection_count_; i++) {
604 this->connections_[i]->process_pending_services();
605 }
606#endif
607
608 // Run advertisement flush / scanner-state poll every 100ms
610 if (now - this->last_advertisement_flush_time_ < 100)
611 return;
613
614#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
615 if (this->connections_free_pending_ && this->api_connection_ != nullptr) {
616 // Resend a dropped slot-state update, paced by the 100 ms gate so the
617 // retry does not hammer the congestion it exists to survive. Every build
618 // sends this at subscribe time (api_connection.cpp), so the drain
619 // compiles on every proxy build.
620 this->connections_free_pending_ = false;
622 }
623#endif
624
625 if (!api::global_api_server->is_connected() || this->api_connection_ == nullptr) {
626#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
627 // The API subscriber is gone: tear down any connections it left behind
628 // (disconnect() on an already-disconnecting slot is a no-op).
629 for (uint8_t i = 0; i < this->connection_count_; i++) {
630 auto *connection = this->connections_[i];
631 if (connection->get_address() != 0) {
632 connection->disconnect();
633 }
634 }
635#endif
636 return;
637 }
638
639#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
640 // Paced retries of owed per-slot notifications; subscriber swaps clear
641 // stale latches before this runs.
642 for (uint8_t i = 0; i < this->connection_count_; i++) {
643 this->connections_[i]->flush_owed_replies_();
644 }
645 // Address-keyed, not slot-keyed, so it gets its own loop; bounded by
646 // connection_count_ like the latch and clear helpers. Not pre-cleared:
647 // the sender clears on success and re-latches on refusal, keeping the
648 // latch's leading-edge warn honest (same shape as the unpair drain).
649 for (uint8_t i = 0; i < this->connection_count_; i++) {
650 auto &owed = this->pending_disconnections_[i];
651 if (owed.empty())
652 continue;
653 this->send_device_disconnected_(owed.address(), owed.error());
654 }
655
656 // An owed unpair reply. Not pre-cleared: the sender clears on success and
657 // re-latches on refusal, keeping its leading-edge warn guard honest.
658 if (!this->pending_unpairing_.empty()) {
659 conn_err_t error = this->pending_unpairing_.error();
660 this->send_device_unpairing(this->pending_unpairing_.address(), error == CONN_OK, error);
661 }
662#endif
663
664#ifdef USE_BLE_SCANNER_STATE_CALLBACK
665 // Resend a dropped scanner-state push (see scanner_state_pending_).
666 if (this->scanner_state_pending_) {
667 this->send_scanner_state_(this->hub_->get_scanner_state());
668 }
669#else
670 // This hub doesn't push scanner-state transitions; poll and report on
671 // change. A hub gaining push emits the define and drops this poll.
672 if (this->hub_->scan_running() != this->last_scan_running_) {
674 }
675#endif
676
677#ifdef USE_WIFI
678 // Wi-Fi (or a coexistence build that can fall back to it): every other
679 // non-empty 100 ms tick (~200 ms) gives partial batches time to fill
680 // toward BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE, so the air gets fewer,
681 // fuller frames. Full batches still ship immediately from the queueing
682 // path, and the owed-reply drains above keep the 100 ms cadence.
683 if (this->response_.advertisements_len != 0) {
684 if (this->adv_flush_toggle_) {
686 }
688 } else {
689 // Nothing pending (idle, or a full batch just shipped inline): arm so
690 // the next batch ships on the next tick.
691 this->adv_flush_toggle_ = true;
692 }
693#else
694 // No Wi-Fi in the build (ethernet): no airtime worth trading latency for,
695 // so partial batches flush every tick.
697#endif
698}
699
701#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
702 this->connections_free_pending_ = false;
703#endif
704#ifdef USE_BLE_SCANNER_STATE_CALLBACK
705 // Owed on unsubscribe; on subscribe the trailing send_scanner_state_()
706 // re-drives it from the hub, so clearing it there is free.
707 this->scanner_state_pending_ = false;
708#else
709 // Force a poll-arm mismatch: a frame refused at subscribe time could
710 // otherwise match the stale detector and never be retried. Inert on
711 // unsubscribe: loop() returns at the no-subscriber gate before the
712 // detector runs, and a re-subscribe re-arms this anyway.
713 this->last_scan_running_ = !this->hub_->scan_running();
714#endif
715#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
717 this->pending_disconnections_.fill({});
718 for (uint8_t i = 0; i < this->connection_count_; i++) {
719 // Neither a partial stream's tail nor an owed done belongs to the next
720 // session; silence (the client's timeout) arbitrates.
721 auto *connection = this->connections_[i];
722 connection->park_service_stream_();
723 connection->clear_owed_flags_();
724 }
725#endif
726}
727
729 if (api_connection != this->api_connection_) {
730 if (this->api_connection_ != nullptr) {
731 // A previous subscriber still holds the slot. This is almost always a
732 // stale connection from a client that dropped without a clean disconnect
733 // and has not yet hit the keepalive timeout; rejecting the new
734 // subscriber would silently starve it of advertisements until it
735 // reconnects, so the newest subscriber wins instead.
736 char old_peername[socket::SOCKADDR_STR_LEN];
737 char new_peername[socket::SOCKADDR_STR_LEN];
738 ESP_LOGW(TAG, "Subscription from %s (%s) replaces %s (%s)", api_connection->get_name(),
739 api_connection->get_peername_to(new_peername), this->api_connection_->get_name(),
740 this->api_connection_->get_peername_to(old_peername));
741 }
742 // Stale retry latches belong to the previous subscriber's session; a
743 // re-subscribe by the current one keeps what it is still owed.
744 this->reset_owed_replies_();
745 }
746 this->api_connection_ = api_connection;
747#ifdef USE_BLE_SCANNER_STATE_CALLBACK
748 // get_scanner_state() is part of the push-hub surface (see BLEHubContract).
749 this->send_scanner_state_(this->hub_->get_scanner_state());
750#else
752#endif
753}
754
756 if (this->api_connection_ != api_connection) {
757 ESP_LOGV(TAG, "API connection is not subscribed");
758 return;
759 }
760 this->api_connection_ = nullptr;
761 this->reset_owed_replies_();
762}
763
764#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
766 if (this->api_connection_ != nullptr) {
768 }
769}
770
772 // Latch only for the current subscriber: loop() resends to api_connection_.
773 if (!api_connection->send_message(this->connections_free_response_) && api_connection == this->api_connection_) {
774 // V like the api layer's own buffer-full log: a D would ride the same
775 // full connection.
776 ESP_LOGV(TAG, "Connections-free update deferred, TCP buffer full");
777 this->connections_free_pending_ = true;
778 }
779}
780
781bool BluetoothProxy::send_device_connection(uint64_t address, bool connected, uint16_t mtu, conn_err_t error) {
782 if (this->api_connection_ == nullptr)
783 return true; // Nobody subscribed: nothing owed
786 call.connected = connected;
787 call.mtu = mtu;
788 call.error = error;
789 return this->api_connection_->send_message(call);
790}
791
793 if (this->api_connection_ == nullptr)
794 return true; // Nobody subscribed: nothing is owed, only a refused frame reports false
797 return this->api_connection_->send_message(call);
798}
799
801 if (this->api_connection_ == nullptr)
802 return true; // Nobody subscribed: nothing is owed, only a refused frame reports false
805 call.handle = handle;
806 call.error = error;
807 return this->api_connection_->send_message(call);
808}
809
810void BluetoothProxy::send_device_pairing(uint64_t address, bool paired, conn_err_t error) {
811 if (this->api_connection_ == nullptr)
812 return;
815 call.paired = paired;
816 call.error = error;
817
818 if (!this->api_connection_->send_message(call)) {
819 // Not latched: a retried PAIR is answered from is_paired(), so the client
820 // recovers on its own. Still worth saying it happened.
821 this->log_reply_dropped_("Pairing", address);
822 }
823}
824
825void BluetoothProxy::send_device_unpairing(uint64_t address, bool success, conn_err_t error) {
826 if (this->api_connection_ == nullptr)
827 return;
828 // An owed success is the authoritative answer: a later attempt for the
829 // same address fails only because the first already removed the bond.
830 if (!this->pending_unpairing_.empty() && this->pending_unpairing_.matches(address) &&
831 this->pending_unpairing_.error() == CONN_OK) {
832 success = true;
833 error = CONN_OK;
834 }
837 call.success = success;
838 call.error = error;
839
840 if (this->api_connection_->send_message(call)) {
841 // A later unpair landing for an address that still has one owed would
842 // otherwise have the drain repeat it.
843 if (this->pending_unpairing_.matches(address)) {
845 }
846 return;
847 }
848 if (this->pending_unpairing_.empty()) {
849 this->log_reply_deferred_("Unpair", address);
850 } else if (!this->pending_unpairing_.matches(address)) {
851 this->log_reply_displaced_("Unpair", this->pending_unpairing_.address(), address);
852 }
853 this->pending_unpairing_.set(address, error);
854}
855
856// GATT arm only: the advertisement-only arm no longer dispatches CLEAR_CACHE,
857// so its response encoder would be dead weight there.
858void BluetoothProxy::send_device_clear_cache(uint64_t address, bool success, conn_err_t error) {
859 if (this->api_connection_ == nullptr)
860 return;
863 call.success = success;
864 call.error = error;
865
866 if (!this->api_connection_->send_message(call)) {
867 // Not latched: clear-cache is idempotent, so a retry gives the same answer.
868 this->log_reply_dropped_("Clear-cache", address);
869 }
870}
871#endif // USE_BLUETOOTH_PROXY_CONNECTIONS
872
873BluetoothProxy *global_bluetooth_proxy = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
874
875} // namespace esphome::bluetooth_proxy
876
877#endif // USE_BLUETOOTH_PROXY
uint8_t address
Definition bl0906.h:4
uint8_t raw[35]
Definition bl0939.h:0
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
const char * get_peername_to(std::span< char, socket::SOCKADDR_STR_LEN > buf) const
Get peer name (IP address) into caller-provided buffer, returns buf for convenience.
const char * get_name() const
bool send_message(const T &msg)
Returns false as soon as the TCP buffer is full.
std::array< uint64_t, BLUETOOTH_PROXY_MAX_CONNECTIONS > allocated
Definition api_pb2.h:2276
enums::BluetoothDeviceRequestType request_type
Definition api_pb2.h:2014
std::array< BluetoothLERawAdvertisement, BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE > advertisements
Definition api_pb2.h:1994
enums::BluetoothScannerMode mode
Definition api_pb2.h:2401
enums::BluetoothScannerState state
Definition api_pb2.h:2400
enums::BluetoothScannerMode configured_mode
Definition api_pb2.h:2402
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)
void log_reply_deferred_(const char *what, uint64_t address)
A latched reply's leading edge; the drain's re-refusals stay quiet.
void get_bluetooth_mac_address_pretty(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > output)
void on_raw_advertisement_(const ble_device_base::RawAdvertisement &raw)
bool adv_flush_toggle_
Wi-Fi only: flush on every other non-empty tick (~200 ms) so partial batches fill; an idle tick re-ar...
void log_not_connected_gatt_(const char *action, const char *type)
void send_scanner_state_(ble_device_base::ScannerState state)
void answer_device_disconnected_(uint64_t address)
Answer a request with connected=false.
void bluetooth_device_request(const api::BluetoothDeviceRequest &msg)
void send_device_unpairing(uint64_t address, bool success, conn_err_t error)
No default error: the drain rebuilds success as (error == CONN_OK), so a caller that omitted it would...
void replace_allocated_slot_(uint64_t find_value, uint64_t set_value)
bool send_gatt_services_done(uint64_t address)
Same convention as send_device_connection: false only on a refused frame.
void bluetooth_gatt_write_descriptor(const api::BluetoothGATTWriteDescriptorRequest &msg)
std::array< PendingReply, BLUETOOTH_PROXY_MAX_CONNECTIONS > pending_disconnections_
void subscribe_api_connection(api::APIConnection *api_connection, uint32_t flags)
void send_device_clear_cache(uint64_t address, bool success, conn_err_t error=CONN_OK)
void reset_connection_slot_(BluetoothConnection *connection, conn_err_t reason)
Free a connection slot after teardown: notify the API client and reset the streaming cursor.
void unsubscribe_api_connection(api::APIConnection *api_connection)
void register_connection(BluetoothConnection *connection)
void send_device_pairing(uint64_t address, bool paired, conn_err_t error=CONN_OK)
bool send_gatt_error(uint64_t address, uint16_t handle, conn_err_t error)
False only when the API refused the frame, so the reply is still owed.
api::BluetoothLERawAdvertisementsResponse response_
void send_device_disconnected_(uint64_t address, conn_err_t error=CONN_OK)
Send connected=false and pool it for the paced drain if refused.
void log_connection_info_(BluetoothConnection *connection, const char *message)
void reset_owed_replies_()
Drop everything the ending session was owed.
bool send_device_connection(uint64_t address, bool connected, uint16_t mtu=0, conn_err_t error=CONN_OK)
False only when a subscriber refused the frame; true = delivered or nobody subscribed.
void log_reply_displaced_(const char *what, uint64_t owed, uint64_t address)
A latched reply lost to a newer one for a different address.
BluetoothConnection * get_connection_(uint64_t address, bool reserve)
void bluetooth_set_connection_params(const api::BluetoothSetConnectionParamsRequest &msg)
bool send_bluetooth_scanner_state_(ble_device_base::ScannerState state)
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 log_reply_dropped_(const char *what, uint64_t address)
Report a reply we deliberately do not latch, so no drop is silent.
void flush_pending_advertisements_()
Caller must ensure api_connection_ is non-null and API server is connected.
std::array< BluetoothConnection *, BLUETOOTH_PROXY_MAX_CONNECTIONS > connections_
void latch_pending_disconnection_(uint64_t address, conn_err_t error)
Pool a refused freed-slot notification for the paced drain.
api::BluetoothConnectionsFreeResponse connections_free_response_
void log_connection_request_ignored_(BluetoothConnection *connection, ClientState state)
void clear_pending_disconnection_(uint64_t address)
Drop any owed freed-slot notification for this address (client reconnected).
One owed address-keyed reply in a single word: 48-bit address low, 16-bit error on top.
constexpr uint64_t address() const
constexpr bool matches(uint64_t address) const
constexpr void set(uint64_t address, conn_err_t error)
constexpr conn_err_t error() const
const LogString * message
Definition component.cpp:35
uint16_t type
uint16_t flags
bool state
Definition fan.h:2
int ret
@ BLUETOOTH_DEVICE_REQUEST_TYPE_UNPAIR
Definition api_pb2.h:233
@ BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITH_CACHE
Definition api_pb2.h:234
@ BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT
Definition api_pb2.h:230
@ BLUETOOTH_DEVICE_REQUEST_TYPE_PAIR
Definition api_pb2.h:232
@ BLUETOOTH_DEVICE_REQUEST_TYPE_CONNECT_V3_WITHOUT_CACHE
Definition api_pb2.h:235
@ BLUETOOTH_DEVICE_REQUEST_TYPE_CLEAR_CACHE
Definition api_pb2.h:236
@ BLUETOOTH_DEVICE_REQUEST_TYPE_DISCONNECT
Definition api_pb2.h:231
@ BLUETOOTH_SCANNER_MODE_PASSIVE
Definition api_pb2.h:249
@ BLUETOOTH_SCANNER_MODE_ACTIVE
Definition api_pb2.h:250
@ BLUETOOTH_SCANNER_STATE_STOPPED
Definition api_pb2.h:246
@ BLUETOOTH_SCANNER_STATE_STARTING
Definition api_pb2.h:242
@ BLUETOOTH_SCANNER_STATE_STOPPING
Definition api_pb2.h:245
@ BLUETOOTH_SCANNER_STATE_RUNNING
Definition api_pb2.h:243
@ BLUETOOTH_SCANNER_STATE_FAILED
Definition api_pb2.h:244
APIServer * global_api_server
const char * client_state_to_string(ClientState state)
ScannerState
Scanner lifecycle, wire-value aligned with the api enum so consumers cast directly (pinned by static_...
Definition ble_hub.h:53
conn_err_t unpair_device(uint64_t address)
conn_err_t clear_gatt_cache(uint64_t address)
BluetoothProxy * global_bluetooth_proxy
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
One raw advertisement as delivered by the controller — a borrowed view, valid only for the duration o...
Definition ble_hub.h:24
uint16_t length
Definition tt21100.cpp:0
spi_device_handle_t handle