ESPHome 2026.10.0-dev
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
27static const char *const TAG = "api";
28
29// APIServer
30APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
31
33
34void APIServer::socket_failed_(const LogString *msg) {
35 ESP_LOGW(TAG, "Socket %s: errno %d", LOG_STR_ARG(msg), errno);
36 this->destroy_socket_();
37 this->mark_failed();
38}
39
42
43#ifdef USE_API_NOISE
44 // Always reserve the slot: flash preferences are positional on esp8266, so
45 // a yaml key build must keep the layout of a runtime key build
46 uint32_t hash = 88491486UL;
48#ifndef USE_API_NOISE_PSK_FROM_YAML
49 // A cleared record loads fine but holds no key
50 if (this->load_and_apply_noise_psk_() && this->noise_ctx_.has_psk()) {
51 ESP_LOGD(TAG, "Loaded saved Noise PSK");
52 }
53#endif
54#endif
55
56 this->socket_ = socket::socket_ip_loop_monitored(SOCK_STREAM, 0).release(); // monitored for incoming connections
57 if (this->socket_ == nullptr) {
58 this->socket_failed_(LOG_STR("creation"));
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 reuseaddr: errno %d", errno);
65 // we can still continue
66 }
67 err = this->socket_->setblocking(false);
68 if (err != 0) {
69 this->socket_failed_(LOG_STR("nonblocking"));
70 return;
71 }
72
73 struct sockaddr_storage server;
74
75 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
76 if (sl == 0) {
77 this->socket_failed_(LOG_STR("set sockaddr"));
78 return;
79 }
80
81 err = this->socket_->bind((struct sockaddr *) &server, sl);
82 if (err != 0) {
83 this->socket_failed_(LOG_STR("bind"));
84 return;
85 }
86
87 err = this->socket_->listen(this->listen_backlog_);
88 if (err != 0) {
89 this->socket_failed_(LOG_STR("listen"));
90 return;
91 }
92
93#ifdef USE_LOGGER
94 if (logger::global_logger != nullptr) {
96 this, [](void *self, uint8_t level, const char *tag, const char *message, size_t message_len) {
97 static_cast<APIServer *>(self)->on_log(level, tag, message, message_len);
98 });
99 }
100#endif
101
102#ifdef USE_CAMERA
103 if (camera::Camera::instance() != nullptr && !camera::Camera::instance()->is_internal()) {
105 }
106#endif
107
108 // Initialize last_connected_ for reboot timeout tracking
110#if defined(USE_PROVISIONING) && defined(USE_API_NOISE)
111 // Register with the provisioning manager (provisioning:) as a source and
112 // report our current state (provisioned == an encryption key is set). When the
113 // window closes, disconnect any client still attempting to provision so it learns
114 // the reason. The manager owns the timeout, window state and on_timeout automation.
118 this->noise_ctx_.has_psk());
120 for (auto &c : this->active_clients()) {
123 // Best-effort: if the send buffer is full the reason is dropped, but the
124 // client still learns the window is closed when it reconnects (rejected at
125 // hello) or via the socket close.
126 if (!c->send_message(req)) {
127 API_LOG_MSG_DROPPED(TAG, "Disconnect request");
128 }
129 }
130 });
131 }
132#endif
133 // Set warning status if reboot timeout is enabled (suppressed while provisioning
134 // is pending so the device waits to be onboarded instead of rebooting).
135 if (this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
136 this->status_set_warning(LOG_STR("waiting for client connection"));
137 }
138}
139
141 // Accept new clients only if the socket exists and has incoming connections
142 if (this->socket_ && this->socket_->ready()) {
143 this->accept_new_connections_();
144 }
145
146 if (this->api_connection_count_ == 0) {
147 // Check reboot timeout - done in loop to avoid scheduler heap churn
148 // (cancelled scheduler items sit in heap memory until their scheduled time).
149 // Suppressed while a provisioning window is pending so the device waits to be
150 // onboarded / reset instead of rebooting itself; resumes once provisioned.
151 if (this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
153 if (now - this->last_connected_ > this->reboot_timeout_) {
154 ESP_LOGE(TAG, "No clients; rebooting");
155 App.reboot();
156 }
157 }
158 return;
159 }
160
161 // Process clients and remove disconnected ones in a single pass
162 // Check network connectivity once for all clients
163 if (!network::is_connected()) {
164 // Network is down - disconnect all clients
165 for (auto &client : this->active_clients()) {
166 client->on_fatal_error();
167 client->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR("Network down; disconnect"));
168 }
169 // Continue to process and clean up the clients below
170 }
171
172 uint8_t client_index = 0;
173 while (client_index < this->api_connection_count_) {
174 auto &client = this->clients_[client_index];
175
176 // Common case: process active client
177 if (!client->flags_.remove) {
178 client->loop();
179 }
180 // Handle disconnection promptly - close socket to free LWIP PCB
181 // resources and prevent retransmit crashes on ESP8266.
182 if (client->flags_.remove) {
183 // Rare case: handle disconnection (don't increment - swapped element needs processing)
184 this->remove_client_(client_index);
185 } else {
186 client_index++;
187 }
188 }
189}
190
191void APIServer::remove_client_(uint8_t client_index) {
192 auto &client = this->clients_[client_index];
193
194#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
196#endif
197 ESP_LOGV(TAG, "Remove connection %s", client->get_name());
198
199#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
200 // Save client info before closing socket and removal for the trigger
201 char peername_buf[socket::SOCKADDR_STR_LEN];
202 std::string client_name(client->get_name());
203 std::string client_peername(client->get_peername_to(peername_buf));
204#endif
205
206 // Close socket now (was deferred from on_fatal_error to allow getpeername)
207 client->helper_->close();
208
209 // Swap-and-reset: move the removed client to the trailing slot and null it out so slots
210 // [api_connection_count_, N) remain nullptr.
211 const uint8_t last_index = this->api_connection_count_ - 1;
212 if (client_index < last_index) {
213 std::swap(this->clients_[client_index], this->clients_[last_index]);
214 }
215 // Drop the count before resetting the slot. reset() runs ~APIConnection(), which can reenter the
216 // server (e.g. voice_assistant unsubscribes in its disconnect trigger, publishing entity state ->
217 // on_*_update iterating active_clients()). Excluding the dying slot from the active range first
218 // keeps that reentrant iteration from dereferencing the now-null slot.
219 this->api_connection_count_--;
220 this->clients_[last_index].reset();
221
222 // Last client disconnected - set warning and start tracking for reboot timeout
223 // (suppressed while provisioning is pending - see loop()).
224 if (this->api_connection_count_ == 0 && this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
225 this->status_set_warning(LOG_STR("waiting for client connection"));
227 }
228
229#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
230 // Fire trigger after client is removed so api.connected reflects the true state
231 this->client_disconnected_trigger_.trigger(client_name, client_peername);
232#endif
233}
234
235void __attribute__((flatten)) APIServer::accept_new_connections_() {
236 while (true) {
237 struct sockaddr_storage source_addr;
238 socklen_t addr_len = sizeof(source_addr);
239
240 auto sock = this->socket_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
241 if (!sock)
242 break;
243
244 char peername[socket::SOCKADDR_STR_LEN];
245 sock->getpeername_to(peername);
246
247 // Check if we're at the connection limit
248 if (this->api_connection_count_ >= MAX_API_CONNECTIONS) {
249 ESP_LOGW(TAG, "Max connections (%d), rejecting %s", MAX_API_CONNECTIONS, peername);
250 // Immediately close - socket destructor will handle cleanup
251 sock.reset();
252 continue;
253 }
254
255 ESP_LOGD(TAG, "Accept %s", peername);
256
257 auto *conn = new APIConnection(std::move(sock), this);
258 this->clients_[this->api_connection_count_++].reset(conn);
259 conn->start();
260
261 // First client connected - clear warning and update timestamp
262 if (this->api_connection_count_ == 1 && this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
263 this->status_clear_warning();
265 }
266 }
267}
268
270 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
271 ESP_LOGCONFIG(TAG,
272 "Server:\n"
273 " Address: %s:%u\n"
274 " Listen backlog: %u\n"
275 " Max connections: %u",
276 network::get_use_address_to(addr_buf), this->port_, this->listen_backlog_, MAX_API_CONNECTIONS);
277#ifdef USE_API_NOISE
278 ESP_LOGCONFIG(TAG, " Noise encryption: %s", YESNO(this->noise_ctx_.has_psk()));
279 if (!this->noise_ctx_.has_psk()) {
280 ESP_LOGCONFIG(TAG, " Supports encryption: YES");
281 }
282#else
283 ESP_LOGCONFIG(TAG, " Noise encryption: NO");
284#endif
285}
286
288
289// Macro for controller update dispatch
290#define API_DISPATCH_UPDATE(entity_type, entity_name) \
291 void APIServer::on_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
292 if (obj->is_internal()) \
293 return; \
294 for (auto &c : this->active_clients()) { \
295 if (c->flags_.state_subscription) \
296 c->send_##entity_name##_state(obj); \
297 } \
298 }
299
300#ifdef USE_BINARY_SENSOR
302#endif
303
304#ifdef USE_COVER
306#endif
307
308#ifdef USE_FAN
310#endif
311
312#ifdef USE_LIGHT
314#endif
315
316#ifdef USE_SENSOR
318#endif
319
320#ifdef USE_SWITCH
322#endif
323
324#ifdef USE_TEXT_SENSOR
326#endif
327
328#ifdef USE_CLIMATE
330#endif
331
332#ifdef USE_NUMBER
334#endif
335
336#ifdef USE_DATETIME_DATE
338#endif
339
340#ifdef USE_DATETIME_TIME
342#endif
343
344#ifdef USE_DATETIME_DATETIME
346#endif
347
348#ifdef USE_TEXT
350#endif
351
352#ifdef USE_SELECT
354#endif
355
356#ifdef USE_LOCK
358#endif
359
360#ifdef USE_VALVE
362#endif
363
364#ifdef USE_MEDIA_PLAYER
366#endif
367
368#ifdef USE_WATER_HEATER
370#endif
371
372#ifdef USE_EVENT
374 if (obj->is_internal())
375 return;
376 for (auto &c : this->active_clients()) {
377 if (c->flags_.state_subscription)
378 c->send_event(obj);
379 }
380}
381#endif
382
383#ifdef USE_UPDATE
384// Update is a special case - the method is called on_update, not on_update_update
386 if (obj->is_internal())
387 return;
388 for (auto &c : this->active_clients()) {
389 if (c->flags_.state_subscription)
390 c->send_update_state(obj);
391 }
392}
393#endif
394
395#ifdef USE_ZWAVE_PROXY
397 // We could add code to manage a second subscription type, but, since this message type is
398 // very infrequent and small, we simply send it to all clients
399 for (auto &c : this->active_clients()) {
400 if (!c->send_message(msg)) {
401 API_LOG_MSG_DROPPED(TAG, "Home ID notification");
402 }
403 }
404}
405#endif
406
407#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY)
409 const std::vector<int32_t> *timings) {
411#ifdef USE_DEVICES
412 resp.device_id = device_id;
413#endif
414 resp.key = key;
415 resp.timings = timings;
416
417 for (auto &c : this->active_clients())
418 c->send_infrared_rf_receive_event(resp);
419}
420#endif
421
422#ifdef USE_ALARM_CONTROL_PANEL
424#endif
425
426#ifdef USE_API_HOMEASSISTANT_SERVICES
428 bool has_subscriber = false;
429 for (auto &client : this->active_clients()) {
430 has_subscriber |= client->send_homeassistant_action(call);
431 }
432 if (!has_subscriber) {
433 // Home Assistant subscribes to actions shortly *after* authenticating, so actions
434 // fired right at connection time (on_client_connected, on_time_sync, ...) can
435 // arrive before the subscription and are lost - warn instead of failing silently.
436 ESP_LOGW(TAG, "Home Assistant %s '%s' dropped; %s",
437 call.is_event ? LOG_STR_LITERAL("event") : LOG_STR_LITERAL("action"), call.service.c_str(),
438 this->is_connected() ? LOG_STR_LITERAL("client has not subscribed to actions (yet)")
439 : LOG_STR_LITERAL("no client connected"));
440 }
441}
442#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
444 this->action_response_callbacks_.push_back({call_id, std::move(callback)});
445}
446
447void APIServer::handle_action_response(uint32_t call_id, bool success, StringRef error_message) {
448 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
449 if (it->call_id == call_id) {
450 auto callback = std::move(it->callback);
451 this->action_response_callbacks_.erase(it);
452 ActionResponse response(success, error_message);
453 callback(response);
454 return;
455 }
456 }
457}
458#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
459void APIServer::handle_action_response(uint32_t call_id, bool success, StringRef error_message,
460 const uint8_t *response_data, size_t response_data_len) {
461 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
462 if (it->call_id == call_id) {
463 auto callback = std::move(it->callback);
464 this->action_response_callbacks_.erase(it);
465 ActionResponse response(success, error_message, response_data, response_data_len);
466 callback(response);
467 return;
468 }
469 }
470}
471#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
472#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
473#endif // USE_API_HOMEASSISTANT_SERVICES
474
475#ifdef USE_API_HOMEASSISTANT_STATES
476// Helper to add subscription (reduces duplication)
477void APIServer::add_state_subscription_(const char *entity_id, const char *attribute,
478 std::function<void(StringRef)> &&f, bool once) {
480 .entity_id = entity_id, .attribute = attribute, .callback = std::move(f), .once = once,
481 // entity_id_dynamic_storage and attribute_dynamic_storage remain nullptr (no heap allocation)
482 });
483}
484
485// Helper to add subscription with heap-allocated strings (reduces duplication)
486void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
487 std::function<void(StringRef)> &&f, bool once) {
489 // Allocate heap storage for the strings
490 sub.entity_id_dynamic_storage = std::make_unique<std::string>(std::move(entity_id));
491 sub.entity_id = sub.entity_id_dynamic_storage->c_str();
492
493 if (attribute.has_value()) {
494 sub.attribute_dynamic_storage = std::make_unique<std::string>(std::move(attribute.value()));
495 sub.attribute = sub.attribute_dynamic_storage->c_str();
496 } else {
497 sub.attribute = nullptr;
498 }
499
500 sub.callback = std::move(f);
501 sub.once = once;
502 this->state_subs_.push_back(std::move(sub));
503}
504
505// New const char* overload (for internal components - zero allocation)
506void APIServer::subscribe_home_assistant_state(const char *entity_id, const char *attribute,
507 std::function<void(StringRef)> &&f) {
508 this->add_state_subscription_(entity_id, attribute, std::move(f), false);
509}
510
511void APIServer::get_home_assistant_state(const char *entity_id, const char *attribute,
512 std::function<void(StringRef)> &&f) {
513 this->add_state_subscription_(entity_id, attribute, std::move(f), true);
514}
515
516// std::string overload with StringRef callback (zero-allocation callback)
517void APIServer::subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
518 std::function<void(StringRef)> &&f) {
519 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
520}
521
522void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
523 std::function<void(StringRef)> &&f) {
524 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
525}
526
527// Legacy helper: wraps std::string callback and delegates to StringRef version
528void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
529 std::function<void(const std::string &)> &&f, bool once) {
530 // Wrap callback to convert StringRef -> std::string, then delegate
531 this->add_state_subscription_(std::move(entity_id), std::move(attribute),
532 std::function<void(StringRef)>([f = std::move(f)](StringRef state) { f(state.str()); }),
533 once);
534}
535
536// Legacy std::string overload (for custom_api_device.h - converts StringRef to std::string)
537void APIServer::subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
538 std::function<void(const std::string &)> &&f) {
539 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
540}
541
542void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
543 std::function<void(const std::string &)> &&f) {
544 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
545}
546
547const std::vector<APIServer::HomeAssistantStateSubscription> &APIServer::get_state_subs() const {
548 return this->state_subs_;
549}
550#endif
551
552#ifdef USE_API_NOISE
553#ifndef USE_API_NOISE_PSK_FROM_YAML
554bool APIServer::update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg,
555 const LogString *fail_log_msg, bool make_active) {
556 if (!this->noise_pref_.save(&new_psk)) {
557 ESP_LOGW(TAG, "%s", LOG_STR_ARG(fail_log_msg));
558 return false;
559 }
560 // ensure it's written immediately
561 if (!global_preferences->sync()) {
562 ESP_LOGW(TAG, "Failed to sync preferences");
563 return false;
564 }
565 ESP_LOGD(TAG, "%s", LOG_STR_ARG(save_log_msg));
566 if (make_active) {
567 this->set_timeout(100, [this]() {
568 // Re-read the PSK from preferences rather than capturing the 32-byte array
569 // in the lambda (which would exceed std::function SBO and heap-allocate).
570 if (!this->load_and_apply_noise_psk_()) {
571 ESP_LOGW(TAG, "Failed to load saved PSK for activation");
572 return;
573 }
574 ESP_LOGW(TAG, "Disconnecting all clients to reset PSK");
575 for (auto &c : this->active_clients()) {
577 if (!c->send_message(req)) {
578 API_LOG_MSG_DROPPED(TAG, "Disconnect request");
579 }
580 }
581 });
582 }
583 return true;
584}
585
587 // Load into a temp so a failed read cannot disturb the key in use
588 SavedNoisePsk loaded{};
589 if (!this->noise_pref_.load(&loaded))
590 return false;
591 this->saved_psk_ = loaded;
592 // An unprovisioned device stores the reserved all-zeros key, which is no key
593 const bool has_key = !noise::NoiseContext::is_all_zeros(this->saved_psk_.psk);
594 this->noise_ctx_.set_psk(has_key ? this->saved_psk_.psk.data() : nullptr);
595 return true;
596}
597
598bool APIServer::save_noise_psk(noise::psk_t psk, bool make_active) {
599 if (this->saved_psk_.psk == psk) {
600 ESP_LOGW(TAG, "New PSK matches old");
601 return true;
602 }
603
604 SavedNoisePsk new_saved_psk{psk};
605 bool result = this->update_noise_psk_(new_saved_psk, LOG_STR("Noise PSK saved"), LOG_STR("Failed to save Noise PSK"),
606 make_active);
607#ifdef USE_PROVISIONING
608 // The device now has a key; report provisioned so the provisioning window is
609 // satisfied and the reboot timeout resumes normal operation.
610 if (result && provisioning::global_provisioning_manager != nullptr) {
612 }
613#endif
614 return result;
615}
616bool APIServer::clear_noise_psk(bool make_active) {
617 SavedNoisePsk empty_psk{};
618 bool result = this->update_noise_psk_(empty_psk, LOG_STR("Noise PSK cleared"), LOG_STR("Failed to clear Noise PSK"),
619 make_active);
620#ifdef USE_PROVISIONING
621 // The key was cleared; report unprovisioned so a subsequent reboot reopens the
622 // provisioning window.
623 if (result && provisioning::global_provisioning_manager != nullptr) {
625 }
626#endif
627 return result;
628}
629#endif // USE_API_NOISE_PSK_FROM_YAML
630#endif
631
632#ifdef USE_HOMEASSISTANT_TIME
634 for (auto &client : this->active_clients()) {
635 if (!client->flags_.remove && client->is_authenticated()) {
636 client->send_time_request();
637 return; // Only request from one client to avoid clock conflicts
638 }
639 }
640}
641#endif
642
644 for (uint8_t i = 0; i < this->api_connection_count_; i++) {
645 if (this->clients_[i]->flags_.state_subscription) {
646 return true;
647 }
648 }
649 return false;
650}
651
652#ifdef USE_LOGGER
653void APIServer::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
654 if (this->shutting_down_) {
655 // Don't try to send logs during shutdown
656 // as it could result in a recursion and
657 // we would be filling a buffer we are trying to clear
658 return;
659 }
660 for (auto &c : this->active_clients()) {
661 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
662 c->try_send_log_message(level, tag, message, message_len);
663 }
664}
665#endif
666
667#ifdef USE_CAMERA
668void APIServer::on_camera_image(const std::shared_ptr<camera::CameraImage> &image) {
669 for (auto &c : this->active_clients()) {
670 if (!c->flags_.remove)
671 c->set_camera_state(image);
672 }
673}
674#endif
675
677 this->shutting_down_ = true;
678
679 // Close the listening socket to prevent new connections
680 this->destroy_socket_();
681
682 // Change batch delay to 5ms for quick flushing during shutdown
683 this->batch_delay_ = 5;
684
685 // Send disconnect requests to all connected clients
686 for (auto &c : this->active_clients()) {
688 if (!c->send_message(req)) {
689 // If we can't send the disconnect request directly (tx_buffer full),
690 // schedule it at the front of the batch so it will be sent with priority
691 c->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
692 }
693 }
694}
695
697 // If network is disconnected, no point trying to flush buffers
698 if (!network::is_connected()) {
699 return true;
700 }
701 this->loop();
702
703 // Return true only when all clients have been torn down
704 return this->api_connection_count_ == 0;
705}
706
707#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
708// Timeout for action calls - matches aioesphomeapi client timeout (default 30s)
709// Can be overridden via USE_API_ACTION_CALL_TIMEOUT_MS define for testing
710#ifndef USE_API_ACTION_CALL_TIMEOUT_MS
711#define USE_API_ACTION_CALL_TIMEOUT_MS 30000 // NOLINT
712#endif
713
715 uint32_t action_call_id = this->next_action_call_id_++;
716 // Handle wraparound (skip 0 as it means "no call")
717 if (this->next_action_call_id_ == 0) {
718 this->next_action_call_id_ = 1;
719 }
720 this->active_action_calls_.push_back({action_call_id, client_call_id, conn});
721
722 // Schedule automatic cleanup after timeout (client will have given up by then)
723 // Uses numeric ID overload to avoid heap allocation from str_sprintf
724 this->set_timeout(action_call_id, USE_API_ACTION_CALL_TIMEOUT_MS, [this, action_call_id]() {
725 ESP_LOGD(TAG, "Action call %" PRIu32 " timed out", action_call_id);
726 this->unregister_active_action_call(action_call_id);
727 });
728
729 return action_call_id;
730}
731
733 // Cancel the timeout for this action call (uses numeric ID overload)
734 this->cancel_timeout(action_call_id);
735
736 // Swap-and-pop is more efficient than remove_if for unordered vectors
737 for (size_t i = 0; i < this->active_action_calls_.size(); i++) {
738 if (this->active_action_calls_[i].action_call_id == action_call_id) {
739 std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
740 this->active_action_calls_.pop_back();
741 return;
742 }
743 }
744}
745
747 // Remove all active action calls for disconnected connection using swap-and-pop
748 for (size_t i = 0; i < this->active_action_calls_.size();) {
749 if (this->active_action_calls_[i].connection == conn) {
750 // Cancel the timeout for this action call (uses numeric ID overload)
751 this->cancel_timeout(this->active_action_calls_[i].action_call_id);
752
753 std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
754 this->active_action_calls_.pop_back();
755 // Don't increment i - need to check the swapped element
756 } else {
757 i++;
758 }
759 }
760}
761
762void APIServer::send_action_response(uint32_t action_call_id, bool success, StringRef error_message) {
763 for (auto &call : this->active_action_calls_) {
764 if (call.action_call_id == action_call_id) {
765 call.connection->send_execute_service_response(call.client_call_id, success, error_message);
766 return;
767 }
768 }
769 ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %" PRIu32, action_call_id);
770}
771#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
772void APIServer::send_action_response(uint32_t action_call_id, bool success, StringRef error_message,
773 const uint8_t *response_data, size_t response_data_len) {
774 for (auto &call : this->active_action_calls_) {
775 if (call.action_call_id == action_call_id) {
776 call.connection->send_execute_service_response(call.client_call_id, success, error_message, response_data,
777 response_data_len);
778 return;
779 }
780 }
781 ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %" PRIu32, action_call_id);
782}
783#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
784#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
785
786} // namespace esphome::api
787#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
static void register_controller(Controller *controller)
Register a controller to receive entity state updates.
bool is_internal() const
Definition entity_base.h:89
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:461
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len)
bool is_connected_with_state_subscription() const
std::array< APIConnectionPtr, MAX_API_CONNECTIONS > clients_
Definition api_server.h:321
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 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)
void on_camera_image(const std::shared_ptr< camera::CameraImage > &image) override
void socket_failed_(const LogString *msg)
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:308
void on_event(event::Event *obj) override
void on_update(update::UpdateEntity *obj) override
std::vector< PendingActionResponse > action_response_callbacks_
Definition api_server.h:350
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)
void handle_action_response(uint32_t call_id, bool success, StringRef error_message)
std::function< void(const class ActionResponse &)> ActionResponseCallback
Definition api_server.h:150
bool provisioning_pending_() const
Definition api_server.h:274
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:371
SavedNoisePsk saved_psk_
Definition api_server.h:369
Trigger< std::string, std::string > client_disconnected_trigger_
Definition api_server.h:313
std::vector< HomeAssistantStateSubscription > state_subs_
Definition api_server.h:329
bool clear_noise_psk(bool make_active=true)
ActiveClientsView active_clients() const
Definition api_server.h:217
bool save_noise_psk(noise::psk_t psk, bool make_active=true)
std::vector< ActiveActionCall > active_action_calls_
Definition api_server.h:341
uint32_t register_active_action_call(uint32_t client_call_id, APIConnection *conn)
noise::NoiseContext noise_ctx_
Definition api_server.h:367
void on_shutdown() override
void on_zwave_proxy_request(const ZWaveProxyRequest &msg)
static constexpr uint16_t MESSAGE_TYPE
Definition api_pb2.h:451
static constexpr uint8_t ESTIMATED_SIZE
Definition api_pb2.h:452
enums::DisconnectReason reason
Definition api_pb2.h:456
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:93
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:187
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:29
static bool is_all_zeros(const psk_t &psk)
Definition noise.h:19
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:32
const LogString * message
Definition component.cpp:35
uint16_t addr_len
bool state
Definition fan.h:2
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
Logger * global_logger
Definition logger.cpp:272
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:11
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:194
std::unique_ptr< ListenSocket > socket_ip_loop_monitored(int type, int protocol)
Definition socket.cpp:130
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 sync()
Commit pending writes to flash.
Definition preferences.h:33
std::unique_ptr< std::string > entity_id_dynamic_storage
Definition api_server.h:230
std::unique_ptr< std::string > attribute_dynamic_storage
Definition api_server.h:231
SemaphoreHandle_t lock