ESPHome 2025.9.3
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 <vector>
14#include <functional>
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 std::string get_combined_info() const {
24 if (name == peername) {
25 // Before Hello message, both are the same
26 return name;
27 }
28 return name + " (" + peername + ")";
29 }
30};
31
32// Keepalive timeout in milliseconds
33static constexpr uint32_t KEEPALIVE_TIMEOUT_MS = 60000;
34// Maximum number of entities to process in a single batch during initial state/info sending
35// This was increased from 20 to 24 after removing the unique_id field from entity info messages,
36// which reduced message sizes allowing more entities per batch without exceeding packet limits
37static constexpr size_t MAX_INITIAL_PER_BATCH = 24;
38// Maximum number of packets to process in a single batch (platform-dependent)
39// This limit exists to prevent stack overflow from the PacketInfo array in process_batch_
40// Each PacketInfo is 8 bytes, so 64 * 8 = 512 bytes, 32 * 8 = 256 bytes
41#if defined(USE_ESP32) || defined(USE_HOST)
42static constexpr size_t MAX_PACKETS_PER_BATCH = 64; // ESP32 has 8KB+ stack, HOST has plenty
43#else
44static constexpr size_t MAX_PACKETS_PER_BATCH = 32; // ESP8266/RP2040/etc have smaller stacks
45#endif
46
47class APIConnection final : public APIServerConnection {
48 public:
49 friend class APIServer;
51 APIConnection(std::unique_ptr<socket::Socket> socket, APIServer *parent);
52 virtual ~APIConnection();
53
54 void start();
55 void loop();
56
61#ifdef USE_BINARY_SENSOR
63#endif
64#ifdef USE_COVER
65 bool send_cover_state(cover::Cover *cover);
66 void cover_command(const CoverCommandRequest &msg) override;
67#endif
68#ifdef USE_FAN
69 bool send_fan_state(fan::Fan *fan);
70 void fan_command(const FanCommandRequest &msg) override;
71#endif
72#ifdef USE_LIGHT
74 void light_command(const LightCommandRequest &msg) override;
75#endif
76#ifdef USE_SENSOR
78#endif
79#ifdef USE_SWITCH
80 bool send_switch_state(switch_::Switch *a_switch);
81 void switch_command(const SwitchCommandRequest &msg) override;
82#endif
83#ifdef USE_TEXT_SENSOR
85#endif
86#ifdef USE_CAMERA
87 void set_camera_state(std::shared_ptr<camera::CameraImage> image);
88 void camera_image(const CameraImageRequest &msg) override;
89#endif
90#ifdef USE_CLIMATE
92 void climate_command(const ClimateCommandRequest &msg) override;
93#endif
94#ifdef USE_NUMBER
96 void number_command(const NumberCommandRequest &msg) override;
97#endif
98#ifdef USE_DATETIME_DATE
100 void date_command(const DateCommandRequest &msg) override;
101#endif
102#ifdef USE_DATETIME_TIME
104 void time_command(const TimeCommandRequest &msg) override;
105#endif
106#ifdef USE_DATETIME_DATETIME
108 void datetime_command(const DateTimeCommandRequest &msg) override;
109#endif
110#ifdef USE_TEXT
111 bool send_text_state(text::Text *text);
112 void text_command(const TextCommandRequest &msg) override;
113#endif
114#ifdef USE_SELECT
115 bool send_select_state(select::Select *select);
116 void select_command(const SelectCommandRequest &msg) override;
117#endif
118#ifdef USE_BUTTON
119 void button_command(const ButtonCommandRequest &msg) override;
120#endif
121#ifdef USE_LOCK
122 bool send_lock_state(lock::Lock *a_lock);
123 void lock_command(const LockCommandRequest &msg) override;
124#endif
125#ifdef USE_VALVE
126 bool send_valve_state(valve::Valve *valve);
127 void valve_command(const ValveCommandRequest &msg) override;
128#endif
129#ifdef USE_MEDIA_PLAYER
131 void media_player_command(const MediaPlayerCommandRequest &msg) override;
132#endif
133 bool try_send_log_message(int level, const char *tag, const char *line, size_t message_len);
134#ifdef USE_API_HOMEASSISTANT_SERVICES
140#endif
141#ifdef USE_BLUETOOTH_PROXY
144
145 void bluetooth_device_request(const BluetoothDeviceRequest &msg) override;
146 void bluetooth_gatt_read(const BluetoothGATTReadRequest &msg) override;
147 void bluetooth_gatt_write(const BluetoothGATTWriteRequest &msg) override;
151 void bluetooth_gatt_notify(const BluetoothGATTNotifyRequest &msg) override;
154
155#endif
156#ifdef USE_HOMEASSISTANT_TIME
161#endif
162
163#ifdef USE_VOICE_ASSISTANT
165 void on_voice_assistant_response(const VoiceAssistantResponse &msg) override;
167 void on_voice_assistant_audio(const VoiceAssistantAudio &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 std::string &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 bool send_connect_response(const ConnectRequest &msg) override;
201 bool send_disconnect_response(const DisconnectRequest &msg) override;
202 bool send_ping_response(const PingRequest &msg) override;
203 bool send_device_info_response(const DeviceInfoRequest &msg) override;
204 void list_entities(const ListEntitiesRequest &msg) override { this->list_entities_iterator_.begin(); }
205 void subscribe_states(const SubscribeStatesRequest &msg) override {
206 this->flags_.state_subscription = true;
208 }
209 void subscribe_logs(const SubscribeLogsRequest &msg) override {
210 this->flags_.log_subscription = msg.level;
211 if (msg.dump_config)
213 }
214#ifdef USE_API_HOMEASSISTANT_SERVICES
218#endif
219#ifdef USE_API_HOMEASSISTANT_STATES
221#endif
222#ifdef USE_API_SERVICES
223 void execute_service(const ExecuteServiceRequest &msg) override;
224#endif
225#ifdef USE_API_NOISE
227#endif
228
229 bool is_authenticated() override {
231 }
232 bool is_connection_setup() override {
234 this->is_authenticated();
235 }
236 uint8_t get_log_subscription_level() const { return this->flags_.log_subscription; }
237
238 // Get client API version for feature detection
239 bool client_supports_api_version(uint16_t major, uint16_t minor) const {
240 return this->client_api_version_major_ > major ||
241 (this->client_api_version_major_ == major && this->client_api_version_minor_ >= minor);
242 }
243
244 void on_fatal_error() override;
245#ifdef USE_API_PASSWORD
246 void on_unauthenticated_access() override;
247#endif
248 void on_no_setup_connection() override;
249 ProtoWriteBuffer create_buffer(uint32_t reserve_size) override {
250 // FIXME: ensure no recursive writes can happen
251
252 // Get header padding size - used for both reserve and insert
253 uint8_t header_padding = this->helper_->frame_header_padding();
254 // Get shared buffer from parent server
255 std::vector<uint8_t> &shared_buf = this->parent_->get_shared_buffer_ref();
256 this->prepare_first_message_buffer(shared_buf, header_padding,
257 reserve_size + header_padding + this->helper_->frame_footer_size());
258 return {&shared_buf};
259 }
260
261 void prepare_first_message_buffer(std::vector<uint8_t> &shared_buf, size_t header_padding, size_t total_size) {
262 shared_buf.clear();
263 // Reserve space for header padding + message + footer
264 // - Header padding: space for protocol headers (7 bytes for Noise, 6 for Plaintext)
265 // - Footer: space for MAC (16 bytes for Noise, 0 for Plaintext)
266 shared_buf.reserve(total_size);
267 // Resize to add header padding so message encoding starts at the correct position
268 shared_buf.resize(header_padding);
269 }
270
271 bool try_to_clear_buffer(bool log_out_of_space);
272 bool send_buffer(ProtoWriteBuffer buffer, uint8_t message_type) override;
273
274 std::string get_client_combined_info() const { return this->client_info_.get_combined_info(); }
275
276 protected:
277 // Helper function to handle authentication completion
279
280#ifdef USE_API_HOMEASSISTANT_STATES
282#endif
283
284 // Non-template helper to encode any ProtoMessage
285 static uint16_t encode_message_to_buffer(ProtoMessage &msg, uint8_t message_type, APIConnection *conn,
286 uint32_t remaining_size, bool is_single);
287
288 // Helper to fill entity state base and encode message
289 static uint16_t fill_and_encode_entity_state(EntityBase *entity, StateResponseProtoMessage &msg, uint8_t message_type,
290 APIConnection *conn, uint32_t remaining_size, bool is_single) {
291 msg.key = entity->get_object_id_hash();
292#ifdef USE_DEVICES
293 msg.device_id = entity->get_device_id();
294#endif
295 return encode_message_to_buffer(msg, message_type, conn, remaining_size, is_single);
296 }
297
298 // Helper to fill entity info base and encode message
299 static uint16_t fill_and_encode_entity_info(EntityBase *entity, InfoResponseProtoMessage &msg, uint8_t message_type,
300 APIConnection *conn, uint32_t remaining_size, bool is_single) {
301 // Set common fields that are shared by all entity types
302 msg.key = entity->get_object_id_hash();
303 // Try to use static reference first to avoid allocation
304 StringRef static_ref = entity->get_object_id_ref_for_api_();
305 // Store dynamic string outside the if-else to maintain lifetime
306 std::string object_id;
307 if (!static_ref.empty()) {
308 msg.set_object_id(static_ref);
309 } else {
310 // Dynamic case - need to allocate
311 object_id = entity->get_object_id();
312 msg.set_object_id(StringRef(object_id));
313 }
314
315 if (entity->has_own_name()) {
316 msg.set_name(entity->get_name());
317 }
318
319 // Set common EntityBase properties
320#ifdef USE_ENTITY_ICON
321 msg.set_icon(entity->get_icon_ref());
322#endif
324 msg.entity_category = static_cast<enums::EntityCategory>(entity->get_entity_category());
325#ifdef USE_DEVICES
326 msg.device_id = entity->get_device_id();
327#endif
328 return encode_message_to_buffer(msg, message_type, conn, remaining_size, is_single);
329 }
330
331#ifdef USE_VOICE_ASSISTANT
332 // Helper to check voice assistant validity and connection ownership
333 inline bool check_voice_assistant_api_connection_() const;
334#endif
335
336 // Helper method to process multiple entities from an iterator in a batch
337 template<typename Iterator> void process_iterator_batch_(Iterator &iterator) {
338 size_t initial_size = this->deferred_batch_.size();
339 while (!iterator.completed() && (this->deferred_batch_.size() - initial_size) < MAX_INITIAL_PER_BATCH) {
340 iterator.advance();
341 }
342
343 // If the batch is full, process it immediately
344 // Note: iterator.advance() already calls schedule_batch_() via schedule_message_()
345 if (this->deferred_batch_.size() >= MAX_INITIAL_PER_BATCH) {
346 this->process_batch_();
347 }
348 }
349
350#ifdef USE_BINARY_SENSOR
351 static uint16_t try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
352 bool is_single);
353 static uint16_t try_send_binary_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
354 bool is_single);
355#endif
356#ifdef USE_COVER
357 static uint16_t try_send_cover_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
358 bool is_single);
359 static uint16_t try_send_cover_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
360#endif
361#ifdef USE_FAN
362 static uint16_t try_send_fan_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
363 static uint16_t try_send_fan_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
364#endif
365#ifdef USE_LIGHT
366 static uint16_t try_send_light_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
367 bool is_single);
368 static uint16_t try_send_light_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
369#endif
370#ifdef USE_SENSOR
371 static uint16_t try_send_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
372 bool is_single);
373 static uint16_t try_send_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
374 bool is_single);
375#endif
376#ifdef USE_SWITCH
377 static uint16_t try_send_switch_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
378 bool is_single);
379 static uint16_t try_send_switch_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
380 bool is_single);
381#endif
382#ifdef USE_TEXT_SENSOR
383 static uint16_t try_send_text_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
384 bool is_single);
385 static uint16_t try_send_text_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
386 bool is_single);
387#endif
388#ifdef USE_CLIMATE
389 static uint16_t try_send_climate_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
390 bool is_single);
391 static uint16_t try_send_climate_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
392 bool is_single);
393#endif
394#ifdef USE_NUMBER
395 static uint16_t try_send_number_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
396 bool is_single);
397 static uint16_t try_send_number_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
398 bool is_single);
399#endif
400#ifdef USE_DATETIME_DATE
401 static uint16_t try_send_date_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
402 static uint16_t try_send_date_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
403#endif
404#ifdef USE_DATETIME_TIME
405 static uint16_t try_send_time_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
406 static uint16_t try_send_time_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
407#endif
408#ifdef USE_DATETIME_DATETIME
409 static uint16_t try_send_datetime_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
410 bool is_single);
411 static uint16_t try_send_datetime_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
412 bool is_single);
413#endif
414#ifdef USE_TEXT
415 static uint16_t try_send_text_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
416 static uint16_t try_send_text_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
417#endif
418#ifdef USE_SELECT
419 static uint16_t try_send_select_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
420 bool is_single);
421 static uint16_t try_send_select_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
422 bool is_single);
423#endif
424#ifdef USE_BUTTON
425 static uint16_t try_send_button_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
426 bool is_single);
427#endif
428#ifdef USE_LOCK
429 static uint16_t try_send_lock_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
430 static uint16_t try_send_lock_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
431#endif
432#ifdef USE_VALVE
433 static uint16_t try_send_valve_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
434 bool is_single);
435 static uint16_t try_send_valve_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
436#endif
437#ifdef USE_MEDIA_PLAYER
438 static uint16_t try_send_media_player_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
439 bool is_single);
440 static uint16_t try_send_media_player_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
441 bool is_single);
442#endif
443#ifdef USE_ALARM_CONTROL_PANEL
444 static uint16_t try_send_alarm_control_panel_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
445 bool is_single);
446 static uint16_t try_send_alarm_control_panel_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
447 bool is_single);
448#endif
449#ifdef USE_EVENT
450 static uint16_t try_send_event_response(event::Event *event, const std::string &event_type, APIConnection *conn,
451 uint32_t remaining_size, bool is_single);
452 static uint16_t try_send_event_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
453#endif
454#ifdef USE_UPDATE
455 static uint16_t try_send_update_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
456 bool is_single);
457 static uint16_t try_send_update_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
458 bool is_single);
459#endif
460#ifdef USE_CAMERA
461 static uint16_t try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
462 bool is_single);
463#endif
464
465 // Method for ListEntitiesDone batching
466 static uint16_t try_send_list_info_done(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
467 bool is_single);
468
469 // Method for DisconnectRequest batching
470 static uint16_t try_send_disconnect_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
471 bool is_single);
472
473 // Batch message method for ping requests
474 static uint16_t try_send_ping_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
475 bool is_single);
476
477 // === Optimal member ordering for 32-bit systems ===
478
479 // Group 1: Pointers (4 bytes each on 32-bit)
480 std::unique_ptr<APIFrameHelper> helper_;
482
483 // Group 2: Larger objects (must be 4-byte aligned)
484 // These contain vectors/pointers internally, so putting them early ensures good alignment
487#ifdef USE_CAMERA
488 std::unique_ptr<camera::CameraImageReader> image_reader_;
489#endif
490
491 // Group 3: Client info struct (24 bytes on 32-bit: 2 strings × 12 bytes each)
493
494 // Group 4: 4-byte types
496#ifdef USE_API_HOMEASSISTANT_STATES
498#endif
499
500 // Function pointer type for message encoding
501 using MessageCreatorPtr = uint16_t (*)(EntityBase *, APIConnection *, uint32_t remaining_size, bool is_single);
502
504 public:
505 // Constructor for function pointer
506 MessageCreator(MessageCreatorPtr ptr) { data_.function_ptr = ptr; }
507
508 // Constructor for string state capture
509 explicit MessageCreator(const std::string &str_value) { data_.string_ptr = new std::string(str_value); }
510
511 // No destructor - cleanup must be called explicitly with message_type
512
513 // Delete copy operations - MessageCreator should only be moved
514 MessageCreator(const MessageCreator &other) = delete;
515 MessageCreator &operator=(const MessageCreator &other) = delete;
516
517 // Move constructor
518 MessageCreator(MessageCreator &&other) noexcept : data_(other.data_) { other.data_.function_ptr = nullptr; }
519
520 // Move assignment
522 if (this != &other) {
523 // IMPORTANT: Caller must ensure cleanup() was called if this contains a string!
524 // In our usage, this happens in add_item() deduplication and vector::erase()
525 data_ = other.data_;
526 other.data_.function_ptr = nullptr;
527 }
528 return *this;
529 }
530
531 // Call operator - uses message_type to determine union type
532 uint16_t operator()(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single,
533 uint8_t message_type) const;
534
535 // Manual cleanup method - must be called before destruction for string types
536 void cleanup(uint8_t message_type) {
537#ifdef USE_EVENT
538 if (message_type == EventResponse::MESSAGE_TYPE && data_.string_ptr != nullptr) {
539 delete data_.string_ptr;
540 data_.string_ptr = nullptr;
541 }
542#endif
543 }
544
545 private:
546 union Data {
547 MessageCreatorPtr function_ptr;
548 std::string *string_ptr;
549 } data_; // 4 bytes on 32-bit, 8 bytes on 64-bit - same as before
550 };
551
552 // Generic batching mechanism for both state updates and entity info
554 struct BatchItem {
555 EntityBase *entity; // Entity pointer
556 MessageCreator creator; // Function that creates the message when needed
557 uint8_t message_type; // Message type for overhead calculation (max 255)
558 uint8_t estimated_size; // Estimated message size (max 255 bytes)
559
560 // Constructor for creating BatchItem
563 };
564
565 std::vector<BatchItem> items;
566 uint32_t batch_start_time{0};
567
568 private:
569 // Helper to cleanup items from the beginning
570 void cleanup_items_(size_t count) {
571 for (size_t i = 0; i < count; i++) {
572 items[i].creator.cleanup(items[i].message_type);
573 }
574 }
575
576 public:
578 // Pre-allocate capacity for typical batch sizes to avoid reallocation
579 items.reserve(8);
580 }
581
583 // Ensure cleanup of any remaining items
584 clear();
585 }
586
587 // Add item to the batch
588 void add_item(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size);
589 // Add item to the front of the batch (for high priority messages like ping)
590 void add_item_front(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size);
591
592 // Clear all items with proper cleanup
593 void clear() {
594 cleanup_items_(items.size());
595 items.clear();
597 }
598
599 // Remove processed items from the front with proper cleanup
600 void remove_front(size_t count) {
601 cleanup_items_(count);
602 items.erase(items.begin(), items.begin() + count);
603 }
604
605 bool empty() const { return items.empty(); }
606 size_t size() const { return items.size(); }
607 const BatchItem &operator[](size_t index) const { return items[index]; }
608 };
609
610 // DeferredBatch here (16 bytes, 4-byte aligned)
612
613 // ConnectionState enum for type safety
614 enum class ConnectionState : uint8_t {
616 CONNECTED = 1,
617 AUTHENTICATED = 2,
618 };
619
620 // Group 5: Pack all small members together to minimize padding
621 // This group starts at a 4-byte boundary after DeferredBatch
622 struct APIFlags {
623 // Connection state only needs 2 bits (3 states)
624 uint8_t connection_state : 2;
625 // Log subscription needs 3 bits (log levels 0-7)
626 uint8_t log_subscription : 3;
627 // Boolean flags (1 bit each)
628 uint8_t remove : 1;
630 uint8_t sent_ping : 1;
631
633 uint8_t next_close : 1;
634 uint8_t batch_scheduled : 1;
635 uint8_t batch_first_message : 1; // For batch buffer allocation
636 uint8_t should_try_send_immediately : 1; // True after initial states are sent
637#ifdef HAS_PROTO_MESSAGE_DUMP
638 uint8_t log_only_mode : 1;
639#endif
640 } flags_{}; // 2 bytes total
641
642 // 2-byte types immediately after flags_ (no padding between them)
645 // Total: 2 (flags) + 2 + 2 = 6 bytes, then 2 bytes padding to next 4-byte boundary
646
647 uint32_t get_batch_delay_ms_() const;
648 // Message will use 8 more bytes than the minimum size, and typical
649 // MTU is 1500. Sometimes users will see as low as 1460 MTU.
650 // If its IPv6 the header is 40 bytes, and if its IPv4
651 // the header is 20 bytes. So we have 1460 - 40 = 1420 bytes
652 // available for the payload. But we also need to add the size of
653 // the protobuf overhead, which is 8 bytes.
654 //
655 // To be safe we pick 1390 bytes as the maximum size
656 // to send in one go. This is the maximum size of a single packet
657 // that can be sent over the network.
658 // This is to avoid fragmentation of the packet.
659 static constexpr size_t MAX_BATCH_PACKET_SIZE = 1390; // MTU
660
661 bool schedule_batch_();
662 void process_batch_();
664 this->deferred_batch_.clear();
665 this->flags_.batch_scheduled = false;
666 }
667
668#ifdef HAS_PROTO_MESSAGE_DUMP
669 // Helper to log a proto message from a MessageCreator object
670 void log_proto_message_(EntityBase *entity, const MessageCreator &creator, uint8_t message_type) {
671 this->flags_.log_only_mode = true;
672 creator(entity, this, MAX_BATCH_PACKET_SIZE, true, message_type);
673 this->flags_.log_only_mode = false;
674 }
675
677 // Use the helper to log the message
678 this->log_proto_message_(item.entity, item.creator, item.message_type);
679 }
680#endif
681
682 // Helper method to send a message either immediately or via batching
683 bool send_message_smart_(EntityBase *entity, MessageCreatorPtr creator, uint8_t message_type,
684 uint8_t estimated_size) {
685 // Try to send immediately if:
686 // 1. It's an UpdateStateResponse (always send immediately to handle cases where
687 // the main loop is blocked, e.g., during OTA updates)
688 // 2. OR: We should try to send immediately (should_try_send_immediately = true)
689 // AND Batch delay is 0 (user has opted in to immediate sending)
690 // 3. AND: Buffer has space available
691 if ((
692#ifdef USE_UPDATE
693 message_type == UpdateStateResponse::MESSAGE_TYPE ||
694#endif
695 (this->flags_.should_try_send_immediately && this->get_batch_delay_ms_() == 0)) &&
696 this->helper_->can_write_without_blocking()) {
697 // Now actually encode and send
698 if (creator(entity, this, MAX_BATCH_PACKET_SIZE, true) &&
699 this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, message_type)) {
700#ifdef HAS_PROTO_MESSAGE_DUMP
701 // Log the message in verbose mode
702 this->log_proto_message_(entity, MessageCreator(creator), message_type);
703#endif
704 return true;
705 }
706
707 // If immediate send failed, fall through to batching
708 }
709
710 // Fall back to scheduled batching
711 return this->schedule_message_(entity, creator, message_type, estimated_size);
712 }
713
714 // Helper function to schedule a deferred message with known message type
715 bool schedule_message_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size) {
716 this->deferred_batch_.add_item(entity, std::move(creator), message_type, estimated_size);
717 return this->schedule_batch_();
718 }
719
720 // Overload for function pointers (for info messages and current state reads)
721 bool schedule_message_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type,
722 uint8_t estimated_size) {
723 return schedule_message_(entity, MessageCreator(function_ptr), message_type, estimated_size);
724 }
725
726 // Helper function to schedule a high priority message at the front of the batch
727 bool schedule_message_front_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type,
728 uint8_t estimated_size) {
729 this->deferred_batch_.add_item_front(entity, MessageCreator(function_ptr), message_type, estimated_size);
730 return this->schedule_batch_();
731 }
732
733 // Helper function to log API errors with errno
734 void log_warning_(const LogString *message, APIError err);
735 // Specific helper for duplicated error message
737};
738
739} // namespace esphome::api
740#endif
void begin(bool include_internal=false)
bool has_own_name() const
Definition entity_base.h:34
uint32_t get_object_id_hash()
const StringRef & get_name() const
StringRef get_icon_ref() const
Definition entity_base.h:62
uint32_t get_device_id() const
Definition entity_base.h:73
bool is_disabled_by_default() const
Definition entity_base.h:50
std::string get_object_id() const
EntityCategory get_entity_category() const
Definition entity_base.h:54
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(const std::string &str_value)
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)
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 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)
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)
bool send_connect_response(const ConnectRequest &msg) override
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
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)
void log_socket_operation_failed_(APIError err)
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)
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
void send_event(event::Event *event, const std::string &event_type)
bool send_sensor_state(sensor::Sensor *sensor)
std::string get_client_combined_info() const
static constexpr size_t MAX_BATCH_PACKET_SIZE
void log_batch_item_(const DeferredBatch::BatchItem &item)
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)
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 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)
static uint16_t try_send_event_response(event::Event *event, const std::string &event_type, 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 number_command(const NumberCommandRequest &msg) override
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
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 send_homeassistant_service_call(const HomeassistantServiceResponse &call)
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)
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:49
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:2727
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:1163
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:1089
void set_object_id(const StringRef &ref)
Definition api_pb2.h:286
enums::EntityCategory entity_category
Definition api_pb2.h:295
void set_icon(const StringRef &ref)
Definition api_pb2.h:293
void set_name(const StringRef &ref)
Definition api_pb2.h:289
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:577
static constexpr uint8_t ESTIMATED_SIZE
Definition api_pb2.h:578
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:2870
Base class for all binary_sensor-type classes.
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:168
Base class for all cover devices.
Definition cover.h:111
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition light_state.h:68
Base class for all locks.
Definition lock.h:103
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
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)
std::string get_combined_info() const