ESPHome 2026.11.0b6
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 <cinttypes>
5#include "api_connection.h"
10#include "esphome/core/hal.h"
11#include "esphome/core/log.h"
12#include "esphome/core/util.h"
14#ifdef USE_API_HOMEASSISTANT_SERVICES
16#endif
17
18#ifdef USE_LOGGER
20#endif
21
22#include <algorithm>
23#include <utility>
24
25namespace esphome::api {
26
27ESPHOME_LOG_TAG(TAG, "api");
28
29// APIServer
30APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
31
32#ifdef USE_API_NOISE
33static constexpr uint32_t NOISE_PSK_PREF_HASH = 88491486UL;
34#endif
35
36#if defined(USE_API_NOISE) && defined(USE_OTA_ENCRYPTION_PROVISIONED)
38 SavedNoisePsk saved;
39#ifdef USE_PREFERENCE_KEY_LOOKUP
40 const bool loaded =
41 global_preferences->load_from_key(NOISE_PSK_PREF_HASH, reinterpret_cast<uint8_t *>(&saved), sizeof(saved));
42#else
43 // Slot backends need the reservation walk; it only lands on the record when the reservations before
44 // it match a normal boot, otherwise the type checked checksum fails the load
45 const bool loaded = global_preferences->make_preference<SavedNoisePsk>(NOISE_PSK_PREF_HASH, true).load(&saved);
46#endif
47 // The all-zeros record means no key
48 if (!loaded || noise::NoiseContext::is_all_zeros(saved.psk))
49 return false;
50 out = saved.psk;
51 return true;
52}
53#endif
54
56
57void APIServer::socket_failed_(const LogString *msg) {
58 ESP_LOGW(TAG, "Socket %s: errno %d", LOG_STR_ARG(msg), errno);
59 this->destroy_socket_();
60#ifdef USE_API_OUTGOING_CONNECTION
61 // Dial-out needs no listener; degrade instead of stopping the component
62 this->status_set_error(LOG_STR("listen socket failed"));
63#else
64 this->mark_failed();
65#endif
66}
67
69#if defined(USE_API_HOMEASSISTANT_STATES) && defined(HOMEASSISTANT_STATE_SUBSCRIPTION_COUNT)
70 this->state_subs_.reserve(HOMEASSISTANT_STATE_SUBSCRIPTION_COUNT);
71#endif
72#ifdef USE_API_NOISE
73 // Always reserve the slot: flash preferences are positional on esp8266, so
74 // a yaml key build must keep the layout of a runtime key build
75 this->noise_pref_ = global_preferences->make_preference<SavedNoisePsk>(NOISE_PSK_PREF_HASH, true);
76#ifndef USE_API_NOISE_PSK_FROM_YAML
77 // A cleared record loads fine but holds no key
78 if (this->load_and_apply_noise_psk_() && this->noise_ctx_.has_psk()) {
79 ESP_LOGD(TAG, "Loaded saved Noise PSK");
80 }
81#endif
82#endif
83
84#ifdef USE_LOGGER
85 if (logger::global_logger != nullptr) {
87 this, [](void *self, uint8_t level, const char *tag, const char *message, size_t message_len) {
88 static_cast<APIServer *>(self)->on_log(level, tag, message, message_len);
89 });
90 }
91#endif
92
93#ifdef USE_CAMERA
94 if (camera::Camera::instance() != nullptr && !camera::Camera::instance()->is_internal()) {
96 }
97#endif
98
99 // Initialize last_connected_ for reboot timeout tracking
101#if defined(USE_PROVISIONING) && defined(USE_API_NOISE)
102 // Register with the provisioning manager (provisioning:) as a source and
103 // report our current state (provisioned == an encryption key is set). When the
104 // window closes, disconnect any client still attempting to provision so it learns
105 // the reason. The manager owns the timeout, window state and on_timeout automation.
109 this->noise_ctx_.has_psk());
111 for (auto &c : this->active_clients()) {
114 // Best-effort: if the send buffer is full the reason is dropped, but the
115 // client still learns the window is closed when it reconnects (rejected at
116 // hello) or via the socket close.
117 if (!c->send_message(req)) {
118 API_LOG_MSG_DROPPED(TAG, "Disconnect request");
119 }
120 }
121 });
122 }
123#endif
124 // Set warning status if reboot timeout is enabled (suppressed while provisioning
125 // is pending so the device waits to be onboarded instead of rebooting).
126 if (this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
127 this->status_set_warning(LOG_STR("waiting for client connection"));
128 }
129#ifdef USE_API_OUTGOING_CONNECTION
130 this->outgoing_conn_.setup();
131#endif
132
133 // Listener last: on failure socket_failed_() returns early, and an
134 // outgoing_connection build keeps dialing out without one
135 this->socket_ = socket::socket_ip_loop_monitored(SOCK_STREAM, 0).release(); // monitored for incoming connections
136 if (this->socket_ == nullptr) {
137 this->socket_failed_(LOG_STR("creation"));
138 return;
139 }
140 int enable = 1;
141 int err = this->socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
142 if (err != 0) {
143 ESP_LOGW(TAG, "Socket reuseaddr: errno %d", errno);
144 // we can still continue
145 }
146 err = this->socket_->setblocking(false);
147 if (err != 0) {
148 this->socket_failed_(LOG_STR("nonblocking"));
149 return;
150 }
151
152 struct sockaddr_storage server;
153
154 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
155 if (sl == 0) {
156 this->socket_failed_(LOG_STR("set sockaddr"));
157 return;
158 }
159
160 err = this->socket_->bind((struct sockaddr *) &server, sl);
161 if (err != 0) {
162 this->socket_failed_(LOG_STR("bind"));
163 return;
164 }
165
166 err = this->socket_->listen(this->listen_backlog_);
167 if (err != 0) {
168 this->socket_failed_(LOG_STR("listen"));
169 }
170}
171
173 // Accept new clients only if the socket exists and has incoming connections
174 if (this->socket_ && this->socket_->ready()) {
175 this->accept_new_connections_();
176 }
177
178 const bool connected = network::is_connected();
179#ifdef USE_NOISE_SPARE_EPHEMERAL
180 if (connected && !noise::has_spare_ephemeral()) {
182 }
183#endif
184
185#ifdef USE_API_OUTGOING_CONNECTION
186 if (!this->shutting_down_) {
187 this->outgoing_conn_.loop(this);
188 }
189#endif
190
191 if (this->api_connection_count_ == 0) {
192 // Check reboot timeout - done in loop to avoid scheduler heap churn
193 // (cancelled scheduler items sit in heap memory until their scheduled time).
194 // Suppressed while a provisioning window is pending so the device waits to be
195 // onboarded / reset instead of rebooting itself; resumes once provisioned.
196 if (this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
198 if (now - this->last_connected_ > this->reboot_timeout_) {
199 ESP_LOGE(TAG, "No clients; rebooting");
200 App.reboot();
201 }
202 }
203 return;
204 }
205
206 // Process clients and remove disconnected ones in a single pass
207 if (!connected) {
208 // Network is down - disconnect all clients
209 for (auto &client : this->active_clients()) {
210 client->on_fatal_error();
211 client->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR("Network down; disconnect"));
212 }
213 // Continue to process and clean up the clients below
214 }
215
216 uint8_t client_index = 0;
217 while (client_index < this->api_connection_count_) {
218 auto &client = this->clients_[client_index];
219
220 // Common case: process active client
221 if (!client->flags_.remove) {
222 client->loop();
223 }
224 // Handle disconnection promptly - close socket to free LWIP PCB
225 // resources and prevent retransmit crashes on ESP8266.
226 if (client->flags_.remove) {
227 // Rare case: handle disconnection (don't increment - swapped element needs processing)
228 this->remove_client_(client_index);
229 } else {
230 client_index++;
231 }
232 }
233}
234
235#ifdef USE_NOISE_SPARE_EPHEMERAL
236// An OTA handshake is not visible here and just pays the refill it triggered
239 for (auto &client : this->active_clients()) {
240 if (client->is_still_connecting(now)) {
241 return;
242 }
243 }
244 // Generating the key pair cannot be split across loop passes
247}
248#endif
249
250void APIServer::remove_client_(uint8_t client_index) {
251 auto &client = this->clients_[client_index];
252
253#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
255#endif
256 ESP_LOGV(TAG, "Remove connection %s", client->get_name());
257
258#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
259 // Save client info before closing socket and removal for the trigger
260 char peername_buf[socket::SOCKADDR_STR_LEN];
261 std::string client_name(client->get_name());
262 std::string client_peername(client->get_peername_to(peername_buf));
263#endif
264
265 // Read before the swap-and-reset below destroys the connection
266 const bool was_authenticated = client->is_authenticated();
267#ifdef USE_API_OUTGOING_CONNECTION
268 if (client->flags_.outgoing_connection_target) {
270 }
271 this->outgoing_conn_.on_client_removed(client.get(), was_authenticated);
272#endif
273
274 // Close socket now (was deferred from on_fatal_error to allow getpeername)
275 client->helper_->close();
276
277 // Swap-and-reset: move the removed client to the trailing slot and null it out so slots
278 // [api_connection_count_, N) remain nullptr.
279 const uint8_t last_index = this->api_connection_count_ - 1;
280 if (client_index < last_index) {
281 std::swap(this->clients_[client_index], this->clients_[last_index]);
282 }
283 // Drop the count before resetting the slot. reset() runs ~APIConnection(), which can reenter the
284 // server (e.g. voice_assistant unsubscribes in its disconnect trigger, publishing entity state ->
285 // on_*_update iterating active_clients()). Excluding the dying slot from the active range first
286 // keeps that reentrant iteration from dereferencing the now-null slot.
287 this->api_connection_count_--;
288 this->clients_[last_index].reset();
289
290 // Last client disconnected - set warning and start tracking for reboot timeout
291 // (suppressed while provisioning is pending - see loop()).
292 // Refresh on every authenticated removal, not just the last one, so an
293 // unauthenticated straggler removed later (e.g. a port scan, or a dial to
294 // a host that accepts TCP but never speaks the API) cannot discard a
295 // healthy session's timestamp and trigger a spurious reboot
296 if (was_authenticated) {
298 }
299 if (this->api_connection_count_ == 0 && this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
300 this->status_set_warning(LOG_STR("waiting for client connection"));
301 }
302
303#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
304 // Fire trigger after client is removed so api.connected reflects the true state
305 this->client_disconnected_trigger_.trigger(client_name, client_peername);
306#endif
307}
308
309void __attribute__((flatten)) APIServer::accept_new_connections_() {
310 while (true) {
311 struct sockaddr_storage source_addr;
312 socklen_t addr_len = sizeof(source_addr);
313
314 auto sock = this->socket_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
315 if (!sock)
316 break;
317
318 char peername[socket::SOCKADDR_STR_LEN];
319 sock->getpeername_to(peername);
320
321 // Check if we're at the connection limit
322 if (this->at_client_limit_()) {
323 ESP_LOGW(TAG, "Max connections (%d), rejecting %s", MAX_API_CONNECTIONS, peername);
324 // Immediately close - socket destructor will handle cleanup
325 sock.reset();
326 continue;
327 }
328
329 ESP_LOGD(TAG, "Accept %s", peername);
330
331 this->add_client_(std::move(sock));
332 }
333}
334
335APIConnection *APIServer::add_client_(std::unique_ptr<socket::Socket> sock) {
336 auto *conn = new APIConnection(std::move(sock), this); // NOLINT(cppcoreguidelines-owning-memory)
337 this->clients_[this->api_connection_count_++].reset(conn);
338 conn->start();
339
340 // First client connected - clear warning. The reboot watchdog timestamp is
341 // refreshed when an authenticated client is removed (see remove_client_),
342 // never on bare TCP connects.
343 if (this->api_connection_count_ == 1 && this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
344 this->status_clear_warning();
345 }
346 return conn;
347}
348
349#ifdef USE_API_OUTGOING_CONNECTION
350APIConnection *APIServer::add_outgoing_client_(std::unique_ptr<socket::Socket> sock) {
351 // Re-check at the handoff: inbound clients may have taken the last slot and
352 // the PSK may have been cleared since the dial started (mark_outgoing()
353 // needs the noise helper)
354 const bool at_limit = this->at_client_limit_();
355 if (at_limit || !this->noise_ctx_.has_psk()) {
356 ESP_LOGW(TAG, "Dropping outgoing connection (%s)",
357 at_limit ? LOG_STR_LITERAL("max connections") : LOG_STR_LITERAL("no key"));
358 return nullptr;
359 }
360 auto *conn = this->add_client_(std::move(sock));
361 // After start(): sends our server hello first so the peer can pick the key
362 conn->mark_outgoing();
363 return conn;
364}
365
370#endif
371
373 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
374 ESP_LOGCONFIG(TAG,
375 "Server:\n"
376 " Address: %s:%u\n"
377 " Listen backlog: %u\n"
378 " Max connections: %u",
379 network::get_use_address_to(addr_buf), this->port_, this->listen_backlog_, MAX_API_CONNECTIONS);
380#ifdef USE_API_NOISE
381 ESP_LOGCONFIG(TAG, " Noise encryption: %s", YESNO(this->noise_ctx_.has_psk()));
382 if (!this->noise_ctx_.has_psk()) {
383 ESP_LOGCONFIG(TAG, " Supports encryption: YES");
384 }
385#else
386 ESP_LOGCONFIG(TAG, " Noise encryption: NO");
387#endif
388#ifdef USE_API_OUTGOING_CONNECTION
390#endif
391}
392
394
395// Macro for controller update dispatch
396#define API_DISPATCH_UPDATE(entity_type, entity_name) \
397 void APIServer::on_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
398 if (obj->is_internal()) \
399 return; \
400 for (auto &c : this->active_clients()) { \
401 if (c->flags_.state_subscription) \
402 c->send_##entity_name##_state(obj); \
403 } \
404 }
405
406#ifdef USE_BINARY_SENSOR
408#endif
409
410#ifdef USE_COVER
412#endif
413
414#ifdef USE_FAN
416#endif
417
418#ifdef USE_LIGHT
420#endif
421
422#ifdef USE_SENSOR
424#endif
425
426#ifdef USE_SWITCH
428#endif
429
430#ifdef USE_TEXT_SENSOR
432#endif
433
434#ifdef USE_CLIMATE
436#endif
437
438#ifdef USE_NUMBER
440#endif
441
442#ifdef USE_DATETIME_DATE
444#endif
445
446#ifdef USE_DATETIME_TIME
448#endif
449
450#ifdef USE_DATETIME_DATETIME
452#endif
453
454#ifdef USE_TEXT
456#endif
457
458#ifdef USE_SELECT
460#endif
461
462#ifdef USE_LOCK
464#endif
465
466#ifdef USE_VALVE
468#endif
469
470#ifdef USE_MEDIA_PLAYER
472#endif
473
474#ifdef USE_WATER_HEATER
476#endif
477
478#ifdef USE_EVENT
480 if (obj->is_internal())
481 return;
482 for (auto &c : this->active_clients()) {
483 if (c->flags_.state_subscription)
484 c->send_event(obj);
485 }
486}
487#endif
488
489#ifdef USE_UPDATE
490// Update is a special case - the method is called on_update, not on_update_update
492 if (obj->is_internal())
493 return;
494 for (auto &c : this->active_clients()) {
495 if (c->flags_.state_subscription)
496 c->send_update_state(obj);
497 }
498}
499#endif
500
501#ifdef USE_ZWAVE_PROXY
503 // We could add code to manage a second subscription type, but, since this message type is
504 // very infrequent and small, we simply send it to all clients
505 for (auto &c : this->active_clients()) {
506 if (!c->send_message(msg)) {
507 API_LOG_MSG_DROPPED(TAG, "Home ID notification");
508 }
509 }
510}
511#endif
512
513#ifdef USE_SERIAL_PROXY_USB_IDENTITY
515 for (auto &c : this->active_clients()) {
516 if (c->flags_.serial_proxy_identity_subscription)
517 c->send_serial_proxy_identity(msg);
518 }
519}
520#endif
521
522#ifdef USE_IR_RF
524 const std::vector<int32_t> *timings) {
526#ifdef USE_DEVICES
527 resp.device_id = device_id;
528#endif
529 resp.key = key;
530 resp.timings = timings;
531
532 for (auto &c : this->active_clients())
533 c->send_infrared_rf_receive_event(resp);
534}
535
536#endif
537
538#ifdef USE_ALARM_CONTROL_PANEL
540#endif
541
542#ifdef USE_API_HOMEASSISTANT_SERVICES
544 bool has_subscriber = false;
545 for (auto &client : this->active_clients()) {
546 has_subscriber |= client->send_homeassistant_action(call);
547 }
548 if (!has_subscriber) {
549 // Home Assistant subscribes to actions shortly *after* authenticating, so actions
550 // fired right at connection time (on_client_connected, on_time_sync, ...) can
551 // arrive before the subscription and are lost - warn instead of failing silently.
552 ESP_LOGW(TAG, "Home Assistant %s '%.*s' dropped; %s",
553 call.is_event ? LOG_STR_LITERAL("event") : LOG_STR_LITERAL("action"),
554 static_cast<int>(call.service.size()), call.service.empty() ? "" : call.service.progmem_ptr(),
555 this->is_connected() ? LOG_STR_LITERAL("client has not subscribed to actions (yet)")
556 : LOG_STR_LITERAL("no client connected"));
557 }
558}
559#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
561 this->action_response_callbacks_.push_back({call_id, std::move(callback)});
562}
563
564void APIServer::handle_action_response(uint32_t call_id, bool success, StringRef error_message) {
565 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
566 if (it->call_id == call_id) {
567 auto callback = std::move(it->callback);
568 this->action_response_callbacks_.erase(it);
569 ActionResponse response(success, error_message);
570 callback(response);
571 return;
572 }
573 }
574}
575#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
576void APIServer::handle_action_response(uint32_t call_id, bool success, StringRef error_message,
577 const uint8_t *response_data, size_t response_data_len) {
578 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
579 if (it->call_id == call_id) {
580 auto callback = std::move(it->callback);
581 this->action_response_callbacks_.erase(it);
582 ActionResponse response(success, error_message, response_data, response_data_len);
583 callback(response);
584 return;
585 }
586 }
587}
588#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
589#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
590#endif // USE_API_HOMEASSISTANT_SERVICES
591
592#ifdef USE_API_HOMEASSISTANT_STATES
593// Helper to add subscription (reduces duplication)
594void APIServer::add_state_subscription_(const char *entity_id, const char *attribute,
595 std::function<void(StringRef)> &&f, bool once) {
597 .entity_id = entity_id,
598 .attribute = attribute,
599 .callback = std::move(f),
600 .once = once,
601 // entity_id_dynamic_storage and attribute_dynamic_storage remain nullptr (no heap allocation)
602 });
603}
604
605// Helper to add subscription with heap-allocated strings (reduces duplication)
606void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
607 std::function<void(StringRef)> &&f, bool once) {
609 // Allocate heap storage for the strings
610 sub.entity_id_dynamic_storage = std::make_unique<std::string>(std::move(entity_id));
611 sub.entity_id = sub.entity_id_dynamic_storage->c_str();
612
613 if (attribute.has_value()) {
614 sub.attribute_dynamic_storage = std::make_unique<std::string>(std::move(attribute.value()));
615 sub.attribute = sub.attribute_dynamic_storage->c_str();
616 } else {
617 sub.attribute = nullptr;
618 }
619
620 sub.callback = std::move(f);
621 sub.once = once;
622 this->state_subs_.push_back(std::move(sub));
623}
624
625// New const char* overload (for internal components - zero allocation)
626void APIServer::subscribe_home_assistant_state(const char *entity_id, const char *attribute,
627 std::function<void(StringRef)> &&f) {
628 this->add_state_subscription_(entity_id, attribute, std::move(f), false);
629}
630
631void APIServer::get_home_assistant_state(const char *entity_id, const char *attribute,
632 std::function<void(StringRef)> &&f) {
633 this->add_state_subscription_(entity_id, attribute, std::move(f), true);
634}
635
636// std::string overload with StringRef callback (zero-allocation callback)
637void APIServer::subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
638 std::function<void(StringRef)> &&f) {
639 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
640}
641
642void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
643 std::function<void(StringRef)> &&f) {
644 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
645}
646
647// Legacy helper: wraps std::string callback and delegates to StringRef version
648void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
649 std::function<void(const std::string &)> &&f, bool once) {
650 // Wrap callback to convert StringRef -> std::string, then delegate
651 this->add_state_subscription_(std::move(entity_id), std::move(attribute),
652 std::function<void(StringRef)>([f = std::move(f)](StringRef state) { f(state.str()); }),
653 once);
654}
655
656// Legacy std::string overload (for custom_api_device.h - converts StringRef to std::string)
657void APIServer::subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
658 std::function<void(const std::string &)> &&f) {
659 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
660}
661
662void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
663 std::function<void(const std::string &)> &&f) {
664 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
665}
666
667const std::vector<APIServer::HomeAssistantStateSubscription> &APIServer::get_state_subs() const {
668 return this->state_subs_;
669}
670#endif
671
672#ifdef USE_API_NOISE
673#ifndef USE_API_NOISE_PSK_FROM_YAML
674bool APIServer::update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg,
675 const LogString *fail_log_msg, bool make_active) {
676 if (!this->noise_pref_.save(&new_psk)) {
677 ESP_LOGW(TAG, "%s", LOG_STR_ARG(fail_log_msg));
678 return false;
679 }
680 // ensure it's written immediately
681 if (!global_preferences->sync()) {
682 ESP_LOGW(TAG, "Failed to sync preferences");
683 return false;
684 }
685 ESP_LOGD(TAG, "%s", LOG_STR_ARG(save_log_msg));
686 if (make_active) {
687 this->set_timeout(100, [this]() {
688 // Re-read the PSK from preferences rather than capturing the 32-byte array
689 // in the lambda (which would exceed std::function SBO and heap-allocate).
690 if (!this->load_and_apply_noise_psk_()) {
691 ESP_LOGW(TAG, "Failed to load saved PSK for activation");
692 return;
693 }
694 ESP_LOGW(TAG, "Disconnecting all clients to reset PSK");
695 for (auto &c : this->active_clients()) {
697 if (!c->send_message(req)) {
698 API_LOG_MSG_DROPPED(TAG, "Disconnect request");
699 }
700 // Force it: a session from before the key was active must not survive
701 c->flags_.next_close = true;
702 }
703 });
704 }
705 return true;
706}
707
709 // Load into a temp so a failed read cannot disturb the key in use
710 SavedNoisePsk loaded{};
711 if (!this->noise_pref_.load(&loaded))
712 return false;
713 this->saved_psk_ = loaded;
714 // An unprovisioned device stores the reserved all-zeros key, which is no key
715 const bool has_key = !noise::NoiseContext::is_all_zeros(this->saved_psk_.psk);
716 this->noise_ctx_.set_psk(has_key ? this->saved_psk_.psk.data() : nullptr);
717 return true;
718}
719
720bool APIServer::save_noise_psk(noise::psk_t psk, bool make_active) {
721 if (this->saved_psk_.psk == psk) {
722 ESP_LOGW(TAG, "New PSK matches old");
723 return true;
724 }
725
726 SavedNoisePsk new_saved_psk{psk};
727 bool result = this->update_noise_psk_(new_saved_psk, LOG_STR("Noise PSK saved"), LOG_STR("Failed to save Noise PSK"),
728 make_active);
729#ifdef USE_PROVISIONING
730 // The device now has a key; report provisioned so the provisioning window is
731 // satisfied and the reboot timeout resumes normal operation.
732 if (result && provisioning::global_provisioning_manager != nullptr) {
734 }
735#endif
736 return result;
737}
738bool APIServer::clear_noise_psk(bool make_active) {
739 SavedNoisePsk empty_psk{};
740 bool result = this->update_noise_psk_(empty_psk, LOG_STR("Noise PSK cleared"), LOG_STR("Failed to clear Noise PSK"),
741 make_active);
742#ifdef USE_PROVISIONING
743 // The key was cleared; report unprovisioned so a subsequent reboot reopens the
744 // provisioning window.
745 if (result && provisioning::global_provisioning_manager != nullptr) {
747 }
748#endif
749 return result;
750}
751#endif // USE_API_NOISE_PSK_FROM_YAML
752#endif
753
754#ifdef USE_HOMEASSISTANT_TIME
756 for (auto &client : this->active_clients()) {
757 if (!client->flags_.remove && client->is_authenticated()) {
758 client->send_time_request();
759 return; // Only request from one client to avoid clock conflicts
760 }
761 }
762}
763#endif
764
766 for (uint8_t i = 0; i < this->api_connection_count_; i++) {
767 if (this->clients_[i]->flags_.state_subscription) {
768 return true;
769 }
770 }
771 return false;
772}
773
774#ifdef USE_LOGGER
775void APIServer::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
776 if (this->shutting_down_) {
777 // Don't try to send logs during shutdown
778 // as it could result in a recursion and
779 // we would be filling a buffer we are trying to clear
780 return;
781 }
782 for (auto &c : this->active_clients()) {
783 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
784 c->try_send_log_message(level, tag, message, message_len);
785 }
786}
787#endif
788
789#ifdef USE_CAMERA
790void APIServer::on_camera_image(const std::shared_ptr<camera::CameraImage> &image) {
791 for (auto &c : this->active_clients()) {
792 if (!c->flags_.remove)
793 c->set_camera_state(image);
794 }
795}
796#endif
797
798// Kept out of api_connection.cpp so GCC inlines its send path as before
800#ifndef USE_DEEP_SLEEP
801 // Queued states first: Home Assistant mishandles states after DisconnectRequest (#22610).
802 // Not with deep sleep: its entities stay available, and the disconnect must not wait on a slow link
803 this->flags_.state_subscription = false;
805 // process_batch_ first flushes any overflow without blocking; stop once the queue stops shrinking
806 for (size_t left = this->deferred_batch_.size(); left != 0;) {
807 this->process_batch_();
808 const size_t now_left = this->deferred_batch_.size();
809 if (now_left >= left)
810 break;
811 left = now_left;
812 }
813#endif
815 if (!this->send_message(req)) {
816 // tx buffer full: first in the queue, so a slow link still delivers it before the teardown timeout.
817 // Due at once: teardown does not advance the cached loop time the batch_delay gate reads
819 this->make_batch_due_now_();
820 }
821}
822
824 this->shutting_down_ = true;
825
826 // Close the listening socket to prevent new connections
827 this->destroy_socket_();
828#ifdef USE_API_OUTGOING_CONNECTION
830#endif
831
832 // Change batch delay to 5ms for quick flushing during shutdown
833 this->batch_delay_ = 5;
834
835 for (auto &c : this->active_clients())
836 c->send_shutdown_disconnect_();
837}
838
840 // If network is disconnected, no point trying to flush buffers
841 if (!network::is_connected()) {
842 return true;
843 }
844 this->loop();
845
846 // Return true only when all clients have been torn down
847 return this->api_connection_count_ == 0;
848}
849
850#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
851// Timeout for action calls - matches aioesphomeapi client timeout (default 30s)
852// Can be overridden via USE_API_ACTION_CALL_TIMEOUT_MS define for testing
853#ifndef USE_API_ACTION_CALL_TIMEOUT_MS
854#define USE_API_ACTION_CALL_TIMEOUT_MS 30000 // NOLINT
855#endif
856
858 uint32_t action_call_id = this->next_action_call_id_++;
859 // Handle wraparound (skip 0 as it means "no call")
860 if (this->next_action_call_id_ == 0) {
861 this->next_action_call_id_ = 1;
862 }
863 this->active_action_calls_.push_back({action_call_id, client_call_id, conn});
864
865 // Schedule automatic cleanup after timeout (client will have given up by then)
866 // Uses numeric ID overload to avoid heap allocation from str_sprintf
867 this->set_timeout(action_call_id, USE_API_ACTION_CALL_TIMEOUT_MS, [this, action_call_id]() {
868 ESP_LOGD(TAG, "Action call %" PRIu32 " timed out", action_call_id);
869 this->unregister_active_action_call(action_call_id);
870 });
871
872 return action_call_id;
873}
874
876 // Cancel the timeout for this action call (uses numeric ID overload)
877 this->cancel_timeout(action_call_id);
878
879 // Swap-and-pop is more efficient than remove_if for unordered vectors
880 for (size_t i = 0; i < this->active_action_calls_.size(); i++) {
881 if (this->active_action_calls_[i].action_call_id == action_call_id) {
882 std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
883 this->active_action_calls_.pop_back();
884 return;
885 }
886 }
887}
888
890 // Remove all active action calls for disconnected connection using swap-and-pop
891 for (size_t i = 0; i < this->active_action_calls_.size();) {
892 if (this->active_action_calls_[i].connection == conn) {
893 // Cancel the timeout for this action call (uses numeric ID overload)
894 this->cancel_timeout(this->active_action_calls_[i].action_call_id);
895
896 std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
897 this->active_action_calls_.pop_back();
898 // Don't increment i - need to check the swapped element
899 } else {
900 i++;
901 }
902 }
903}
904
905void APIServer::send_action_response(uint32_t action_call_id, bool success, StringRef error_message) {
906 for (auto &call : this->active_action_calls_) {
907 if (call.action_call_id == action_call_id) {
908 call.connection->send_execute_service_response(call.client_call_id, success, error_message);
909 return;
910 }
911 }
912 ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %" PRIu32, action_call_id);
913}
914#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
915void APIServer::send_action_response(uint32_t action_call_id, bool success, StringRef error_message,
916 const uint8_t *response_data, size_t response_data_len) {
917 for (auto &call : this->active_action_calls_) {
918 if (call.action_call_id == action_call_id) {
919 call.connection->send_execute_service_response(call.client_call_id, success, error_message, response_data,
920 response_data_len);
921 return;
922 }
923 }
924 ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %" PRIu32, action_call_id);
925}
926#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
927#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
928
929} // namespace esphome::api
930#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.
void mark_failed()
Mark this component as failed.
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void status_clear_warning()
Definition component.h:309
bool is_internal() const
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:557
Leaves a stretch of the current loop pass out of the blocking warning.
struct esphome::api::APIConnection::APIFlags flags_
bool send_message(const T &msg)
Returns false as soon as the TCP buffer is full.
bool schedule_message_front_(EntityBase *entity, uint16_t message_type, uint8_t estimated_size)
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len)
bool is_connected_with_state_subscription() const
OutgoingConnectionManager outgoing_conn_
Definition api_server.h:407
std::array< APIConnectionPtr, MAX_API_CONNECTIONS > clients_
Definition api_server.h:349
void register_action_response_callback(uint32_t call_id, ActionResponseCallback callback)
void send_infrared_rf_receive_event(uint32_t device_id, uint32_t key, const std::vector< int32_t > *timings)
void on_update(update::UpdateEntity *obj)
void add_state_subscription_(const char *entity_id, const char *attribute, std::function< void(StringRef)> &&f, bool once)
void get_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> &&f)
bool at_client_limit_() const
Definition api_server.h:285
void on_camera_image(const std::shared_ptr< camera::CameraImage > &image) override
void socket_failed_(const LogString *msg)
Log the failure, drop the listen socket, and mark the component failed unless this build can still di...
void dump_config() override
void unregister_active_action_calls_for_connection(APIConnection *conn)
void handle_disconnect(APIConnection *conn)
void send_action_response(uint32_t action_call_id, bool success, StringRef error_message)
void setup() override
bool teardown() override
void unregister_active_action_call(uint32_t action_call_id)
void send_homeassistant_action(const HomeassistantActionRequest &call)
socket::ListenSocket * socket_
Definition api_server.h:336
std::vector< PendingActionResponse > action_response_callbacks_
Definition api_server.h:378
const std::vector< HomeAssistantStateSubscription > & get_state_subs() const
void send_serial_proxy_identity(const SerialProxyIdentity &msg)
Tell every subscribed client that a serial proxy port's identity changed.
void subscribe_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> &&f)
void handle_action_response(uint32_t call_id, bool success, StringRef error_message)
std::function< void(const class ActionResponse &)> ActionResponseCallback
Definition api_server.h:159
void on_event(event::Event *obj)
bool provisioning_pending_() const
Definition api_server.h:300
bool update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg, const LogString *fail_log_msg, bool make_active)
ESPPreferenceObject noise_pref_
Definition api_server.h:404
SavedNoisePsk saved_psk_
Definition api_server.h:402
Trigger< std::string, std::string > client_disconnected_trigger_
Definition api_server.h:341
std::vector< HomeAssistantStateSubscription > state_subs_
Definition api_server.h:357
bool clear_noise_psk(bool make_active=true)
ActiveClientsView active_clients() const
Definition api_server.h:233
void on_outgoing_target_client(APIConnection *conn)
bool save_noise_psk(noise::psk_t psk, bool make_active=true)
APIConnection * add_client_(std::unique_ptr< socket::Socket > sock)
Takes the socket into a new connection and starts it; callers must have checked at_client_limit_() fi...
std::vector< ActiveActionCall > active_action_calls_
Definition api_server.h:369
APIConnection * add_outgoing_client_(std::unique_ptr< socket::Socket > sock)
uint32_t register_active_action_call(uint32_t client_call_id, APIConnection *conn)
noise::NoiseContext noise_ctx_
Definition api_server.h:400
void on_shutdown() override
void on_zwave_proxy_request(const ZWaveProxyRequest &msg)
static constexpr uint16_t MESSAGE_TYPE
Definition api_pb2.h:489
static constexpr uint8_t ESTIMATED_SIZE
Definition api_pb2.h:490
enums::DisconnectReason reason
Definition api_pb2.h:494
void on_client_removed(APIConnection *conn, bool was_authenticated)
Clears the dialed-connection gate; dying unauthenticated escalates the backoff.
void on_target_client(APIConnection *conn)
A key-verified client declared itself a dial-back target; last one wins.
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:18
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:192
Base class for all cover devices.
Definition cover.h:115
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:112
void add_log_callback(void *instance, void(*fn)(void *, uint8_t, const char *, const char *, size_t))
Register a log callback to receive log messages.
Definition logger.h:203
void set_psk(const uint8_t *psk)
psk points at 32 bytes that outlive the context (PROGMEM or caller owned RAM); nullptr means no key.
Definition noise.h:32
static bool is_all_zeros(const psk_t &psk)
Definition noise.h:22
Base-class for all numbers.
Definition number.h:29
void set_source_provisioned(uint8_t source, bool provisioned)
Base-class for all selects.
Definition select.h:28
Base-class for all sensors.
Definition sensor.h:48
bool ready() const
Check if the socket has buffered data ready to read.
Definition socket.h:106
int bind(const struct sockaddr *addr, socklen_t addrlen)
int setsockopt(int level, int optname, const void *optval, socklen_t optlen)
std::unique_ptr< BSDSocketImpl > accept_loop_monitored(struct sockaddr *addr, socklen_t *addrlen)
Base class for all switches.
Definition switch.h:43
Base-class for all text inputs.
Definition text.h:20
Base class for all valve devices.
Definition valve.h:102
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
const LogString * message
Definition component.cpp:35
uint16_t addr_len
const char * key
bool state
Definition fan.h:2
std::vector< uint8_t > & out
Definition gif.cpp:49
uint32_t socklen_t
Definition headers.h:109
@ DISCONNECT_REASON_PROVISIONING_CLOSED
Definition api_pb2.h:20
APIServer * global_api_server
ESPHOME_LOG_TAG(TAG, "api.connection")
API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor) API_DISPATCH_UPDATE(cover
bool load_saved_noise_psk(noise::psk_t &out)
One-shot read of the provisioned key for a boot without an api server (safe mode); false when there i...
Logger * global_logger
Definition logger.cpp:396
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
const char * get_use_address_to(std::span< char, USE_ADDRESS_BUFFER_SIZE > buf)
Get the active network address for logging.
Definition util.cpp:72
std::array< uint8_t, 32 > psk_t
Definition noise.h:14
bool has_spare_ephemeral()
Definition noise.h:52
void prepare_spare_ephemeral()
Fill the slot; blocks for the base point multiply.
Definition noise.cpp:31
ProvisioningManager * global_provisioning_manager
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().
std::unique_ptr< ListenSocket > socket_ip_loop_monitored(int type, int protocol)
Definition socket.h:175
ESPPreferences * global_preferences
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
bool load_from_key(uint32_t, uint8_t *, size_t)
Definition preferences.h:26
bool sync()
Commit pending writes to flash.
Definition preferences.h:33
std::unique_ptr< std::string > entity_id_dynamic_storage
Definition api_server.h:246
std::unique_ptr< std::string > attribute_dynamic_storage
Definition api_server.h:247
SemaphoreHandle_t lock