ESPHome 2026.1.2
Loading...
Searching...
No Matches
api_server.cpp
Go to the documentation of this file.
1#include "api_server.h"
2#ifdef USE_API
3#include <cerrno>
4#include "api_connection.h"
9#include "esphome/core/hal.h"
10#include "esphome/core/log.h"
11#include "esphome/core/util.h"
13#ifdef USE_API_HOMEASSISTANT_SERVICES
15#endif
16
17#ifdef USE_LOGGER
19#endif
20
21#include <algorithm>
22#include <utility>
23
24namespace esphome::api {
25
26static const char *const TAG = "api";
27
28// APIServer
29APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
30
32 global_api_server = this;
33 // Pre-allocate shared write buffer
34 shared_write_buffer_.reserve(64);
35}
36
39
40#ifdef USE_API_NOISE
41 uint32_t hash = 88491486UL;
42
44
45#ifndef USE_API_NOISE_PSK_FROM_YAML
46 // Only load saved PSK if not set from YAML
47 SavedNoisePsk noise_pref_saved{};
48 if (this->noise_pref_.load(&noise_pref_saved)) {
49 ESP_LOGD(TAG, "Loaded saved Noise PSK");
50 this->set_noise_psk(noise_pref_saved.psk);
51 }
52#endif
53#endif
54
55 this->socket_ = socket::socket_ip_loop_monitored(SOCK_STREAM, 0); // monitored for incoming connections
56 if (this->socket_ == nullptr) {
57 ESP_LOGW(TAG, "Could not create socket");
58 this->mark_failed();
59 return;
60 }
61 int enable = 1;
62 int err = this->socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
63 if (err != 0) {
64 ESP_LOGW(TAG, "Socket unable to set reuseaddr: errno %d", err);
65 // we can still continue
66 }
67 err = this->socket_->setblocking(false);
68 if (err != 0) {
69 ESP_LOGW(TAG, "Socket unable to set nonblocking mode: errno %d", err);
70 this->mark_failed();
71 return;
72 }
73
74 struct sockaddr_storage server;
75
76 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
77 if (sl == 0) {
78 ESP_LOGW(TAG, "Socket unable to set sockaddr: errno %d", errno);
79 this->mark_failed();
80 return;
81 }
82
83 err = this->socket_->bind((struct sockaddr *) &server, sl);
84 if (err != 0) {
85 ESP_LOGW(TAG, "Socket unable to bind: errno %d", errno);
86 this->mark_failed();
87 return;
88 }
89
90 err = this->socket_->listen(this->listen_backlog_);
91 if (err != 0) {
92 ESP_LOGW(TAG, "Socket unable to listen: errno %d", errno);
93 this->mark_failed();
94 return;
95 }
96
97#ifdef USE_LOGGER
98 if (logger::global_logger != nullptr) {
100 }
101#endif
102
103#ifdef USE_CAMERA
104 if (camera::Camera::instance() != nullptr && !camera::Camera::instance()->is_internal()) {
106 }
107#endif
108
109 // Initialize last_connected_ for reboot timeout tracking
111 // Set warning status if reboot timeout is enabled
112 if (this->reboot_timeout_ != 0) {
113 this->status_set_warning();
114 }
115}
116
118 // Accept new clients only if the socket exists and has incoming connections
119 if (this->socket_ && this->socket_->ready()) {
120 while (true) {
121 struct sockaddr_storage source_addr;
122 socklen_t addr_len = sizeof(source_addr);
123
124 auto sock = this->socket_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
125 if (!sock)
126 break;
127
128 char peername[socket::SOCKADDR_STR_LEN];
129 sock->getpeername_to(peername);
130
131 // Check if we're at the connection limit
132 if (this->clients_.size() >= this->max_connections_) {
133 ESP_LOGW(TAG, "Max connections (%d), rejecting %s", this->max_connections_, peername);
134 // Immediately close - socket destructor will handle cleanup
135 sock.reset();
136 continue;
137 }
138
139 ESP_LOGD(TAG, "Accept %s", peername);
140
141 auto *conn = new APIConnection(std::move(sock), this);
142 this->clients_.emplace_back(conn);
143 conn->start();
144
145 // First client connected - clear warning and update timestamp
146 if (this->clients_.size() == 1 && this->reboot_timeout_ != 0) {
147 this->status_clear_warning();
149 }
150 }
151 }
152
153 if (this->clients_.empty()) {
154 // Check reboot timeout - done in loop to avoid scheduler heap churn
155 // (cancelled scheduler items sit in heap memory until their scheduled time)
156 if (this->reboot_timeout_ != 0) {
157 const uint32_t now = App.get_loop_component_start_time();
158 if (now - this->last_connected_ > this->reboot_timeout_) {
159 ESP_LOGE(TAG, "No clients; rebooting");
160 App.reboot();
161 }
162 }
163 return;
164 }
165
166 // Process clients and remove disconnected ones in a single pass
167 // Check network connectivity once for all clients
168 if (!network::is_connected()) {
169 // Network is down - disconnect all clients
170 for (auto &client : this->clients_) {
171 client->on_fatal_error();
172 client->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR("Network down; disconnect"));
173 }
174 // Continue to process and clean up the clients below
175 }
176
177 size_t client_index = 0;
178 while (client_index < this->clients_.size()) {
179 auto &client = this->clients_[client_index];
180
181 if (!client->flags_.remove) {
182 // Common case: process active client
183 client->loop();
184 client_index++;
185 continue;
186 }
187
188 // Rare case: handle disconnection
189#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
191#endif
192 ESP_LOGV(TAG, "Remove connection %s", client->get_name());
193
194#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
195 // Save client info before removal for the trigger
196 std::string client_name(client->get_name());
197 std::string client_peername(client->get_peername());
198#endif
199
200 // Swap with the last element and pop (avoids expensive vector shifts)
201 if (client_index < this->clients_.size() - 1) {
202 std::swap(this->clients_[client_index], this->clients_.back());
203 }
204 this->clients_.pop_back();
205
206 // Last client disconnected - set warning and start tracking for reboot timeout
207 if (this->clients_.empty() && this->reboot_timeout_ != 0) {
208 this->status_set_warning();
210 }
211
212#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
213 // Fire trigger after client is removed so api.connected reflects the true state
214 this->client_disconnected_trigger_->trigger(client_name, client_peername);
215#endif
216 // Don't increment client_index since we need to process the swapped element
217 }
218}
219
221 ESP_LOGCONFIG(TAG,
222 "Server:\n"
223 " Address: %s:%u\n"
224 " Listen backlog: %u\n"
225 " Max connections: %u",
227#ifdef USE_API_NOISE
228 ESP_LOGCONFIG(TAG, " Noise encryption: %s", YESNO(this->noise_ctx_.has_psk()));
229 if (!this->noise_ctx_.has_psk()) {
230 ESP_LOGCONFIG(TAG, " Supports encryption: YES");
231 }
232#else
233 ESP_LOGCONFIG(TAG, " Noise encryption: NO");
234#endif
235}
236
238
239// Macro for controller update dispatch
240#define API_DISPATCH_UPDATE(entity_type, entity_name) \
241 void APIServer::on_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
242 if (obj->is_internal()) \
243 return; \
244 for (auto &c : this->clients_) { \
245 if (c->flags_.state_subscription) \
246 c->send_##entity_name##_state(obj); \
247 } \
248 }
249
250#ifdef USE_BINARY_SENSOR
252#endif
253
254#ifdef USE_COVER
256#endif
257
258#ifdef USE_FAN
260#endif
261
262#ifdef USE_LIGHT
264#endif
265
266#ifdef USE_SENSOR
268#endif
269
270#ifdef USE_SWITCH
272#endif
273
274#ifdef USE_TEXT_SENSOR
276#endif
277
278#ifdef USE_CLIMATE
280#endif
281
282#ifdef USE_NUMBER
284#endif
285
286#ifdef USE_DATETIME_DATE
288#endif
289
290#ifdef USE_DATETIME_TIME
292#endif
293
294#ifdef USE_DATETIME_DATETIME
296#endif
297
298#ifdef USE_TEXT
300#endif
301
302#ifdef USE_SELECT
304#endif
305
306#ifdef USE_LOCK
308#endif
309
310#ifdef USE_VALVE
312#endif
313
314#ifdef USE_MEDIA_PLAYER
316#endif
317
318#ifdef USE_WATER_HEATER
320#endif
321
322#ifdef USE_EVENT
324 if (obj->is_internal())
325 return;
326 for (auto &c : this->clients_) {
327 if (c->flags_.state_subscription)
328 c->send_event(obj);
329 }
330}
331#endif
332
333#ifdef USE_UPDATE
334// Update is a special case - the method is called on_update, not on_update_update
336 if (obj->is_internal())
337 return;
338 for (auto &c : this->clients_) {
339 if (c->flags_.state_subscription)
340 c->send_update_state(obj);
341 }
342}
343#endif
344
345#ifdef USE_ZWAVE_PROXY
347 // We could add code to manage a second subscription type, but, since this message type is
348 // very infrequent and small, we simply send it to all clients
349 for (auto &c : this->clients_)
350 c->send_message(msg, api::ZWaveProxyRequest::MESSAGE_TYPE);
351}
352#endif
353
354#ifdef USE_IR_RF
355void APIServer::send_infrared_rf_receive_event([[maybe_unused]] uint32_t device_id, uint32_t key,
356 const std::vector<int32_t> *timings) {
358#ifdef USE_DEVICES
359 resp.device_id = device_id;
360#endif
361 resp.key = key;
362 resp.timings = timings;
363
364 for (auto &c : this->clients_)
365 c->send_infrared_rf_receive_event(resp);
366}
367#endif
368
369#ifdef USE_ALARM_CONTROL_PANEL
371#endif
372
374
375void APIServer::set_port(uint16_t port) { this->port_ = port; }
376
377void APIServer::set_batch_delay(uint16_t batch_delay) { this->batch_delay_ = batch_delay; }
378
379#ifdef USE_API_HOMEASSISTANT_SERVICES
381 for (auto &client : this->clients_) {
382 client->send_homeassistant_action(call);
383 }
384}
385#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
387 this->action_response_callbacks_.push_back({call_id, std::move(callback)});
388}
389
390void APIServer::handle_action_response(uint32_t call_id, bool success, StringRef error_message) {
391 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
392 if (it->call_id == call_id) {
393 auto callback = std::move(it->callback);
394 this->action_response_callbacks_.erase(it);
395 ActionResponse response(success, error_message);
396 callback(response);
397 return;
398 }
399 }
400}
401#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
402void APIServer::handle_action_response(uint32_t call_id, bool success, StringRef error_message,
403 const uint8_t *response_data, size_t response_data_len) {
404 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
405 if (it->call_id == call_id) {
406 auto callback = std::move(it->callback);
407 this->action_response_callbacks_.erase(it);
408 ActionResponse response(success, error_message, response_data, response_data_len);
409 callback(response);
410 return;
411 }
412 }
413}
414#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
415#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
416#endif // USE_API_HOMEASSISTANT_SERVICES
417
418#ifdef USE_API_HOMEASSISTANT_STATES
419// Helper to add subscription (reduces duplication)
420void APIServer::add_state_subscription_(const char *entity_id, const char *attribute, std::function<void(StringRef)> f,
421 bool once) {
423 .entity_id = entity_id, .attribute = attribute, .callback = std::move(f), .once = once,
424 // entity_id_dynamic_storage and attribute_dynamic_storage remain nullptr (no heap allocation)
425 });
426}
427
428// Helper to add subscription with heap-allocated strings (reduces duplication)
429void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
430 std::function<void(StringRef)> f, bool once) {
432 // Allocate heap storage for the strings
433 sub.entity_id_dynamic_storage = std::make_unique<std::string>(std::move(entity_id));
434 sub.entity_id = sub.entity_id_dynamic_storage->c_str();
435
436 if (attribute.has_value()) {
437 sub.attribute_dynamic_storage = std::make_unique<std::string>(std::move(attribute.value()));
438 sub.attribute = sub.attribute_dynamic_storage->c_str();
439 } else {
440 sub.attribute = nullptr;
441 }
442
443 sub.callback = std::move(f);
444 sub.once = once;
445 this->state_subs_.push_back(std::move(sub));
446}
447
448// New const char* overload (for internal components - zero allocation)
449void APIServer::subscribe_home_assistant_state(const char *entity_id, const char *attribute,
450 std::function<void(StringRef)> f) {
451 this->add_state_subscription_(entity_id, attribute, std::move(f), false);
452}
453
454void APIServer::get_home_assistant_state(const char *entity_id, const char *attribute,
455 std::function<void(StringRef)> f) {
456 this->add_state_subscription_(entity_id, attribute, std::move(f), true);
457}
458
459// std::string overload with StringRef callback (zero-allocation callback)
461 std::function<void(StringRef)> f) {
462 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
463}
464
465void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
466 std::function<void(StringRef)> f) {
467 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
468}
469
470// Legacy helper: wraps std::string callback and delegates to StringRef version
471void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
472 std::function<void(const std::string &)> f, bool once) {
473 // Wrap callback to convert StringRef -> std::string, then delegate
474 this->add_state_subscription_(std::move(entity_id), std::move(attribute),
475 std::function<void(StringRef)>([f = std::move(f)](StringRef state) { f(state.str()); }),
476 once);
477}
478
479// Legacy std::string overload (for custom_api_device.h - converts StringRef to std::string)
481 std::function<void(const std::string &)> f) {
482 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
483}
484
485void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
486 std::function<void(const std::string &)> f) {
487 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
488}
489
490const std::vector<APIServer::HomeAssistantStateSubscription> &APIServer::get_state_subs() const {
491 return this->state_subs_;
492}
493#endif
494
495uint16_t APIServer::get_port() const { return this->port_; }
496
497void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
498
499#ifdef USE_API_NOISE
500bool APIServer::update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg,
501 const LogString *fail_log_msg, const psk_t &active_psk, bool make_active) {
502 if (!this->noise_pref_.save(&new_psk)) {
503 ESP_LOGW(TAG, "%s", LOG_STR_ARG(fail_log_msg));
504 return false;
505 }
506 // ensure it's written immediately
507 if (!global_preferences->sync()) {
508 ESP_LOGW(TAG, "Failed to sync preferences");
509 return false;
510 }
511 ESP_LOGD(TAG, "%s", LOG_STR_ARG(save_log_msg));
512 if (make_active) {
513 this->set_timeout(100, [this, active_psk]() {
514 ESP_LOGW(TAG, "Disconnecting all clients to reset PSK");
515 this->set_noise_psk(active_psk);
516 for (auto &c : this->clients_) {
518 c->send_message(req, DisconnectRequest::MESSAGE_TYPE);
519 }
520 });
521 }
522 return true;
523}
524
525bool APIServer::save_noise_psk(psk_t psk, bool make_active) {
526#ifdef USE_API_NOISE_PSK_FROM_YAML
527 // When PSK is set from YAML, this function should never be called
528 // but if it is, reject the change
529 ESP_LOGW(TAG, "Key set in YAML");
530 return false;
531#else
532 auto &old_psk = this->noise_ctx_.get_psk();
533 if (std::equal(old_psk.begin(), old_psk.end(), psk.begin())) {
534 ESP_LOGW(TAG, "New PSK matches old");
535 return true;
536 }
537
538 SavedNoisePsk new_saved_psk{psk};
539 return this->update_noise_psk_(new_saved_psk, LOG_STR("Noise PSK saved"), LOG_STR("Failed to save Noise PSK"), psk,
540 make_active);
541#endif
542}
543bool APIServer::clear_noise_psk(bool make_active) {
544#ifdef USE_API_NOISE_PSK_FROM_YAML
545 // When PSK is set from YAML, this function should never be called
546 // but if it is, reject the change
547 ESP_LOGW(TAG, "Key set in YAML");
548 return false;
549#else
550 SavedNoisePsk empty_psk{};
551 psk_t empty{};
552 return this->update_noise_psk_(empty_psk, LOG_STR("Noise PSK cleared"), LOG_STR("Failed to clear Noise PSK"), empty,
553 make_active);
554#endif
555}
556#endif
557
558#ifdef USE_HOMEASSISTANT_TIME
560 for (auto &client : this->clients_) {
561 if (!client->flags_.remove && client->is_authenticated()) {
562 client->send_time_request();
563 return; // Only request from one client to avoid clock conflicts
564 }
565 }
566}
567#endif
568
569bool APIServer::is_connected(bool state_subscription_only) const {
570 if (!state_subscription_only) {
571 return !this->clients_.empty();
572 }
573
574 for (const auto &client : this->clients_) {
575 if (client->flags_.state_subscription) {
576 return true;
577 }
578 }
579 return false;
580}
581
582#ifdef USE_LOGGER
583void APIServer::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
584 if (this->shutting_down_) {
585 // Don't try to send logs during shutdown
586 // as it could result in a recursion and
587 // we would be filling a buffer we are trying to clear
588 return;
589 }
590 for (auto &c : this->clients_) {
591 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
592 c->try_send_log_message(level, tag, message, message_len);
593 }
594}
595#endif
596
597#ifdef USE_CAMERA
598void APIServer::on_camera_image(const std::shared_ptr<camera::CameraImage> &image) {
599 for (auto &c : this->clients_) {
600 if (!c->flags_.remove)
601 c->set_camera_state(image);
602 }
603}
604#endif
605
607 this->shutting_down_ = true;
608
609 // Close the listening socket to prevent new connections
610 if (this->socket_) {
611 this->socket_->close();
612 this->socket_ = nullptr;
613 }
614
615 // Change batch delay to 5ms for quick flushing during shutdown
616 this->batch_delay_ = 5;
617
618 // Send disconnect requests to all connected clients
619 for (auto &c : this->clients_) {
621 if (!c->send_message(req, DisconnectRequest::MESSAGE_TYPE)) {
622 // If we can't send the disconnect request directly (tx_buffer full),
623 // schedule it at the front of the batch so it will be sent with priority
624 c->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
625 }
626 }
627}
628
630 // If network is disconnected, no point trying to flush buffers
631 if (!network::is_connected()) {
632 return true;
633 }
634 this->loop();
635
636 // Return true only when all clients have been torn down
637 return this->clients_.empty();
638}
639
640#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
641// Timeout for action calls - matches aioesphomeapi client timeout (default 30s)
642// Can be overridden via USE_API_ACTION_CALL_TIMEOUT_MS define for testing
643#ifndef USE_API_ACTION_CALL_TIMEOUT_MS
644#define USE_API_ACTION_CALL_TIMEOUT_MS 30000 // NOLINT
645#endif
646
647uint32_t APIServer::register_active_action_call(uint32_t client_call_id, APIConnection *conn) {
648 uint32_t action_call_id = this->next_action_call_id_++;
649 // Handle wraparound (skip 0 as it means "no call")
650 if (this->next_action_call_id_ == 0) {
651 this->next_action_call_id_ = 1;
652 }
653 this->active_action_calls_.push_back({action_call_id, client_call_id, conn});
654
655 // Schedule automatic cleanup after timeout (client will have given up by then)
656 // Uses numeric ID overload to avoid heap allocation from str_sprintf
657 this->set_timeout(action_call_id, USE_API_ACTION_CALL_TIMEOUT_MS, [this, action_call_id]() {
658 ESP_LOGD(TAG, "Action call %u timed out", action_call_id);
659 this->unregister_active_action_call(action_call_id);
660 });
661
662 return action_call_id;
663}
664
665void APIServer::unregister_active_action_call(uint32_t action_call_id) {
666 // Cancel the timeout for this action call (uses numeric ID overload)
667 this->cancel_timeout(action_call_id);
668
669 // Swap-and-pop is more efficient than remove_if for unordered vectors
670 for (size_t i = 0; i < this->active_action_calls_.size(); i++) {
671 if (this->active_action_calls_[i].action_call_id == action_call_id) {
672 std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
673 this->active_action_calls_.pop_back();
674 return;
675 }
676 }
677}
678
680 // Remove all active action calls for disconnected connection using swap-and-pop
681 for (size_t i = 0; i < this->active_action_calls_.size();) {
682 if (this->active_action_calls_[i].connection == conn) {
683 // Cancel the timeout for this action call (uses numeric ID overload)
684 this->cancel_timeout(this->active_action_calls_[i].action_call_id);
685
686 std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
687 this->active_action_calls_.pop_back();
688 // Don't increment i - need to check the swapped element
689 } else {
690 i++;
691 }
692 }
693}
694
695void APIServer::send_action_response(uint32_t action_call_id, bool success, StringRef error_message) {
696 for (auto &call : this->active_action_calls_) {
697 if (call.action_call_id == action_call_id) {
698 call.connection->send_execute_service_response(call.client_call_id, success, error_message);
699 return;
700 }
701 }
702 ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %u", action_call_id);
703}
704#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
705void APIServer::send_action_response(uint32_t action_call_id, bool success, StringRef error_message,
706 const uint8_t *response_data, size_t response_data_len) {
707 for (auto &call : this->active_action_calls_) {
708 if (call.action_call_id == action_call_id) {
709 call.connection->send_execute_service_response(call.client_call_id, success, error_message, response_data,
710 response_data_len);
711 return;
712 }
713 }
714 ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %u", action_call_id);
715}
716#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
717#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
718
719} // namespace esphome::api
720#endif
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
virtual void mark_failed()
Mark this component as failed.
void status_set_warning(const char *message=nullptr)
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:445
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") bool cancel_timeout(const std boo cancel_timeout)(const char *name)
Cancel a timeout function.
Definition component.h:465
void status_clear_warning()
static void register_controller(Controller *controller)
Register a controller to receive entity state updates.
bool save(const T *src)
Definition preferences.h:21
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
bool is_internal() const
Definition entity_base.h:76
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
void trigger(const Ts &...x)
Inform the parent automation that the event has triggered.
Definition automation.h:238
const psk_t & get_psk() const
void register_action_response_callback(uint32_t call_id, ActionResponseCallback callback)
std::vector< std::unique_ptr< APIConnection > > clients_
Definition api_server.h:267
void send_infrared_rf_receive_event(uint32_t device_id, uint32_t key, const std::vector< int32_t > *timings)
void on_camera_image(const std::shared_ptr< camera::CameraImage > &image) override
void set_port(uint16_t port)
void dump_config() override
void unregister_active_action_calls_for_connection(APIConnection *conn)
void handle_disconnect(APIConnection *conn)
void set_batch_delay(uint16_t batch_delay)
void set_reboot_timeout(uint32_t reboot_timeout)
void add_state_subscription_(const char *entity_id, const char *attribute, std::function< void(StringRef)> f, bool once)
void send_action_response(uint32_t action_call_id, bool success, StringRef error_message)
bool save_noise_psk(psk_t psk, bool make_active=true)
void setup() override
bool teardown() override
APINoiseContext noise_ctx_
Definition api_server.h:305
void unregister_active_action_call(uint32_t action_call_id)
void send_homeassistant_action(const HomeassistantActionRequest &call)
void on_event(event::Event *obj) override
void on_update(update::UpdateEntity *obj) override
std::vector< PendingActionResponse > action_response_callbacks_
Definition api_server.h:291
const std::vector< HomeAssistantStateSubscription > & get_state_subs() const
void subscribe_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> f)
Trigger< std::string, std::string > * client_disconnected_trigger_
Definition api_server.h:259
std::vector< uint8_t > shared_write_buffer_
Definition api_server.h:268
void handle_action_response(uint32_t call_id, bool success, StringRef error_message)
std::function< void(const class ActionResponse &)> ActionResponseCallback
Definition api_server.h:141
bool update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg, const LogString *fail_log_msg, const psk_t &active_psk, bool make_active)
bool is_connected(bool state_subscription_only=false) const
ESPPreferenceObject noise_pref_
Definition api_server.h:306
std::vector< HomeAssistantStateSubscription > state_subs_
Definition api_server.h:270
void on_zwave_proxy_request(const esphome::api::ProtoMessage &msg)
bool clear_noise_psk(bool make_active=true)
uint16_t get_port() const
std::vector< ActiveActionCall > active_action_calls_
Definition api_server.h:282
void set_noise_psk(psk_t psk)
Definition api_server.h:77
void get_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> f)
float get_setup_priority() const override
std::unique_ptr< socket::Socket > socket_
Definition api_server.h:254
uint32_t register_active_action_call(uint32_t client_call_id, APIConnection *conn)
void on_shutdown() override
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len) override
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:393
static constexpr uint8_t ESTIMATED_SIZE
Definition api_pb2.h:394
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:3033
Base class for all binary_sensor-type classes.
virtual void add_listener(CameraListener *listener)=0
Add a listener to receive camera events.
static Camera * instance()
The singleton instance of the camera implementation.
Definition camera.cpp:19
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:182
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
void add_log_listener(LogListener *listener)
Register a log listener to receive log messages.
Definition logger.h:217
Base-class for all numbers.
Definition number.h:29
bool has_value() const
Definition optional.h:92
value_type const & value() const
Definition optional.h:94
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:106
const char * message
Definition component.cpp:38
uint16_t addr_len
bool state
Definition fan.h:0
uint32_t socklen_t
Definition headers.h:97
APIServer * global_api_server
API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor) API_DISPATCH_UPDATE(cover
std::array< uint8_t, 32 > psk_t
Logger * global_logger
const char * get_use_address()
Get the active network hostname.
Definition util.cpp:88
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.cpp:26
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.cpp:88
std::unique_ptr< Socket > socket_ip_loop_monitored(int type, int protocol)
Definition socket.cpp:102
socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port)
Set a sockaddr to the any address and specified port for the IP version used by socket_ip().
Definition socket.cpp:149
ESPPreferences * global_preferences
Application App
Global storage of Application pointer - only one Application can exist.
std::unique_ptr< std::string > entity_id_dynamic_storage
Definition api_server.h:203
std::unique_ptr< std::string > attribute_dynamic_storage
Definition api_server.h:204