ESPHome 2025.12.0-dev
Loading...
Searching...
No Matches
api_connection.h
Go to the documentation of this file.
1#pragma once
2
4#ifdef USE_API
5#include "api_frame_helper.h"
6#include "api_pb2.h"
7#include "api_pb2_service.h"
8#include "api_server.h"
12
13#include <functional>
14#include <vector>
15
16namespace esphome::api {
17
18// Client information structure
19struct ClientInfo {
20 std::string name; // Client name from Hello message
21 std::string peername; // IP:port from socket
22};
23
24// Keepalive timeout in milliseconds
25static constexpr uint32_t KEEPALIVE_TIMEOUT_MS = 60000;
26// Maximum number of entities to process in a single batch during initial state/info sending
27// This was increased from 20 to 24 after removing the unique_id field from entity info messages,
28// which reduced message sizes allowing more entities per batch without exceeding packet limits
29static constexpr size_t MAX_INITIAL_PER_BATCH = 24;
30// Maximum number of packets to process in a single batch (platform-dependent)
31// This limit exists to prevent stack overflow from the PacketInfo array in process_batch_
32// Each PacketInfo is 8 bytes, so 64 * 8 = 512 bytes, 32 * 8 = 256 bytes
33#if defined(USE_ESP32) || defined(USE_HOST)
34static constexpr size_t MAX_PACKETS_PER_BATCH = 64; // ESP32 has 8KB+ stack, HOST has plenty
35#else
36static constexpr size_t MAX_PACKETS_PER_BATCH = 32; // ESP8266/RP2040/etc have smaller stacks
37#endif
38
39class APIConnection final : public APIServerConnection {
40 public:
41 friend class APIServer;
43 APIConnection(std::unique_ptr<socket::Socket> socket, APIServer *parent);
44 virtual ~APIConnection();
45
46 void start();
47 void loop();
48
53#ifdef USE_BINARY_SENSOR
55#endif
56#ifdef USE_COVER
57 bool send_cover_state(cover::Cover *cover);
58 void cover_command(const CoverCommandRequest &msg) override;
59#endif
60#ifdef USE_FAN
61 bool send_fan_state(fan::Fan *fan);
62 void fan_command(const FanCommandRequest &msg) override;
63#endif
64#ifdef USE_LIGHT
66 void light_command(const LightCommandRequest &msg) override;
67#endif
68#ifdef USE_SENSOR
70#endif
71#ifdef USE_SWITCH
72 bool send_switch_state(switch_::Switch *a_switch);
73 void switch_command(const SwitchCommandRequest &msg) override;
74#endif
75#ifdef USE_TEXT_SENSOR
77#endif
78#ifdef USE_CAMERA
79 void set_camera_state(std::shared_ptr<camera::CameraImage> image);
80 void camera_image(const CameraImageRequest &msg) override;
81#endif
82#ifdef USE_CLIMATE
84 void climate_command(const ClimateCommandRequest &msg) override;
85#endif
86#ifdef USE_NUMBER
88 void number_command(const NumberCommandRequest &msg) override;
89#endif
90#ifdef USE_DATETIME_DATE
92 void date_command(const DateCommandRequest &msg) override;
93#endif
94#ifdef USE_DATETIME_TIME
96 void time_command(const TimeCommandRequest &msg) override;
97#endif
98#ifdef USE_DATETIME_DATETIME
100 void datetime_command(const DateTimeCommandRequest &msg) override;
101#endif
102#ifdef USE_TEXT
103 bool send_text_state(text::Text *text);
104 void text_command(const TextCommandRequest &msg) override;
105#endif
106#ifdef USE_SELECT
107 bool send_select_state(select::Select *select);
108 void select_command(const SelectCommandRequest &msg) override;
109#endif
110#ifdef USE_BUTTON
111 void button_command(const ButtonCommandRequest &msg) override;
112#endif
113#ifdef USE_LOCK
114 bool send_lock_state(lock::Lock *a_lock);
115 void lock_command(const LockCommandRequest &msg) override;
116#endif
117#ifdef USE_VALVE
118 bool send_valve_state(valve::Valve *valve);
119 void valve_command(const ValveCommandRequest &msg) override;
120#endif
121#ifdef USE_MEDIA_PLAYER
123 void media_player_command(const MediaPlayerCommandRequest &msg) override;
124#endif
125 bool try_send_log_message(int level, const char *tag, const char *line, size_t message_len);
126#ifdef USE_API_HOMEASSISTANT_SERVICES
132#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
134#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
135#endif // USE_API_HOMEASSISTANT_SERVICES
136#ifdef USE_BLUETOOTH_PROXY
139
140 void bluetooth_device_request(const BluetoothDeviceRequest &msg) override;
141 void bluetooth_gatt_read(const BluetoothGATTReadRequest &msg) override;
142 void bluetooth_gatt_write(const BluetoothGATTWriteRequest &msg) override;
146 void bluetooth_gatt_notify(const BluetoothGATTNotifyRequest &msg) override;
149
150#endif
151#ifdef USE_HOMEASSISTANT_TIME
156#endif
157
158#ifdef USE_VOICE_ASSISTANT
160 void on_voice_assistant_response(const VoiceAssistantResponse &msg) override;
162 void on_voice_assistant_audio(const VoiceAssistantAudio &msg) override;
167#endif
168
169#ifdef USE_ZWAVE_PROXY
170 void zwave_proxy_frame(const ZWaveProxyFrame &msg) override;
171 void zwave_proxy_request(const ZWaveProxyRequest &msg) override;
172#endif
173
174#ifdef USE_ALARM_CONTROL_PANEL
177#endif
178
179#ifdef USE_EVENT
180 void send_event(event::Event *event, const char *event_type);
181#endif
182
183#ifdef USE_UPDATE
185 void update_command(const UpdateCommandRequest &msg) override;
186#endif
187
188 void on_disconnect_response(const DisconnectResponse &value) override;
189 void on_ping_response(const PingResponse &value) override {
190 // we initiated ping
191 this->flags_.sent_ping = false;
192 }
193#ifdef USE_API_HOMEASSISTANT_STATES
195#endif
196#ifdef USE_HOMEASSISTANT_TIME
197 void on_get_time_response(const GetTimeResponse &value) override;
198#endif
199 bool send_hello_response(const HelloRequest &msg) override;
200#ifdef USE_API_PASSWORD
201 bool send_authenticate_response(const AuthenticationRequest &msg) override;
202#endif
203 bool send_disconnect_response(const DisconnectRequest &msg) override;
204 bool send_ping_response(const PingRequest &msg) override;
205 bool send_device_info_response(const DeviceInfoRequest &msg) override;
206 void list_entities(const ListEntitiesRequest &msg) override { this->list_entities_iterator_.begin(); }
207 void subscribe_states(const SubscribeStatesRequest &msg) override {
208 this->flags_.state_subscription = true;
210 }
211 void subscribe_logs(const SubscribeLogsRequest &msg) override {
212 this->flags_.log_subscription = msg.level;
213 if (msg.dump_config)
215 }
216#ifdef USE_API_HOMEASSISTANT_SERVICES
220#endif
221#ifdef USE_API_HOMEASSISTANT_STATES
223#endif
224#ifdef USE_API_SERVICES
225 void execute_service(const ExecuteServiceRequest &msg) override;
226#endif
227#ifdef USE_API_NOISE
229#endif
230
231 bool is_authenticated() override {
233 }
234 bool is_connection_setup() override {
236 this->is_authenticated();
237 }
238 uint8_t get_log_subscription_level() const { return this->flags_.log_subscription; }
239
240 // Get client API version for feature detection
241 bool client_supports_api_version(uint16_t major, uint16_t minor) const {
242 return this->client_api_version_major_ > major ||
243 (this->client_api_version_major_ == major && this->client_api_version_minor_ >= minor);
244 }
245
246 void on_fatal_error() override;
247#ifdef USE_API_PASSWORD
248 void on_unauthenticated_access() override;
249#endif
250 void on_no_setup_connection() override;
251 ProtoWriteBuffer create_buffer(uint32_t reserve_size) override {
252 // FIXME: ensure no recursive writes can happen
253
254 // Get header padding size - used for both reserve and insert
255 uint8_t header_padding = this->helper_->frame_header_padding();
256 // Get shared buffer from parent server
257 std::vector<uint8_t> &shared_buf = this->parent_->get_shared_buffer_ref();
258 this->prepare_first_message_buffer(shared_buf, header_padding,
259 reserve_size + header_padding + this->helper_->frame_footer_size());
260 return {&shared_buf};
261 }
262
263 void prepare_first_message_buffer(std::vector<uint8_t> &shared_buf, size_t header_padding, size_t total_size) {
264 shared_buf.clear();
265 // Reserve space for header padding + message + footer
266 // - Header padding: space for protocol headers (7 bytes for Noise, 6 for Plaintext)
267 // - Footer: space for MAC (16 bytes for Noise, 0 for Plaintext)
268 shared_buf.reserve(total_size);
269 // Resize to add header padding so message encoding starts at the correct position
270 shared_buf.resize(header_padding);
271 }
272
273 bool try_to_clear_buffer(bool log_out_of_space);
274 bool send_buffer(ProtoWriteBuffer buffer, uint8_t message_type) override;
275
276 const std::string &get_name() const { return this->client_info_.name; }
277 const std::string &get_peername() const { return this->client_info_.peername; }
278
279 protected:
280 // Helper function to handle authentication completion
282
283#ifdef USE_API_HOMEASSISTANT_STATES
285#endif
286
287 // Non-template helper to encode any ProtoMessage
288 static uint16_t encode_message_to_buffer(ProtoMessage &msg, uint8_t message_type, APIConnection *conn,
289 uint32_t remaining_size, bool is_single);
290
291 // Helper to fill entity state base and encode message
292 static uint16_t fill_and_encode_entity_state(EntityBase *entity, StateResponseProtoMessage &msg, uint8_t message_type,
293 APIConnection *conn, uint32_t remaining_size, bool is_single) {
294 msg.key = entity->get_object_id_hash();
295#ifdef USE_DEVICES
296 msg.device_id = entity->get_device_id();
297#endif
298 return encode_message_to_buffer(msg, message_type, conn, remaining_size, is_single);
299 }
300
301 // Helper to fill entity info base and encode message
302 static uint16_t fill_and_encode_entity_info(EntityBase *entity, InfoResponseProtoMessage &msg, uint8_t message_type,
303 APIConnection *conn, uint32_t remaining_size, bool is_single) {
304 // Set common fields that are shared by all entity types
305 msg.key = entity->get_object_id_hash();
306 // Try to use static reference first to avoid allocation
307 StringRef static_ref = entity->get_object_id_ref_for_api_();
308 // Store dynamic string outside the if-else to maintain lifetime
309 std::string object_id;
310 if (!static_ref.empty()) {
311 msg.set_object_id(static_ref);
312 } else {
313 // Dynamic case - need to allocate
314 object_id = entity->get_object_id();
315 msg.set_object_id(StringRef(object_id));
316 }
317
318 if (entity->has_own_name()) {
319 msg.set_name(entity->get_name());
320 }
321
322 // Set common EntityBase properties
323#ifdef USE_ENTITY_ICON
324 msg.set_icon(entity->get_icon_ref());
325#endif
327 msg.entity_category = static_cast<enums::EntityCategory>(entity->get_entity_category());
328#ifdef USE_DEVICES
329 msg.device_id = entity->get_device_id();
330#endif
331 return encode_message_to_buffer(msg, message_type, conn, remaining_size, is_single);
332 }
333
334#ifdef USE_VOICE_ASSISTANT
335 // Helper to check voice assistant validity and connection ownership
336 inline bool check_voice_assistant_api_connection_() const;
337#endif
338
339 // Helper method to process multiple entities from an iterator in a batch
340 template<typename Iterator> void process_iterator_batch_(Iterator &iterator) {
341 size_t initial_size = this->deferred_batch_.size();
342 while (!iterator.completed() && (this->deferred_batch_.size() - initial_size) < MAX_INITIAL_PER_BATCH) {
343 iterator.advance();
344 }
345
346 // If the batch is full, process it immediately
347 // Note: iterator.advance() already calls schedule_batch_() via schedule_message_()
348 if (this->deferred_batch_.size() >= MAX_INITIAL_PER_BATCH) {
349 this->process_batch_();
350 }
351 }
352
353#ifdef USE_BINARY_SENSOR
354 static uint16_t try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
355 bool is_single);
356 static uint16_t try_send_binary_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
357 bool is_single);
358#endif
359#ifdef USE_COVER
360 static uint16_t try_send_cover_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
361 bool is_single);
362 static uint16_t try_send_cover_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
363#endif
364#ifdef USE_FAN
365 static uint16_t try_send_fan_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
366 static uint16_t try_send_fan_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
367#endif
368#ifdef USE_LIGHT
369 static uint16_t try_send_light_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
370 bool is_single);
371 static uint16_t try_send_light_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
372#endif
373#ifdef USE_SENSOR
374 static uint16_t try_send_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
375 bool is_single);
376 static uint16_t try_send_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
377 bool is_single);
378#endif
379#ifdef USE_SWITCH
380 static uint16_t try_send_switch_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
381 bool is_single);
382 static uint16_t try_send_switch_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
383 bool is_single);
384#endif
385#ifdef USE_TEXT_SENSOR
386 static uint16_t try_send_text_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
387 bool is_single);
388 static uint16_t try_send_text_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
389 bool is_single);
390#endif
391#ifdef USE_CLIMATE
392 static uint16_t try_send_climate_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
393 bool is_single);
394 static uint16_t try_send_climate_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
395 bool is_single);
396#endif
397#ifdef USE_NUMBER
398 static uint16_t try_send_number_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
399 bool is_single);
400 static uint16_t try_send_number_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
401 bool is_single);
402#endif
403#ifdef USE_DATETIME_DATE
404 static uint16_t try_send_date_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
405 static uint16_t try_send_date_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
406#endif
407#ifdef USE_DATETIME_TIME
408 static uint16_t try_send_time_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
409 static uint16_t try_send_time_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
410#endif
411#ifdef USE_DATETIME_DATETIME
412 static uint16_t try_send_datetime_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
413 bool is_single);
414 static uint16_t try_send_datetime_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
415 bool is_single);
416#endif
417#ifdef USE_TEXT
418 static uint16_t try_send_text_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
419 static uint16_t try_send_text_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
420#endif
421#ifdef USE_SELECT
422 static uint16_t try_send_select_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
423 bool is_single);
424 static uint16_t try_send_select_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
425 bool is_single);
426#endif
427#ifdef USE_BUTTON
428 static uint16_t try_send_button_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
429 bool is_single);
430#endif
431#ifdef USE_LOCK
432 static uint16_t try_send_lock_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
433 static uint16_t try_send_lock_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
434#endif
435#ifdef USE_VALVE
436 static uint16_t try_send_valve_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
437 bool is_single);
438 static uint16_t try_send_valve_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
439#endif
440#ifdef USE_MEDIA_PLAYER
441 static uint16_t try_send_media_player_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
442 bool is_single);
443 static uint16_t try_send_media_player_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
444 bool is_single);
445#endif
446#ifdef USE_ALARM_CONTROL_PANEL
447 static uint16_t try_send_alarm_control_panel_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
448 bool is_single);
449 static uint16_t try_send_alarm_control_panel_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
450 bool is_single);
451#endif
452#ifdef USE_EVENT
453 static uint16_t try_send_event_response(event::Event *event, const char *event_type, APIConnection *conn,
454 uint32_t remaining_size, bool is_single);
455 static uint16_t try_send_event_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
456#endif
457#ifdef USE_UPDATE
458 static uint16_t try_send_update_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
459 bool is_single);
460 static uint16_t try_send_update_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
461 bool is_single);
462#endif
463#ifdef USE_CAMERA
464 static uint16_t try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
465 bool is_single);
466#endif
467
468 // Method for ListEntitiesDone batching
469 static uint16_t try_send_list_info_done(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
470 bool is_single);
471
472 // Method for DisconnectRequest batching
473 static uint16_t try_send_disconnect_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
474 bool is_single);
475
476 // Batch message method for ping requests
477 static uint16_t try_send_ping_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
478 bool is_single);
479
480 // === Optimal member ordering for 32-bit systems ===
481
482 // Group 1: Pointers (4 bytes each on 32-bit)
483 std::unique_ptr<APIFrameHelper> helper_;
485
486 // Group 2: Larger objects (must be 4-byte aligned)
487 // These contain vectors/pointers internally, so putting them early ensures good alignment
490#ifdef USE_CAMERA
491 std::unique_ptr<camera::CameraImageReader> image_reader_;
492#endif
493
494 // Group 3: Client info struct (24 bytes on 32-bit: 2 strings × 12 bytes each)
496
497 // Group 4: 4-byte types
499#ifdef USE_API_HOMEASSISTANT_STATES
501#endif
502
503 // Function pointer type for message encoding
504 using MessageCreatorPtr = uint16_t (*)(EntityBase *, APIConnection *, uint32_t remaining_size, bool is_single);
505
507 public:
508 // Constructor for function pointer
509 MessageCreator(MessageCreatorPtr ptr) { data_.function_ptr = ptr; }
510
511 // Constructor for const char * (Event types - no allocation needed)
512 explicit MessageCreator(const char *str_value) { data_.const_char_ptr = str_value; }
513
514 // Delete copy operations - MessageCreator should only be moved
515 MessageCreator(const MessageCreator &other) = delete;
516 MessageCreator &operator=(const MessageCreator &other) = delete;
517
518 // Move constructor
519 MessageCreator(MessageCreator &&other) noexcept : data_(other.data_) { other.data_.function_ptr = nullptr; }
520
521 // Move assignment
523 if (this != &other) {
524 data_ = other.data_;
525 other.data_.function_ptr = nullptr;
526 }
527 return *this;
528 }
529
530 // Call operator - uses message_type to determine union type
531 uint16_t operator()(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single,
532 uint8_t message_type) const;
533
534 private:
535 union Data {
536 MessageCreatorPtr function_ptr;
537 const char *const_char_ptr;
538 } data_; // 4 bytes on 32-bit, 8 bytes on 64-bit - same as before
539 };
540
541 // Generic batching mechanism for both state updates and entity info
543 struct BatchItem {
544 EntityBase *entity; // Entity pointer
545 MessageCreator creator; // Function that creates the message when needed
546 uint8_t message_type; // Message type for overhead calculation (max 255)
547 uint8_t estimated_size; // Estimated message size (max 255 bytes)
548
549 // Constructor for creating BatchItem
552 };
553
554 std::vector<BatchItem> items;
555 uint32_t batch_start_time{0};
556
558 // Pre-allocate capacity for typical batch sizes to avoid reallocation
559 items.reserve(8);
560 }
561
562 // Add item to the batch
563 void add_item(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size);
564 // Add item to the front of the batch (for high priority messages like ping)
565 void add_item_front(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size);
566
567 // Clear all items
568 void clear() {
569 items.clear();
571 }
572
573 // Remove processed items from the front
574 void remove_front(size_t count) { items.erase(items.begin(), items.begin() + count); }
575
576 bool empty() const { return items.empty(); }
577 size_t size() const { return items.size(); }
578 const BatchItem &operator[](size_t index) const { return items[index]; }
579 };
580
581 // DeferredBatch here (16 bytes, 4-byte aligned)
583
584 // ConnectionState enum for type safety
585 enum class ConnectionState : uint8_t {
587 CONNECTED = 1,
588 AUTHENTICATED = 2,
589 };
590
591 // Group 5: Pack all small members together to minimize padding
592 // This group starts at a 4-byte boundary after DeferredBatch
593 struct APIFlags {
594 // Connection state only needs 2 bits (3 states)
595 uint8_t connection_state : 2;
596 // Log subscription needs 3 bits (log levels 0-7)
597 uint8_t log_subscription : 3;
598 // Boolean flags (1 bit each)
599 uint8_t remove : 1;
601 uint8_t sent_ping : 1;
602
604 uint8_t next_close : 1;
605 uint8_t batch_scheduled : 1;
606 uint8_t batch_first_message : 1; // For batch buffer allocation
607 uint8_t should_try_send_immediately : 1; // True after initial states are sent
608#ifdef HAS_PROTO_MESSAGE_DUMP
609 uint8_t log_only_mode : 1;
610#endif
611 } flags_{}; // 2 bytes total
612
613 // 2-byte types immediately after flags_ (no padding between them)
616 // Total: 2 (flags) + 2 + 2 = 6 bytes, then 2 bytes padding to next 4-byte boundary
617
618 uint32_t get_batch_delay_ms_() const;
619 // Message will use 8 more bytes than the minimum size, and typical
620 // MTU is 1500. Sometimes users will see as low as 1460 MTU.
621 // If its IPv6 the header is 40 bytes, and if its IPv4
622 // the header is 20 bytes. So we have 1460 - 40 = 1420 bytes
623 // available for the payload. But we also need to add the size of
624 // the protobuf overhead, which is 8 bytes.
625 //
626 // To be safe we pick 1390 bytes as the maximum size
627 // to send in one go. This is the maximum size of a single packet
628 // that can be sent over the network.
629 // This is to avoid fragmentation of the packet.
630 static constexpr size_t MAX_BATCH_PACKET_SIZE = 1390; // MTU
631
632 bool schedule_batch_();
633 void process_batch_();
635 this->deferred_batch_.clear();
636 this->flags_.batch_scheduled = false;
637 }
638
639#ifdef HAS_PROTO_MESSAGE_DUMP
640 // Helper to log a proto message from a MessageCreator object
641 void log_proto_message_(EntityBase *entity, const MessageCreator &creator, uint8_t message_type) {
642 this->flags_.log_only_mode = true;
643 creator(entity, this, MAX_BATCH_PACKET_SIZE, true, message_type);
644 this->flags_.log_only_mode = false;
645 }
646
648 // Use the helper to log the message
649 this->log_proto_message_(item.entity, item.creator, item.message_type);
650 }
651#endif
652
653 // Helper to check if a message type should bypass batching
654 // Returns true if:
655 // 1. It's an UpdateStateResponse (always send immediately to handle cases where
656 // the main loop is blocked, e.g., during OTA updates)
657 // 2. It's an EventResponse (events are edge-triggered - every occurrence matters)
658 // 3. OR: User has opted into immediate sending (should_try_send_immediately = true
659 // AND batch_delay = 0)
660 inline bool should_send_immediately_(uint8_t message_type) const {
661 return (
662#ifdef USE_UPDATE
663 message_type == UpdateStateResponse::MESSAGE_TYPE ||
664#endif
665#ifdef USE_EVENT
666 message_type == EventResponse::MESSAGE_TYPE ||
667#endif
668 (this->flags_.should_try_send_immediately && this->get_batch_delay_ms_() == 0));
669 }
670
671 // Helper method to send a message either immediately or via batching
672 // Tries immediate send if should_send_immediately_() returns true and buffer has space
673 // Falls back to batching if immediate send fails or isn't applicable
674 bool send_message_smart_(EntityBase *entity, MessageCreatorPtr creator, uint8_t message_type,
675 uint8_t estimated_size) {
676 if (this->should_send_immediately_(message_type) && this->helper_->can_write_without_blocking()) {
677 // Now actually encode and send
678 if (creator(entity, this, MAX_BATCH_PACKET_SIZE, true) &&
679 this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, message_type)) {
680#ifdef HAS_PROTO_MESSAGE_DUMP
681 // Log the message in verbose mode
682 this->log_proto_message_(entity, MessageCreator(creator), message_type);
683#endif
684 return true;
685 }
686
687 // If immediate send failed, fall through to batching
688 }
689
690 // Fall back to scheduled batching
691 return this->schedule_message_(entity, creator, message_type, estimated_size);
692 }
693
694 // Overload for MessageCreator (used by events which need to capture event_type)
695 bool send_message_smart_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size) {
696 // Try to send immediately if message type should bypass batching and buffer has space
697 if (this->should_send_immediately_(message_type) && this->helper_->can_write_without_blocking()) {
698 // Now actually encode and send
699 if (creator(entity, this, MAX_BATCH_PACKET_SIZE, true, message_type) &&
700 this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, message_type)) {
701#ifdef HAS_PROTO_MESSAGE_DUMP
702 // Log the message in verbose mode
703 this->log_proto_message_(entity, creator, message_type);
704#endif
705 return true;
706 }
707
708 // If immediate send failed, fall through to batching
709 }
710
711 // Fall back to scheduled batching
712 return this->schedule_message_(entity, std::move(creator), message_type, estimated_size);
713 }
714
715 // Helper function to schedule a deferred message with known message type
716 bool schedule_message_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size) {
717 this->deferred_batch_.add_item(entity, std::move(creator), message_type, estimated_size);
718 return this->schedule_batch_();
719 }
720
721 // Overload for function pointers (for info messages and current state reads)
722 bool schedule_message_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type,
723 uint8_t estimated_size) {
724 return schedule_message_(entity, MessageCreator(function_ptr), message_type, estimated_size);
725 }
726
727 // Helper function to schedule a high priority message at the front of the batch
728 bool schedule_message_front_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type,
729 uint8_t estimated_size) {
730 this->deferred_batch_.add_item_front(entity, MessageCreator(function_ptr), message_type, estimated_size);
731 return this->schedule_batch_();
732 }
733
734 // Helper function to log API errors with errno
735 void log_warning_(const LogString *message, APIError err);
736 // Helper to handle fatal errors with logging
737 inline void fatal_error_with_log_(const LogString *message, APIError err) {
738 this->on_fatal_error();
739 this->log_warning_(message, err);
740 }
741};
742
743} // namespace esphome::api
744#endif
void begin(bool include_internal=false)
bool has_own_name() const
Definition entity_base.h:38
uint32_t get_object_id_hash()
const StringRef & get_name() const
StringRef get_icon_ref() const
Definition entity_base.h:69
uint32_t get_device_id() const
Definition entity_base.h:80
bool is_disabled_by_default() const
Definition entity_base.h:54
std::string get_object_id() const
EntityCategory get_entity_category() const
Definition entity_base.h:58
StringRef get_object_id_ref_for_api_() const
StringRef is a reference to a string owned by something else.
Definition string_ref.h:22
constexpr bool empty() const
Definition string_ref.h:71
MessageCreator(MessageCreator &&other) noexcept
uint16_t operator()(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single, uint8_t message_type) const
MessageCreator(const MessageCreator &other)=delete
MessageCreator & operator=(const MessageCreator &other)=delete
MessageCreator & operator=(MessageCreator &&other) noexcept
static uint16_t try_send_binary_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_climate_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_authenticate_response(const AuthenticationRequest &msg) override
struct esphome::api::APIConnection::APIFlags flags_
bool send_ping_response(const PingRequest &msg) override
bool send_message_smart_(EntityBase *entity, MessageCreatorPtr creator, uint8_t message_type, uint8_t estimated_size)
void subscribe_voice_assistant(const SubscribeVoiceAssistantRequest &msg) override
static uint16_t try_send_switch_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void select_command(const SelectCommandRequest &msg) override
static uint16_t try_send_event_response(event::Event *event, const char *event_type, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t encode_message_to_buffer(ProtoMessage &msg, uint8_t message_type, APIConnection *conn, uint32_t remaining_size, bool is_single)
void bluetooth_gatt_write(const BluetoothGATTWriteRequest &msg) override
static uint16_t try_send_text_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_fan_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_media_player_state(media_player::MediaPlayer *media_player)
void zwave_proxy_frame(const ZWaveProxyFrame &msg) override
static uint16_t try_send_datetime_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_time_state(datetime::TimeEntity *time)
static uint16_t try_send_date_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void time_command(const TimeCommandRequest &msg) override
static uint16_t try_send_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void update_command(const UpdateCommandRequest &msg) override
void on_ping_response(const PingResponse &value) override
static uint16_t try_send_lock_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void on_voice_assistant_announce_request(const VoiceAssistantAnnounceRequest &msg) override
void prepare_first_message_buffer(std::vector< uint8_t > &shared_buf, size_t header_padding, size_t total_size)
bool send_subscribe_bluetooth_connections_free_response(const SubscribeBluetoothConnectionsFreeRequest &msg) override
ProtoWriteBuffer create_buffer(uint32_t reserve_size) override
static uint16_t try_send_lock_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_time_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_text_sensor_state(text_sensor::TextSensor *text_sensor)
bool send_fan_state(fan::Fan *fan)
static uint16_t try_send_switch_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void bluetooth_scanner_set_mode(const BluetoothScannerSetModeRequest &msg) override
static uint16_t try_send_media_player_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void on_voice_assistant_response(const VoiceAssistantResponse &msg) override
void zwave_proxy_request(const ZWaveProxyRequest &msg) override
bool check_voice_assistant_api_connection_() const
void log_proto_message_(EntityBase *entity, const MessageCreator &creator, uint8_t message_type)
static uint16_t try_send_number_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
InitialStateIterator initial_state_iterator_
void subscribe_logs(const SubscribeLogsRequest &msg) override
std::unique_ptr< APIFrameHelper > helper_
void date_command(const DateCommandRequest &msg) override
bool schedule_message_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type, uint8_t estimated_size)
void set_camera_state(std::shared_ptr< camera::CameraImage > image)
const std::string & get_peername() const
static uint16_t try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
uint32_t get_batch_delay_ms_() const
bool send_sensor_state(sensor::Sensor *sensor)
static constexpr size_t MAX_BATCH_PACKET_SIZE
void log_batch_item_(const DeferredBatch::BatchItem &item)
void on_homeassistant_action_response(const HomeassistantActionResponse &msg) override
void datetime_command(const DateTimeCommandRequest &msg) override
uint16_t(*)(EntityBase *, APIConnection *, uint32_t remaining_size, bool is_single) MessageCreatorPtr
void voice_assistant_set_configuration(const VoiceAssistantSetConfiguration &msg) override
bool send_binary_sensor_state(binary_sensor::BinarySensor *binary_sensor)
void process_iterator_batch_(Iterator &iterator)
static uint16_t try_send_climate_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_valve_state(valve::Valve *valve)
static uint16_t try_send_light_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_select_state(select::Select *select)
void send_event(event::Event *event, const char *event_type)
bool send_switch_state(switch_::Switch *a_switch)
void bluetooth_gatt_write_descriptor(const BluetoothGATTWriteDescriptorRequest &msg) override
void bluetooth_gatt_read(const BluetoothGATTReadRequest &msg) override
static uint16_t try_send_ping_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void text_command(const TextCommandRequest &msg) override
bool should_send_immediately_(uint8_t message_type) const
bool send_lock_state(lock::Lock *a_lock)
bool send_hello_response(const HelloRequest &msg) override
static uint16_t try_send_button_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_time_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_text_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_datetime_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_list_info_done(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_valve_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_media_player_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_update_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_update_state(update::UpdateEntity *update)
void on_voice_assistant_audio(const VoiceAssistantAudio &msg) override
static uint16_t fill_and_encode_entity_state(EntityBase *entity, StateResponseProtoMessage &msg, uint8_t message_type, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool schedule_message_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size)
static uint16_t try_send_light_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void alarm_control_panel_command(const AlarmControlPanelCommandRequest &msg) override
static uint16_t fill_and_encode_entity_info(EntityBase *entity, InfoResponseProtoMessage &msg, uint8_t message_type, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_fan_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_device_info_response(const DeviceInfoRequest &msg) override
bool schedule_message_front_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type, uint8_t estimated_size)
void unsubscribe_bluetooth_le_advertisements(const UnsubscribeBluetoothLEAdvertisementsRequest &msg) override
void fatal_error_with_log_(const LogString *message, APIError err)
void number_command(const NumberCommandRequest &msg) override
const std::string & get_name() const
void log_warning_(const LogString *message, APIError err)
void list_entities(const ListEntitiesRequest &msg) override
std::unique_ptr< camera::CameraImageReader > image_reader_
void media_player_command(const MediaPlayerCommandRequest &msg) override
void bluetooth_gatt_notify(const BluetoothGATTNotifyRequest &msg) override
void subscribe_homeassistant_services(const SubscribeHomeassistantServicesRequest &msg) override
APIConnection(std::unique_ptr< socket::Socket > socket, APIServer *parent)
void subscribe_states(const SubscribeStatesRequest &msg) override
void subscribe_bluetooth_le_advertisements(const SubscribeBluetoothLEAdvertisementsRequest &msg) override
bool send_date_state(datetime::DateEntity *date)
static uint16_t try_send_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_update_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void bluetooth_gatt_read_descriptor(const BluetoothGATTReadDescriptorRequest &msg) override
void climate_command(const ClimateCommandRequest &msg) override
static uint16_t try_send_valve_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void bluetooth_gatt_get_services(const BluetoothGATTGetServicesRequest &msg) override
bool is_connection_setup() override
bool send_number_state(number::Number *number)
void on_voice_assistant_timer_event_response(const VoiceAssistantTimerEventResponse &msg) override
void fan_command(const FanCommandRequest &msg) override
void on_voice_assistant_event_response(const VoiceAssistantEventResponse &msg) override
static uint16_t try_send_select_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_noise_encryption_set_key_response(const NoiseEncryptionSetKeyRequest &msg) override
void send_homeassistant_action(const HomeassistantActionRequest &call)
bool send_light_state(light::LightState *light)
bool send_voice_assistant_get_configuration_response(const VoiceAssistantConfigurationRequest &msg) override
void valve_command(const ValveCommandRequest &msg) override
void on_home_assistant_state_response(const HomeAssistantStateResponse &msg) override
void cover_command(const CoverCommandRequest &msg) override
uint8_t get_log_subscription_level() const
void on_get_time_response(const GetTimeResponse &value) override
static uint16_t try_send_select_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void subscribe_home_assistant_states(const SubscribeHomeAssistantStatesRequest &msg) override
void on_disconnect_response(const DisconnectResponse &value) override
bool send_datetime_state(datetime::DateTimeEntity *datetime)
ListEntitiesIterator list_entities_iterator_
static uint16_t try_send_alarm_control_panel_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_text_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_disconnect_response(const DisconnectRequest &msg) override
bool send_alarm_control_panel_state(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel)
static uint16_t try_send_text_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void camera_image(const CameraImageRequest &msg) override
void light_command(const LightCommandRequest &msg) override
bool send_text_state(text::Text *text)
void switch_command(const SwitchCommandRequest &msg) override
static uint16_t try_send_cover_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool send_message_smart_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size)
static uint16_t try_send_date_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool try_send_log_message(int level, const char *tag, const char *line, size_t message_len)
static uint16_t try_send_disconnect_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_number_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
bool client_supports_api_version(uint16_t major, uint16_t minor) const
void lock_command(const LockCommandRequest &msg) override
void bluetooth_device_request(const BluetoothDeviceRequest &msg) override
bool send_buffer(ProtoWriteBuffer buffer, uint8_t message_type) override
void execute_service(const ExecuteServiceRequest &msg) override
bool send_climate_state(climate::Climate *climate)
bool try_to_clear_buffer(bool log_out_of_space)
bool send_cover_state(cover::Cover *cover)
void button_command(const ButtonCommandRequest &msg) override
static uint16_t try_send_alarm_control_panel_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_cover_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
static uint16_t try_send_event_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void on_unauthenticated_access() override
bool send_message(const ProtoMessage &msg, uint8_t message_type)
std::vector< uint8_t > & get_shared_buffer_ref()
Definition api_server.h:52
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:2802
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:1213
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:1106
void set_object_id(const StringRef &ref)
Definition api_pb2.h:293
enums::EntityCategory entity_category
Definition api_pb2.h:302
void set_icon(const StringRef &ref)
Definition api_pb2.h:300
void set_name(const StringRef &ref)
Definition api_pb2.h:296
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:594
static constexpr uint8_t ESTIMATED_SIZE
Definition api_pb2.h:595
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:2945
Base class for all binary_sensor-type classes.
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:178
Base class for all cover devices.
Definition cover.h:112
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition light_state.h:69
Base class for all locks.
Definition lock.h:109
Base-class for all numbers.
Definition number.h:30
Base-class for all selects.
Definition select.h:31
Base-class for all sensors.
Definition sensor.h:42
Base class for all switches.
Definition switch.h:39
Base-class for all text inputs.
Definition text.h:24
Base class for all valve devices.
Definition valve.h:105
const char * message
Definition component.cpp:38
Application App
Global storage of Application pointer - only one Application can exist.
BatchItem(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size)
const BatchItem & operator[](size_t index) const
void add_item(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size)
void add_item_front(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size)