ESPHome 2025.12.5
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_USER_DEFINED_ACTIONS
225 void execute_service(const ExecuteServiceRequest &msg) override;
226#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
227 void send_execute_service_response(uint32_t call_id, bool success, const std::string &error_message);
228#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
229 void send_execute_service_response(uint32_t call_id, bool success, const std::string &error_message,
230 const uint8_t *response_data, size_t response_data_len);
231#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
232#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
233#endif
234#ifdef USE_API_NOISE
236#endif
237
238 bool is_authenticated() override {
240 }
241 bool is_connection_setup() override {
243 this->is_authenticated();
244 }
245 uint8_t get_log_subscription_level() const { return this->flags_.log_subscription; }
246
247 // Get client API version for feature detection
248 bool client_supports_api_version(uint16_t major, uint16_t minor) const {
249 return this->client_api_version_major_ > major ||
250 (this->client_api_version_major_ == major && this->client_api_version_minor_ >= minor);
251 }
252
253 void on_fatal_error() override;
254#ifdef USE_API_PASSWORD
255 void on_unauthenticated_access() override;
256#endif
257 void on_no_setup_connection() override;
258 ProtoWriteBuffer create_buffer(uint32_t reserve_size) override {
259 // FIXME: ensure no recursive writes can happen
260
261 // Get header padding size - used for both reserve and insert
262 uint8_t header_padding = this->helper_->frame_header_padding();
263 // Get shared buffer from parent server
264 std::vector<uint8_t> &shared_buf = this->parent_->get_shared_buffer_ref();
265 this->prepare_first_message_buffer(shared_buf, header_padding,
266 reserve_size + header_padding + this->helper_->frame_footer_size());
267 return {&shared_buf};
268 }
269
270 void prepare_first_message_buffer(std::vector<uint8_t> &shared_buf, size_t header_padding, size_t total_size) {
271 shared_buf.clear();
272 // Reserve space for header padding + message + footer
273 // - Header padding: space for protocol headers (7 bytes for Noise, 6 for Plaintext)
274 // - Footer: space for MAC (16 bytes for Noise, 0 for Plaintext)
275 shared_buf.reserve(total_size);
276 // Resize to add header padding so message encoding starts at the correct position
277 shared_buf.resize(header_padding);
278 }
279
280 bool try_to_clear_buffer(bool log_out_of_space);
281 bool send_buffer(ProtoWriteBuffer buffer, uint8_t message_type) override;
282
283 const std::string &get_name() const { return this->client_info_.name; }
284 const std::string &get_peername() const { return this->client_info_.peername; }
285
286 protected:
287 // Helper function to handle authentication completion
289
290#ifdef USE_API_HOMEASSISTANT_STATES
292#endif
293
294 // Non-template helper to encode any ProtoMessage
295 static uint16_t encode_message_to_buffer(ProtoMessage &msg, uint8_t message_type, APIConnection *conn,
296 uint32_t remaining_size, bool is_single);
297
298 // Helper to fill entity state base and encode message
299 static uint16_t fill_and_encode_entity_state(EntityBase *entity, StateResponseProtoMessage &msg, uint8_t message_type,
300 APIConnection *conn, uint32_t remaining_size, bool is_single) {
301 msg.key = entity->get_object_id_hash();
302#ifdef USE_DEVICES
303 msg.device_id = entity->get_device_id();
304#endif
305 return encode_message_to_buffer(msg, message_type, conn, remaining_size, is_single);
306 }
307
308 // Helper to fill entity info base and encode message
309 static uint16_t fill_and_encode_entity_info(EntityBase *entity, InfoResponseProtoMessage &msg, uint8_t message_type,
310 APIConnection *conn, uint32_t remaining_size, bool is_single) {
311 // Set common fields that are shared by all entity types
312 msg.key = entity->get_object_id_hash();
313 // Try to use static reference first to avoid allocation
314 StringRef static_ref = entity->get_object_id_ref_for_api_();
315 // Store dynamic string outside the if-else to maintain lifetime
316 std::string object_id;
317 if (!static_ref.empty()) {
318 msg.set_object_id(static_ref);
319 } else {
320 // Dynamic case - need to allocate
321 object_id = entity->get_object_id();
322 msg.set_object_id(StringRef(object_id));
323 }
324
325 if (entity->has_own_name()) {
326 msg.set_name(entity->get_name());
327 }
328
329 // Set common EntityBase properties
330#ifdef USE_ENTITY_ICON
331 msg.set_icon(entity->get_icon_ref());
332#endif
334 msg.entity_category = static_cast<enums::EntityCategory>(entity->get_entity_category());
335#ifdef USE_DEVICES
336 msg.device_id = entity->get_device_id();
337#endif
338 return encode_message_to_buffer(msg, message_type, conn, remaining_size, is_single);
339 }
340
341#ifdef USE_VOICE_ASSISTANT
342 // Helper to check voice assistant validity and connection ownership
343 inline bool check_voice_assistant_api_connection_() const;
344#endif
345
346 // Helper method to process multiple entities from an iterator in a batch
347 template<typename Iterator> void process_iterator_batch_(Iterator &iterator) {
348 size_t initial_size = this->deferred_batch_.size();
349 while (!iterator.completed() && (this->deferred_batch_.size() - initial_size) < MAX_INITIAL_PER_BATCH) {
350 iterator.advance();
351 }
352
353 // If the batch is full, process it immediately
354 // Note: iterator.advance() already calls schedule_batch_() via schedule_message_()
355 if (this->deferred_batch_.size() >= MAX_INITIAL_PER_BATCH) {
356 this->process_batch_();
357 }
358 }
359
360#ifdef USE_BINARY_SENSOR
361 static uint16_t try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
362 bool is_single);
363 static uint16_t try_send_binary_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
364 bool is_single);
365#endif
366#ifdef USE_COVER
367 static uint16_t try_send_cover_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
368 bool is_single);
369 static uint16_t try_send_cover_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
370#endif
371#ifdef USE_FAN
372 static uint16_t try_send_fan_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
373 static uint16_t try_send_fan_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
374#endif
375#ifdef USE_LIGHT
376 static uint16_t try_send_light_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
377 bool is_single);
378 static uint16_t try_send_light_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
379#endif
380#ifdef USE_SENSOR
381 static uint16_t try_send_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
382 bool is_single);
383 static uint16_t try_send_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
384 bool is_single);
385#endif
386#ifdef USE_SWITCH
387 static uint16_t try_send_switch_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
388 bool is_single);
389 static uint16_t try_send_switch_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
390 bool is_single);
391#endif
392#ifdef USE_TEXT_SENSOR
393 static uint16_t try_send_text_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
394 bool is_single);
395 static uint16_t try_send_text_sensor_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
396 bool is_single);
397#endif
398#ifdef USE_CLIMATE
399 static uint16_t try_send_climate_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
400 bool is_single);
401 static uint16_t try_send_climate_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
402 bool is_single);
403#endif
404#ifdef USE_NUMBER
405 static uint16_t try_send_number_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
406 bool is_single);
407 static uint16_t try_send_number_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
408 bool is_single);
409#endif
410#ifdef USE_DATETIME_DATE
411 static uint16_t try_send_date_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
412 static uint16_t try_send_date_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
413#endif
414#ifdef USE_DATETIME_TIME
415 static uint16_t try_send_time_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
416 static uint16_t try_send_time_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
417#endif
418#ifdef USE_DATETIME_DATETIME
419 static uint16_t try_send_datetime_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
420 bool is_single);
421 static uint16_t try_send_datetime_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
422 bool is_single);
423#endif
424#ifdef USE_TEXT
425 static uint16_t try_send_text_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
426 static uint16_t try_send_text_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
427#endif
428#ifdef USE_SELECT
429 static uint16_t try_send_select_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
430 bool is_single);
431 static uint16_t try_send_select_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
432 bool is_single);
433#endif
434#ifdef USE_BUTTON
435 static uint16_t try_send_button_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
436 bool is_single);
437#endif
438#ifdef USE_LOCK
439 static uint16_t try_send_lock_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
440 static uint16_t try_send_lock_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
441#endif
442#ifdef USE_VALVE
443 static uint16_t try_send_valve_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
444 bool is_single);
445 static uint16_t try_send_valve_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
446#endif
447#ifdef USE_MEDIA_PLAYER
448 static uint16_t try_send_media_player_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
449 bool is_single);
450 static uint16_t try_send_media_player_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
451 bool is_single);
452#endif
453#ifdef USE_ALARM_CONTROL_PANEL
454 static uint16_t try_send_alarm_control_panel_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
455 bool is_single);
456 static uint16_t try_send_alarm_control_panel_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
457 bool is_single);
458#endif
459#ifdef USE_EVENT
460 static uint16_t try_send_event_response(event::Event *event, const char *event_type, APIConnection *conn,
461 uint32_t remaining_size, bool is_single);
462 static uint16_t try_send_event_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single);
463#endif
464#ifdef USE_UPDATE
465 static uint16_t try_send_update_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
466 bool is_single);
467 static uint16_t try_send_update_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
468 bool is_single);
469#endif
470#ifdef USE_CAMERA
471 static uint16_t try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
472 bool is_single);
473#endif
474
475 // Method for ListEntitiesDone batching
476 static uint16_t try_send_list_info_done(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
477 bool is_single);
478
479 // Method for DisconnectRequest batching
480 static uint16_t try_send_disconnect_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
481 bool is_single);
482
483 // Batch message method for ping requests
484 static uint16_t try_send_ping_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
485 bool is_single);
486
487 // === Optimal member ordering for 32-bit systems ===
488
489 // Group 1: Pointers (4 bytes each on 32-bit)
490 std::unique_ptr<APIFrameHelper> helper_;
492
493 // Group 2: Larger objects (must be 4-byte aligned)
494 // These contain vectors/pointers internally, so putting them early ensures good alignment
497#ifdef USE_CAMERA
498 std::unique_ptr<camera::CameraImageReader> image_reader_;
499#endif
500
501 // Group 3: Client info struct (24 bytes on 32-bit: 2 strings × 12 bytes each)
503
504 // Group 4: 4-byte types
506#ifdef USE_API_HOMEASSISTANT_STATES
508#endif
509
510 // Function pointer type for message encoding
511 using MessageCreatorPtr = uint16_t (*)(EntityBase *, APIConnection *, uint32_t remaining_size, bool is_single);
512
514 public:
515 MessageCreator(MessageCreatorPtr ptr) { data_.function_ptr = ptr; }
516 explicit MessageCreator(const char *str_value) { data_.const_char_ptr = str_value; }
517
518 // Call operator - uses message_type to determine union type
519 uint16_t operator()(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single,
520 uint8_t message_type) const;
521
522 private:
523 union Data {
524 MessageCreatorPtr function_ptr;
525 const char *const_char_ptr;
526 } data_; // 4 bytes on 32-bit, 8 bytes on 64-bit
527 };
528
529 // Generic batching mechanism for both state updates and entity info
531 struct BatchItem {
532 EntityBase *entity; // Entity pointer
533 MessageCreator creator; // Function that creates the message when needed
534 uint8_t message_type; // Message type for overhead calculation (max 255)
535 uint8_t estimated_size; // Estimated message size (max 255 bytes)
536
537 // Constructor for creating BatchItem
540 };
541
542 std::vector<BatchItem> items;
543 uint32_t batch_start_time{0};
544
545 // No pre-allocation - log connections never use batching, and for
546 // connections that do, buffers are released after initial sync anyway
547
548 // Add item to the batch
549 void add_item(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size);
550 // Add item to the front of the batch (for high priority messages like ping)
551 void add_item_front(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size);
552
553 // Clear all items
554 void clear() {
555 items.clear();
557 }
558
559 // Remove processed items from the front
560 void remove_front(size_t count) { items.erase(items.begin(), items.begin() + count); }
561
562 bool empty() const { return items.empty(); }
563 size_t size() const { return items.size(); }
564 const BatchItem &operator[](size_t index) const { return items[index]; }
565 // Release excess capacity - only releases if items already empty
567 // Safe to call: batch is processed before release_buffer is called,
568 // and if any items remain (partial processing), we must not clear them.
569 // Use swap trick since shrink_to_fit() is non-binding and may be ignored.
570 if (items.empty()) {
571 std::vector<BatchItem>().swap(items);
572 }
573 }
574 };
575
576 // DeferredBatch here (16 bytes, 4-byte aligned)
578
579 // ConnectionState enum for type safety
580 enum class ConnectionState : uint8_t {
582 CONNECTED = 1,
583 AUTHENTICATED = 2,
584 };
585
586 // Group 5: Pack all small members together to minimize padding
587 // This group starts at a 4-byte boundary after DeferredBatch
588 struct APIFlags {
589 // Connection state only needs 2 bits (3 states)
590 uint8_t connection_state : 2;
591 // Log subscription needs 3 bits (log levels 0-7)
592 uint8_t log_subscription : 3;
593 // Boolean flags (1 bit each)
594 uint8_t remove : 1;
596 uint8_t sent_ping : 1;
597
599 uint8_t next_close : 1;
600 uint8_t batch_scheduled : 1;
601 uint8_t batch_first_message : 1; // For batch buffer allocation
602 uint8_t should_try_send_immediately : 1; // True after initial states are sent
603#ifdef HAS_PROTO_MESSAGE_DUMP
604 uint8_t log_only_mode : 1;
605#endif
606 } flags_{}; // 2 bytes total
607
608 // 2-byte types immediately after flags_ (no padding between them)
611 // Total: 2 (flags) + 2 + 2 = 6 bytes, then 2 bytes padding to next 4-byte boundary
612
613 uint32_t get_batch_delay_ms_() const;
614 // Message will use 8 more bytes than the minimum size, and typical
615 // MTU is 1500. Sometimes users will see as low as 1460 MTU.
616 // If its IPv6 the header is 40 bytes, and if its IPv4
617 // the header is 20 bytes. So we have 1460 - 40 = 1420 bytes
618 // available for the payload. But we also need to add the size of
619 // the protobuf overhead, which is 8 bytes.
620 //
621 // To be safe we pick 1390 bytes as the maximum size
622 // to send in one go. This is the maximum size of a single packet
623 // that can be sent over the network.
624 // This is to avoid fragmentation of the packet.
625 static constexpr size_t MAX_BATCH_PACKET_SIZE = 1390; // MTU
626
627 bool schedule_batch_();
628 void process_batch_();
630 this->deferred_batch_.clear();
631 this->flags_.batch_scheduled = false;
632 }
633
634#ifdef HAS_PROTO_MESSAGE_DUMP
635 // Helper to log a proto message from a MessageCreator object
636 void log_proto_message_(EntityBase *entity, const MessageCreator &creator, uint8_t message_type) {
637 this->flags_.log_only_mode = true;
638 creator(entity, this, MAX_BATCH_PACKET_SIZE, true, message_type);
639 this->flags_.log_only_mode = false;
640 }
641
643 // Use the helper to log the message
644 this->log_proto_message_(item.entity, item.creator, item.message_type);
645 }
646#endif
647
648 // Helper to check if a message type should bypass batching
649 // Returns true if:
650 // 1. It's an UpdateStateResponse (always send immediately to handle cases where
651 // the main loop is blocked, e.g., during OTA updates)
652 // 2. It's an EventResponse (events are edge-triggered - every occurrence matters)
653 // 3. OR: User has opted into immediate sending (should_try_send_immediately = true
654 // AND batch_delay = 0)
655 inline bool should_send_immediately_(uint8_t message_type) const {
656 return (
657#ifdef USE_UPDATE
658 message_type == UpdateStateResponse::MESSAGE_TYPE ||
659#endif
660#ifdef USE_EVENT
661 message_type == EventResponse::MESSAGE_TYPE ||
662#endif
663 (this->flags_.should_try_send_immediately && this->get_batch_delay_ms_() == 0));
664 }
665
666 // Helper method to send a message either immediately or via batching
667 // Tries immediate send if should_send_immediately_() returns true and buffer has space
668 // Falls back to batching if immediate send fails or isn't applicable
669 bool send_message_smart_(EntityBase *entity, MessageCreatorPtr creator, uint8_t message_type,
670 uint8_t estimated_size) {
671 if (this->should_send_immediately_(message_type) && this->helper_->can_write_without_blocking()) {
672 // Now actually encode and send
673 if (creator(entity, this, MAX_BATCH_PACKET_SIZE, true) &&
674 this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, message_type)) {
675#ifdef HAS_PROTO_MESSAGE_DUMP
676 // Log the message in verbose mode
677 this->log_proto_message_(entity, MessageCreator(creator), message_type);
678#endif
679 return true;
680 }
681
682 // If immediate send failed, fall through to batching
683 }
684
685 // Fall back to scheduled batching
686 return this->schedule_message_(entity, creator, message_type, estimated_size);
687 }
688
689 // Overload for MessageCreator (used by events which need to capture event_type)
690 bool send_message_smart_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size) {
691 // Try to send immediately if message type should bypass batching and buffer has space
692 if (this->should_send_immediately_(message_type) && this->helper_->can_write_without_blocking()) {
693 // Now actually encode and send
694 if (creator(entity, this, MAX_BATCH_PACKET_SIZE, true, message_type) &&
695 this->send_buffer(ProtoWriteBuffer{&this->parent_->get_shared_buffer_ref()}, message_type)) {
696#ifdef HAS_PROTO_MESSAGE_DUMP
697 // Log the message in verbose mode
698 this->log_proto_message_(entity, creator, message_type);
699#endif
700 return true;
701 }
702
703 // If immediate send failed, fall through to batching
704 }
705
706 // Fall back to scheduled batching
707 return this->schedule_message_(entity, creator, message_type, estimated_size);
708 }
709
710 // Helper function to schedule a deferred message with known message type
711 bool schedule_message_(EntityBase *entity, MessageCreator creator, uint8_t message_type, uint8_t estimated_size) {
712 this->deferred_batch_.add_item(entity, creator, message_type, estimated_size);
713 return this->schedule_batch_();
714 }
715
716 // Overload for function pointers (for info messages and current state reads)
717 bool schedule_message_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type,
718 uint8_t estimated_size) {
719 return schedule_message_(entity, MessageCreator(function_ptr), message_type, estimated_size);
720 }
721
722 // Helper function to schedule a high priority message at the front of the batch
723 bool schedule_message_front_(EntityBase *entity, MessageCreatorPtr function_ptr, uint8_t message_type,
724 uint8_t estimated_size) {
725 this->deferred_batch_.add_item_front(entity, MessageCreator(function_ptr), message_type, estimated_size);
726 return this->schedule_batch_();
727 }
728
729 // Helper function to log API errors with errno
730 void log_warning_(const LogString *message, APIError err);
731 // Helper to handle fatal errors with logging
732 inline void fatal_error_with_log_(const LogString *message, APIError err) {
733 this->on_fatal_error();
734 this->log_warning_(message, err);
735 }
736};
737
738} // namespace esphome::api
739#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:72
uint32_t get_device_id() const
Definition entity_base.h:83
bool is_disabled_by_default() const
Definition entity_base.h:57
std::string get_object_id() const
EntityCategory get_entity_category() const
Definition entity_base.h:61
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
uint16_t operator()(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single, uint8_t message_type) const
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 send_execute_service_response(uint32_t call_id, bool success, const std::string &error_message)
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:75
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:2844
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:1221
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:1114
void set_object_id(const StringRef &ref)
Definition api_pb2.h:300
enums::EntityCategory entity_category
Definition api_pb2.h:309
void set_icon(const StringRef &ref)
Definition api_pb2.h:307
void set_name(const StringRef &ref)
Definition api_pb2.h:303
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:601
static constexpr uint8_t ESTIMATED_SIZE
Definition api_pb2.h:602
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:2987
Base class for all binary_sensor-type classes.
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:177
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:91
Base class for all locks.
Definition lock.h:111
Base-class for all numbers.
Definition number.h:29
Base-class for all selects.
Definition select.h:30
Base-class for all sensors.
Definition sensor.h:43
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:106
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)