ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
bluetooth_connection_hub.cpp
Go to the documentation of this file.
1// The proxy's per-slot connection wrapper, shared by every platform.
2//
3// SERVICE STREAMING HAZARD - read before touching the streaming code here or
4// in the platform streamers (bluetooth_connection_bluedroid.cpp).
5//
6// A V3 client caches the service list it receives as the device's complete,
7// permanent database. Nothing on the wire marks a list as partial, so a
8// stream that is truncated, has a skipped batch, or is terminated early
9// would be cached whole and poison every later session with the device.
10//
11// The rule: it is always better to send nothing and let the client time out
12// than to let services-done follow an incomplete stream. Concretely:
13// - a refused batch rewinds the cursor and is retried, never skipped;
14// - services-done is sent only after every batch was accepted;
15// - every interruption (subscriber lost or swapped, backend abort,
16// bounds-check failure) parks or aborts WITHOUT services-done and drops
17// any owed done;
18// - a new GetServices supersedes an owed done, so a stale done can never
19// land on a fresh request's empty accumulator and cache it as empty.
20// The client only caches a list terminated by services-done within the same
21// request; timeouts, disconnects and errors raise instead of caching.
23#include "relaxed_conn_params.h"
24
25#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
26
29#include "esphome/core/hal.h"
31#include "esphome/core/log.h"
32
34
35ESPHOME_LOG_TAG(TAG, "bluetooth_connection");
36
37// Shared by every slot, as a retry can land on another one
38// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
39static RelaxedConnParams relaxed_conn_params;
40
42 // Keep the proxy's pre-allocated connections-free message in step
43 this->proxy_->update_address_slot_(this->address_, address);
44 // Slot changing hands: anything owed belonged to the old address. The
45 // choke point for every reassignment, not just reset_connection_()'s path.
46 this->clear_owed_flags_();
47 this->address_ = address;
48 if (address == 0) {
49 this->address_str_[0] = '\0';
50 return;
51 }
52 uint8_t mac[MAC_ADDRESS_SIZE];
55}
56
57void BluetoothConnection::initiate_connection(uint8_t address_type) {
58 // No connect timeout here: the API client's own timeout or the api-gone
59 // sweep drives disconnect().
60 this->state_ = ClientState::CONNECTING;
61 this->forget_relaxed_ = false;
62 // Backends apply it to uncached connects only; cached ones always use MEDIUM
63 bool relaxed = relaxed_conn_params.use_relaxed(this->address_);
64 this->opened_relaxed_ = relaxed;
65 this->backend_->set_relaxed_open(relaxed);
66 int err = this->backend_->connect(this->address_, address_type);
67 if (err != 0) {
68 ESP_LOGW(TAG, "[%d] [%s] connect failed, err=%d", this->connection_index_, this->address_str_, err);
69 this->reset_connection_(err);
70 }
71}
72
74 // Idempotent: the proxy's teardown loop calls this every 100 ms while the
75 // API subscriber is gone, and a repeat call reaching the backend would
76 // re-arm its teardown timer so the safety timeout never fires.
77 if (this->state_ == ClientState::IDLE || this->state_ == ClientState::DISCONNECTING) {
78 return;
79 }
80 int err = this->backend_->gatt_disconnect();
81 if (err != 0) {
82 // Nonzero means nothing to tear down (both backends): free the slot.
83 // Accepted teardowns always reach a terminal report.
84 ESP_LOGW(TAG, "[%d] [%s] disconnect while backend idle, err=%d", this->connection_index_, this->address_str_, err);
85 this->reset_connection_(err);
86 return;
87 }
88 this->state_ = ClientState::DISCONNECTING;
89}
90
92 if (this->address_ == 0) {
93 // A drop before completion already answered: reset_connection_slot_ sends
94 // the connection response, which the client's pair watcher raises on.
95 return;
96 }
97 this->paired_ = status == 0;
98 this->proxy_->send_device_pairing(this->address_, status == 0, status);
99}
100
102 if (this->pending_error_ != 0) {
103 reason = this->pending_error_;
104 this->pending_error_ = 0;
105 }
106 if (this->forget_relaxed_ && !this->services_discovered_ && relaxed_conn_params.forget(this->address_))
107 this->log_mode_change_(false);
108 this->forget_relaxed_ = false;
109 this->state_ = ClientState::IDLE;
110 this->services_discovered_ = false;
111 this->paired_ = false;
112 // Link gone: the slot may hold a different device before the drain runs.
113 this->clear_owed_flags_();
114 this->backend_->release_services();
115 this->proxy_->reset_connection_slot_(this, reason);
116}
117
118// ---- backend event listener ----
119
120void BluetoothConnection::on_connection_state(bool connected, uint16_t mtu, int error) {
121 if (connected && this->address_ == 0) {
122 // Late completion for a slot that was already freed: nothing to report,
123 // and the api-gone sweep or a new reservation owns the slot now.
124 // Return ignored: nonzero just means the backend was already idle, and
125 // re-arming a freed slot could clobber a new reservation.
126 this->backend_->gatt_disconnect();
127 return;
128 }
129 if (connected && this->state_ == ClientState::DISCONNECTING) {
130 // The link came up after a disconnect request won the race; finish the
131 // teardown instead of reporting a connection the client no longer wants.
132 int err = this->backend_->gatt_disconnect();
133 if (err != 0) {
134 // Nothing left to tear down after all.
135 this->reset_connection_(err);
136 }
137 return;
138 }
139 if (connected) {
140 this->mtu_ = mtu;
141 if (this->connection_type_ == ConnectionType::V3_WITH_CACHE) {
142 // The API client has the services cached; never discover them. No
143 // discovery phase needs the fast interval, so settle straight into the
144 // shared steady-state parameters. Both backends already open cached
145 // connections with these values (esp32 prefer-params, rp2 initiating
146 // params), so this request is normally redundant - kept as a backstop
147 // in case the initial parameters were negotiated away.
148 this->state_ = ClientState::ESTABLISHED;
149 // The one D-level line for a cached connect; the uncached path narrates
150 // through "Discovery finished" instead.
151 ESP_LOGD(TAG, "[%d] [%s] Connected with cached services, sending connected (mtu=%u)", this->connection_index_,
152 this->address_str_, mtu);
153 int param_err = this->backend_->update_connection_params(ble_device_base::MEDIUM_MIN_CONN_INTERVAL,
154 ble_device_base::MEDIUM_MAX_CONN_INTERVAL, 0,
155 ble_device_base::MEDIUM_CONN_TIMEOUT);
156 if (param_err != 0) {
157 // Survivable: the link just stays on the fast interval.
158 ESP_LOGW(TAG, "[%d] [%s] conn param update failed, err=%d", this->connection_index_, this->address_str_,
159 param_err);
160 }
161 this->send_connected_reply_();
163 return;
164 }
165 // V3_WITHOUT_CACHE: discover services first — the connected response is
166 // sent when discovery completes (MTU + services before the response).
167 this->state_ = ClientState::CONNECTED;
168 int err = this->backend_->discover_services();
169 if (err != 0) {
170 ESP_LOGW(TAG, "[%d] [%s] discover_services failed, err=%d", this->connection_index_, this->address_str_, err);
171 // Latch the real cause for the disconnect report.
172 this->latch_pending_error_(err);
173 this->disconnect();
174 }
175 return;
176 }
177 // Disconnected, connect failed, or teardown complete
178 if (this->address_ == 0) {
179 return; // Slot already freed
180 }
181 ESP_LOGD(TAG, "[%d] [%s] Disconnected, reason=0x%02x, freeing slot", this->connection_index_, this->address_str_,
182 error);
183 this->reset_connection_(error);
184}
185
186void BluetoothConnection::on_link_open(bool established) {
187 if (this->address_ == 0 || this->connection_type_ != ConnectionType::V3_WITHOUT_CACHE)
188 return;
189 if (this->opened_relaxed_) {
190 // A link that came up only after a cancel won the race does not count
191 if (!established || this->state_ != ClientState::DISCONNECTING)
192 this->forget_relaxed_ = true;
193 } else if (established) {
194 relaxed_conn_params.fast_connected(this->address_);
195 } else if (relaxed_conn_params.fast_failed(this->address_)) {
196 this->log_mode_change_(true);
197 }
198}
199
201 ESP_LOGW(TAG, "[%d] [%s] %s, next attempt uses %s", this->connection_index_, this->address_str_,
202 relaxed ? LOG_STR_LITERAL("Link not established at FAST twice")
203 : LOG_STR_LITERAL("MEDIUM attempt did not finish"),
204 relaxed ? LOG_STR_LITERAL("MEDIUM") : LOG_STR_LITERAL("FAST"));
205}
206
208 if (error != 0) {
209 ESP_LOGW(TAG, "[%d] [%s] Service discovery failed, err=%d", this->connection_index_, this->address_str_, error);
210 // Carry the GATT error into the disconnection report so the client sees
211 // the real cause instead of a generic HCI reason.
212 this->latch_pending_error_(error);
213 this->disconnect();
214 return;
215 }
216 ESP_LOGD(TAG, "[%d] [%s] Discovery finished, sending connected (mtu=%u)", this->connection_index_, this->address_str_,
217 this->mtu_);
218 this->state_ = ClientState::ESTABLISHED;
219 this->services_discovered_ = true;
220 this->send_connected_reply_();
222}
223
225 // Connected first: the client should never see services-done or an ack for
226 // a link it has not been told is up. Structural, not size-dependent: a
227 // still-owed connected reply defers the smaller sends to the next tick.
228 if (this->connected_reply_owed_) {
229 this->send_connected_reply_();
230 if (this->connected_reply_owed_) {
231 // The retry limits are wall-clock windows: age the deferred budgets so
232 // a reply cannot outlive the window it was sized for.
233 if (this->send_service_ == SERVICES_DONE_PENDING) {
234 this->age_services_done_();
235 }
236 if (this->has_pending_ack_()) {
237 this->age_pending_ack_();
238 }
239 return;
240 }
241 }
242 if (this->send_service_ == SERVICES_DONE_PENDING) {
243 this->send_services_done_();
244 }
245 if (this->has_pending_ack_()) {
246 this->flush_pending_ack_();
247 }
248}
249
251 if (this->proxy_->send_device_connection(this->address_, true, this->mtu_)) {
252 this->connected_reply_owed_ = false;
253 return;
254 }
255 // Warn on the leading edge only, as elsewhere: the drop must be visible but
256 // must not add traffic to the connection that just refused a frame.
257 if (!this->connected_reply_owed_) {
258 ESP_LOGW(TAG, "[%d] [%s] Connected reply deferred, TCP buffer full", this->connection_index_, this->address_str_);
259 this->connected_reply_owed_ = true;
260 }
261}
262
263void BluetoothConnection::log_gatt_operation_error_(const char *operation, uint16_t handle, int status) {
264 ESP_LOGW(TAG, "[%d] [%s] Error %s for handle 0x%2X, status=%d", this->connection_index_, this->address_str_,
265 operation, handle, status);
266}
267
269 if (this->batch_stalled_)
270 return;
271 this->batch_stalled_ = true;
272 ESP_LOGW(TAG, "[%d] [%s] Service batch deferred, TCP buffer full; retrying", this->connection_index_,
273 this->address_str_);
274}
275
277template<typename Response>
278static bool send_handle_reply(api::APIConnection *api_connection, uint64_t address, uint16_t handle) {
279 Response resp;
280 resp.address = address;
281 resp.handle = handle;
282 return api_connection->send_message(resp);
283}
284
287 if (kind == PendingAck::PENDING_ACK_ERROR) {
288 // Proxy owns the error reply and reports a refusal the same way.
289 return this->proxy_->send_gatt_error(this->address_, handle, error);
290 }
291 auto *api_connection = this->proxy_->get_api_connection();
292 if (api_connection == nullptr)
293 return true; // Nobody subscribed: nothing is owed
294 switch (kind) {
296 return send_handle_reply<api::BluetoothGATTWriteResponse>(api_connection, this->address_, handle);
298 return send_handle_reply<api::BluetoothGATTNotifyResponse>(api_connection, this->address_, handle);
300 case PendingAck::PENDING_ACK_ERROR: // returned above
301 return true;
302 }
303 // No default label above, so a new enumerator is a -Wswitch warning rather
304 // than a silent notify reply. This return only satisfies -Wreturn-type.
305 return true;
306}
307
309 if (this->try_send_ack_(kind, handle, error))
310 return;
311 // Report a newly owed reply and a displaced one; displacing is the case
312 // that loses a reply. Re-refusing the same one stays quiet, and so does a
313 // fresh deferral for the handle already warned about: a congested bulk
314 // transfer re-asks the same handle every cycle and each ack would warn.
315 if (!this->has_pending_ack_()) {
316 if (!this->ack_deferred_warned_ || this->pending_ack_handle_ != handle) {
317 ESP_LOGW(TAG, "[%d] [%s] GATT reply for handle 0x%04X deferred, TCP buffer full", this->connection_index_,
318 this->address_str_, handle);
319 this->ack_deferred_warned_ = true;
320 }
321 } else if (this->pending_ack_handle_ != handle || this->pending_ack_ != kind) {
322 ESP_LOGW(TAG, "[%d] [%s] GATT reply for handle 0x%04X dropped for handle 0x%04X", this->connection_index_,
323 this->address_str_, this->pending_ack_handle_, handle);
324 }
325 this->latch_pending_ack_(kind, handle, error);
326}
327
329 if (!this->has_pending_ack_())
330 return;
331 if (this->try_send_ack_(this->pending_ack_, this->pending_ack_handle_, this->pending_ack_error_)) {
332 this->clear_pending_ack_();
333 return;
334 }
335 this->age_pending_ack_();
336}
337
339 if (++this->pending_ack_retries_ >= PENDING_ACK_RETRY_LIMIT) {
340 // Undeliverable: past here the client has given up and may have re-asked,
341 // and a late reply would answer the new request instead of this one.
342 ESP_LOGW(TAG, "[%d] [%s] GATT reply for handle 0x%04X undeliverable, abandoning", this->connection_index_,
343 this->address_str_, this->pending_ack_handle_);
344 this->clear_pending_ack_();
345 }
346}
347
348void BluetoothConnection::on_read_result(uint16_t handle, const uint8_t *data, uint16_t len, int error) {
349 // Late completion for a freed slot; nothing to report.
350 if (this->address_ == 0)
351 return;
352 if (error != 0) {
353 this->log_gatt_operation_error_("reading char/descriptor", handle, error);
354 this->send_gatt_error_(handle, error);
355 return;
356 }
357 auto *api_connection = this->proxy_->get_api_connection();
358 if (api_connection == nullptr)
359 return;
361 resp.address = this->address_;
362 resp.handle = handle;
363 resp.set_data(data, len);
364 if (!api_connection->send_message(resp)) {
365 // Not latched: would mean holding the payload through the congestion
366 // that refused it. The client's read timeout arbitrates.
367 ESP_LOGW(TAG, "[%d] [%s] Failed to send read response", this->connection_index_, this->address_str_);
368 }
369}
370
372 if (this->address_ == 0)
373 return;
374 if (error != 0) {
375 this->log_gatt_operation_error_("writing char/descriptor", handle, error);
376 this->send_gatt_error_(handle, error);
377 return;
378 }
380}
381
382void BluetoothConnection::on_notify_state(uint16_t handle, bool enabled, int error) {
383 if (this->address_ == 0)
384 return;
385 if (error != 0) {
386 this->log_gatt_operation_error_(enabled ? "registering notifications" : "unregistering notifications", handle,
387 error);
388 this->send_gatt_error_(handle, error);
389 return;
390 }
392}
393
394void BluetoothConnection::on_notify_data(uint16_t handle, const uint8_t *data, uint16_t len) {
395 if (this->address_ == 0)
396 return;
397 ESP_LOGV(TAG, "[%d] [%s] Notify: handle=0x%2X", this->connection_index_, this->address_str_, handle);
398 auto *api_connection = this->proxy_->get_api_connection();
399 if (api_connection == nullptr)
400 return;
402 resp.address = this->address_;
403 resp.handle = handle;
404 resp.set_data(data, len);
405 if (!api_connection->send_message(resp)) {
406 // Not latched, same reason as the read reply. Notify data is lossy: the
407 // peripheral will not resend it. Warn on the first drop only; a congested
408 // link drops a whole stream and one line per notify floods the log.
409 if (!this->notify_drop_warned_) {
410 ESP_LOGW(TAG, "[%d] [%s] Failed to send notify data response, handle 0x%04X", this->connection_index_,
411 this->address_str_, handle);
412 this->notify_drop_warned_ = true;
413 } else {
414 ESP_LOGV(TAG, "[%d] [%s] Failed to send notify data response, handle 0x%04X", this->connection_index_,
415 this->address_str_, handle);
416 }
417 }
418}
419
420// ---- GATT operations ----
421
422conn_err_t BluetoothConnection::check_connected_op_(const char *action, const char *type) const {
423 if (this->connected()) {
424 return CONN_OK;
425 }
426 ESP_LOGW(TAG, "[%d] [%s] Cannot %s GATT %s, not connected.", this->connection_index_, this->address_str_, action,
427 type);
428 return GATT_NOT_CONNECTED;
429}
430
433 if (conn_err_t err = this->check_connected_op_("read", "characteristic"); err != CONN_OK)
434 return err;
435 ESP_LOGV(TAG, "[%d] [%s] Reading GATT characteristic handle %d", this->connection_index_, this->address_str_, handle);
436 return this->backend_->read_characteristic(handle);
437}
438
440 bool response) {
442 if (conn_err_t err = this->check_connected_op_("write", "characteristic"); err != CONN_OK)
443 return err;
444 ESP_LOGV(TAG, "[%d] [%s] Writing GATT characteristic handle %d", this->connection_index_, this->address_str_, handle);
445 return this->backend_->write_characteristic(handle, data, static_cast<uint16_t>(length), response);
446}
447
450 if (conn_err_t err = this->check_connected_op_("read", "descriptor"); err != CONN_OK)
451 return err;
452 ESP_LOGV(TAG, "[%d] [%s] Reading GATT descriptor handle %d", this->connection_index_, this->address_str_, handle);
453 return this->backend_->read_descriptor(handle);
454}
455
456// The neutral backend contract performs descriptor writes acknowledged, so
457// the response flag is intentionally ignored (esp32 maps it to RSP/NO_RSP).
458conn_err_t BluetoothConnection::write_descriptor(uint16_t handle, const uint8_t *data, size_t length,
459 bool /*response*/) {
461 if (conn_err_t err = this->check_connected_op_("write", "descriptor"); err != CONN_OK)
462 return err;
463 ESP_LOGV(TAG, "[%d] [%s] Writing GATT descriptor handle %d", this->connection_index_, this->address_str_, handle);
464 return this->backend_->write_descriptor(handle, data, static_cast<uint16_t>(length));
465}
466
469 if (conn_err_t err = this->check_connected_op_("notify", "characteristic"); err != CONN_OK)
470 return err;
471 ESP_LOGV(TAG, "[%d] [%s] %s GATT characteristic notifications handle %d", this->connection_index_, this->address_str_,
472 enable ? "Registering for" : "Unregistering for", handle);
473 return this->backend_->notify_characteristic(handle, enable);
474}
475
476conn_err_t BluetoothConnection::update_connection_params(uint16_t min_interval, uint16_t max_interval, uint16_t latency,
477 uint16_t timeout) {
478 if (conn_err_t err = this->check_connected_op_("update params of", "connection"); err != CONN_OK)
479 return err;
480 return this->backend_->update_connection_params(min_interval, max_interval, latency, timeout);
481}
482
483// ---- Service streaming ----
484
486 if (this->proxy_->send_gatt_services_done(this->address_)) {
487 // Sent, or subscriber gone (park silently; its timeout arbitrates).
488 this->send_service_ = DONE_SENDING_SERVICES;
489 return;
490 }
491 if (this->send_service_ != SERVICES_DONE_PENDING) {
492 // Warn on the transition only; retries stay silent.
493 ESP_LOGW(TAG, "[%d] [%s] Failed to send services done, retrying", this->connection_index_, this->address_str_);
494 this->services_done_retries_ = 0;
495 this->send_service_ = SERVICES_DONE_PENDING;
496 } else {
497 this->age_services_done_();
498 }
499}
500
502 if (++this->services_done_retries_ >= SERVICES_DONE_RETRY_LIMIT) {
503 // Undeliverable (see SERVICES_DONE_RETRY_LIMIT); silence arbitrates.
504 ESP_LOGW(TAG, "[%d] [%s] Services done undeliverable, abandoning", this->connection_index_, this->address_str_);
505 this->send_service_ = DONE_SENDING_SERVICES;
506 }
507}
508
510 auto table = this->backend_->get_service_table();
511 if (this->send_service_ >= table.service_count) {
512 this->backend_->release_services();
513 this->send_services_done_();
514 return;
515 }
516
517 // The subscriber vanished mid-stream; the api-gone sweep tears the
518 // connection down anyway.
519 auto *api_conn = this->proxy_->get_api_connection();
520 if (api_conn == nullptr) {
521 ESP_LOGW(TAG, "[%d] [%s] API connection lost while streaming services", this->connection_index_,
522 this->address_str_);
523 this->park_service_stream_();
524 return;
525 }
526
527 // Check if client supports efficient UUIDs
528 bool use_efficient_uuids = this->proxy_->client_supports_efficient_uuids();
529
530 // Prepare response
532 resp.address = this->address_;
533
534 // Dynamic batching based on actual size, same contract as the esp32 streamer
535 size_t current_size = resp.calculate_size();
536 int16_t batch_start = this->send_service_;
537
538 while (this->send_service_ < table.service_count) {
539 const auto &service = table.services[this->send_service_];
540
541 // If this service likely won't fit, send current batch (unless it's the first)
542 size_t estimated_size = estimate_service_size(service.characteristic_count, use_efficient_uuids);
543 if (!resp.services.empty() && (current_size + estimated_size > MAX_PACKET_SIZE)) {
544 break;
545 }
546
547 resp.services.emplace_back();
548 auto &service_resp = resp.services.back();
549 fill_gatt_uuid(service_resp.uuid, service_resp.short_uuid, service.uuid, use_efficient_uuids);
550 service_resp.handle = service.start_handle;
551
552 // Bounds-check the backend's index ranges against the table totals rather
553 // than trusting its discovery bookkeeping blindly. A miscounted non-empty
554 // range must not stream a truncated database as authoritative (V3 clients
555 // cache it permanently): abort and tear the connection down; the client
556 // times out and retries. Empty ranges are tolerated regardless of index.
557 uint16_t char_count = service.characteristic_count;
558 if (char_count != 0 && service.first_characteristic + char_count > table.characteristic_count) {
559 ESP_LOGE(TAG, "[%d] [%s] Characteristic range out of bounds (service %d), aborting stream",
560 this->connection_index_, this->address_str_, this->send_service_);
561 this->abort_service_stream(ble_device_base::GATT_ERR_UNLIKELY);
562 return;
563 }
564 if (char_count > 0) {
565 service_resp.characteristics.init(char_count);
566 for (uint16_t ci = 0; ci < char_count; ci++) {
567 const auto &chr = table.characteristics[service.first_characteristic + ci];
568 service_resp.characteristics.emplace_back();
569 auto &characteristic_resp = service_resp.characteristics.back();
570 fill_gatt_uuid(characteristic_resp.uuid, characteristic_resp.short_uuid, chr.uuid, use_efficient_uuids);
571 characteristic_resp.handle = chr.value_handle;
572 characteristic_resp.properties = chr.properties;
573 uint16_t desc_count = chr.descriptor_count;
574 if (desc_count != 0 && chr.first_descriptor + desc_count > table.descriptor_count) {
575 ESP_LOGE(TAG, "[%d] [%s] Descriptor range out of bounds (service %d), aborting stream",
576 this->connection_index_, this->address_str_, this->send_service_);
577 this->abort_service_stream(ble_device_base::GATT_ERR_UNLIKELY);
578 return;
579 }
580 if (desc_count == 0) {
581 continue;
582 }
583 characteristic_resp.descriptors.init(desc_count);
584 for (uint16_t di = 0; di < desc_count; di++) {
585 const auto &desc = table.descriptors[chr.first_descriptor + di];
586 characteristic_resp.descriptors.emplace_back();
587 auto &descriptor_resp = characteristic_resp.descriptors.back();
588 fill_gatt_uuid(descriptor_resp.uuid, descriptor_resp.short_uuid, desc.uuid, use_efficient_uuids);
589 descriptor_resp.handle = desc.handle;
590 }
591 }
592 }
593
594 if (close_service_batch(resp, current_size, this->send_service_, this->connection_index_, this->address_str_) !=
596 break;
597 }
598 }
599
600 // Send the message with dynamically batched services; on a failed send,
601 // rewind the cursor so the batch is retried instead of silently skipped
602 // (bounded: a subscriber that stays gone ends streaming via the api-lost
603 // rewind above).
604 if (!api_conn->send_message(resp)) {
605 this->note_batch_stalled_();
606 this->send_service_ = batch_start;
607 return;
608 }
609 this->batch_stalled_ = false;
610}
611
612} // namespace esphome::bluetooth_connection
613
614#endif // USE_BLUETOOTH_PROXY_CONNECTIONS
uint8_t status
Definition bl0942.h:8
bool send_message(const T &msg)
Returns false as soon as the TCP buffer is full.
std::vector< BluetoothGATTService > services
Definition api_pb2.h:2624
void set_data(const uint8_t *data, size_t len)
Definition api_pb2.h:2796
void set_data(const uint8_t *data, size_t len)
Definition api_pb2.h:2687
bool try_send_ack_(PendingAck kind, uint16_t handle, conn_err_t error)
Sole construction site for these replies, shared by send and retry.
void on_read_result(uint16_t handle, const uint8_t *data, uint16_t len, int error) override
void initiate_connection(uint8_t address_type)
Start connecting with the API address type (BLE_ADDR_TYPE_* code space).
void latch_pending_ack_(PendingAck kind, uint16_t handle, conn_err_t error=0)
Latch a refused reply for the proxy drain.
conn_err_t write_descriptor(uint16_t handle, const uint8_t *data, size_t length, bool response)
bool connected_reply_owed_
An owed connected=true reply; the proxy's paced drain re-offers it.
void supersede_pending_ack_(uint16_t handle, PendingAck kind)
Drop an owed reply this re-ask makes stale.
void latch_pending_error_(conn_err_t err)
First cause wins: a later, less specific error must not overwrite it.
void abort_service_stream(conn_err_t err)
Streamer abort: latch the GATT cause, park the cursor, tear down.
void age_pending_ack_()
Advance the retry budget and abandon at the limit, without sending.
void send_gatt_error_(uint16_t handle, conn_err_t error)
Report a rejected request.
conn_err_t check_connected_op_(const char *action, const char *type) const
void age_services_done_()
Advance the retry budget and abandon at the limit, without sending.
void log_gatt_operation_error_(const char *operation, uint16_t handle, int status)
bool notify_drop_warned_
Set on the first dropped notify; later drops log at verbose only.
void on_write_result(uint16_t handle, int error) override
bool batch_stalled_
Set while a refused batch is retrying, so only the first one warns.
void flush_pending_ack_()
Re-offer the owed reply; clears on success, stays owed on a refusal.
bool forget_relaxed_
This MEDIUM attempt failed or its link came up; reset sends the address back to FAST unless discovery...
void on_notify_state(uint16_t handle, bool enabled, int error) override
conn_err_t notify_characteristic(uint16_t handle, bool enable)
void on_connection_state(bool connected, uint16_t mtu, int error) override
void send_services_done_()
Send services-done and settle the cursor: DONE when it lands (or no subscriber), SERVICES_DONE_PENDIN...
bool ack_deferred_warned_
Set once the deferred warn fired; with an unchanged pending_ack_handle_ it keeps re-deferrals of the ...
void park_service_stream_()
Park the stream without services-done and free any held table: an interrupted stream must never be de...
void flush_owed_replies_()
Re-offer everything this slot owes.
void note_batch_stalled_()
Warn on the stall's leading edge only.
conn_err_t write_characteristic(uint16_t handle, const uint8_t *data, size_t length, bool response)
void on_notify_data(uint16_t handle, const uint8_t *data, uint16_t len) override
void send_ack_(PendingAck kind, uint16_t handle, conn_err_t error=0)
First attempt: send, and latch it for the drain if the API refuses.
void send_connected_reply_()
Send the connected=true reply, latching it if the API refuses.
conn_err_t update_connection_params(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout)
void clear_owed_flags_()
Drop everything this slot owes, in one write to the shared tail byte.
void fast_connected(uint64_t address)
A FAST link came up: forgets a single earlier failure. Relaxed entries stay.
bool send_gatt_services_done(uint64_t address)
Same convention as send_device_connection: false only on a refused frame.
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 update_address_slot_(uint64_t old_address, uint64_t new_address)
Keep the pre-allocated connections-free message in step when a connection slot changes address (0 = f...
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.
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.
bool client_supports_efficient_uuids() const
Whether the subscribed API client understands 16/32-bit UUID fields.
uint8_t type
void uint64_to_mac_msb_first(uint64_t address, uint8_t out[6])
Unpack a uint64 BLE address into printable (MSB-first) byte order — the order bd_addr_t / esp_bd_addr...
Definition ble_device.h:205
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...
ESPHOME_LOG_TAG(TAG, "bluetooth_connection")
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...
PendingAck
A refused GATT reply owed to the current subscriber.
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...
const void size_t len
Definition hal.h:68
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:2001
uint16_t length
Definition tt21100.cpp:0
spi_device_handle_t handle