ESPHome 2025.10.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 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_ZWAVE_PROXY
175 void zwave_proxy_frame(const ZWaveProxyFrame &msg) override;
176 void zwave_proxy_request(const ZWaveProxyRequest &msg) override;
177#endif
178
179#ifdef USE_ALARM_CONTROL_PANEL
182#endif
183
184#ifdef USE_EVENT
185 void send_event(event::Event *event, const std::string &event_type);
186#endif
187
188#ifdef USE_UPDATE
190 void update_command(const UpdateCommandRequest &msg) override;
191#endif
192
193 void on_disconnect_response(const DisconnectResponse &value) override;
194 void on_ping_response(const PingResponse &value) override {
195 // we initiated ping
196 this->flags_.sent_ping = false;
197 }
198#ifdef USE_API_HOMEASSISTANT_STATES
200#endif
201#ifdef USE_HOMEASSISTANT_TIME
202 void on_get_time_response(const GetTimeResponse &value) override;
203#endif
204 bool send_hello_response(const HelloRequest &msg) override;
205#ifdef USE_API_PASSWORD
206 bool send_authenticate_response(const AuthenticationRequest &msg) override;
207#endif
208 bool send_disconnect_response(const DisconnectRequest &msg) override;
209 bool send_ping_response(const PingRequest &msg) override;
210 bool send_device_info_response(const DeviceInfoRequest &msg) override;
211 void list_entities(const ListEntitiesRequest &msg) override { this->list_entities_iterator_.begin(); }
212 void subscribe_states(const SubscribeStatesRequest &msg) override {
213 this->flags_.state_subscription = true;
215 }
216 void subscribe_logs(const SubscribeLogsRequest &msg) override {
217 this->flags_.log_subscription = msg.level;
218 if (msg.dump_config)
220 }
221#ifdef USE_API_HOMEASSISTANT_SERVICES
225#endif
226#ifdef USE_API_HOMEASSISTANT_STATES
228#endif
229#ifdef USE_API_SERVICES
230 void execute_service(const ExecuteServiceRequest &msg) override;
231#endif
232#ifdef USE_API_NOISE
234#endif
235
236 bool is_authenticated() override {
238 }
239 bool is_connection_setup() override {
241 this->is_authenticated();
242 }
243 uint8_t get_log_subscription_level() const { return this->flags_.log_subscription; }
244
245 // Get client API version for feature detection
246 bool client_supports_api_version(uint16_t major, uint16_t minor) const {
247 return this->client_api_version_major_ > major ||
248 (this->client_api_version_major_ == major && this->client_api_version_minor_ >= minor);
249 }
250
251 void on_fatal_error() override;
252#ifdef USE_API_PASSWORD
253 void on_unauthenticated_access() override;
254#endif
255 void on_no_setup_connection() override;
256 ProtoWriteBuffer create_buffer(uint32_t reserve_size) override {
257 // FIXME: ensure no recursive writes can happen
258
259 // Get header padding size - used for both reserve and insert
260 uint8_t header_padding = this->helper_->frame_header_padding();
261 // Get shared buffer from parent server
262 std::vector<uint8_t> &shared_buf = this->parent_->get_shared_buffer_ref();
263 this->prepare_first_message_buffer(shared_buf, header_padding,
264 reserve_size + header_padding + this->helper_->frame_footer_size());
265 return {&shared_buf};
266 }
267
268 void prepare_first_message_buffer(std::vector<uint8_t> &shared_buf, size_t header_padding, size_t total_size) {
269 shared_buf.clear();
270 // Reserve space for header padding + message + footer
271 // - Header padding: space for protocol headers (7 bytes for Noise, 6 for Plaintext)
272 // - Footer: space for MAC (16 bytes for Noise, 0 for Plaintext)
273 shared_buf.reserve(total_size);
274 // Resize to add header padding so message encoding starts at the correct position
275 shared_buf.resize(header_padding);
276 }
277
278 bool try_to_clear_buffer(bool log_out_of_space);
279 bool send_buffer(ProtoWriteBuffer buffer, uint8_t message_type) override;
280
281 std::string get_client_combined_info() const { return this->client_info_.get_combined_info(); }
282
283 protected:
284 // Helper function to handle authentication completion
286
287#ifdef USE_API_HOMEASSISTANT_STATES
289#endif
290
291 // Non-template helper to encode any ProtoMessage
292 static uint16_t encode_message_to_buffer(ProtoMessage &msg, uint8_t message_type, APIConnection *conn,
293 uint32_t remaining_size, bool is_single);
294
295 // Helper to fill entity state base and encode message
296 static uint16_t fill_and_encode_entity_state(EntityBase *entity, StateResponseProtoMessage &msg, uint8_t message_type,
297 APIConnection *conn, uint32_t remaining_size, bool is_single) {
298 msg.key = entity->get_object_id_hash();
299#ifdef USE_DEVICES
300 msg.device_id = entity->get_device_id();
301#endif
302 return encode_message_to_buffer(msg, message_type, conn, remaining_size, is_single);
303 }
304
305 // Helper to fill entity info base and encode message
306 static uint16_t fill_and_encode_entity_info(EntityBase *entity, InfoResponseProtoMessage &msg, uint8_t message_type,
307 APIConnection *conn, uint32_t remaining_size, bool is_single) {
308 // Set common fields that are shared by all entity types
309 msg.key = entity->get_object_id_hash();
310 // Try to use static reference first to avoid allocation
311 StringRef static_ref = entity->get_object_id_ref_for_api_();
312 // Store dynamic string outside the if-else to maintain lifetime
313 std::string object_id;
314 if (!static_ref.empty()) {
315 msg.set_object_id(static_ref);
316 } else {
317 // Dynamic case - need to allocate
318 object_id = entity->get_object_id();
319 msg.set_object_id(StringRef(object_id));
320 }
321
322 if (entity->has_own_name()) {
323 msg.set_name(entity->get_name());
324 }
325
326 // Set common EntityBase properties
327#ifdef USE_ENTITY_ICON
328 msg.set_icon(entity->get_icon_ref());
329#endif
331 msg.entity_category = static_cast<enums::EntityCategory>(entity->get_entity_category());
332#ifdef USE_DEVICES
333 msg.device_id = entity->get_device_id();
334#endif
335 return encode_message_to_buffer(msg, message_type, conn, remaining_size, is_single);
336 }
337
338#ifdef USE_VOICE_ASSISTANT
339 // Helper to check voice assistant validity and connection ownership
340 inline bool check_voice_assistant_api_connection_() const;
341#endif
342
343 // Helper method to process multiple entities from an iterator in a batch
344 template<typename Iterator> void process_iterator_batch_(Iterator &iterator) {
345 size_t initial_size = this->deferred_batch_.size();
346 while (!iterator.completed() && (this->deferred_batch_.size() - initial_size) < MAX_INITIAL_PER_BATCH) {
347 iterator.advance();
348 }
349
350 // If the batch is full, process it immediately
351 // Note: iterator.advance() already calls schedule_batch_() via schedule_message_()
352 if (this->deferred_batch_.size() >= MAX_INITIAL_PER_BATCH) {
353 this->process_batch_();
354 }
355 }
356
357#ifdef USE_BINARY_SENSOR
358 static uint16_t try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
359 bool is_single);
360 static uint16_t try_send_binary_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
361 bool is_single);
362#endif
363#ifdef USE_COVER
364 static uint16_t try_send_cover_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
365 bool is_single);
366 static uint16_t try_send_cover_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
367#endif
368#ifdef USE_FAN
369 static uint16_t try_send_fan_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
370 static uint16_t try_send_fan_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
371#endif
372#ifdef USE_LIGHT
373 static uint16_t try_send_light_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
374 bool is_single);
375 static uint16_t try_send_light_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
376#endif
377#ifdef USE_SENSOR
378 static uint16_t try_send_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
379 bool is_single);
380 static uint16_t try_send_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
381 bool is_single);
382#endif
383#ifdef USE_SWITCH
384 static uint16_t try_send_switch_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
385 bool is_single);
386 static uint16_t try_send_switch_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
387 bool is_single);
388#endif
389#ifdef USE_TEXT_SENSOR
390 static uint16_t try_send_text_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
391 bool is_single);
392 static uint16_t try_send_text_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
393 bool is_single);
394#endif
395#ifdef USE_CLIMATE
396 static uint16_t try_send_climate_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
397 bool is_single);
398 static uint16_t try_send_climate_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
399 bool is_single);
400#endif
401#ifdef USE_NUMBER
402 static uint16_t try_send_number_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
403 bool is_single);
404 static uint16_t try_send_number_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
405 bool is_single);
406#endif
407#ifdef USE_DATETIME_DATE
408 static uint16_t try_send_date_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
409 static uint16_t try_send_date_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
410#endif
411#ifdef USE_DATETIME_TIME
412 static uint16_t try_send_time_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
413 static uint16_t try_send_time_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
414#endif
415#ifdef USE_DATETIME_DATETIME
416 static uint16_t try_send_datetime_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
417 bool is_single);
418 static uint16_t try_send_datetime_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
419 bool is_single);
420#endif
421#ifdef USE_TEXT
422 static uint16_t try_send_text_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
423 static uint16_t try_send_text_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
424#endif
425#ifdef USE_SELECT
426 static uint16_t try_send_select_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
427 bool is_single);
428 static uint16_t try_send_select_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
429 bool is_single);
430#endif
431#ifdef USE_BUTTON
432 static uint16_t try_send_button_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
433 bool is_single);
434#endif
435#ifdef USE_LOCK
436 static uint16_t try_send_lock_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
437 static uint16_t try_send_lock_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
438#endif
439#ifdef USE_VALVE
440 static uint16_t try_send_valve_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
441 bool is_single);
442 static uint16_t try_send_valve_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
443#endif
444#ifdef USE_MEDIA_PLAYER
445 static uint16_t try_send_media_player_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
446 bool is_single);
447 static uint16_t try_send_media_player_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
448 bool is_single);
449#endif
450#ifdef USE_ALARM_CONTROL_PANEL
451 static uint16_t try_send_alarm_control_panel_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
452 bool is_single);
453 static uint16_t try_send_alarm_control_panel_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
454 bool is_single);
455#endif
456#ifdef USE_EVENT
457 static uint16_t try_send_event_response(event::Event *event, const std::string &event_type, APIConnection *conn,
458 uint32_t remaining_size, bool is_single);
459 static uint16_t try_send_event_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
460#endif
461#ifdef USE_UPDATE
462 static uint16_t try_send_update_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
463 bool is_single);
464 static uint16_t try_send_update_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
465 bool is_single);
466#endif
467#ifdef USE_CAMERA
468 static uint16_t try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
469 bool is_single);
470#endif
471
472 // Method for ListEntitiesDone batching
473 static uint16_t try_send_list_info_done(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
474 bool is_single);
475
476 // Method for DisconnectRequest batching
477 static uint16_t try_send_disconnect_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
478 bool is_single);
479
480 // Batch message method for ping requests
481 static uint16_t try_send_ping_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
482 bool is_single);
483
484 // === Optimal member ordering for 32-bit systems ===
485
486 // Group 1: Pointers (4 bytes each on 32-bit)
487 std::unique_ptr<APIFrameHelper> helper_;
489
490 // Group 2: Larger objects (must be 4-byte aligned)
491 // These contain vectors/pointers internally, so putting them early ensures good alignment
494#ifdef USE_CAMERA
495 std::unique_ptr<camera::CameraImageReader> image_reader_;
496#endif
497
498 // Group 3: Client info struct (24 bytes on 32-bit: 2 strings × 12 bytes each)
500
501 // Group 4: 4-byte types
503#ifdef USE_API_HOMEASSISTANT_STATES
505#endif
506
507 // Function pointer type for message encoding
508 using MessageCreatorPtr = uint16_t (*)(EntityBase *, APIConnection *, uint32_t remaining_size, bool is_single);
509
511 public:
512 // Constructor for function pointer
513 MessageCreator(MessageCreatorPtr ptr) { data_.function_ptr = ptr; }
514
515 // Constructor for string state capture
516 explicit MessageCreator(const std::string &str_value) { data_.string_ptr = new std::string(str_value); }
517
518 // No destructor - cleanup must be called explicitly with message_type
519
520 // Delete copy operations - MessageCreator should only be moved
521 MessageCreator(const MessageCreator &other) = delete;
522 MessageCreator &operator=(const MessageCreator &other) = delete;
523
524 // Move constructor
525 MessageCreator(MessageCreator &&other) noexcept : data_(other.data_) { other.data_.function_ptr = nullptr; }
526
527 // Move assignment
529 if (this != &other) {
530 // IMPORTANT: Caller must ensure cleanup() was called if this contains a string!
531 // In our usage, this happens in add_item() deduplication and vector::erase()
532 data_ = other.data_;
533 other.data_.function_ptr = nullptr;
534 }
535 return *this;
536 }
537
538 // Call operator - uses message_type to determine union type
539 uint16_t operator()(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single,
540 uint8_t message_type) const;
541
542 // Manual cleanup method - must be called before destruction for string types
543 void cleanup(uint8_t message_type) {
544#ifdef USE_EVENT
545 if (message_type == EventResponse::MESSAGE_TYPE && data_.string_ptr != nullptr) {
546 delete data_.string_ptr;
547 data_.string_ptr = nullptr;
548 }
549#endif
550 }
551
552 private:
553 union Data {
554 MessageCreatorPtr function_ptr;
555 std::string *string_ptr;
556 } data_; // 4 bytes on 32-bit, 8 bytes on 64-bit - same as before
557 };
558
559 // Generic batching mechanism for both state updates and entity info
561 struct BatchItem {
562 EntityBase *entity; // Entity pointer
563 MessageCreator creator; // Function that creates the message when needed
564 uint8_t message_type; // Message type for overhead calculation (max 255)
565 uint8_t estimated_size; // Estimated message size (max 255 bytes)
566
567 // Constructor for creating BatchItem
570 };
571
572 std::vector<BatchItem> items;
573 uint32_t batch_start_time{0};
574
575 private:
576 // Helper to cleanup items from the beginning
577 void cleanup_items_(size_t count) {
578 for (size_t i = 0; i < count; i++) {
579 items[i].creator.cleanup(items[i].message_type);
580 }
581 }
582
583 public:
585 // Pre-allocate capacity for typical batch sizes to avoid reallocation
586 items.reserve(8);
587 }
588
590 // Ensure cleanup of any remaining items
591 clear();
592 }
593
594 // Add item to the batch
595 void add_item(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size);
596 // Add item to the front of the batch (for high priority messages like ping)
597 void add_item_front(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size);
598
599 // Clear all items with proper cleanup
600 void clear() {
601 cleanup_items_(items.size());
602 items.clear();
604 }
605
606 // Remove processed items from the front with proper cleanup
607 void remove_front(size_t count) {
608 cleanup_items_(count);
609 items.erase(items.begin(), items.begin() + count);
610 }
611
612 bool empty() const { return items.empty(); }
613 size_t size() const { return items.size(); }
614 const BatchItem &operator[](size_t index) const { return items[index]; }
615 };
616
617 // DeferredBatch here (16 bytes, 4-byte aligned)
619
620 // ConnectionState enum for type safety
621 enum class ConnectionState : uint8_t {
623 CONNECTED = 1,
624 AUTHENTICATED = 2,
625 };
626
627 // Group 5: Pack all small members together to minimize padding
628 // This group starts at a 4-byte boundary after DeferredBatch
629 struct APIFlags {
630 // Connection state only needs 2 bits (3 states)
631 uint8_t connection_state : 2;
632 // Log subscription needs 3 bits (log levels 0-7)
633 uint8_t log_subscription : 3;
634 // Boolean flags (1 bit each)
635 uint8_t remove : 1;
637 uint8_t sent_ping : 1;
638
640 uint8_t next_close : 1;
641 uint8_t batch_scheduled : 1;
642 uint8_t batch_first_message : 1; // For batch buffer allocation
643 uint8_t should_try_send_immediately : 1; // True after initial states are sent
644#ifdef HAS_PROTO_MESSAGE_DUMP
645 uint8_t log_only_mode : 1;
646#endif
647 } flags_{}; // 2 bytes total
648
649 // 2-byte types immediately after flags_ (no padding between them)
652 // Total: 2 (flags) + 2 + 2 = 6 bytes, then 2 bytes padding to next 4-byte boundary
653
654 uint32_t get_batch_delay_ms_() const;
655 // Message will use 8 more bytes than the minimum size, and typical
656 // MTU is 1500. Sometimes users will see as low as 1460 MTU.
657 // If its IPv6 the header is 40 bytes, and if its IPv4
658 // the header is 20 bytes. So we have 1460 - 40 = 1420 bytes
659 // available for the payload. But we also need to add the size of
660 // the protobuf overhead, which is 8 bytes.
661 //
662 // To be safe we pick 1390 bytes as the maximum size
663 // to send in one go. This is the maximum size of a single packet
664 // that can be sent over the network.
665 // This is to avoid fragmentation of the packet.
666 static constexpr size_t MAX_BATCH_PACKET_SIZE = 1390; // MTU
667
668 bool schedule_batch_();
669 void process_batch_();
671 this->deferred_batch_.clear();
672 this->flags_.batch_scheduled = false;
673 }
674
675#ifdef HAS_PROTO_MESSAGE_DUMP
676 // Helper to log a proto message from a MessageCreator object
677 void log_proto_message_(EntityBase *entity, const MessageCreator &creator, uint8_t message_type) {
678 this->flags_.log_only_mode = true;
679 creator(entity, this, MAX_BATCH_PACKET_SIZE, true, message_type);
680 this->flags_.log_only_mode = false;
681 }
682
684 // Use the helper to log the message
685 this->log_proto_message_(item.entity, item.creator, item.message_type);
686 }
687#endif
688
689 // Helper method to send a message either immediately or via batching
690 bool send_message_smart_(EntityBase *entity, MessageCreatorPtr creator, uint8_t message_type,
691 uint8_t estimated_size) {
692 // Try to send immediately if:
693 // 1. It's an UpdateStateResponse (always send immediately to handle cases where
694 // the main loop is blocked, e.g., during OTA updates)
695 // 2. OR: We should try to send immediately (should_try_send_immediately = true)
696 // AND Batch delay is 0 (user has opted in to immediate sending)
697 // 3. AND: Buffer has space available
698 if ((
699#ifdef USE_UPDATE
700 message_type == UpdateStateResponse::MESSAGE_TYPE ||
701#endif
702 (this->flags_.should_try_send_immediately && this->get_batch_delay_ms_() == 0)) &&
703 this->helper_->can_write_without_blocking()) {
704 // Now actually encode and send
705 if (creator(entity, this, MAX_BATCH_PACKET_SIZE, true) &&
706 this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, message_type)) {
707#ifdef HAS_PROTO_MESSAGE_DUMP
708 // Log the message in verbose mode
709 this->log_proto_message_(entity, MessageCreator(creator), message_type);
710#endif
711 return true;
712 }
713
714 // If immediate send failed, fall through to batching
715 }
716
717 // Fall back to scheduled batching
718 return this->schedule_message_(entity, creator, message_type, estimated_size);
719 }
720
721 // Helper function to schedule a deferred message with known message type
722 bool schedule_message_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size) {
723 this->deferred_batch_.add_item(entity, std::move(creator), message_type, estimated_size);
724 return this->schedule_batch_();
725 }
726
727 // Overload for function pointers (for info messages and current state reads)
728 bool schedule_message_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type,
729 uint8_t estimated_size) {
730 return schedule_message_(entity, MessageCreator(function_ptr), message_type, estimated_size);
731 }
732
733 // Helper function to schedule a high priority message at the front of the batch
734 bool schedule_message_front_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type,
735 uint8_t estimated_size) {
736 this->deferred_batch_.add_item_front(entity, MessageCreator(function_ptr), message_type, estimated_size);
737 return this->schedule_batch_();
738 }
739
740 // Helper function to log API errors with errno
741 void log_warning_(const LogString *message, APIError err);
742 // Specific helper for duplicated error message
744};
745
746} // namespace esphome::api
747#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)
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 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)
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
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)
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:51
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:2766
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:1180
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:2909
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