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