ESPHome 2026.9.0
Loading...
Searching...
No Matches
api_connection.cpp
Go to the documentation of this file.
1#include "api_connection.h"
2#ifdef USE_API
3#include "api_connection_buffer.h" // for the APIServer-dependent APIConnection inlines
4#ifdef USE_API_NOISE
6#endif
7#ifdef USE_API_PLAINTEXT
9#endif
10#ifdef USE_API_USER_DEFINED_ACTIONS
11#include "user_services.h"
12#endif
13#include <cerrno>
14#include <cinttypes>
15#include <functional>
16#include <limits>
17#include <new>
18#include <utility>
19#ifdef USE_ESP8266
20#include <pgmspace.h>
21#endif
25#include "esphome/core/hal.h"
27#include "esphome/core/log.h"
29#ifdef USE_PROVISIONING
31#endif
32
33#ifdef USE_DEEP_SLEEP
35#endif
36#ifdef USE_HOMEASSISTANT_TIME
38#endif
39#ifdef USE_BLUETOOTH_PROXY
41#endif
42#ifdef USE_CLIMATE
44#endif
45#ifdef USE_VOICE_ASSISTANT
47#endif
48#ifdef USE_ZWAVE_PROXY
50#endif
51#ifdef USE_WATER_HEATER
53#endif
54#ifdef USE_INFRARED
56#endif
57#ifdef USE_RADIO_FREQUENCY
59#endif
60
61namespace esphome::api {
62
63// Maximum messages to read per loop iteration to prevent starving other components.
64// This is a balance between API responsiveness and allowing other components to run.
65// Since each message could contain multiple protobuf messages when using packet batching,
66// this limits the number of messages processed, not the number of TCP packets.
67static constexpr uint8_t MAX_MESSAGES_PER_LOOP = 10;
68static constexpr uint8_t MAX_PING_RETRIES = 60;
69static constexpr uint16_t PING_RETRY_INTERVAL = 1000;
70static constexpr uint32_t KEEPALIVE_DISCONNECT_TIMEOUT = (KEEPALIVE_TIMEOUT_MS * 5) / 2;
71// Timeout for completing the handshake (Noise transport + HelloRequest).
72// A stalled handshake from a buggy client or network glitch holds a connection
73// slot, which can prevent legitimate clients from reconnecting. Also hardens
74// against the less likely case of intentional connection slot exhaustion.
75//
76// 60s is intentionally high: on ESP8266 with power_save_mode: LIGHT and weak
77// WiFi (-70 dBm+), TCP retransmissions push real-world handshake times to
78// 28-30s. See https://github.com/esphome/esphome/issues/14999
79static constexpr uint32_t HANDSHAKE_TIMEOUT_MS = 60000;
80
81static constexpr auto ESPHOME_VERSION_REF = StringRef::from_lit(ESPHOME_VERSION);
82
83// Cross-validate C++ constants against proto max_data_length annotations in api.proto
84static_assert(MAC_ADDRESS_PRETTY_BUFFER_SIZE - 1 == 17,
85 "Update max_data_length for mac_address/bluetooth_mac_address in api.proto");
86static_assert(Application::BUILD_TIME_STR_SIZE - 1 == 25, "Update max_data_length for compilation_time in api.proto");
87static_assert(sizeof(ESPHOME_VERSION) - 1 <= 32, "Update max_data_length for esphome_version in api.proto");
88static_assert(ESPHOME_DEVICE_NAME_MAX_LEN <= 31, "Update max_data_length for name in api.proto");
89static_assert(ESPHOME_FRIENDLY_NAME_MAX_LEN <= 120, "Update max_data_length for friendly_name in api.proto");
90
91static const char *const TAG = "api.connection";
92
93#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_WARN
94void log_dropped_message(const char *tag, int line, const LogString *what) {
95 esp_log_printf_(ESPHOME_LOG_LEVEL_WARN, tag, line, ESPHOME_LOG_FORMAT("%s dropped, TCP buffer full"),
96 LOG_STR_ARG(what));
97}
98#endif
99#ifdef USE_CAMERA
100static const int CAMERA_STOP_STREAM = 5000;
101#endif
102
103#ifdef USE_DEVICES
104// Helper macro for entity command handlers - gets entity by key and device_id, returns if not found, and creates call
105// object
106#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
107 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
108 if ((entity_var) == nullptr) \
109 return; \
110 auto call = (entity_var)->make_call();
111
112// Helper macro for entity command handlers that don't use make_call() - gets entity by key and device_id and returns if
113// not found
114#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
115 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
116 if ((entity_var) == nullptr) \
117 return;
118
119// Helper macro for multi-entity dispatch: looks up an entity by key and device_id without early return or make_call().
120// Use when multiple entity types must be checked in sequence (at most one will match).
121#define ENTITY_COMMAND_LOOKUP(entity_type, entity_var, getter_name) \
122 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id)
123
124#else // No device support, use simpler macros
125// Helper macro for entity command handlers - gets entity by key, returns if not found, and creates call
126// object
127#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
128 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
129 if ((entity_var) == nullptr) \
130 return; \
131 auto call = (entity_var)->make_call();
132
133// Helper macro for entity command handlers that don't use make_call() - gets entity by key and returns if
134// not found
135#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
136 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
137 if ((entity_var) == nullptr) \
138 return;
139
140// Helper macro for multi-entity dispatch: looks up an entity by key without early return or make_call().
141// Use when multiple entity types must be checked in sequence (at most one will match).
142#define ENTITY_COMMAND_LOOKUP(entity_type, entity_var, getter_name) \
143 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key)
144
145#endif // USE_DEVICES
146
147APIConnection::APIConnection(std::unique_ptr<socket::Socket> sock, APIServer *parent) : parent_(parent) {
148#if defined(USE_API_PLAINTEXT) && defined(USE_API_NOISE)
149 auto &noise_ctx = parent->get_noise_ctx();
150 if (noise_ctx.has_psk()) {
151 this->helper_ = std::unique_ptr<APIFrameHelper>{new APINoiseFrameHelper(std::move(sock), noise_ctx)};
152 } else {
153 this->helper_ = std::unique_ptr<APIFrameHelper>{new APIPlaintextFrameHelper(std::move(sock))};
154 }
155#elif defined(USE_API_PLAINTEXT)
156 this->helper_ = std::unique_ptr<APIPlaintextFrameHelper>{new APIPlaintextFrameHelper(std::move(sock))};
157#elif defined(USE_API_NOISE)
158 this->helper_ =
159 std::unique_ptr<APINoiseFrameHelper>{new APINoiseFrameHelper(std::move(sock), parent->get_noise_ctx())};
160#else
161#error "No frame helper defined"
162#endif
163}
164
165void APIConnection::start() {
166 this->last_traffic_ = App.get_loop_component_start_time();
167
168 APIError err = this->helper_->init();
169 if (err != APIError::OK) {
170 this->fatal_error_with_log_(LOG_STR("Helper init failed"), err);
171 return;
172 }
173 // Initialize client name with peername (IP address) until Hello message provides actual name
174 char peername[socket::SOCKADDR_STR_LEN];
175 this->helper_->set_client_name(this->helper_->get_peername_to(peername), strlen(peername));
176}
177
178APIConnection::~APIConnection() {
179 this->destroy_active_iterator_();
180#ifdef USE_BLUETOOTH_PROXY
181 if (bluetooth_proxy::global_bluetooth_proxy->get_api_connection() == this) {
183 }
184#endif
185#ifdef USE_VOICE_ASSISTANT
186 if (voice_assistant::global_voice_assistant->get_api_connection() == this) {
188 }
189#endif
190#ifdef USE_ZWAVE_PROXY
191 if (zwave_proxy::global_zwave_proxy != nullptr && zwave_proxy::global_zwave_proxy->get_api_connection() == this) {
192 zwave_proxy::global_zwave_proxy->zwave_proxy_request(this, enums::ZWAVE_PROXY_REQUEST_TYPE_UNSUBSCRIBE);
193 }
194#endif
195#ifdef USE_SERIAL_PROXY
196 for (auto *proxy : App.get_serial_proxies()) {
197 if (proxy->get_api_connection() == this) {
198 proxy->serial_proxy_request(this, enums::SERIAL_PROXY_REQUEST_TYPE_UNSUBSCRIBE);
199 }
200 }
201#endif
202}
203
204#if defined(USE_API_NOISE) && defined(USE_API_PLAINTEXT)
205void APIConnection::upgrade_helper_to_noise_() {
206 // The client opened with a Noise hello while this device has no encryption
207 // key set. Replace the plaintext helper with a Noise helper so the key can
208 // be provisioned over an encrypted channel: the noise context PSK is all
209 // zeros when unprovisioned, and NNpsk0 still runs a fresh ephemeral X25519
210 // exchange, so a passive listener cannot read the session. A publicly known
211 // PSK authenticates nobody; this protects against sniffing only.
212 auto *plaintext = static_cast<APIPlaintextFrameHelper *>(this->helper_.get());
213 uint8_t header[3];
214 uint8_t header_len = plaintext->get_consumed_header(header);
215 auto *noise = new APINoiseFrameHelper(plaintext->release_socket_for_switch(), this->parent_->get_noise_ctx());
216 // Carry over the peername-based client name (Hello has not arrived yet)
217 const char *name = plaintext->get_client_name();
218 noise->set_client_name(name, strlen(name));
219 this->helper_.reset(noise); // destroys the plaintext helper
220 APIError err = noise->init_from_handoff(header, header_len);
221 if (err != APIError::OK) {
222 this->fatal_error_with_log_(LOG_STR("Noise handoff failed"), err);
223 }
224}
225#endif // USE_API_NOISE && USE_API_PLAINTEXT
226
227void APIConnection::destroy_active_iterator_() {
228 switch (this->active_iterator_) {
229 case ActiveIterator::LIST_ENTITIES:
230 this->iterator_storage_.list_entities.~ListEntitiesIterator();
231 break;
232 case ActiveIterator::INITIAL_STATE:
233 this->iterator_storage_.initial_state.~InitialStateIterator();
234 break;
235 case ActiveIterator::NONE:
236 break;
237 }
238 this->active_iterator_ = ActiveIterator::NONE;
239}
240
241void APIConnection::begin_iterator_(ActiveIterator type) {
242 this->destroy_active_iterator_();
243 this->active_iterator_ = type;
244 if (type == ActiveIterator::LIST_ENTITIES) {
245 new (&this->iterator_storage_.list_entities) ListEntitiesIterator(this);
246 this->iterator_storage_.list_entities.begin();
247 } else {
248 new (&this->iterator_storage_.initial_state) InitialStateIterator(this);
249 this->iterator_storage_.initial_state.begin();
250 }
251}
252
253void APIConnection::loop() {
254 if (this->flags_.next_close) {
255 // requested a disconnect - don't close socket here, let APIServer::loop() do it
256 // so getpeername() still works for the disconnect trigger
257 this->flags_.remove = true;
258 return;
259 }
260
261 APIError err = this->helper_->loop();
262 if (err != APIError::OK) {
263 this->fatal_error_with_log_(LOG_STR("Socket operation failed"), err);
264 return;
265 }
266
268 // Check if socket has data ready before attempting to read.
269 // Also try reading if we hit the message limit last time — LWIP's rcvevent
270 // (used by is_socket_ready) tracks pbuf dequeues, not bytes. When multiple
271 // messages share a TCP segment, the last message's data stays in LWIP's
272 // lastdata cache after rcvevent hits 0, making is_socket_ready() return false
273 // even though data remains.
274 if (this->helper_->is_socket_ready() || this->flags_.may_have_remaining_data) {
275 this->flags_.may_have_remaining_data = false;
276 // Read up to MAX_MESSAGES_PER_LOOP messages per loop to improve throughput
277 uint8_t message_count = 0;
278 for (; message_count < MAX_MESSAGES_PER_LOOP; message_count++) {
279 ReadPacketBuffer buffer;
280 err = this->helper_->read_packet(&buffer);
281 if (err == APIError::WOULD_BLOCK) {
282 // No more data available
283 break;
284 } else if (err != APIError::OK) {
285#if defined(USE_API_NOISE) && defined(USE_API_PLAINTEXT)
286 // Checked inside the error branch to keep the hot err == OK path
287 // free of it; this can only fire on the first bytes of a plaintext
288 // helper on an unprovisioned device
289 if (err == APIError::PROTOCOL_SWITCH_TO_NOISE) {
290 this->upgrade_helper_to_noise_();
291 return;
292 }
293#endif
294 this->fatal_error_with_log_(LOG_STR("Reading failed"), err);
295 return;
296 } else {
297 // Only update last_traffic_ after authentication to ensure the
298 // handshake timeout is an absolute deadline from connection start.
299 // Pre-auth messages (e.g. PingRequest) must not reset the timer.
300 if (this->is_authenticated()) {
301 this->last_traffic_ = now;
302 }
303 // read a packet
304 this->read_message_(buffer.data_len, buffer.type, buffer.data);
305 if (this->flags_.remove)
306 return;
307 }
308 }
309 // If we hit the limit, there may be more data remaining in LWIP's
310 // lastdata cache that rcvevent doesn't account for.
311 if (message_count == MAX_MESSAGES_PER_LOOP) {
312 this->flags_.may_have_remaining_data = true;
313 }
314 }
315
316 // Process deferred batch if scheduled and timer has expired
317 if (this->flags_.batch_scheduled && now - this->deferred_batch_.batch_start_time >= this->get_batch_delay_ms_()) {
318 this->process_batch_();
319 }
320
321 if (this->active_iterator_ != ActiveIterator::NONE) {
322 this->process_active_iterator_();
323 }
324
325 // Disconnect clients that haven't completed the handshake in time.
326 // Stale half-open connections from buggy clients or network issues can
327 // accumulate and block legitimate clients from reconnecting.
328 if (!this->is_authenticated() && now - this->last_traffic_ > HANDSHAKE_TIMEOUT_MS) {
329 this->on_fatal_error();
330 this->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR("handshake timeout; disconnecting"));
331 return;
332 }
333
334 // Keepalive: only call into the cold path when enough time has elapsed.
335 // When sent_ping is true, last_traffic_ hasn't been updated so this
336 // condition is already satisfied — covers both send-ping and disconnect cases.
337 if (now - this->last_traffic_ > KEEPALIVE_TIMEOUT_MS) {
338 this->check_keepalive_(now);
339 }
340
341#ifdef USE_API_HOMEASSISTANT_STATES
342 if (state_subs_at_ >= 0) {
343 this->process_state_subscriptions_();
344 }
345#endif
346
347#ifdef USE_CAMERA
348 // Process camera last - state updates are higher priority
349 // (missing a frame is fine, missing a state update is not)
350 this->try_send_camera_image_();
351#endif
352}
353
354void APIConnection::check_keepalive_(uint32_t now) {
355 // Caller guarantees: now - last_traffic_ > KEEPALIVE_TIMEOUT_MS
356 if (this->flags_.sent_ping) {
357 // Disconnect if not responded within 2.5*keepalive
358 if (now - this->last_traffic_ > KEEPALIVE_DISCONNECT_TIMEOUT) {
359 on_fatal_error();
360 this->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR("is unresponsive; disconnecting"));
361 }
362 } else if (!this->flags_.remove) {
363 // Only send ping if we're not disconnecting
364 ESP_LOGVV(TAG, "Sending keepalive PING");
365 PingRequest req;
366 this->flags_.sent_ping = this->send_message(req);
367 if (this->flags_.sent_ping) {
368 // Quiet for a keepalive period and the ping is on its way: a one-off stall's storage can go
369 this->helper_->release_overflow_buffer();
370 } else {
371 // If we can't send the ping request directly (tx_buffer full),
372 // schedule it at the front of the batch so it will be sent with priority
373 ESP_LOGW(TAG, "Buffer full, ping queued");
374 this->schedule_message_front_(nullptr, PingRequest::MESSAGE_TYPE, PingRequest::ESTIMATED_SIZE);
375 this->flags_.sent_ping = true; // Mark as sent to avoid scheduling multiple pings
376 }
377 }
378}
379
380void APIConnection::process_active_iterator_() {
381 // Caller ensures active_iterator_ != NONE
382 if (this->active_iterator_ == ActiveIterator::LIST_ENTITIES) {
383 if (this->iterator_storage_.list_entities.completed()) {
384 this->destroy_active_iterator_();
385 if (this->flags_.state_subscription) {
386 this->begin_iterator_(ActiveIterator::INITIAL_STATE);
387 } else {
388 this->finalize_iterator_sync_();
389 }
390 } else {
391 this->process_iterator_batch_(this->iterator_storage_.list_entities);
392 }
393 } else { // INITIAL_STATE
394 if (this->iterator_storage_.initial_state.completed()) {
395 this->destroy_active_iterator_();
396 this->finalize_iterator_sync_();
397 } else {
398 this->process_iterator_batch_(this->iterator_storage_.initial_state);
399 }
400 }
401}
402
403void APIConnection::finalize_iterator_sync_() {
404 // Flush any remaining batched messages immediately so clients
405 // receive completion responses (e.g. ListEntitiesDoneResponse)
406 // without waiting for the batch timer.
407 if (!this->deferred_batch_.empty()) {
408 this->process_batch_();
409 }
410 // Enable immediate sending for future state changes
411 this->flags_.should_try_send_immediately = true;
412 // Release excess memory from buffers that grew during initial sync
413 this->deferred_batch_.release_buffer();
414 this->helper_->release_buffers();
415}
416
417void APIConnection::process_iterator_batch_(ComponentIterator &iterator) {
418 // Budget by remaining batch capacity so a pass cannot overfill the batch;
419 // stops early on a refused send and resumes next loop pass
420 size_t batch_size = this->deferred_batch_.size();
421 if (batch_size < MAX_INITIAL_BATCH_SIZE)
422 iterator.try_advance(MAX_INITIAL_BATCH_SIZE - batch_size);
423
424 // Flush immediately once enough is queued (not guaranteed every pass);
425 // partial batches go out via the batch timer or finalize_iterator_sync_()
426 if (this->deferred_batch_.size() >= MAX_INITIAL_BATCH_SIZE) {
427 this->process_batch_();
428 }
429}
430
431bool APIConnection::send_disconnect_response_() {
432 // remote initiated disconnect_client
433 // don't close yet, we still need to send the disconnect response
434 // close will happen on next loop
435 this->log_client_(ESPHOME_LOG_LEVEL_DEBUG, LOG_STR("disconnected"));
436 this->flags_.next_close = true;
438 return this->send_message(resp);
439}
440void APIConnection::on_disconnect_response() {
441 // Don't close socket here, let APIServer::loop() do it
442 // so getpeername() still works for the disconnect trigger
443 this->flags_.remove = true;
444}
445
446uint16_t APIConnection::fill_and_encode_entity_state(EntityBase *entity, StateResponseProtoMessage &msg,
447 CalculateSizeFn size_fn, MessageEncodeFn encode_fn,
448 APIConnection *conn, uint32_t remaining_size) {
449 msg.key = entity->get_object_id_hash();
450#ifdef USE_DEVICES
451 msg.device_id = entity->get_device_id();
452#endif
453 return encode_to_buffer(size_fn(&msg), encode_fn, &msg, conn, remaining_size);
454}
455
456uint16_t APIConnection::fill_and_encode_entity_info(EntityBase *entity, InfoResponseProtoMessage &msg,
457 CalculateSizeFn size_fn, MessageEncodeFn encode_fn,
458 APIConnection *conn, uint32_t remaining_size) {
459 // Set common fields that are shared by all entity types
460 msg.key = entity->get_object_id_hash();
461
462 if (entity->has_own_name()) {
463 msg.name = entity->get_name();
464 }
465
466 // Set common EntityBase properties
467#ifdef USE_ENTITY_ICON
468 char icon_buf[MAX_ICON_LENGTH];
469 msg.icon = StringRef(entity->get_icon_to(icon_buf));
470#endif
472 msg.entity_category = static_cast<enums::EntityCategory>(entity->get_entity_category());
473#ifdef USE_DEVICES
474 msg.device_id = entity->get_device_id();
475#endif
476 return encode_to_buffer_slow(size_fn(&msg), encode_fn, &msg, conn, remaining_size);
477}
478
479uint16_t APIConnection::fill_and_encode_entity_info_with_device_class(EntityBase *entity, InfoResponseProtoMessage &msg,
480 StringRef &device_class_field,
481 CalculateSizeFn size_fn,
482 MessageEncodeFn encode_fn, APIConnection *conn,
483 uint32_t remaining_size) {
484 char dc_buf[MAX_DEVICE_CLASS_LENGTH];
485 device_class_field = StringRef(entity->get_device_class_to(dc_buf));
486 return fill_and_encode_entity_info(entity, msg, size_fn, encode_fn, conn, remaining_size);
487}
488
489#ifdef USE_BINARY_SENSOR
490bool APIConnection::send_binary_sensor_state(binary_sensor::BinarySensor *binary_sensor) {
491 return this->send_message_smart_(binary_sensor, BinarySensorStateResponse::MESSAGE_TYPE,
492 BinarySensorStateResponse::ESTIMATED_SIZE);
493}
494
495uint16_t APIConnection::try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
496 auto *binary_sensor = static_cast<binary_sensor::BinarySensor *>(entity);
498 resp.state = binary_sensor->state;
499 resp.missing_state = !binary_sensor->has_state();
500 return fill_and_encode_entity_state(binary_sensor, resp, conn, remaining_size);
501}
502
503uint16_t APIConnection::try_send_binary_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
504 auto *binary_sensor = static_cast<binary_sensor::BinarySensor *>(entity);
506 msg.is_status_binary_sensor = binary_sensor->is_status_binary_sensor();
507 return fill_and_encode_entity_info_with_device_class(binary_sensor, msg, msg.device_class, conn, remaining_size);
508}
509#endif
510
511#ifdef USE_COVER
512bool APIConnection::send_cover_state(cover::Cover *cover) {
513 return this->send_message_smart_(cover, CoverStateResponse::MESSAGE_TYPE, CoverStateResponse::ESTIMATED_SIZE);
514}
515uint16_t APIConnection::try_send_cover_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
516 auto *cover = static_cast<cover::Cover *>(entity);
518 auto traits = cover->get_traits();
519 msg.position = cover->position;
520 if (traits.get_supports_tilt())
521 msg.tilt = cover->tilt;
522 msg.current_operation = static_cast<enums::CoverOperation>(cover->current_operation);
523 return fill_and_encode_entity_state(cover, msg, conn, remaining_size);
524}
525uint16_t APIConnection::try_send_cover_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
526 auto *cover = static_cast<cover::Cover *>(entity);
528 auto traits = cover->get_traits();
529 msg.assumed_state = traits.get_is_assumed_state();
530 msg.supports_position = traits.get_supports_position();
531 msg.supports_tilt = traits.get_supports_tilt();
532 msg.supports_stop = traits.get_supports_stop();
533 return fill_and_encode_entity_info_with_device_class(cover, msg, msg.device_class, conn, remaining_size);
534}
535void APIConnection::on_cover_command_request(const CoverCommandRequest &msg) {
536 ENTITY_COMMAND_MAKE_CALL(cover::Cover, cover, cover)
537 if (msg.has_position)
538 call.set_position(msg.position);
539 if (msg.has_tilt)
540 call.set_tilt(msg.tilt);
541 if (msg.stop)
542 call.set_command_stop();
543 call.perform();
544}
545#endif
546
547#ifdef USE_FAN
548bool APIConnection::send_fan_state(fan::Fan *fan) {
549 return this->send_message_smart_(fan, FanStateResponse::MESSAGE_TYPE, FanStateResponse::ESTIMATED_SIZE);
550}
551uint16_t APIConnection::try_send_fan_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
552 auto *fan = static_cast<fan::Fan *>(entity);
554 auto traits = fan->get_traits();
555 msg.state = fan->state;
556 if (traits.supports_oscillation())
557 msg.oscillating = fan->oscillating;
558 if (traits.supports_speed()) {
559 msg.speed_level = fan->speed;
560 }
561 if (traits.supports_direction())
562 msg.direction = static_cast<enums::FanDirection>(fan->direction);
563 if (traits.supports_preset_modes() && fan->has_preset_mode())
564 msg.preset_mode = fan->get_preset_mode();
565 return fill_and_encode_entity_state(fan, msg, conn, remaining_size);
566}
567uint16_t APIConnection::try_send_fan_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
568 auto *fan = static_cast<fan::Fan *>(entity);
570 auto traits = fan->get_traits();
571 msg.supports_oscillation = traits.supports_oscillation();
572 msg.supports_speed = traits.supports_speed();
573 msg.supports_direction = traits.supports_direction();
574 msg.supported_speed_count = traits.supported_speed_count();
575 msg.supported_preset_modes = &traits.supported_preset_modes();
576 return fill_and_encode_entity_info(fan, msg, conn, remaining_size);
577}
578void APIConnection::on_fan_command_request(const FanCommandRequest &msg) {
579 ENTITY_COMMAND_MAKE_CALL(fan::Fan, fan, fan)
580 if (msg.has_state)
581 call.set_state(msg.state);
582 if (msg.has_oscillating)
583 call.set_oscillating(msg.oscillating);
584 if (msg.has_speed_level) {
585 // Prefer level
586 call.set_speed(msg.speed_level);
587 }
588 if (msg.has_direction)
589 call.set_direction(static_cast<fan::FanDirection>(msg.direction));
590 if (msg.has_preset_mode)
591 call.set_preset_mode(msg.preset_mode.c_str(), msg.preset_mode.size());
592 call.perform();
593}
594#endif
595
596#ifdef USE_LIGHT
597bool APIConnection::send_light_state(light::LightState *light) {
598 return this->send_message_smart_(light, LightStateResponse::MESSAGE_TYPE, LightStateResponse::ESTIMATED_SIZE);
599}
600uint16_t APIConnection::try_send_light_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
601 auto *light = static_cast<light::LightState *>(entity);
603 auto values = light->remote_values;
604 auto color_mode = values.get_color_mode();
605 resp.state = values.is_on();
606 resp.color_mode = static_cast<enums::ColorMode>(color_mode);
607 resp.brightness = values.get_brightness();
608 resp.color_brightness = values.get_color_brightness();
609 resp.red = values.get_red();
610 resp.green = values.get_green();
611 resp.blue = values.get_blue();
612 resp.white = values.get_white();
613 resp.color_temperature = values.get_color_temperature();
614 resp.cold_white = values.get_cold_white();
615 resp.warm_white = values.get_warm_white();
616 if (light->supports_effects()) {
617 resp.effect = light->get_effect_name();
618 }
619 return fill_and_encode_entity_state(light, resp, conn, remaining_size);
620}
621uint16_t APIConnection::try_send_light_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
622 auto *light = static_cast<light::LightState *>(entity);
624 auto traits = light->get_traits();
625 auto supported_modes = traits.get_supported_color_modes();
626 // Pass pointer to ColorModeMask so the iterator can encode actual ColorMode enum values
627 msg.supported_color_modes = &supported_modes;
628 if (traits.supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE) ||
629 traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE)) {
630 msg.min_mireds = traits.get_min_mireds();
631 msg.max_mireds = traits.get_max_mireds();
632 }
633 FixedVector<const char *> effects_list;
634 if (light->supports_effects()) {
635 auto &light_effects = light->get_effects();
636 effects_list.init(light_effects.size() + 1);
637 effects_list.push_back("None");
638 for (auto *effect : light_effects) {
639 // c_str() is safe as effect names are null-terminated strings from codegen
640 effects_list.push_back(effect->get_name().c_str());
641 }
642 }
643 msg.effects = &effects_list;
644 return fill_and_encode_entity_info(light, msg, conn, remaining_size);
645}
646void APIConnection::on_light_command_request(const LightCommandRequest &msg) {
647 ENTITY_COMMAND_MAKE_CALL(light::LightState, light, light)
648 if (msg.has_state)
649 call.set_state(msg.state);
650 if (msg.has_brightness)
651 call.set_brightness(msg.brightness);
652 if (msg.has_color_mode)
653 call.set_color_mode(static_cast<light::ColorMode>(msg.color_mode));
654 if (msg.has_color_brightness)
655 call.set_color_brightness(msg.color_brightness);
656 if (msg.has_rgb) {
657 call.set_red(msg.red);
658 call.set_green(msg.green);
659 call.set_blue(msg.blue);
660 }
661 if (msg.has_white)
662 call.set_white(msg.white);
663 if (msg.has_color_temperature)
664 call.set_color_temperature(msg.color_temperature);
665 if (msg.has_cold_white)
666 call.set_cold_white(msg.cold_white);
667 if (msg.has_warm_white)
668 call.set_warm_white(msg.warm_white);
669 if (msg.has_transition_length)
670 call.set_transition_length(msg.transition_length);
671 if (msg.has_flash_length)
672 call.set_flash_length(msg.flash_length);
673 if (msg.has_effect)
674 call.set_effect(msg.effect.c_str(), msg.effect.size());
675 call.perform();
676}
677#endif
678
679#ifdef USE_SENSOR
680bool APIConnection::send_sensor_state(sensor::Sensor *sensor) {
681 return this->send_message_smart_(sensor, SensorStateResponse::MESSAGE_TYPE, SensorStateResponse::ESTIMATED_SIZE);
682}
683
684uint16_t APIConnection::try_send_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
685 auto *sensor = static_cast<sensor::Sensor *>(entity);
687 resp.state = sensor->state;
688 resp.missing_state = !sensor->has_state();
689 return fill_and_encode_entity_state(sensor, resp, conn, remaining_size);
690}
691
692uint16_t APIConnection::try_send_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
693 auto *sensor = static_cast<sensor::Sensor *>(entity);
695 msg.unit_of_measurement = sensor->get_unit_of_measurement_ref();
696 msg.accuracy_decimals = sensor->get_accuracy_decimals();
697 msg.force_update = sensor->get_force_update();
698 msg.state_class = static_cast<enums::SensorStateClass>(sensor->get_state_class());
699 return fill_and_encode_entity_info_with_device_class(sensor, msg, msg.device_class, conn, remaining_size);
700}
701#endif
702
703#ifdef USE_SWITCH
704bool APIConnection::send_switch_state(switch_::Switch *a_switch) {
705 return this->send_message_smart_(a_switch, SwitchStateResponse::MESSAGE_TYPE, SwitchStateResponse::ESTIMATED_SIZE);
706}
707
708uint16_t APIConnection::try_send_switch_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
709 auto *a_switch = static_cast<switch_::Switch *>(entity);
711 resp.state = a_switch->state;
712 return fill_and_encode_entity_state(a_switch, resp, conn, remaining_size);
713}
714
715uint16_t APIConnection::try_send_switch_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
716 auto *a_switch = static_cast<switch_::Switch *>(entity);
718 msg.assumed_state = a_switch->assumed_state();
719 return fill_and_encode_entity_info_with_device_class(a_switch, msg, msg.device_class, conn, remaining_size);
720}
721void APIConnection::on_switch_command_request(const SwitchCommandRequest &msg) {
722 ENTITY_COMMAND_GET(switch_::Switch, a_switch, switch)
723
724 if (msg.state) {
725 a_switch->turn_on();
726 } else {
727 a_switch->turn_off();
728 }
729}
730#endif
731
732#ifdef USE_TEXT_SENSOR
733bool APIConnection::send_text_sensor_state(text_sensor::TextSensor *text_sensor) {
734 return this->send_message_smart_(text_sensor, TextSensorStateResponse::MESSAGE_TYPE,
735 TextSensorStateResponse::ESTIMATED_SIZE);
736}
737
738uint16_t APIConnection::try_send_text_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
739 auto *text_sensor = static_cast<text_sensor::TextSensor *>(entity);
741 resp.state = StringRef(text_sensor->state);
742 resp.missing_state = !text_sensor->has_state();
743 return fill_and_encode_entity_state(text_sensor, resp, conn, remaining_size);
744}
745uint16_t APIConnection::try_send_text_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
746 auto *text_sensor = static_cast<text_sensor::TextSensor *>(entity);
748 return fill_and_encode_entity_info_with_device_class(text_sensor, msg, msg.device_class, conn, remaining_size);
749}
750#endif
751
752#ifdef USE_CLIMATE
753bool APIConnection::send_climate_state(climate::Climate *climate) {
754 return this->send_message_smart_(climate, ClimateStateResponse::MESSAGE_TYPE, ClimateStateResponse::ESTIMATED_SIZE);
755}
756uint16_t APIConnection::try_send_climate_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
757 auto *climate = static_cast<climate::Climate *>(entity);
759 auto traits = climate->get_traits();
760 resp.mode = static_cast<enums::ClimateMode>(climate->mode);
761 resp.action = static_cast<enums::ClimateAction>(climate->action);
762 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_TEMPERATURE))
763 resp.current_temperature = climate->current_temperature;
764 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_TWO_POINT_TARGET_TEMPERATURE |
766 resp.target_temperature_low = climate->target_temperature_low;
767 resp.target_temperature_high = climate->target_temperature_high;
768 } else {
769 resp.target_temperature = climate->target_temperature;
770 }
771 if (traits.get_supports_fan_modes() && climate->fan_mode.has_value())
772 resp.fan_mode = static_cast<enums::ClimateFanMode>(climate->fan_mode.value());
773 if (!traits.get_supported_custom_fan_modes().empty() && climate->has_custom_fan_mode()) {
774 resp.custom_fan_mode = climate->get_custom_fan_mode();
775 }
776 if (traits.get_supports_presets() && climate->preset.has_value()) {
777 resp.preset = static_cast<enums::ClimatePreset>(climate->preset.value());
778 }
779 if (!traits.get_supported_custom_presets().empty() && climate->has_custom_preset()) {
780 resp.custom_preset = climate->get_custom_preset();
781 }
782 if (traits.get_supports_swing_modes())
783 resp.swing_mode = static_cast<enums::ClimateSwingMode>(climate->swing_mode);
784 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_HUMIDITY))
785 resp.current_humidity = climate->current_humidity;
786 if (traits.has_feature_flags(climate::CLIMATE_SUPPORTS_TARGET_HUMIDITY))
787 resp.target_humidity = climate->target_humidity;
788 return fill_and_encode_entity_state(climate, resp, conn, remaining_size);
789}
790uint16_t APIConnection::try_send_climate_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
791 auto *climate = static_cast<climate::Climate *>(entity);
793 auto traits = climate->get_traits();
794 // Flags set for backward compatibility, deprecated in 2025.11.0
797 msg.supports_two_point_target_temperature = traits.has_feature_flags(
800 msg.supports_action = traits.has_feature_flags(climate::CLIMATE_SUPPORTS_ACTION);
801 // Current feature flags and other supported parameters
802 msg.feature_flags = traits.get_feature_flags();
803 msg.temperature_unit = static_cast<enums::TemperatureUnit>(traits.get_temperature_unit());
804 msg.supported_modes = &traits.get_supported_modes();
805 msg.visual_min_temperature = traits.get_visual_min_temperature();
806 msg.visual_max_temperature = traits.get_visual_max_temperature();
807 msg.visual_target_temperature_step = traits.get_visual_target_temperature_step();
808 msg.visual_current_temperature_step = traits.get_visual_current_temperature_step();
809 msg.visual_min_humidity = traits.get_visual_min_humidity();
810 msg.visual_max_humidity = traits.get_visual_max_humidity();
811 msg.supported_fan_modes = &traits.get_supported_fan_modes();
812 msg.supported_custom_fan_modes = &traits.get_supported_custom_fan_modes();
813 msg.supported_presets = &traits.get_supported_presets();
814 msg.supported_custom_presets = &traits.get_supported_custom_presets();
815 msg.supported_swing_modes = &traits.get_supported_swing_modes();
816 return fill_and_encode_entity_info(climate, msg, conn, remaining_size);
817}
818void APIConnection::on_climate_command_request(const ClimateCommandRequest &msg) {
819 ENTITY_COMMAND_MAKE_CALL(climate::Climate, climate, climate)
820 if (msg.has_mode)
821 call.set_mode(static_cast<climate::ClimateMode>(msg.mode));
823 call.set_target_temperature(msg.target_temperature);
825 call.set_target_temperature_low(msg.target_temperature_low);
827 call.set_target_temperature_high(msg.target_temperature_high);
828 if (msg.has_target_humidity)
829 call.set_target_humidity(msg.target_humidity);
830 if (msg.has_fan_mode)
831 call.set_fan_mode(static_cast<climate::ClimateFanMode>(msg.fan_mode));
832 if (msg.has_custom_fan_mode)
833 call.set_fan_mode(msg.custom_fan_mode.c_str(), msg.custom_fan_mode.size());
834 if (msg.has_preset)
835 call.set_preset(static_cast<climate::ClimatePreset>(msg.preset));
836 if (msg.has_custom_preset)
837 call.set_preset(msg.custom_preset.c_str(), msg.custom_preset.size());
838 if (msg.has_swing_mode)
839 call.set_swing_mode(static_cast<climate::ClimateSwingMode>(msg.swing_mode));
840 call.perform();
841}
842#endif
843
844#ifdef USE_NUMBER
845bool APIConnection::send_number_state(number::Number *number) {
846 return this->send_message_smart_(number, NumberStateResponse::MESSAGE_TYPE, NumberStateResponse::ESTIMATED_SIZE);
847}
848
849uint16_t APIConnection::try_send_number_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
850 auto *number = static_cast<number::Number *>(entity);
852 resp.state = number->state;
853 resp.missing_state = !number->has_state();
854 return fill_and_encode_entity_state(number, resp, conn, remaining_size);
855}
856
857uint16_t APIConnection::try_send_number_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
858 auto *number = static_cast<number::Number *>(entity);
860 msg.unit_of_measurement = number->get_unit_of_measurement_ref();
861 msg.mode = static_cast<enums::NumberMode>(number->traits.get_mode());
862 msg.min_value = number->traits.get_min_value();
863 msg.max_value = number->traits.get_max_value();
864 msg.step = number->traits.get_step();
865 return fill_and_encode_entity_info_with_device_class(number, msg, msg.device_class, conn, remaining_size);
866}
867void APIConnection::on_number_command_request(const NumberCommandRequest &msg) {
868 ENTITY_COMMAND_MAKE_CALL(number::Number, number, number)
869 call.set_value(msg.state);
870 call.perform();
871}
872#endif
873
874#ifdef USE_DATETIME_DATE
875bool APIConnection::send_date_state(datetime::DateEntity *date) {
876 return this->send_message_smart_(date, DateStateResponse::MESSAGE_TYPE, DateStateResponse::ESTIMATED_SIZE);
877}
878uint16_t APIConnection::try_send_date_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
879 auto *date = static_cast<datetime::DateEntity *>(entity);
881 resp.missing_state = !date->has_state();
882 resp.year = date->year;
883 resp.month = date->month;
884 resp.day = date->day;
885 return fill_and_encode_entity_state(date, resp, conn, remaining_size);
886}
887uint16_t APIConnection::try_send_date_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
888 auto *date = static_cast<datetime::DateEntity *>(entity);
890 return fill_and_encode_entity_info(date, msg, conn, remaining_size);
891}
892void APIConnection::on_date_command_request(const DateCommandRequest &msg) {
893 ENTITY_COMMAND_MAKE_CALL(datetime::DateEntity, date, date)
894 call.set_date(msg.year, msg.month, msg.day);
895 call.perform();
896}
897#endif
898
899#ifdef USE_DATETIME_TIME
900bool APIConnection::send_time_state(datetime::TimeEntity *time) {
901 return this->send_message_smart_(time, TimeStateResponse::MESSAGE_TYPE, TimeStateResponse::ESTIMATED_SIZE);
902}
903uint16_t APIConnection::try_send_time_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
904 auto *time = static_cast<datetime::TimeEntity *>(entity);
906 resp.missing_state = !time->has_state();
907 resp.hour = time->hour;
908 resp.minute = time->minute;
909 resp.second = time->second;
910 return fill_and_encode_entity_state(time, resp, conn, remaining_size);
911}
912uint16_t APIConnection::try_send_time_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
913 auto *time = static_cast<datetime::TimeEntity *>(entity);
915 return fill_and_encode_entity_info(time, msg, conn, remaining_size);
916}
917void APIConnection::on_time_command_request(const TimeCommandRequest &msg) {
918 ENTITY_COMMAND_MAKE_CALL(datetime::TimeEntity, time, time)
919 call.set_time(msg.hour, msg.minute, msg.second);
920 call.perform();
921}
922#endif
923
924#ifdef USE_DATETIME_DATETIME
925bool APIConnection::send_datetime_state(datetime::DateTimeEntity *datetime) {
926 return this->send_message_smart_(datetime, DateTimeStateResponse::MESSAGE_TYPE,
927 DateTimeStateResponse::ESTIMATED_SIZE);
928}
929uint16_t APIConnection::try_send_datetime_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
930 auto *datetime = static_cast<datetime::DateTimeEntity *>(entity);
932 resp.missing_state = !datetime->has_state();
933 if (datetime->has_state()) {
934 ESPTime state = datetime->state_as_esptime();
935 resp.epoch_seconds = state.timestamp;
936 }
937 return fill_and_encode_entity_state(datetime, resp, conn, remaining_size);
938}
939uint16_t APIConnection::try_send_datetime_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
940 auto *datetime = static_cast<datetime::DateTimeEntity *>(entity);
942 return fill_and_encode_entity_info(datetime, msg, conn, remaining_size);
943}
944void APIConnection::on_date_time_command_request(const DateTimeCommandRequest &msg) {
945 ENTITY_COMMAND_MAKE_CALL(datetime::DateTimeEntity, datetime, datetime)
946 call.set_datetime(msg.epoch_seconds);
947 call.perform();
948}
949#endif
950
951#ifdef USE_TEXT
952bool APIConnection::send_text_state(text::Text *text) {
953 return this->send_message_smart_(text, TextStateResponse::MESSAGE_TYPE, TextStateResponse::ESTIMATED_SIZE);
954}
955
956uint16_t APIConnection::try_send_text_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
957 auto *text = static_cast<text::Text *>(entity);
959 resp.state = StringRef(text->state);
960 resp.missing_state = !text->has_state();
961 return fill_and_encode_entity_state(text, resp, conn, remaining_size);
962}
963
964uint16_t APIConnection::try_send_text_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
965 auto *text = static_cast<text::Text *>(entity);
967 msg.mode = static_cast<enums::TextMode>(text->traits.get_mode());
968 msg.min_length = text->traits.get_min_length();
969 msg.max_length = text->traits.get_max_length();
970 msg.pattern = text->traits.get_pattern_ref();
971 return fill_and_encode_entity_info(text, msg, conn, remaining_size);
972}
973void APIConnection::on_text_command_request(const TextCommandRequest &msg) {
974 ENTITY_COMMAND_MAKE_CALL(text::Text, text, text)
975 call.set_value(msg.state.c_str(), msg.state.size());
976 call.perform();
977}
978#endif
979
980#ifdef USE_SELECT
981bool APIConnection::send_select_state(select::Select *select) {
982 return this->send_message_smart_(select, SelectStateResponse::MESSAGE_TYPE, SelectStateResponse::ESTIMATED_SIZE);
983}
984
985uint16_t APIConnection::try_send_select_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
986 auto *select = static_cast<select::Select *>(entity);
988 resp.state = select->current_option();
989 resp.missing_state = !select->has_state();
990 return fill_and_encode_entity_state(select, resp, conn, remaining_size);
991}
992
993uint16_t APIConnection::try_send_select_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
994 auto *select = static_cast<select::Select *>(entity);
996 msg.options = &select->traits.get_options();
997 return fill_and_encode_entity_info(select, msg, conn, remaining_size);
998}
999void APIConnection::on_select_command_request(const SelectCommandRequest &msg) {
1000 ENTITY_COMMAND_MAKE_CALL(select::Select, select, select)
1001 call.set_option(msg.state.c_str(), msg.state.size());
1002 call.perform();
1003}
1004#endif
1005
1006#ifdef USE_BUTTON
1007uint16_t APIConnection::try_send_button_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1008 auto *button = static_cast<button::Button *>(entity);
1010 return fill_and_encode_entity_info_with_device_class(button, msg, msg.device_class, conn, remaining_size);
1011}
1013 ENTITY_COMMAND_GET(button::Button, button, button)
1014 button->press();
1015}
1016#endif
1017
1018#ifdef USE_LOCK
1019bool APIConnection::send_lock_state(lock::Lock *a_lock) {
1020 return this->send_message_smart_(a_lock, LockStateResponse::MESSAGE_TYPE, LockStateResponse::ESTIMATED_SIZE);
1021}
1022
1023uint16_t APIConnection::try_send_lock_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1024 auto *a_lock = static_cast<lock::Lock *>(entity);
1025 LockStateResponse resp;
1026 resp.state = static_cast<enums::LockState>(a_lock->state);
1027 return fill_and_encode_entity_state(a_lock, resp, conn, remaining_size);
1028}
1029
1030uint16_t APIConnection::try_send_lock_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1031 auto *a_lock = static_cast<lock::Lock *>(entity);
1033 msg.assumed_state = a_lock->traits.get_assumed_state();
1034 msg.supports_open = a_lock->traits.get_supports_open();
1035 msg.requires_code = a_lock->traits.get_requires_code();
1036 return fill_and_encode_entity_info(a_lock, msg, conn, remaining_size);
1037}
1038void APIConnection::on_lock_command_request(const LockCommandRequest &msg) {
1039 ENTITY_COMMAND_GET(lock::Lock, a_lock, lock)
1040
1041 switch (msg.command) {
1042 case enums::LOCK_UNLOCK:
1043 a_lock->unlock();
1044 break;
1045 case enums::LOCK_LOCK:
1046 a_lock->lock();
1047 break;
1048 case enums::LOCK_OPEN:
1049 a_lock->open();
1050 break;
1051 }
1052}
1053#endif
1054
1055#ifdef USE_VALVE
1056bool APIConnection::send_valve_state(valve::Valve *valve) {
1057 return this->send_message_smart_(valve, ValveStateResponse::MESSAGE_TYPE, ValveStateResponse::ESTIMATED_SIZE);
1058}
1059uint16_t APIConnection::try_send_valve_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1060 auto *valve = static_cast<valve::Valve *>(entity);
1061 ValveStateResponse resp;
1062 resp.position = valve->position;
1063 resp.current_operation = static_cast<enums::ValveOperation>(valve->current_operation);
1064 return fill_and_encode_entity_state(valve, resp, conn, remaining_size);
1065}
1066uint16_t APIConnection::try_send_valve_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1067 auto *valve = static_cast<valve::Valve *>(entity);
1069 auto traits = valve->get_traits();
1070 msg.assumed_state = traits.get_is_assumed_state();
1071 msg.supports_position = traits.get_supports_position();
1072 msg.supports_stop = traits.get_supports_stop();
1073 return fill_and_encode_entity_info_with_device_class(valve, msg, msg.device_class, conn, remaining_size);
1074}
1075void APIConnection::on_valve_command_request(const ValveCommandRequest &msg) {
1076 ENTITY_COMMAND_MAKE_CALL(valve::Valve, valve, valve)
1077 if (msg.has_position)
1078 call.set_position(msg.position);
1079 if (msg.stop)
1080 call.set_command_stop();
1081 call.perform();
1082}
1083#endif
1084
1085#ifdef USE_MEDIA_PLAYER
1086bool APIConnection::send_media_player_state(media_player::MediaPlayer *media_player) {
1087 return this->send_message_smart_(media_player, MediaPlayerStateResponse::MESSAGE_TYPE,
1088 MediaPlayerStateResponse::ESTIMATED_SIZE);
1089}
1090uint16_t APIConnection::try_send_media_player_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1091 auto *media_player = static_cast<media_player::MediaPlayer *>(entity);
1095 : media_player->state;
1096 resp.state = static_cast<enums::MediaPlayerState>(report_state);
1097 resp.volume = media_player->volume;
1098 resp.muted = media_player->is_muted();
1099 return fill_and_encode_entity_state(media_player, resp, conn, remaining_size);
1100}
1101uint16_t APIConnection::try_send_media_player_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1102 auto *media_player = static_cast<media_player::MediaPlayer *>(entity);
1104 auto traits = media_player->get_traits();
1105 msg.feature_flags = traits.get_feature_flags();
1106 for (auto &supported_format : traits.get_supported_formats()) {
1107 msg.supported_formats.emplace_back();
1108 auto &media_format = msg.supported_formats.back();
1109 media_format.format = StringRef(supported_format.format);
1110 media_format.sample_rate = supported_format.sample_rate;
1111 media_format.num_channels = supported_format.num_channels;
1112 media_format.purpose = static_cast<enums::MediaPlayerFormatPurpose>(supported_format.purpose);
1113 media_format.sample_bytes = supported_format.sample_bytes;
1114 }
1115 return fill_and_encode_entity_info(media_player, msg, conn, remaining_size);
1116}
1117void APIConnection::on_media_player_command_request(const MediaPlayerCommandRequest &msg) {
1118 ENTITY_COMMAND_MAKE_CALL(media_player::MediaPlayer, media_player, media_player)
1119 if (msg.has_command) {
1120 call.set_command(static_cast<media_player::MediaPlayerCommand>(msg.command));
1121 }
1122 if (msg.has_volume) {
1123 call.set_volume(msg.volume);
1124 }
1125 if (msg.has_media_url) {
1126 call.set_media_url(msg.media_url);
1127 }
1128 if (msg.has_announcement) {
1129 call.set_announcement(msg.announcement);
1130 }
1131 call.perform();
1132}
1133#endif
1134
1135#ifdef USE_CAMERA
1136void APIConnection::try_send_camera_image_() {
1137 if (!this->image_reader_)
1138 return;
1139
1140 const auto *cam = camera::Camera::instance();
1141 // Send as many chunks as possible without blocking
1142 while (this->image_reader_->available()) {
1143 if (!this->helper_->can_write_without_blocking())
1144 return;
1145
1146 uint32_t to_send = std::min((size_t) MAX_BATCH_PACKET_SIZE, this->image_reader_->available());
1147 bool done = this->image_reader_->available() == to_send;
1148
1150 msg.key = cam->get_object_id_hash();
1151 msg.set_data(this->image_reader_->peek_data_buffer(), to_send);
1152 msg.done = done;
1153#ifdef USE_DEVICES
1154 msg.device_id = cam->get_device_id();
1155#endif
1156
1157 if (!this->send_message(msg)) {
1158 return; // Send failed, try again later
1159 }
1160 this->image_reader_->consume_data(to_send);
1161 if (done) {
1162 this->image_reader_->return_image();
1163 return;
1164 }
1165 }
1166}
1167void APIConnection::set_camera_state(std::shared_ptr<camera::CameraImage> image) {
1168 if (!this->flags_.state_subscription)
1169 return;
1170 if (this->image_reader_ && this->image_reader_->available())
1171 return;
1172 if (!image->was_requested_by(esphome::camera::API_REQUESTER) && !image->was_requested_by(esphome::camera::IDLE))
1173 return;
1174 if (!this->image_reader_) {
1175 // Created on the first image this connection will send, so connections
1176 // that never receive one never pay for a reader. Only a registered
1177 // camera's listener can reach this, so instance() is non-null here.
1178 this->image_reader_ = std::unique_ptr<camera::CameraImageReader>{camera::Camera::instance()->create_image_reader()};
1179 }
1180 this->image_reader_->set_image(std::move(image));
1181 // Try to send immediately to reduce latency
1182 this->try_send_camera_image_();
1183}
1184uint16_t APIConnection::try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1185 auto *camera = static_cast<camera::Camera *>(entity);
1187 return fill_and_encode_entity_info(camera, msg, conn, remaining_size);
1188}
1189void APIConnection::on_camera_image_request(const CameraImageRequest &msg) {
1190 if (camera::Camera::instance() == nullptr)
1191 return;
1192
1193 if (msg.single)
1195 if (msg.stream) {
1197
1198 App.scheduler.set_timeout(this->parent_, "api_camera_stop_stream", CAMERA_STOP_STREAM,
1200 }
1201}
1202#endif
1203
1204#ifdef USE_HOMEASSISTANT_TIME
1205void APIConnection::on_get_time_response(const GetTimeResponse &value) {
1208#if defined(USE_HOMEASSISTANT_TIMEZONE) && defined(USE_TIME_TIMEZONE)
1209 // Apply only if the sender provided pre-parsed timezone data (Home Assistant 2026.3.0
1210 // and newer); field presence distinguishes a genuine all-zero UTC timezone from an
1211 // absent field. Older clients send only the deprecated timezone string, which is no
1212 // longer decoded; for them the device keeps its codegen-configured timezone.
1213 if (value.has_parsed_timezone) {
1214 const auto &pt = value.parsed_timezone;
1216 tz.std_offset_seconds = pt.std_offset_seconds;
1217 tz.dst_offset_seconds = pt.dst_offset_seconds;
1218 tz.dst_start.time_seconds = pt.dst_start.time_seconds;
1219 tz.dst_start.day = static_cast<uint16_t>(pt.dst_start.day);
1220 tz.dst_start.type = static_cast<time::DSTRuleType>(pt.dst_start.type);
1221 tz.dst_start.month = static_cast<uint8_t>(pt.dst_start.month);
1222 tz.dst_start.week = static_cast<uint8_t>(pt.dst_start.week);
1223 tz.dst_start.day_of_week = static_cast<uint8_t>(pt.dst_start.day_of_week);
1224 tz.dst_end.time_seconds = pt.dst_end.time_seconds;
1225 tz.dst_end.day = static_cast<uint16_t>(pt.dst_end.day);
1226 tz.dst_end.type = static_cast<time::DSTRuleType>(pt.dst_end.type);
1227 tz.dst_end.month = static_cast<uint8_t>(pt.dst_end.month);
1228 tz.dst_end.week = static_cast<uint8_t>(pt.dst_end.week);
1229 tz.dst_end.day_of_week = static_cast<uint8_t>(pt.dst_end.day_of_week);
1231 }
1232#endif
1233 }
1234}
1235#endif
1236
1237#ifdef USE_BLUETOOTH_PROXY
1238void APIConnection::on_subscribe_bluetooth_le_advertisements_request(
1241}
1242void APIConnection::on_unsubscribe_bluetooth_le_advertisements_request() {
1244}
1245#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
1246void APIConnection::on_bluetooth_device_request(const BluetoothDeviceRequest &msg) {
1248}
1249void APIConnection::on_bluetooth_gatt_read_request(const BluetoothGATTReadRequest &msg) {
1251}
1252void APIConnection::on_bluetooth_gatt_write_request(const BluetoothGATTWriteRequest &msg) {
1254}
1255void APIConnection::on_bluetooth_gatt_read_descriptor_request(const BluetoothGATTReadDescriptorRequest &msg) {
1257}
1258void APIConnection::on_bluetooth_gatt_write_descriptor_request(const BluetoothGATTWriteDescriptorRequest &msg) {
1260}
1261void APIConnection::on_bluetooth_gatt_get_services_request(const BluetoothGATTGetServicesRequest &msg) {
1263}
1264
1265void APIConnection::on_bluetooth_gatt_notify_request(const BluetoothGATTNotifyRequest &msg) {
1267}
1268
1269bool APIConnection::send_subscribe_bluetooth_connections_free_response_() {
1271 return true;
1272}
1273void APIConnection::on_subscribe_bluetooth_connections_free_request() {
1274 if (!this->send_subscribe_bluetooth_connections_free_response_()) {
1275 this->on_fatal_error();
1276 }
1277}
1278
1279void APIConnection::on_bluetooth_set_connection_params_request(const BluetoothSetConnectionParamsRequest &msg) {
1281}
1282#endif
1283
1284void APIConnection::on_bluetooth_scanner_set_mode_request(const BluetoothScannerSetModeRequest &msg) {
1286 msg.mode == enums::BluetoothScannerMode::BLUETOOTH_SCANNER_MODE_ACTIVE);
1287}
1288#endif
1289
1290#ifdef USE_VOICE_ASSISTANT
1291bool APIConnection::check_voice_assistant_api_connection_() const {
1292 return voice_assistant::global_voice_assistant != nullptr &&
1294}
1295
1296void APIConnection::on_subscribe_voice_assistant_request(const SubscribeVoiceAssistantRequest &msg) {
1299 }
1300}
1301void APIConnection::on_voice_assistant_response(const VoiceAssistantResponse &msg) {
1302 if (!this->check_voice_assistant_api_connection_()) {
1303 return;
1304 }
1305
1306 if (msg.error) {
1308 return;
1309 }
1310 if (msg.port == 0) {
1311 // Use API Audio
1313 } else {
1314 struct sockaddr_storage storage;
1315 socklen_t len = sizeof(storage);
1316 this->helper_->getpeername((struct sockaddr *) &storage, &len);
1318 }
1319};
1320void APIConnection::on_voice_assistant_event_response(const VoiceAssistantEventResponse &msg) {
1321 if (this->check_voice_assistant_api_connection_()) {
1323 }
1324}
1325void APIConnection::on_voice_assistant_audio(const VoiceAssistantAudio &msg) {
1326 if (this->check_voice_assistant_api_connection_()) {
1328 }
1329};
1330void APIConnection::on_voice_assistant_timer_event_response(const VoiceAssistantTimerEventResponse &msg) {
1331 if (this->check_voice_assistant_api_connection_()) {
1333 }
1334};
1335
1336void APIConnection::on_voice_assistant_announce_request(const VoiceAssistantAnnounceRequest &msg) {
1337 if (this->check_voice_assistant_api_connection_()) {
1339 }
1340}
1341
1342bool APIConnection::send_voice_assistant_get_configuration_response_(
1343 const VoiceAssistantConfigurationRequest & /*msg*/) {
1345 if (!this->check_voice_assistant_api_connection_()) {
1346 // send_message encodes synchronously, so this stack local outlives the encode
1347 const std::vector<std::string> empty_wake_words;
1348 resp.active_wake_words = &empty_wake_words;
1349 return this->send_message(resp);
1350 }
1351
1353 for (auto &wake_word : config.available_wake_words) {
1354 resp.available_wake_words.emplace_back();
1355 auto &resp_wake_word = resp.available_wake_words.back();
1356 resp_wake_word.id = StringRef(wake_word.id);
1357 resp_wake_word.wake_word = StringRef(wake_word.wake_word);
1358 for (const auto &lang : wake_word.trained_languages) {
1359 resp_wake_word.trained_languages.push_back(lang);
1360 }
1361 }
1362
1363 resp.active_wake_words = &config.active_wake_words;
1364 resp.max_active_wake_words = config.max_active_wake_words;
1365 return this->send_message(resp);
1366}
1367void APIConnection::on_voice_assistant_configuration_request(const VoiceAssistantConfigurationRequest &msg) {
1368 if (!this->send_voice_assistant_get_configuration_response_(msg)) {
1369 this->on_fatal_error();
1370 }
1371}
1372
1373void APIConnection::on_voice_assistant_set_configuration(const VoiceAssistantSetConfiguration &msg) {
1374 if (this->check_voice_assistant_api_connection_()) {
1376 }
1377}
1378#endif
1379
1380#ifdef USE_ZWAVE_PROXY
1381void APIConnection::on_z_wave_proxy_frame(const ZWaveProxyFrame &msg) {
1383}
1384
1385void APIConnection::on_z_wave_proxy_request(const ZWaveProxyRequest &msg) {
1387 resp.type = msg.type;
1389 if (!this->send_message(resp)) {
1390 API_LOG_MSG_DROPPED(TAG, "Z-Wave proxy response");
1391 }
1392}
1393#endif
1394
1395#ifdef USE_ALARM_CONTROL_PANEL
1396bool APIConnection::send_alarm_control_panel_state(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel) {
1397 return this->send_message_smart_(a_alarm_control_panel, AlarmControlPanelStateResponse::MESSAGE_TYPE,
1398 AlarmControlPanelStateResponse::ESTIMATED_SIZE);
1399}
1400uint16_t APIConnection::try_send_alarm_control_panel_state(EntityBase *entity, APIConnection *conn,
1401 uint32_t remaining_size) {
1402 auto *a_alarm_control_panel = static_cast<alarm_control_panel::AlarmControlPanel *>(entity);
1404 resp.state = static_cast<enums::AlarmControlPanelState>(a_alarm_control_panel->get_state());
1405 return fill_and_encode_entity_state(a_alarm_control_panel, resp, conn, remaining_size);
1406}
1407uint16_t APIConnection::try_send_alarm_control_panel_info(EntityBase *entity, APIConnection *conn,
1408 uint32_t remaining_size) {
1409 auto *a_alarm_control_panel = static_cast<alarm_control_panel::AlarmControlPanel *>(entity);
1411 msg.supported_features = a_alarm_control_panel->get_supported_features();
1412 msg.requires_code = a_alarm_control_panel->get_requires_code();
1413 msg.requires_code_to_arm = a_alarm_control_panel->get_requires_code_to_arm();
1414 return fill_and_encode_entity_info(a_alarm_control_panel, msg, conn, remaining_size);
1415}
1416void APIConnection::on_alarm_control_panel_command_request(const AlarmControlPanelCommandRequest &msg) {
1417 ENTITY_COMMAND_MAKE_CALL(alarm_control_panel::AlarmControlPanel, a_alarm_control_panel, alarm_control_panel)
1418 switch (msg.command) {
1419 case enums::ALARM_CONTROL_PANEL_DISARM:
1420 call.disarm();
1421 break;
1422 case enums::ALARM_CONTROL_PANEL_ARM_AWAY:
1423 call.arm_away();
1424 break;
1425 case enums::ALARM_CONTROL_PANEL_ARM_HOME:
1426 call.arm_home();
1427 break;
1428 case enums::ALARM_CONTROL_PANEL_ARM_NIGHT:
1429 call.arm_night();
1430 break;
1431 case enums::ALARM_CONTROL_PANEL_ARM_VACATION:
1432 call.arm_vacation();
1433 break;
1434 case enums::ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS:
1435 call.arm_custom_bypass();
1436 break;
1437 case enums::ALARM_CONTROL_PANEL_TRIGGER:
1438 call.pending();
1439 break;
1440 }
1441 call.set_code(msg.code.c_str(), msg.code.size());
1442 call.perform();
1443}
1444#endif
1445
1446#ifdef USE_WATER_HEATER
1447bool APIConnection::send_water_heater_state(water_heater::WaterHeater *water_heater) {
1448 return this->send_message_smart_(water_heater, WaterHeaterStateResponse::MESSAGE_TYPE,
1449 WaterHeaterStateResponse::ESTIMATED_SIZE);
1450}
1451uint16_t APIConnection::try_send_water_heater_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1452 auto *wh = static_cast<water_heater::WaterHeater *>(entity);
1454 resp.mode = static_cast<enums::WaterHeaterMode>(wh->get_mode());
1455 resp.current_temperature = wh->get_current_temperature();
1456 resp.target_temperature = wh->get_target_temperature();
1457 resp.target_temperature_low = wh->get_target_temperature_low();
1458 resp.target_temperature_high = wh->get_target_temperature_high();
1459 resp.state = wh->get_state();
1460
1461 return fill_and_encode_entity_state(wh, resp, conn, remaining_size);
1462}
1463uint16_t APIConnection::try_send_water_heater_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1464 auto *wh = static_cast<water_heater::WaterHeater *>(entity);
1466 auto traits = wh->get_traits();
1467 msg.min_temperature = traits.get_min_temperature();
1468 msg.max_temperature = traits.get_max_temperature();
1469 msg.target_temperature_step = traits.get_target_temperature_step();
1470 msg.supported_modes = &traits.get_supported_modes();
1471 msg.supported_features = traits.get_feature_flags();
1472 msg.temperature_unit = static_cast<enums::TemperatureUnit>(traits.get_temperature_unit());
1473 return fill_and_encode_entity_info(wh, msg, conn, remaining_size);
1474}
1475
1476void APIConnection::on_water_heater_command_request(const WaterHeaterCommandRequest &msg) {
1477 ENTITY_COMMAND_MAKE_CALL(water_heater::WaterHeater, water_heater, water_heater)
1478 if (msg.has_fields & enums::WATER_HEATER_COMMAND_HAS_MODE)
1479 call.set_mode(static_cast<water_heater::WaterHeaterMode>(msg.mode));
1480 if (msg.has_fields & enums::WATER_HEATER_COMMAND_HAS_TARGET_TEMPERATURE)
1481 call.set_target_temperature(msg.target_temperature);
1482 if (msg.has_fields & enums::WATER_HEATER_COMMAND_HAS_TARGET_TEMPERATURE_LOW)
1483 call.set_target_temperature_low(msg.target_temperature_low);
1484 if (msg.has_fields & enums::WATER_HEATER_COMMAND_HAS_TARGET_TEMPERATURE_HIGH)
1485 call.set_target_temperature_high(msg.target_temperature_high);
1486 if ((msg.has_fields & enums::WATER_HEATER_COMMAND_HAS_AWAY_STATE) ||
1487 (msg.has_fields & enums::WATER_HEATER_COMMAND_HAS_STATE)) {
1488 call.set_away((msg.state & water_heater::WATER_HEATER_STATE_AWAY) != 0);
1489 }
1490 if ((msg.has_fields & enums::WATER_HEATER_COMMAND_HAS_ON_STATE) ||
1491 (msg.has_fields & enums::WATER_HEATER_COMMAND_HAS_STATE)) {
1492 call.set_on((msg.state & water_heater::WATER_HEATER_STATE_ON) != 0);
1493 }
1494 call.perform();
1495}
1496#endif
1497
1498#ifdef USE_EVENT
1499// Event is a special case - unlike other entities with simple state fields,
1500// events store their state in a member accessed via obj->get_last_event_type()
1501void APIConnection::send_event(event::Event *event) {
1502 this->send_message_smart_(event, EventResponse::MESSAGE_TYPE, EventResponse::ESTIMATED_SIZE,
1503 event->get_last_event_type_index());
1504}
1505uint16_t APIConnection::try_send_event_response(event::Event *event, StringRef event_type, APIConnection *conn,
1506 uint32_t remaining_size) {
1507 EventResponse resp;
1508 resp.event_type = event_type;
1509 return fill_and_encode_entity_state(event, resp, conn, remaining_size);
1510}
1511
1512uint16_t APIConnection::try_send_event_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1513 auto *event = static_cast<event::Event *>(entity);
1515 msg.event_types = &event->get_event_types();
1516 return fill_and_encode_entity_info_with_device_class(event, msg, msg.device_class, conn, remaining_size);
1517}
1518#endif
1519
1520#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY)
1521void APIConnection::on_infrared_rf_transmit_raw_timings_request(const InfraredRFTransmitRawTimingsRequest &msg) {
1522 // Dispatch by key: infrared entities are checked first, then radio frequency entities.
1523 // The key is unique across all entity instances on a device, so at most one lookup will succeed.
1524#ifdef USE_INFRARED
1525 ENTITY_COMMAND_LOOKUP(infrared::Infrared, infrared, infrared);
1526 if (infrared != nullptr) {
1527 auto call = infrared->make_call();
1528 call.set_carrier_frequency(msg.carrier_frequency);
1529 call.set_raw_timings_packed(msg.timings_data_, msg.timings_length_, msg.timings_count_);
1530 call.set_repeat_count(msg.repeat_count);
1531 call.perform();
1532 return;
1533 }
1534#endif
1535#ifdef USE_RADIO_FREQUENCY
1536 ENTITY_COMMAND_LOOKUP(radio_frequency::RadioFrequency, radio_frequency, radio_frequency);
1537 if (radio_frequency != nullptr) {
1538 auto call = radio_frequency->make_call();
1539 call.set_frequency(msg.carrier_frequency);
1540 call.set_modulation(static_cast<radio_frequency::RadioFrequencyModulation>(msg.modulation));
1541 call.set_repeat_count(msg.repeat_count);
1542 call.set_raw_timings_packed(msg.timings_data_, msg.timings_length_, msg.timings_count_);
1543 call.perform();
1544 }
1545#endif
1546}
1547#endif
1548
1549#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY)
1550void APIConnection::send_infrared_rf_receive_event(const InfraredRFReceiveEvent &msg) {
1551 if (!this->send_message(msg)) {
1552 // V: fires per decoded frame with no subscription gate, so a warning
1553 // would flood the congested link it reports on.
1554 ESP_LOGV(TAG, "IR/RF event dropped, TCP buffer full");
1555 }
1556}
1557#endif
1558
1559#ifdef USE_SERIAL_PROXY
1560static enums::SerialProxyStatus serial_proxy_result_to_status(serial_proxy::SerialProxyResult result) {
1561 switch (result) {
1563 return enums::SERIAL_PROXY_STATUS_OK;
1565 return enums::SERIAL_PROXY_STATUS_ASSUMED_SUCCESS;
1567 return enums::SERIAL_PROXY_STATUS_PORT_IN_USE;
1569 return enums::SERIAL_PROXY_STATUS_INVALID_ARGUMENT;
1571 return enums::SERIAL_PROXY_STATUS_TIMEOUT;
1573 return enums::SERIAL_PROXY_STATUS_NOT_SUPPORTED;
1575 return enums::SERIAL_PROXY_STATUS_ERROR;
1576 }
1577 return enums::SERIAL_PROXY_STATUS_ERROR; // Unreachable; all enum values handled above
1578}
1579
1580static void send_serial_proxy_ack(APIConnection *conn, uint32_t instance, enums::SerialProxyRequestType type,
1581 enums::SerialProxyStatus status) {
1582 SerialProxyRequestResponse resp{};
1583 resp.instance = instance;
1584 resp.type = type;
1585 resp.status = status;
1586 if (!conn->send_message(resp)) {
1587 API_LOG_MSG_DROPPED(TAG, "Serial proxy response");
1588 }
1589}
1590
1591void APIConnection::on_serial_proxy_configure_request(const SerialProxyConfigureRequest &msg) {
1592 auto &proxies = App.get_serial_proxies();
1593 if (msg.instance >= proxies.size()) {
1594 ESP_LOGW(TAG, "Serial proxy instance %" PRIu32 " out of range (max %" PRIu32 ")", msg.instance,
1595 static_cast<uint32_t>(proxies.size()));
1596 send_serial_proxy_ack(this, msg.instance, enums::SERIAL_PROXY_REQUEST_TYPE_CONFIGURE,
1597 enums::SERIAL_PROXY_STATUS_INVALID_ARGUMENT);
1598 return;
1599 }
1600 serial_proxy::SerialProxyResult result = proxies[msg.instance]->configure(
1601 this, msg.baudrate, msg.flow_control, static_cast<uint8_t>(msg.parity), msg.stop_bits, msg.data_size);
1602 send_serial_proxy_ack(this, msg.instance, enums::SERIAL_PROXY_REQUEST_TYPE_CONFIGURE,
1603 serial_proxy_result_to_status(result));
1604}
1605
1606void APIConnection::on_serial_proxy_write_request(const SerialProxyWriteRequest &msg) {
1607 auto &proxies = App.get_serial_proxies();
1608 if (msg.instance >= proxies.size()) {
1609 ESP_LOGW(TAG, "Serial proxy instance %" PRIu32 " out of range", msg.instance);
1610 return;
1611 }
1612 proxies[msg.instance]->write_from_client(this, msg.data, msg.data_len);
1613}
1614
1615void APIConnection::on_serial_proxy_set_modem_pins_request(const SerialProxySetModemPinsRequest &msg) {
1616 auto &proxies = App.get_serial_proxies();
1617 if (msg.instance >= proxies.size()) {
1618 ESP_LOGW(TAG, "Serial proxy instance %" PRIu32 " out of range", msg.instance);
1619 send_serial_proxy_ack(this, msg.instance, enums::SERIAL_PROXY_REQUEST_TYPE_SET_MODEM_PINS,
1620 enums::SERIAL_PROXY_STATUS_INVALID_ARGUMENT);
1621 return;
1622 }
1623 serial_proxy::SerialProxyResult result = proxies[msg.instance]->set_modem_pins(this, msg.line_states);
1624 send_serial_proxy_ack(this, msg.instance, enums::SERIAL_PROXY_REQUEST_TYPE_SET_MODEM_PINS,
1625 serial_proxy_result_to_status(result));
1626}
1627
1628void APIConnection::on_serial_proxy_get_modem_pins_request(const SerialProxyGetModemPinsRequest &msg) {
1629 auto &proxies = App.get_serial_proxies();
1631 resp.instance = msg.instance;
1632 if (msg.instance >= proxies.size()) {
1633 ESP_LOGW(TAG, "Serial proxy instance %" PRIu32 " out of range", msg.instance);
1634 // Pre-1.16 clients do not read the status field and would take this error
1635 // for a successful "both pins deasserted" answer; let them time out as before
1636 if (!this->client_supports_api_version(1, 16)) {
1637 return;
1638 }
1639 resp.status = enums::SERIAL_PROXY_STATUS_INVALID_ARGUMENT;
1640 } else {
1641 resp.line_states = proxies[msg.instance]->get_modem_pins();
1642 }
1643 if (!this->send_message(resp)) {
1644 API_LOG_MSG_DROPPED(TAG, "Serial proxy response");
1645 }
1646}
1647
1648void APIConnection::on_serial_proxy_request(const SerialProxyRequest &msg) {
1649 auto &proxies = App.get_serial_proxies();
1650 if (msg.instance >= proxies.size()) {
1651 ESP_LOGW(TAG, "Serial proxy instance %" PRIu32 " out of range", msg.instance);
1652 send_serial_proxy_ack(this, msg.instance, msg.type, enums::SERIAL_PROXY_STATUS_INVALID_ARGUMENT);
1653 return;
1654 }
1655 auto *proxy = proxies[msg.instance];
1657 switch (msg.type) {
1658 case enums::SERIAL_PROXY_REQUEST_TYPE_SUBSCRIBE:
1659 case enums::SERIAL_PROXY_REQUEST_TYPE_UNSUBSCRIBE:
1660 status = serial_proxy_result_to_status(proxy->serial_proxy_request(this, msg.type));
1661 break;
1662 case enums::SERIAL_PROXY_REQUEST_TYPE_FLUSH:
1663 status = serial_proxy_result_to_status(proxy->flush_port(this));
1664 break;
1665 case enums::SERIAL_PROXY_REQUEST_TYPE_CONFIGURE:
1666 case enums::SERIAL_PROXY_REQUEST_TYPE_SET_MODEM_PINS:
1667 // Response-only discriminators; never valid in a request
1668 ESP_LOGW(TAG, "Response-only serial proxy request type: %" PRIu32, static_cast<uint32_t>(msg.type));
1669 status = enums::SERIAL_PROXY_STATUS_INVALID_ARGUMENT;
1670 break;
1671 default:
1672 ESP_LOGW(TAG, "Unknown serial proxy request type: %" PRIu32, static_cast<uint32_t>(msg.type));
1673 status = enums::SERIAL_PROXY_STATUS_NOT_SUPPORTED;
1674 break;
1675 }
1676 send_serial_proxy_ack(this, msg.instance, msg.type, status);
1677}
1678
1679void APIConnection::send_serial_proxy_data(const SerialProxyDataReceived &msg) {
1680 if (!this->send_message(msg)) {
1681 ESP_LOGV(TAG, "Serial proxy data dropped, TCP buffer full");
1682 }
1683}
1684#endif
1685
1686#ifdef USE_INFRARED
1687uint16_t APIConnection::try_send_infrared_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1688 auto *infrared = static_cast<infrared::Infrared *>(entity);
1690 msg.capabilities = infrared->get_capability_flags();
1691 msg.receiver_frequency = infrared->get_traits().get_receiver_frequency_hz();
1692 return fill_and_encode_entity_info(infrared, msg, conn, remaining_size);
1693}
1694#endif
1695
1696#ifdef USE_RADIO_FREQUENCY
1697uint16_t APIConnection::try_send_radio_frequency_info(EntityBase *entity, APIConnection *conn,
1698 uint32_t remaining_size) {
1699 auto *rf = static_cast<radio_frequency::RadioFrequency *>(entity);
1701 msg.capabilities = rf->get_capability_flags();
1702 msg.frequency_min = rf->get_traits().get_frequency_min_hz();
1703 msg.frequency_max = rf->get_traits().get_frequency_max_hz();
1704 msg.supported_modulations = rf->get_traits().get_supported_modulations();
1705 return fill_and_encode_entity_info(rf, msg, conn, remaining_size);
1706}
1707#endif
1708
1709#ifdef USE_UPDATE
1710bool APIConnection::send_update_state(update::UpdateEntity *update) {
1711 return this->send_message_smart_(update, UpdateStateResponse::MESSAGE_TYPE, UpdateStateResponse::ESTIMATED_SIZE);
1712}
1713uint16_t APIConnection::try_send_update_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1714 auto *update = static_cast<update::UpdateEntity *>(entity);
1716 resp.missing_state = !update->has_state();
1717 if (update->has_state()) {
1719 if (update->update_info.has_progress) {
1720 resp.has_progress = true;
1721 resp.progress = update->update_info.progress;
1722 }
1723 resp.current_version = StringRef(update->update_info.current_version);
1724 resp.latest_version = StringRef(update->update_info.latest_version);
1725 resp.title = StringRef(update->update_info.title);
1726 resp.release_summary = StringRef(update->update_info.summary);
1727 resp.release_url = StringRef(update->update_info.release_url);
1728 }
1729 return fill_and_encode_entity_state(update, resp, conn, remaining_size);
1730}
1731uint16_t APIConnection::try_send_update_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
1732 auto *update = static_cast<update::UpdateEntity *>(entity);
1734 return fill_and_encode_entity_info_with_device_class(update, msg, msg.device_class, conn, remaining_size);
1735}
1736void APIConnection::on_update_command_request(const UpdateCommandRequest &msg) {
1737 ENTITY_COMMAND_GET(update::UpdateEntity, update, update)
1738
1739 switch (msg.command) {
1740 case enums::UPDATE_COMMAND_UPDATE:
1741 update->perform();
1742 break;
1743 case enums::UPDATE_COMMAND_CHECK:
1744 update->check();
1745 break;
1746 case enums::UPDATE_COMMAND_NONE:
1747 ESP_LOGE(TAG, "UPDATE_COMMAND_NONE not handled; confirm command is correct");
1748 break;
1749 default:
1750 ESP_LOGW(TAG, "Unknown update command: %" PRIu32, msg.command);
1751 break;
1752 }
1753}
1754#endif
1755
1756bool APIConnection::try_send_log_message(int level, const char *tag, const char *line, size_t message_len) {
1758 msg.level = static_cast<enums::LogLevel>(level);
1759 msg.set_message(reinterpret_cast<const uint8_t *>(line), message_len);
1760 return this->send_message(msg);
1761}
1762
1763void APIConnection::complete_authentication_() {
1764 // Early return if already authenticated
1765 if (this->flags_.connection_state == static_cast<uint8_t>(ConnectionState::AUTHENTICATED)) {
1766 return;
1767 }
1768
1769 this->flags_.connection_state = static_cast<uint8_t>(ConnectionState::AUTHENTICATED);
1770 // Reset traffic timer so keepalive starts from authentication, not connection start
1771 this->last_traffic_ = App.get_loop_component_start_time();
1772 this->log_client_(ESPHOME_LOG_LEVEL_DEBUG, LOG_STR("connected"));
1773#ifdef USE_API_CLIENT_CONNECTED_TRIGGER
1774 {
1775 char peername[socket::SOCKADDR_STR_LEN];
1776 this->parent_->get_client_connected_trigger()->trigger(std::string(this->helper_->get_client_name()),
1777 std::string(this->helper_->get_peername_to(peername)));
1778 }
1779#endif
1780#ifdef USE_HOMEASSISTANT_TIME
1782 this->send_time_request();
1783 }
1784#endif
1785#ifdef USE_ZWAVE_PROXY
1786 if (zwave_proxy::global_zwave_proxy != nullptr) {
1788 }
1789#endif
1790}
1791
1792bool APIConnection::send_hello_response_(const HelloRequest &msg) {
1793 // Copy client name with truncation if needed (set_client_name handles truncation)
1794 this->helper_->set_client_name(msg.client_info.c_str(), msg.client_info.size());
1795 this->client_api_version_major_ =
1796 static_cast<uint8_t>(std::min<uint32_t>(msg.api_version_major, std::numeric_limits<uint8_t>::max()));
1797 this->client_api_version_minor_ =
1798 static_cast<uint8_t>(std::min<uint32_t>(msg.api_version_minor, std::numeric_limits<uint8_t>::max()));
1799 char peername[socket::SOCKADDR_STR_LEN];
1800 ESP_LOGV(TAG, "Hello from client: '%s' | %s | API Version %u.%u", this->helper_->get_client_name(),
1801 this->helper_->get_peername_to(peername), this->client_api_version_major_, this->client_api_version_minor_);
1802
1803 HelloResponse resp;
1804 resp.api_version_major = 1;
1805 resp.api_version_minor = 16;
1806 // Send only the version string - the client only logs this for debugging and doesn't use it otherwise
1807 resp.server_info = ESPHOME_VERSION_REF;
1808 resp.name = StringRef(App.get_name());
1809
1810#ifdef USE_PROVISIONING
1812 // The provisioning window has closed without the device being provisioned.
1813 // Acknowledge the hello so the client can read the server name, then request
1814 // disconnect with the reason. Authentication is intentionally not completed.
1815 this->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR("Provisioning closed; rejecting connection"));
1816 if (!this->send_message(resp)) {
1817 API_LOG_MSG_DROPPED(TAG, "Hello response");
1818 }
1820 req.reason = enums::DISCONNECT_REASON_PROVISIONING_CLOSED;
1821 return this->send_message(req);
1822 }
1823#endif
1824
1825 // Auto-authenticate - password auth was removed in ESPHome 2026.1.0
1826 this->complete_authentication_();
1827
1828 return this->send_message(resp);
1829}
1830
1831bool APIConnection::send_ping_response_() {
1832 PingResponse resp;
1833 return this->send_message(resp);
1834}
1835
1836bool APIConnection::send_device_info_response_() {
1837 DeviceInfoResponse resp;
1838 resp.name = StringRef(App.get_name());
1840#ifdef USE_AREAS
1842#endif
1843 char mac_address[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1844 uint8_t mac[MAC_ADDRESS_SIZE];
1846 format_mac_addr_upper(mac, mac_address);
1847 resp.mac_address = StringRef(mac_address);
1848
1849 resp.esphome_version = ESPHOME_VERSION_REF;
1850
1851 // Stack buffer for build time string
1852 char build_time_str[Application::BUILD_TIME_STR_SIZE];
1853 App.get_build_time_string(build_time_str);
1854 resp.compilation_time = StringRef(build_time_str);
1855
1856 // Manufacturer string - define once, handle ESP8266 PROGMEM separately
1857#if defined(USE_ESP8266) || defined(USE_ESP32)
1858#define ESPHOME_MANUFACTURER "Espressif"
1859#elif defined(USE_RP2)
1860#define ESPHOME_MANUFACTURER "Raspberry Pi"
1861#elif defined(USE_BK72XX)
1862#define ESPHOME_MANUFACTURER "Beken"
1863#elif defined(USE_LN882X)
1864#define ESPHOME_MANUFACTURER "Lightning"
1865#elif defined(USE_NRF52)
1866#define ESPHOME_MANUFACTURER "Nordic Semiconductor"
1867#elif defined(USE_RTL87XX)
1868#define ESPHOME_MANUFACTURER "Realtek"
1869#elif defined(USE_HOST)
1870#define ESPHOME_MANUFACTURER "Host"
1871#endif
1872
1873#ifdef USE_ESP8266
1874 // ESP8266 requires PROGMEM for flash storage, copy to stack for memcpy compatibility
1875 static const char MANUFACTURER_PROGMEM[] PROGMEM = ESPHOME_MANUFACTURER;
1876 char manufacturer_buf[sizeof(MANUFACTURER_PROGMEM)];
1877 memcpy_P(manufacturer_buf, MANUFACTURER_PROGMEM, sizeof(MANUFACTURER_PROGMEM));
1878 resp.manufacturer = StringRef(manufacturer_buf, sizeof(MANUFACTURER_PROGMEM) - 1);
1879#else
1880 static constexpr auto MANUFACTURER = StringRef::from_lit(ESPHOME_MANUFACTURER);
1881 resp.manufacturer = MANUFACTURER;
1882#endif
1883 static_assert(sizeof(ESPHOME_MANUFACTURER) - 1 <= 20, "Update max_data_length for manufacturer in api.proto");
1884#undef ESPHOME_MANUFACTURER
1885
1886#ifdef USE_ESP8266
1887 static const char MODEL_PROGMEM[] PROGMEM = ESPHOME_BOARD;
1888 char model_buf[sizeof(MODEL_PROGMEM)];
1889 memcpy_P(model_buf, MODEL_PROGMEM, sizeof(MODEL_PROGMEM));
1890 resp.model = StringRef(model_buf, sizeof(MODEL_PROGMEM) - 1);
1891#else
1892 static constexpr auto MODEL = StringRef::from_lit(ESPHOME_BOARD);
1893 resp.model = MODEL;
1894#endif
1895#ifdef USE_DEEP_SLEEP
1897#endif
1898#ifdef ESPHOME_PROJECT_NAME
1899#ifdef USE_ESP8266
1900 static const char PROJECT_NAME_PROGMEM[] PROGMEM = ESPHOME_PROJECT_NAME;
1901 static const char PROJECT_VERSION_PROGMEM[] PROGMEM = ESPHOME_PROJECT_VERSION;
1902 char project_name_buf[sizeof(PROJECT_NAME_PROGMEM)];
1903 char project_version_buf[sizeof(PROJECT_VERSION_PROGMEM)];
1904 memcpy_P(project_name_buf, PROJECT_NAME_PROGMEM, sizeof(PROJECT_NAME_PROGMEM));
1905 memcpy_P(project_version_buf, PROJECT_VERSION_PROGMEM, sizeof(PROJECT_VERSION_PROGMEM));
1906 resp.project_name = StringRef(project_name_buf, sizeof(PROJECT_NAME_PROGMEM) - 1);
1907 resp.project_version = StringRef(project_version_buf, sizeof(PROJECT_VERSION_PROGMEM) - 1);
1908#else
1909 static constexpr auto PROJECT_NAME = StringRef::from_lit(ESPHOME_PROJECT_NAME);
1910 static constexpr auto PROJECT_VERSION = StringRef::from_lit(ESPHOME_PROJECT_VERSION);
1911 resp.project_name = PROJECT_NAME;
1912 resp.project_version = PROJECT_VERSION;
1913#endif
1914#endif
1915#ifdef USE_WEBSERVER
1916 resp.webserver_port = USE_WEBSERVER_PORT;
1917#endif
1918#ifdef USE_BLUETOOTH_PROXY
1920 char bluetooth_mac[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1922 resp.bluetooth_mac_address = StringRef(bluetooth_mac);
1923#endif
1924#ifdef USE_VOICE_ASSISTANT
1926#endif
1927#ifdef USE_ZWAVE_PROXY
1930#endif
1931#ifdef USE_SERIAL_PROXY
1932 size_t serial_proxy_index = 0;
1933 for (auto const &proxy : App.get_serial_proxies()) {
1934 if (serial_proxy_index >= SERIAL_PROXY_COUNT)
1935 break;
1936 auto &info = resp.serial_proxies[serial_proxy_index++];
1937 info.name = StringRef(proxy->get_name());
1938 info.port_type = proxy->get_port_type();
1939 info.configured_line_states = proxy->get_configured_modem_pins();
1940 }
1941#endif
1942#ifdef USE_API_NOISE
1943 resp.api_encryption_supported = true;
1944#ifndef USE_API_NOISE_PSK_FROM_YAML
1945 // No key from YAML: while no key is set, the key can be provisioned over a
1946 // zero-PSK Noise connection. Gated on the YAML define (not the plaintext
1947 // one) so this advertisement survives the plaintext removal in 2027.2.0.
1948 resp.api_encryption_provisionable = !this->parent_->get_noise_ctx().has_psk();
1949#endif
1950#endif
1951#ifdef USE_DEVICES
1952 size_t device_index = 0;
1953 for (auto const &device : App.get_devices()) {
1954 if (device_index >= ESPHOME_DEVICE_COUNT)
1955 break;
1956 auto &device_info = resp.devices[device_index++];
1957 device_info.device_id = device->get_device_id();
1958 device_info.name = StringRef(device->get_name());
1959 device_info.area_id = device->get_area_id();
1960 }
1961#endif
1962#ifdef USE_AREAS
1963 size_t area_index = 0;
1964 for (auto const &area : App.get_areas()) {
1965 if (area_index >= ESPHOME_AREA_COUNT)
1966 break;
1967 auto &area_info = resp.areas[area_index++];
1968 area_info.area_id = area->get_area_id();
1969 area_info.name = StringRef(area->get_name());
1970 }
1971#endif
1972
1973 return this->send_message(resp);
1974}
1975bool APIConnection::send_device_capabilities_response_() {
1976 // These are the same values DeviceInfoResponse still reports for older clients. Keep the blocks
1977 // below in sync with send_device_info_response_() until those copies are removed.
1979#ifdef USE_BLUETOOTH_PROXY
1981 char bluetooth_mac[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1983 resp.bluetooth_proxy.mac_address = StringRef(bluetooth_mac);
1984#endif
1985#ifdef USE_VOICE_ASSISTANT
1987#endif
1988#ifdef USE_ZWAVE_PROXY
1991#endif
1992#ifdef USE_SERIAL_PROXY
1993 size_t serial_proxy_index = 0;
1994 for (auto const &proxy : App.get_serial_proxies()) {
1995 if (serial_proxy_index >= SERIAL_PROXY_COUNT)
1996 break;
1997 auto &info = resp.serial_proxies[serial_proxy_index++];
1998 info.name = StringRef(proxy->get_name());
1999 info.port_type = proxy->get_port_type();
2000 info.configured_line_states = proxy->get_configured_modem_pins();
2001 }
2002#endif
2003 return this->send_message(resp);
2004}
2005void APIConnection::on_hello_request(const HelloRequest &msg) {
2006 if (!this->send_hello_response_(msg)) {
2007 this->on_fatal_error();
2008 }
2009}
2010void APIConnection::on_disconnect_request(const DisconnectRequest & /*msg*/) {
2011 // The reason is informational when a client disconnects us; we always ack and close.
2012 if (!this->send_disconnect_response_()) {
2013 this->on_fatal_error();
2014 }
2015}
2016void APIConnection::on_ping_request() {
2017 if (!this->send_ping_response_()) {
2018 this->on_fatal_error();
2019 }
2020}
2021void APIConnection::on_device_info_request() {
2022 if (!this->send_device_info_response_()) {
2023 this->on_fatal_error();
2024 }
2025}
2026void APIConnection::on_device_capabilities_request() {
2027 if (!this->send_device_capabilities_response_()) {
2028 this->on_fatal_error();
2029 }
2030}
2031
2032#ifdef USE_API_HOMEASSISTANT_STATES
2033void APIConnection::on_home_assistant_state_response(const HomeAssistantStateResponse &msg) {
2034 // Skip if entity_id is empty (invalid message)
2035 if (msg.entity_id.empty()) {
2036 return;
2037 }
2038
2039 // Null-terminate state in-place for safe c_str() usage (e.g., parse_number in callbacks).
2040 // Safe: decode is complete, byte after string data was already consumed during parse,
2041 // and frame helpers reserve RX_BUF_NULL_TERMINATOR extra byte in rx_buf_.
2042 // const_cast is safe: msg references mutable rx_buf_ data; the const& handler
2043 // signature is a generated protobuf pattern, not a true immutability contract.
2044 if (!msg.state.empty()) {
2045 const_cast<char *>(msg.state.c_str())[msg.state.size()] = '\0';
2046 }
2047
2048 for (auto &it : this->parent_->get_state_subs()) {
2049 if (msg.entity_id != it.entity_id) {
2050 continue;
2051 }
2052
2053 // If subscriber has attribute filter (non-null), message attribute must match it;
2054 // if subscriber has no filter (nullptr), message must have no attribute.
2055 if (it.attribute != nullptr ? msg.attribute != it.attribute : !msg.attribute.empty()) {
2056 continue;
2057 }
2058
2059 it.callback(msg.state);
2060 }
2061}
2062#endif
2063#ifdef USE_API_USER_DEFINED_ACTIONS
2064void APIConnection::on_execute_service_request(const ExecuteServiceRequest &msg) {
2065 // Null-terminate string args in-place for safe c_str() usage in YAML service triggers.
2066 // Safe: full ExecuteServiceRequest decode is complete, all bytes in rx_buf_ consumed,
2067 // and frame helpers reserve RX_BUF_NULL_TERMINATOR extra byte for the last field.
2068 // const_cast is safe: msg references mutable rx_buf_ data; the const& handler
2069 // signature is a generated protobuf pattern, not a true immutability contract.
2070 for (auto &arg : const_cast<ExecuteServiceRequest &>(msg).args) {
2071 if (!arg.string_.empty()) {
2072 const_cast<char *>(arg.string_.c_str())[arg.string_.size()] = '\0';
2073 }
2074 }
2075 bool found = false;
2076#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
2077 // Register the call and get a unique server-generated action_call_id
2078 // This avoids collisions when multiple clients use the same call_id
2079 uint32_t action_call_id = 0;
2080 if (msg.call_id != 0) {
2081 action_call_id = this->parent_->register_active_action_call(msg.call_id, this);
2082 }
2083 // Use the overload that passes action_call_id separately (avoids copying msg)
2084 for (auto *service : this->parent_->get_user_services()) {
2085 if (service->execute_service(msg, action_call_id)) {
2086 found = true;
2087 }
2088 }
2089#else
2090 for (auto *service : this->parent_->get_user_services()) {
2091 if (service->execute_service(msg)) {
2092 found = true;
2093 }
2094 }
2095#endif
2096 if (!found) {
2097 ESP_LOGV(TAG, "Could not find service");
2098 }
2099 // Note: For services with supports_response != none, the call is unregistered
2100 // by an automatically appended APIUnregisterServiceCallAction at the end of
2101 // the action list. This ensures async actions (delays, waits) complete first.
2102}
2103#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
2104void APIConnection::send_execute_service_response(uint32_t call_id, bool success, StringRef error_message) {
2106 resp.call_id = call_id;
2107 resp.success = success;
2108 resp.error_message = error_message;
2109 if (!this->send_message(resp)) {
2110 API_LOG_MSG_DROPPED(TAG, "Action response");
2111 }
2112}
2113#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
2114void APIConnection::send_execute_service_response(uint32_t call_id, bool success, StringRef error_message,
2115 const uint8_t *response_data, size_t response_data_len) {
2117 resp.call_id = call_id;
2118 resp.success = success;
2119 resp.error_message = error_message;
2120 resp.response_data = response_data;
2121 resp.response_data_len = response_data_len;
2122 if (!this->send_message(resp)) {
2123 API_LOG_MSG_DROPPED(TAG, "Action response");
2124 }
2125}
2126#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
2127#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
2128#endif
2129
2130#ifdef USE_API_HOMEASSISTANT_SERVICES
2131bool APIConnection::send_homeassistant_action(const HomeassistantActionRequest &call) {
2132 if (!this->flags_.service_call_subscription)
2133 return false;
2134 if (!this->send_message(call)) {
2135 API_LOG_MSG_DROPPED(TAG, "Action request");
2136 }
2137 return true;
2138}
2139#endif // USE_API_HOMEASSISTANT_SERVICES
2140
2141#ifdef USE_HOMEASSISTANT_TIME
2142void APIConnection::send_time_request() {
2143 GetTimeRequest req;
2144 if (!this->send_message(req)) {
2145 API_LOG_MSG_DROPPED(TAG, "Time request");
2146 }
2147}
2148#endif // USE_HOMEASSISTANT_TIME
2149
2150#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
2151void APIConnection::on_homeassistant_action_response(const HomeassistantActionResponse &msg) {
2152#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
2153 if (msg.response_data_len > 0) {
2154 this->parent_->handle_action_response(msg.call_id, msg.success, msg.error_message, msg.response_data,
2155 msg.response_data_len);
2156 } else
2157#endif
2158 {
2159 this->parent_->handle_action_response(msg.call_id, msg.success, msg.error_message);
2160 }
2161};
2162#endif
2163#ifdef USE_API_NOISE
2164bool APIConnection::send_noise_encryption_set_key_response_(const NoiseEncryptionSetKeyRequest &msg) {
2166 resp.success = false;
2167#ifdef USE_API_NOISE_PSK_FROM_YAML
2168 // A yaml key cannot be changed at runtime, so no decode or save path is built
2169 ESP_LOGW(TAG, "Key set in YAML");
2170#else
2171#ifdef USE_PROVISIONING
2172 // Refuse to set a key once the provisioning window has closed (defense in depth;
2173 // such connections are already rejected at hello).
2175 ESP_LOGW(TAG, "Provisioning closed; rejecting key set");
2176 return this->send_message(resp);
2177 }
2178#endif
2179
2180 noise::psk_t psk{};
2181 if (msg.key_len == 0) {
2182 if (this->parent_->clear_noise_psk(true)) {
2183 resp.success = true;
2184 } else {
2185 ESP_LOGW(TAG, "Failed to clear encryption key");
2186 }
2187 } else if (base64_decode(msg.key, msg.key_len, psk.data(), psk.size()) != psk.size()) {
2188 ESP_LOGW(TAG, "Invalid encryption key length");
2189 } else if (noise::NoiseContext::is_all_zeros(psk)) {
2190 // Accepting the reserved provisioning PSK would report success without
2191 // enabling encryption (or silently clear an existing key)
2192 ESP_LOGW(TAG, "Rejecting all-zero encryption key");
2193 } else if (!this->parent_->save_noise_psk(psk, true)) {
2194 ESP_LOGW(TAG, "Failed to save encryption key");
2195 } else {
2196 resp.success = true;
2197#ifdef USE_API_PLAINTEXT
2198 if (this->helper_->frame_footer_size() == 0) {
2199 // Plaintext transport has no frame footer; Noise always has the MAC footer.
2200 // Remove after 2027.2.0 together with plaintext support on keyless devices.
2201 ESP_LOGW(TAG, "Key received over plaintext; deprecated, will be removed in 2027.2.0");
2202 }
2203#endif
2204 }
2205#endif // USE_API_NOISE_PSK_FROM_YAML
2206
2207 return this->send_message(resp);
2208}
2209void APIConnection::on_noise_encryption_set_key_request(const NoiseEncryptionSetKeyRequest &msg) {
2210 if (!this->send_noise_encryption_set_key_response_(msg)) {
2211 this->on_fatal_error();
2212 }
2213}
2214#endif
2215#ifdef USE_API_HOMEASSISTANT_STATES
2216void APIConnection::on_subscribe_home_assistant_states_request() { state_subs_at_ = 0; }
2217#endif
2218bool APIConnection::try_to_clear_buffer_slow_(bool log_out_of_space) {
2219 delay(0);
2220 APIError err = this->helper_->loop();
2221 if (err != APIError::OK) {
2222 this->fatal_error_with_log_(LOG_STR("Socket operation failed"), err);
2223 return false;
2224 }
2225 if (this->helper_->can_write_without_blocking())
2226 return true;
2227 if (log_out_of_space) {
2228 // VV: refusals are either reported by the sending call site (naming what
2229 // was lost) or retried without loss (the deferred batch), so this generic
2230 // line only duplicates them.
2231 ESP_LOGVV(TAG, "Cannot send message because of TCP buffer space");
2232 }
2233 return false;
2234}
2235bool APIConnection::send_message_(uint32_t payload_size, uint16_t message_type, MessageEncodeFn encode_fn,
2236 const void *msg) {
2237#ifdef HAS_PROTO_MESSAGE_DUMP
2238 // Skip dump for log messages (recursive logging risk) and camera frames (high-frequency noise)
2239 if (message_type != SubscribeLogsResponse::MESSAGE_TYPE
2240#ifdef USE_CAMERA
2241 && message_type != CameraImageResponse::MESSAGE_TYPE
2242#endif
2243 ) {
2244 auto *proto_msg = static_cast<const ProtoMessage *>(msg);
2245 DumpBuffer dump_buf;
2246 this->log_send_message_(proto_msg->message_name(), proto_msg->dump_to(dump_buf));
2247 }
2248#endif
2249 if (!this->prepare_first_message_buffer(payload_size)) [[unlikely]] {
2250 this->fatal_out_of_memory_();
2251 return false;
2252 }
2253 auto &shared_buf = this->parent_->get_shared_buffer_ref();
2254 size_t write_start = shared_buf.size();
2255#ifdef ESPHOME_DEBUG_API
2256 assert(shared_buf.capacity() >= write_start + payload_size);
2257#endif
2258 // Capacity reserved above, cannot fail
2259 (void) shared_buf.resize(write_start + payload_size);
2260 ProtoWriteBuffer buffer{&shared_buf, write_start};
2261 encode_fn(msg, buffer PROTO_ENCODE_DEBUG_INIT(&shared_buf));
2262 return this->send_buffer(ProtoWriteBuffer{&shared_buf}, message_type);
2263}
2264// encode_to_buffer is defined inline in api_connection.h (ESPHOME_ALWAYS_INLINE)
2265
2266// Noinline version for cold paths — single shared copy
2267uint16_t APIConnection::encode_to_buffer_slow(uint32_t calculated_size, MessageEncodeFn encode_fn, const void *msg,
2268 APIConnection *conn, uint32_t remaining_size) {
2269 return encode_to_buffer(calculated_size, encode_fn, msg, conn, remaining_size);
2270}
2271bool APIConnection::send_buffer(ProtoWriteBuffer buffer, uint16_t message_type) {
2272 const bool is_log_message = (message_type == SubscribeLogsResponse::MESSAGE_TYPE);
2273
2274 if (!this->try_to_clear_buffer(!is_log_message)) {
2275 return false;
2276 }
2277
2278 // Set TCP_NODELAY based on message type - see set_nodelay_for_message() for details
2279 this->helper_->set_nodelay_for_message(is_log_message);
2280
2281 APIError err = this->helper_->write_protobuf_packet(message_type, buffer);
2282 if (err == APIError::WOULD_BLOCK)
2283 return false;
2284 if (err != APIError::OK) {
2285 this->fatal_error_with_log_(LOG_STR("Packet write failed"), err);
2286 return false;
2287 }
2288 // Do not set last_traffic_ on send
2289 return true;
2290}
2291void APIConnection::on_no_setup_connection() {
2292 this->on_fatal_error();
2293 this->log_client_(ESPHOME_LOG_LEVEL_DEBUG, LOG_STR("no connection setup"));
2294}
2295void APIConnection::fatal_out_of_memory_() {
2296 this->fatal_error_with_log_(LOG_STR("Out of memory"), APIError::OUT_OF_MEMORY);
2297}
2298void APIConnection::on_fatal_error() {
2299 // Don't close socket here - keep it open so getpeername() works for logging
2300 // Socket will be closed when client is removed from the list in APIServer::loop()
2301 this->flags_.remove = true;
2302}
2303
2304bool APIConnection::schedule_message_front_(EntityBase *entity, uint16_t message_type, uint8_t estimated_size) {
2305 this->deferred_batch_.add_item_front(entity, message_type, estimated_size);
2306 return this->schedule_batch_();
2307}
2308
2309bool APIConnection::send_message_smart_(EntityBase *entity, uint16_t message_type, uint8_t estimated_size,
2310 uint8_t aux_data_index) {
2311 if (this->should_send_immediately_(message_type) && this->helper_->can_write_without_blocking()) {
2312 // No local for the shared buffer here: keeping it live across
2313 // dispatch_message_ costs a register and spills message_type into the
2314 // batching path's dedup loop (measured on x86 GCC -Os)
2315 if (!this->prepare_first_message_buffer(estimated_size)) [[unlikely]] {
2316 this->fatal_out_of_memory_();
2317 return false;
2318 }
2319 DeferredBatch::BatchItem item{entity, message_type, estimated_size, aux_data_index};
2320 if (this->dispatch_message_(item, MAX_BATCH_PACKET_SIZE, true) &&
2321 this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, message_type)) {
2322#ifdef HAS_PROTO_MESSAGE_DUMP
2323 this->log_batch_item_(item);
2324#endif
2325 return true;
2326 }
2327 // An OOM during the immediate attempt marks the connection for removal;
2328 // don't queue more work (schedule_message_'s push_back may allocate again)
2329 if (this->flags_.remove) [[unlikely]]
2330 return false;
2331 }
2332 return this->schedule_message_(entity, message_type, estimated_size, aux_data_index);
2333}
2334
2335bool APIConnection::schedule_batch_() {
2336 if (!this->flags_.batch_scheduled) {
2337 this->flags_.batch_scheduled = true;
2338 this->deferred_batch_.batch_start_time = App.get_loop_component_start_time();
2339 }
2340 return true;
2341}
2342
2343void APIConnection::process_batch_() {
2344 if (this->deferred_batch_.empty()) {
2345 this->flags_.batch_scheduled = false;
2346 return;
2347 }
2348
2349 // Ensure TCP_NODELAY is on before draining overflow and writing batch data.
2350 // Log messages enable Nagle (NODELAY off) to coalesce small packets.
2351 // If Nagle is still on when we try to drain, LWIP holds data in the
2352 // Nagle buffer, the TCP send buffer stays full, and the overflow
2353 // buffer can never drain — blocking the batch write indefinitely.
2354 this->helper_->set_nodelay_for_message(false);
2355
2356 // Try to clear buffer first
2357 if (!this->try_to_clear_buffer(true)) {
2358 // Can't write now, we'll try again later
2359 return;
2360 }
2361
2362 // Get shared buffer reference once to avoid multiple calls
2363 auto &shared_buf = this->parent_->get_shared_buffer_ref();
2364 size_t num_items = this->deferred_batch_.size();
2365
2366 // Cache these values to avoid repeated virtual calls
2367 const uint8_t header_padding = this->helper_->frame_header_padding();
2368 const uint8_t footer_size = this->helper_->frame_footer_size();
2369
2370 // Pre-calculate exact buffer size needed based on message types
2371 uint32_t total_estimated_size = num_items * (header_padding + footer_size);
2372 for (size_t i = 0; i < num_items; i++) {
2373 total_estimated_size += this->deferred_batch_[i].estimated_size;
2374 }
2375 // Clamp to MAX_BATCH_PACKET_SIZE — we won't send more than that per batch
2376 if (total_estimated_size > MAX_BATCH_PACKET_SIZE) {
2377 total_estimated_size = MAX_BATCH_PACKET_SIZE;
2378 }
2379
2380 if (!this->prepare_first_message_buffer(header_padding, total_estimated_size)) [[unlikely]] {
2381 this->fatal_out_of_memory_();
2382 this->clear_batch_();
2383 return;
2384 }
2385
2386 // Fast path for single message - buffer already allocated above
2387 if (num_items == 1) {
2388 const auto &item = this->deferred_batch_[0];
2389 // Let dispatch_message_ calculate size and encode if it fits
2390 uint16_t payload_size = this->dispatch_message_(item, std::numeric_limits<uint16_t>::max(), true);
2391
2392 if (payload_size > 0 && this->send_buffer(ProtoWriteBuffer{&shared_buf}, item.message_type)) {
2393#ifdef HAS_PROTO_MESSAGE_DUMP
2394 // Log message after send attempt for VV debugging
2395 this->log_batch_item_(item);
2396#endif
2397 this->clear_batch_();
2398 } else if (payload_size == 0) {
2399 // payload_size == 0 with remove set means encoding hit OOM and the
2400 // connection is being dropped; warn only for a genuinely oversized message
2401 if (!this->flags_.remove) {
2402 ESP_LOGW(TAG, "Message too large to send: type=%u", item.message_type);
2403 }
2404 this->clear_batch_();
2405 }
2406 return;
2407 }
2408
2409 // Multi-message path — heavy stack frame isolated in separate noinline function
2410 this->process_batch_multi_(shared_buf, num_items, header_padding, footer_size);
2411}
2412
2413// Separated from process_batch_() so the single-message fast path gets a minimal
2414// stack frame without the MAX_MESSAGES_PER_BATCH * sizeof(MessageInfo) array.
2415void APIConnection::process_batch_multi_(APIBuffer &shared_buf, size_t num_items, uint8_t header_padding,
2416 uint8_t footer_size) {
2417 // Ensure MessageInfo remains trivially destructible for our placement new approach
2418 static_assert(std::is_trivially_destructible<MessageInfo>::value,
2419 "MessageInfo must remain trivially destructible with this placement-new approach");
2420
2421 const size_t messages_to_process = std::min(num_items, MAX_MESSAGES_PER_BATCH);
2422
2423 // Stack-allocated array for message info
2424 alignas(MessageInfo) char message_info_storage[MAX_MESSAGES_PER_BATCH * sizeof(MessageInfo)];
2425 MessageInfo *message_info = reinterpret_cast<MessageInfo *>(message_info_storage);
2426 size_t items_processed = 0;
2427 uint16_t remaining_size = std::numeric_limits<uint16_t>::max();
2428 // Track where each message's header begins in the buffer
2429 // First message: offset 0 (max padding, may have unused leading bytes)
2430 // Subsequent messages: offset points to exact header start (no gaps)
2431 uint32_t current_offset = 0;
2432
2433 // Process items and encode directly to buffer (up to our limit)
2434 for (size_t i = 0; i < messages_to_process; i++) {
2435 const auto &item = this->deferred_batch_[i];
2436 // Try to encode message via dispatch
2437 // The dispatch function calculates overhead to determine if the message fits
2438 uint16_t payload_size = this->dispatch_message_(item, remaining_size, i == 0);
2439
2440 if (payload_size == 0) {
2441 // Message won't fit, stop processing
2442 break;
2443 }
2444
2445 // Message was encoded successfully
2446 // payload_size = header_size + proto_payload_size + footer_size
2447 uint16_t proto_payload_size = payload_size - this->batch_header_size_ - footer_size;
2448 // Use placement new to construct MessageInfo in pre-allocated stack array
2449 // This avoids default-constructing all MAX_MESSAGES_PER_BATCH elements
2450 // Explicit destruction is not needed because MessageInfo is trivially destructible,
2451 // as ensured by the static_assert in its definition.
2452 new (&message_info[items_processed++])
2453 MessageInfo(item.message_type, current_offset, proto_payload_size, this->batch_header_size_);
2454 // After first message, set remaining size to MAX_BATCH_PACKET_SIZE to avoid fragmentation
2455 if (items_processed == 1) {
2456 remaining_size = MAX_BATCH_PACKET_SIZE;
2457 }
2458 remaining_size -= payload_size;
2459 // Calculate where the next message's header padding will start
2460 // Current buffer size + footer space for this message
2461 current_offset = shared_buf.size() + footer_size;
2462 }
2463
2464 if (items_processed > 0) {
2465 // Add footer space for the last message (for Noise protocol MAC)
2466 if (footer_size > 0 && !shared_buf.resize(shared_buf.size() + footer_size)) [[unlikely]] {
2467 this->fatal_out_of_memory_();
2468 this->clear_batch_();
2469 return;
2470 }
2471
2472 // Send all collected messages
2473 APIError err = this->helper_->write_protobuf_messages(ProtoWriteBuffer{&shared_buf},
2474 std::span<const MessageInfo>(message_info, items_processed));
2475 if (err != APIError::OK && err != APIError::WOULD_BLOCK) {
2476 this->fatal_error_with_log_(LOG_STR("Batch write failed"), err);
2477 }
2478
2479#ifdef HAS_PROTO_MESSAGE_DUMP
2480 // Log messages after send attempt for VV debugging
2481 // It's safe to use the buffer for logging at this point regardless of send result
2482 for (size_t i = 0; i < items_processed; i++) {
2483 const auto &item = this->deferred_batch_[i];
2484 this->log_batch_item_(item);
2485 }
2486#endif
2487
2488 // Partial batch — remove processed items and reschedule
2489 if (items_processed < this->deferred_batch_.size()) {
2490 this->deferred_batch_.remove_front(items_processed);
2491 this->schedule_batch_();
2492 return;
2493 }
2494 }
2495
2496 // All items processed (or none could be processed)
2497 this->clear_batch_();
2498}
2499
2500// Dispatch message encoding based on message_type
2501// Switch assigns function pointer, single call site for smaller code size
2502uint16_t APIConnection::dispatch_message_(const DeferredBatch::BatchItem &item, uint32_t remaining_size,
2503 bool batch_first) {
2504 this->flags_.batch_first_message = batch_first;
2505 this->batch_message_type_ = item.message_type;
2506#ifdef USE_EVENT
2507 // Events need aux_data_index to look up event type from entity
2508 if (item.message_type == EventResponse::MESSAGE_TYPE) {
2509 // Skip if aux_data_index is invalid (should never happen in normal operation)
2510 if (item.aux_data_index == DeferredBatch::AUX_DATA_UNUSED)
2511 return 0;
2512 auto *event = static_cast<event::Event *>(item.entity);
2513 return try_send_event_response(event, StringRef::from_maybe_nullptr(event->get_event_type(item.aux_data_index)),
2514 this, remaining_size);
2515 }
2516#endif
2517
2518 // All other message types use function pointer lookup via switch
2519 MessageCreatorPtr func = nullptr;
2520
2521// Macros to reduce repetitive switch cases
2522#define CASE_STATE_INFO(entity_name, StateResp, InfoResp) \
2523 case StateResp::MESSAGE_TYPE: \
2524 func = &try_send_##entity_name##_state; \
2525 break; \
2526 case InfoResp::MESSAGE_TYPE: \
2527 func = &try_send_##entity_name##_info; \
2528 break;
2529#define CASE_INFO_ONLY(entity_name, InfoResp) \
2530 case InfoResp::MESSAGE_TYPE: \
2531 func = &try_send_##entity_name##_info; \
2532 break;
2533
2534 switch (item.message_type) {
2535#ifdef USE_BINARY_SENSOR
2536 CASE_STATE_INFO(binary_sensor, BinarySensorStateResponse, ListEntitiesBinarySensorResponse)
2537#endif
2538#ifdef USE_COVER
2539 CASE_STATE_INFO(cover, CoverStateResponse, ListEntitiesCoverResponse)
2540#endif
2541#ifdef USE_FAN
2542 CASE_STATE_INFO(fan, FanStateResponse, ListEntitiesFanResponse)
2543#endif
2544#ifdef USE_LIGHT
2545 CASE_STATE_INFO(light, LightStateResponse, ListEntitiesLightResponse)
2546#endif
2547#ifdef USE_SENSOR
2548 CASE_STATE_INFO(sensor, SensorStateResponse, ListEntitiesSensorResponse)
2549#endif
2550#ifdef USE_SWITCH
2551 CASE_STATE_INFO(switch, SwitchStateResponse, ListEntitiesSwitchResponse)
2552#endif
2553#ifdef USE_BUTTON
2554 CASE_INFO_ONLY(button, ListEntitiesButtonResponse)
2555#endif
2556#ifdef USE_TEXT_SENSOR
2557 CASE_STATE_INFO(text_sensor, TextSensorStateResponse, ListEntitiesTextSensorResponse)
2558#endif
2559#ifdef USE_CLIMATE
2560 CASE_STATE_INFO(climate, ClimateStateResponse, ListEntitiesClimateResponse)
2561#endif
2562#ifdef USE_NUMBER
2563 CASE_STATE_INFO(number, NumberStateResponse, ListEntitiesNumberResponse)
2564#endif
2565#ifdef USE_DATETIME_DATE
2566 CASE_STATE_INFO(date, DateStateResponse, ListEntitiesDateResponse)
2567#endif
2568#ifdef USE_DATETIME_TIME
2569 CASE_STATE_INFO(time, TimeStateResponse, ListEntitiesTimeResponse)
2570#endif
2571#ifdef USE_DATETIME_DATETIME
2572 CASE_STATE_INFO(datetime, DateTimeStateResponse, ListEntitiesDateTimeResponse)
2573#endif
2574#ifdef USE_TEXT
2575 CASE_STATE_INFO(text, TextStateResponse, ListEntitiesTextResponse)
2576#endif
2577#ifdef USE_SELECT
2578 CASE_STATE_INFO(select, SelectStateResponse, ListEntitiesSelectResponse)
2579#endif
2580#ifdef USE_LOCK
2582#endif
2583#ifdef USE_VALVE
2584 CASE_STATE_INFO(valve, ValveStateResponse, ListEntitiesValveResponse)
2585#endif
2586#ifdef USE_MEDIA_PLAYER
2587 CASE_STATE_INFO(media_player, MediaPlayerStateResponse, ListEntitiesMediaPlayerResponse)
2588#endif
2589#ifdef USE_ALARM_CONTROL_PANEL
2590 CASE_STATE_INFO(alarm_control_panel, AlarmControlPanelStateResponse, ListEntitiesAlarmControlPanelResponse)
2591#endif
2592#ifdef USE_WATER_HEATER
2593 CASE_STATE_INFO(water_heater, WaterHeaterStateResponse, ListEntitiesWaterHeaterResponse)
2594#endif
2595#ifdef USE_CAMERA
2596 CASE_INFO_ONLY(camera, ListEntitiesCameraResponse)
2597#endif
2598#ifdef USE_INFRARED
2599 CASE_INFO_ONLY(infrared, ListEntitiesInfraredResponse)
2600#endif
2601#ifdef USE_RADIO_FREQUENCY
2602 CASE_INFO_ONLY(radio_frequency, ListEntitiesRadioFrequencyResponse)
2603#endif
2604#ifdef USE_EVENT
2605 CASE_INFO_ONLY(event, ListEntitiesEventResponse)
2606#endif
2607#ifdef USE_UPDATE
2608 CASE_STATE_INFO(update, UpdateStateResponse, ListEntitiesUpdateResponse)
2609#endif
2610 // Special messages (not entity state/info)
2611 case ListEntitiesDoneResponse::MESSAGE_TYPE:
2612 func = &try_send_list_info_done;
2613 break;
2614 case DisconnectRequest::MESSAGE_TYPE:
2615 func = &try_send_disconnect_request;
2616 break;
2617 case PingRequest::MESSAGE_TYPE:
2618 func = &try_send_ping_request;
2619 break;
2620 default:
2621 return 0;
2622 }
2623
2624#undef CASE_STATE_INFO
2625#undef CASE_INFO_ONLY
2626
2627 return func(item.entity, this, remaining_size);
2628}
2629
2630uint16_t APIConnection::try_send_list_info_done(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
2632 return encode_message_to_buffer(resp, conn, remaining_size);
2633}
2634
2635uint16_t APIConnection::try_send_disconnect_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
2637 return encode_message_to_buffer(req, conn, remaining_size);
2638}
2639
2640uint16_t APIConnection::try_send_ping_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size) {
2641 PingRequest req;
2642 return encode_message_to_buffer(req, conn, remaining_size);
2643}
2644
2645#ifdef USE_API_HOMEASSISTANT_STATES
2646void APIConnection::process_state_subscriptions_() {
2647 const auto &subs = this->parent_->get_state_subs();
2648 if (this->state_subs_at_ >= static_cast<int>(subs.size())) {
2649 this->state_subs_at_ = -1;
2650 return;
2651 }
2652
2653 const auto &it = subs[this->state_subs_at_];
2655 resp.entity_id = StringRef(it.entity_id);
2656
2657 // Avoid string copy by using the const char* pointer if it exists
2658 resp.attribute = it.attribute != nullptr ? StringRef(it.attribute) : StringRef("");
2659
2660 resp.once = it.once;
2661 if (this->send_message(resp)) {
2662 this->state_subs_at_++;
2663 }
2664}
2665#endif // USE_API_HOMEASSISTANT_STATES
2666
2667void APIConnection::log_client_(int level, const LogString *message) {
2668 char peername[socket::SOCKADDR_STR_LEN];
2669 esp_log_printf_(level, TAG, __LINE__, ESPHOME_LOG_FORMAT("%s (%s): %s"), this->helper_->get_client_name(),
2670 this->helper_->get_peername_to(peername), LOG_STR_ARG(message));
2671}
2672
2673void APIConnection::log_warning_(const LogString *message, APIError err) {
2674 char peername[socket::SOCKADDR_STR_LEN];
2675 ESP_LOGW(TAG, "%s (%s): %s %s errno=%d", this->helper_->get_client_name(), this->helper_->get_peername_to(peername),
2676 LOG_STR_ARG(message), LOG_STR_ARG(api_error_to_logstr(err)), errno);
2677}
2678
2679} // namespace esphome::api
2680#endif
uint8_t status
Definition bl0942.h:8
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
const auto & get_areas()
static constexpr size_t BUILD_TIME_STR_SIZE
Size of buffer required for build time string (including null terminator)
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
void get_build_time_string(std::span< char, BUILD_TIME_STR_SIZE > buffer)
Copy the build time string into the provided buffer Buffer must be BUILD_TIME_STR_SIZE bytes (compile...
const char * get_area() const
Get the area of this Application set by pre_setup().
const auto & get_devices()
auto & get_serial_proxies() const
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.
void begin(bool include_internal=false)
ESPHOME_ALWAYS_INLINE void try_advance(size_t max_steps)
Run up to max_steps iteration steps; stops early when iteration completes or a callback refuses (that...
const char * get_device_class_to(std::span< char, MAX_DEVICE_CLASS_LENGTH > buffer) const
bool has_own_name() const
Definition entity_base.h:74
const StringRef & get_name() const
Definition entity_base.h:71
const char * get_icon_to(std::span< char, MAX_ICON_LENGTH > buffer) const
uint32_t get_object_id_hash() const
Definition entity_base.h:77
uint32_t get_device_id() const
bool is_disabled_by_default() const
EntityCategory get_entity_category() const
Fixed-capacity vector - sized once through init() or try_init(); push_back never reallocates This avo...
Definition helpers.h:558
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:685
void init(size_t n)
Definition helpers.h:648
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
constexpr const char * c_str() const
Definition string_ref.h:73
constexpr bool empty() const
Definition string_ref.h:76
constexpr size_type size() const
Definition string_ref.h:74
static constexpr StringRef from_lit(const CharT(&s)[N])
Definition string_ref.h:50
static StringRef from_maybe_nullptr(const char *s)
Definition string_ref.h:53
Byte buffer that skips zero-initialization on resize().
Definition api_buffer.h:26
size_t size() const
Definition api_buffer.h:55
bool resize(size_t n) ESPHOME_ALWAYS_INLINE
Returns false if allocation fails; the buffer is left unchanged. No zero-fill.
Definition api_buffer.h:33
void on_button_command_request(const ButtonCommandRequest &msg)
uint8_t *(*)(const void *, ProtoWriteBuffer &PROTO_ENCODE_DEBUG_PARAM) MessageEncodeFn
APIConnection(std::unique_ptr< socket::Socket > socket, APIServer *parent)
uint16_t(*)(EntityBase *, APIConnection *, uint32_t remaining_size) MessageCreatorPtr
uint32_t(*)(const void *) CalculateSizeFn
uint8_t get_consumed_header(uint8_t out[3]) const
noise::NoiseContext & get_noise_ctx()
Definition api_server.h:87
enums::AlarmControlPanelStateCommand command
Definition api_pb2.h:2742
enums::AlarmControlPanelState state
Definition api_pb2.h:2726
enums::BluetoothScannerMode mode
Definition api_pb2.h:2440
void set_data(const uint8_t *data, size_t len)
Definition api_pb2.h:1452
enums::ClimateSwingMode swing_mode
Definition api_pb2.h:1563
enums::ClimateFanMode fan_mode
Definition api_pb2.h:1561
enums::ClimatePreset preset
Definition api_pb2.h:1567
enums::ClimateFanMode fan_mode
Definition api_pb2.h:1530
enums::ClimateSwingMode swing_mode
Definition api_pb2.h:1531
enums::ClimateAction action
Definition api_pb2.h:1529
enums::ClimatePreset preset
Definition api_pb2.h:1533
enums::CoverOperation current_operation
Definition api_pb2.h:766
std::array< SerialProxyInfo, SERIAL_PROXY_COUNT > serial_proxies
Definition api_pb2.h:677
VoiceAssistantCapabilities voice_assistant
Definition api_pb2.h:671
ZWaveProxyCapabilities zwave_proxy
Definition api_pb2.h:674
BluetoothProxyCapabilities bluetooth_proxy
Definition api_pb2.h:668
std::array< AreaInfo, ESPHOME_AREA_COUNT > areas
Definition api_pb2.h:594
std::array< SerialProxyInfo, SERIAL_PROXY_COUNT > serial_proxies
Definition api_pb2.h:606
std::array< DeviceInfo, ESPHOME_DEVICE_COUNT > devices
Definition api_pb2.h:591
enums::DisconnectReason reason
Definition api_pb2.h:456
Fixed-size buffer for message dumps - avoids heap allocation.
Definition proto.h:543
enums::FanDirection direction
Definition api_pb2.h:849
enums::FanDirection direction
Definition api_pb2.h:826
ParsedTimezone parsed_timezone
Definition api_pb2.h:1305
enums::EntityCategory entity_category
Definition api_pb2.h:382
enums::ColorMode color_mode
Definition api_pb2.h:893
const std::vector< const char * > * supported_custom_presets
Definition api_pb2.h:1501
const climate::ClimateSwingModeMask * supported_swing_modes
Definition api_pb2.h:1498
enums::TemperatureUnit temperature_unit
Definition api_pb2.h:1508
const std::vector< const char * > * supported_custom_fan_modes
Definition api_pb2.h:1499
const climate::ClimatePresetMask * supported_presets
Definition api_pb2.h:1500
const climate::ClimateFanModeMask * supported_fan_modes
Definition api_pb2.h:1497
const climate::ClimateModeMask * supported_modes
Definition api_pb2.h:1492
const FixedVector< const char * > * event_types
Definition api_pb2.h:2926
const std::vector< const char * > * supported_preset_modes
Definition api_pb2.h:808
const FixedVector< const char * > * effects
Definition api_pb2.h:875
const light::ColorModeMask * supported_color_modes
Definition api_pb2.h:872
std::vector< MediaPlayerSupportedFormat > supported_formats
Definition api_pb2.h:1927
const FixedVector< const char * > * options
Definition api_pb2.h:1711
enums::SensorStateClass state_class
Definition api_pb2.h:966
const water_heater::WaterHeaterModeMask * supported_modes
Definition api_pb2.h:1593
enums::LockCommand command
Definition api_pb2.h:1858
enums::MediaPlayerCommand command
Definition api_pb2.h:1963
enums::MediaPlayerState state
Definition api_pb2.h:1944
enums::SerialProxyParity parity
Definition api_pb2.h:3272
enums::SerialProxyRequestType type
Definition api_pb2.h:3379
void set_message(const uint8_t *data, size_t len)
Definition api_pb2.h:1105
enums::UpdateCommand command
Definition api_pb2.h:3106
enums::ValveOperation current_operation
Definition api_pb2.h:2980
std::vector< VoiceAssistantWakeWord > available_wake_words
Definition api_pb2.h:2673
const std::vector< std::string > * active_wake_words
Definition api_pb2.h:2674
std::vector< std::string > active_wake_words
Definition api_pb2.h:2691
enums::ZWaveProxyRequestType type
Definition api_pb2.h:3142
enums::ZWaveProxyRequestType type
Definition api_pb2.h:3162
Base class for all binary_sensor-type classes.
void bluetooth_gatt_read(const api::BluetoothGATTReadRequest &msg)
void bluetooth_gatt_send_services(const api::BluetoothGATTGetServicesRequest &msg)
void get_bluetooth_mac_address_pretty(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > output)
void bluetooth_device_request(const api::BluetoothDeviceRequest &msg)
void bluetooth_gatt_write_descriptor(const api::BluetoothGATTWriteDescriptorRequest &msg)
void subscribe_api_connection(api::APIConnection *api_connection, uint32_t flags)
void unsubscribe_api_connection(api::APIConnection *api_connection)
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)
Base class for all buttons.
Definition button.h:25
Abstract camera base class.
Definition camera.h:115
virtual CameraImageReader * create_image_reader()=0
Returns a new camera image reader that keeps track of the JPEG data in the camera image.
virtual void start_stream(CameraRequester requester)=0
virtual void stop_stream(CameraRequester requester)=0
virtual void request_image(CameraRequester requester)=0
static Camera * instance()
The singleton instance of the camera implementation.
Definition camera.cpp:18
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:187
Base class for all cover devices.
Definition cover.h:110
uint8_t get_last_event_type_index() const
Return index of last triggered event type, or max uint8_t if no event triggered yet.
Definition event.h:53
Infrared - Base class for infrared remote control implementations.
Definition infrared.h:114
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition light_state.h:93
Base class for all locks.
Definition lock.h:112
static bool is_all_zeros(const psk_t &psk)
Definition noise.h:19
Base-class for all numbers.
Definition number.h:29
RadioFrequency - Base class for radio frequency implementations.
Base-class for all selects.
Definition select.h:29
Base-class for all sensors.
Definition sensor.h:47
Base class for all switches.
Definition switch.h:38
Base-class for all text inputs.
Definition text.h:21
Base class for all valve devices.
Definition valve.h:103
void on_timer_event(const api::VoiceAssistantTimerEventResponse &msg)
void on_audio(const api::VoiceAssistantAudio &msg)
void client_subscription(api::APIConnection *client, bool subscribe)
void on_event(const api::VoiceAssistantEventResponse &msg)
void on_announce(const api::VoiceAssistantAnnounceRequest &msg)
api::APIConnection * get_api_connection() const
void on_set_configuration(const std::vector< std::string > &active_wake_words)
uint32_t get_feature_flags() const
Definition zwave_proxy.h:67
void send_frame(api::APIConnection *api_connection, const uint8_t *data, size_t length)
void api_connection_authenticated(api::APIConnection *conn)
api::enums::ZWaveProxyStatus zwave_proxy_request(api::APIConnection *api_connection, api::enums::ZWaveProxyRequestType type)
const LogString * message
Definition component.cpp:35
uint16_t type
bool state
Definition fan.h:2
uint32_t socklen_t
Definition headers.h:99
const LogString * api_error_to_logstr(APIError err)
void log_dropped_message(const char *tag, int line, const LogString *what)
BluetoothProxy * global_bluetooth_proxy
@ CLIMATE_SUPPORTS_CURRENT_HUMIDITY
@ CLIMATE_SUPPORTS_TWO_POINT_TARGET_TEMPERATURE
@ CLIMATE_SUPPORTS_CURRENT_TEMPERATURE
@ CLIMATE_REQUIRES_TWO_POINT_TARGET_TEMPERATURE
ClimatePreset
Enum for all preset modes NOTE: If adding values, update ClimatePresetMask in climate_traits....
ClimateSwingMode
Enum for all modes a climate swing can be in NOTE: If adding values, update ClimateSwingModeMask in c...
ClimateMode
Enum for all modes a climate device can be in.
ClimateFanMode
NOTE: If adding values, update ClimateFanModeMask in climate_traits.h to use the new last value.
FanDirection
Simple enum to represent the direction of a fan.
Definition fan.h:20
HomeassistantTime * global_homeassistant_time
ColorMode
Color modes are a combination of color capabilities that can be used at the same time.
Definition color_mode.h:49
@ COLOR_TEMPERATURE
Color temperature can be controlled.
@ COLD_WARM_WHITE
Brightness of cold and warm white output can be controlled.
std::array< uint8_t, 32 > psk_t
Definition noise.h:11
ProvisioningManager * global_provisioning_manager
RadioFrequencyModulation
Modulation types supported by radio frequency implementations.
SerialProxyResult
Result of a client-initiated operation; mapped to api::enums::SerialProxyStatus by the API layer.
@ SERIAL_PROXY_RESULT_TIMEOUT
Timed out before TX completed.
@ SERIAL_PROXY_RESULT_ERROR
Driver or hardware error.
@ SERIAL_PROXY_RESULT_NOT_SUPPORTED
Requested feature is not available on this instance.
@ SERIAL_PROXY_RESULT_PORT_IN_USE
Denied: another live client holds the port.
@ SERIAL_PROXY_RESULT_OK
Operation completed or request accepted.
@ SERIAL_PROXY_RESULT_INVALID_ARGUMENT
A parameter value is out of range.
@ SERIAL_PROXY_RESULT_ASSUMED_SUCCESS
Platform cannot confirm TX drain; success assumed.
void set_global_tz(const ParsedTimezone &tz)
Set the global timezone used by epoch_to_local_tm() when called without a timezone.
Definition posix_tz.cpp:14
DSTRuleType
Type of DST transition rule.
Definition posix_tz.h:11
VoiceAssistant * global_voice_assistant
@ WATER_HEATER_STATE_ON
Water heater is on (not in standby)
@ WATER_HEATER_STATE_AWAY
Away/vacation mode is currently active.
ZWaveProxy * global_zwave_proxy
void HOT esp_log_printf_(int level, const char *tag, int line, const char *format,...)
Definition log.cpp:21
const void size_t len
Definition hal.h:64
std::vector< uint8_t > base64_decode(const std::string &encoded_string)
Decode a base64 string to a byte vector.
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
Definition helpers.cpp:87
void HOT delay(uint32_t ms)
Definition hal.cpp:85
Application App
Global storage of Application pointer - only one Application can exist.
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:1536
static void uint32_t
A more user-friendly version of struct tm from time.h.
Definition time.h:23
uint16_t day
Day of year (for JULIAN_NO_LEAP and DAY_OF_YEAR)
Definition posix_tz.h:21
DSTRuleType type
Type of rule.
Definition posix_tz.h:22
uint8_t week
Week 1-5, 5 = last (for MONTH_WEEK_DAY)
Definition posix_tz.h:24
int32_t time_seconds
Seconds after midnight (default 7200 = 2:00 AM)
Definition posix_tz.h:20
uint8_t day_of_week
Day 0-6, 0 = Sunday (for MONTH_WEEK_DAY)
Definition posix_tz.h:25
uint8_t month
Month 1-12 (for MONTH_WEEK_DAY)
Definition posix_tz.h:23
Parsed POSIX timezone information (packed for 32-bit: 32 bytes)
Definition posix_tz.h:29
DSTRule dst_end
When DST ends.
Definition posix_tz.h:33
DSTRule dst_start
When DST starts.
Definition posix_tz.h:32
int32_t dst_offset_seconds
DST offset from UTC in seconds.
Definition posix_tz.h:31
int32_t std_offset_seconds
Standard time offset from UTC in seconds (positive = west)
Definition posix_tz.h:30
uint32_t payload_size()
SemaphoreHandle_t lock
const uint8_t ESPHOME_WEBSERVER_INDEX_HTML[] PROGMEM
Definition web_server.h:28