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