ESPHome 2026.8.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 uint32_t hash = 88491486UL;
45
47
48#ifndef USE_API_NOISE_PSK_FROM_YAML
49 // Only load saved PSK if not set from YAML
50 if (this->load_and_apply_noise_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 c->send_message(req);
127 }
128 });
129 }
130#endif
131 // Set warning status if reboot timeout is enabled (suppressed while provisioning
132 // is pending so the device waits to be onboarded instead of rebooting).
133 if (this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
134 this->status_set_warning(LOG_STR("waiting for client connection"));
135 }
136}
137
139 // Accept new clients only if the socket exists and has incoming connections
140 if (this->socket_ && this->socket_->ready()) {
141 this->accept_new_connections_();
142 }
143
144 if (this->api_connection_count_ == 0) {
145 // Check reboot timeout - done in loop to avoid scheduler heap churn
146 // (cancelled scheduler items sit in heap memory until their scheduled time).
147 // Suppressed while a provisioning window is pending so the device waits to be
148 // onboarded / reset instead of rebooting itself; resumes once provisioned.
149 if (this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
151 if (now - this->last_connected_ > this->reboot_timeout_) {
152 ESP_LOGE(TAG, "No clients; rebooting");
153 App.reboot();
154 }
155 }
156 return;
157 }
158
159 // Process clients and remove disconnected ones in a single pass
160 // Check network connectivity once for all clients
161 if (!network::is_connected()) {
162 // Network is down - disconnect all clients
163 for (auto &client : this->active_clients()) {
164 client->on_fatal_error();
165 client->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR("Network down; disconnect"));
166 }
167 // Continue to process and clean up the clients below
168 }
169
170 uint8_t client_index = 0;
171 while (client_index < this->api_connection_count_) {
172 auto &client = this->clients_[client_index];
173
174 // Common case: process active client
175 if (!client->flags_.remove) {
176 client->loop();
177 }
178 // Handle disconnection promptly - close socket to free LWIP PCB
179 // resources and prevent retransmit crashes on ESP8266.
180 if (client->flags_.remove) {
181 // Rare case: handle disconnection (don't increment - swapped element needs processing)
182 this->remove_client_(client_index);
183 } else {
184 client_index++;
185 }
186 }
187}
188
189void APIServer::remove_client_(uint8_t client_index) {
190 auto &client = this->clients_[client_index];
191
192#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
194#endif
195 ESP_LOGV(TAG, "Remove connection %s", client->get_name());
196
197#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
198 // Save client info before closing socket and removal for the trigger
199 char peername_buf[socket::SOCKADDR_STR_LEN];
200 std::string client_name(client->get_name());
201 std::string client_peername(client->get_peername_to(peername_buf));
202#endif
203
204 // Close socket now (was deferred from on_fatal_error to allow getpeername)
205 client->helper_->close();
206
207 // Swap-and-reset: move the removed client to the trailing slot and null it out so slots
208 // [api_connection_count_, N) remain nullptr.
209 const uint8_t last_index = this->api_connection_count_ - 1;
210 if (client_index < last_index) {
211 std::swap(this->clients_[client_index], this->clients_[last_index]);
212 }
213 // Drop the count before resetting the slot. reset() runs ~APIConnection(), which can reenter the
214 // server (e.g. voice_assistant unsubscribes in its disconnect trigger, publishing entity state ->
215 // on_*_update iterating active_clients()). Excluding the dying slot from the active range first
216 // keeps that reentrant iteration from dereferencing the now-null slot.
217 this->api_connection_count_--;
218 this->clients_[last_index].reset();
219
220 // Last client disconnected - set warning and start tracking for reboot timeout
221 // (suppressed while provisioning is pending - see loop()).
222 if (this->api_connection_count_ == 0 && this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
223 this->status_set_warning(LOG_STR("waiting for client connection"));
225 }
226
227#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
228 // Fire trigger after client is removed so api.connected reflects the true state
229 this->client_disconnected_trigger_.trigger(client_name, client_peername);
230#endif
231}
232
233void __attribute__((flatten)) APIServer::accept_new_connections_() {
234 while (true) {
235 struct sockaddr_storage source_addr;
236 socklen_t addr_len = sizeof(source_addr);
237
238 auto sock = this->socket_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
239 if (!sock)
240 break;
241
242 char peername[socket::SOCKADDR_STR_LEN];
243 sock->getpeername_to(peername);
244
245 // Check if we're at the connection limit
246 if (this->api_connection_count_ >= MAX_API_CONNECTIONS) {
247 ESP_LOGW(TAG, "Max connections (%d), rejecting %s", MAX_API_CONNECTIONS, peername);
248 // Immediately close - socket destructor will handle cleanup
249 sock.reset();
250 continue;
251 }
252
253 ESP_LOGD(TAG, "Accept %s", peername);
254
255 auto *conn = new APIConnection(std::move(sock), this);
256 this->clients_[this->api_connection_count_++].reset(conn);
257 conn->start();
258
259 // First client connected - clear warning and update timestamp
260 if (this->api_connection_count_ == 1 && this->reboot_timeout_ != 0 && !this->provisioning_pending_()) {
261 this->status_clear_warning();
263 }
264 }
265}
266
268 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
269 ESP_LOGCONFIG(TAG,
270 "Server:\n"
271 " Address: %s:%u\n"
272 " Listen backlog: %u\n"
273 " Max connections: %u",
274 network::get_use_address_to(addr_buf), this->port_, this->listen_backlog_, MAX_API_CONNECTIONS);
275#ifdef USE_API_NOISE
276 ESP_LOGCONFIG(TAG, " Noise encryption: %s", YESNO(this->noise_ctx_.has_psk()));
277 if (!this->noise_ctx_.has_psk()) {
278 ESP_LOGCONFIG(TAG, " Supports encryption: YES");
279 }
280#else
281 ESP_LOGCONFIG(TAG, " Noise encryption: NO");
282#endif
283}
284
286
287// Macro for controller update dispatch
288#define API_DISPATCH_UPDATE(entity_type, entity_name) \
289 void APIServer::on_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
290 if (obj->is_internal()) \
291 return; \
292 for (auto &c : this->active_clients()) { \
293 if (c->flags_.state_subscription) \
294 c->send_##entity_name##_state(obj); \
295 } \
296 }
297
298#ifdef USE_BINARY_SENSOR
300#endif
301
302#ifdef USE_COVER
304#endif
305
306#ifdef USE_FAN
308#endif
309
310#ifdef USE_LIGHT
312#endif
313
314#ifdef USE_SENSOR
316#endif
317
318#ifdef USE_SWITCH
320#endif
321
322#ifdef USE_TEXT_SENSOR
324#endif
325
326#ifdef USE_CLIMATE
328#endif
329
330#ifdef USE_NUMBER
332#endif
333
334#ifdef USE_DATETIME_DATE
336#endif
337
338#ifdef USE_DATETIME_TIME
340#endif
341
342#ifdef USE_DATETIME_DATETIME
344#endif
345
346#ifdef USE_TEXT
348#endif
349
350#ifdef USE_SELECT
352#endif
353
354#ifdef USE_LOCK
356#endif
357
358#ifdef USE_VALVE
360#endif
361
362#ifdef USE_MEDIA_PLAYER
364#endif
365
366#ifdef USE_WATER_HEATER
368#endif
369
370#ifdef USE_EVENT
372 if (obj->is_internal())
373 return;
374 for (auto &c : this->active_clients()) {
375 if (c->flags_.state_subscription)
376 c->send_event(obj);
377 }
378}
379#endif
380
381#ifdef USE_UPDATE
382// Update is a special case - the method is called on_update, not on_update_update
384 if (obj->is_internal())
385 return;
386 for (auto &c : this->active_clients()) {
387 if (c->flags_.state_subscription)
388 c->send_update_state(obj);
389 }
390}
391#endif
392
393#ifdef USE_ZWAVE_PROXY
395 // We could add code to manage a second subscription type, but, since this message type is
396 // very infrequent and small, we simply send it to all clients
397 for (auto &c : this->active_clients())
398 c->send_message(msg);
399}
400#endif
401
402#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY)
404 const std::vector<int32_t> *timings) {
406#ifdef USE_DEVICES
407 resp.device_id = device_id;
408#endif
409 resp.key = key;
410 resp.timings = timings;
411
412 for (auto &c : this->active_clients())
413 c->send_infrared_rf_receive_event(resp);
414}
415#endif
416
417#ifdef USE_ALARM_CONTROL_PANEL
419#endif
420
422
423void APIServer::set_port(uint16_t port) { this->port_ = port; }
424
425void APIServer::set_batch_delay(uint16_t batch_delay) { this->batch_delay_ = batch_delay; }
426
427#ifdef USE_API_HOMEASSISTANT_SERVICES
429 bool has_subscriber = false;
430 for (auto &client : this->active_clients()) {
431 has_subscriber |= client->send_homeassistant_action(call);
432 }
433 if (!has_subscriber) {
434 // Home Assistant subscribes to actions shortly *after* authenticating, so actions
435 // fired right at connection time (on_client_connected, on_time_sync, ...) can
436 // arrive before the subscription and are lost - warn instead of failing silently.
437 ESP_LOGW(TAG, "Home Assistant %s '%s' dropped; %s", call.is_event ? "event" : "action", call.service.c_str(),
438 this->is_connected() ? "client has not subscribed to actions (yet)" : "no client connected");
439 }
440}
441#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
443 this->action_response_callbacks_.push_back({call_id, std::move(callback)});
444}
445
446void APIServer::handle_action_response(uint32_t call_id, bool success, StringRef error_message) {
447 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
448 if (it->call_id == call_id) {
449 auto callback = std::move(it->callback);
450 this->action_response_callbacks_.erase(it);
451 ActionResponse response(success, error_message);
452 callback(response);
453 return;
454 }
455 }
456}
457#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
458void APIServer::handle_action_response(uint32_t call_id, bool success, StringRef error_message,
459 const uint8_t *response_data, size_t response_data_len) {
460 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
461 if (it->call_id == call_id) {
462 auto callback = std::move(it->callback);
463 this->action_response_callbacks_.erase(it);
464 ActionResponse response(success, error_message, response_data, response_data_len);
465 callback(response);
466 return;
467 }
468 }
469}
470#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
471#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
472#endif // USE_API_HOMEASSISTANT_SERVICES
473
474#ifdef USE_API_HOMEASSISTANT_STATES
475// Helper to add subscription (reduces duplication)
476void APIServer::add_state_subscription_(const char *entity_id, const char *attribute,
477 std::function<void(StringRef)> &&f, bool once) {
479 .entity_id = entity_id, .attribute = attribute, .callback = std::move(f), .once = once,
480 // entity_id_dynamic_storage and attribute_dynamic_storage remain nullptr (no heap allocation)
481 });
482}
483
484// Helper to add subscription with heap-allocated strings (reduces duplication)
485void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
486 std::function<void(StringRef)> &&f, bool once) {
488 // Allocate heap storage for the strings
489 sub.entity_id_dynamic_storage = std::make_unique<std::string>(std::move(entity_id));
490 sub.entity_id = sub.entity_id_dynamic_storage->c_str();
491
492 if (attribute.has_value()) {
493 sub.attribute_dynamic_storage = std::make_unique<std::string>(std::move(attribute.value()));
494 sub.attribute = sub.attribute_dynamic_storage->c_str();
495 } else {
496 sub.attribute = nullptr;
497 }
498
499 sub.callback = std::move(f);
500 sub.once = once;
501 this->state_subs_.push_back(std::move(sub));
502}
503
504// New const char* overload (for internal components - zero allocation)
505void APIServer::subscribe_home_assistant_state(const char *entity_id, const char *attribute,
506 std::function<void(StringRef)> &&f) {
507 this->add_state_subscription_(entity_id, attribute, std::move(f), false);
508}
509
510void APIServer::get_home_assistant_state(const char *entity_id, const char *attribute,
511 std::function<void(StringRef)> &&f) {
512 this->add_state_subscription_(entity_id, attribute, std::move(f), true);
513}
514
515// std::string overload with StringRef callback (zero-allocation callback)
516void APIServer::subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
517 std::function<void(StringRef)> &&f) {
518 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
519}
520
521void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
522 std::function<void(StringRef)> &&f) {
523 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
524}
525
526// Legacy helper: wraps std::string callback and delegates to StringRef version
527void APIServer::add_state_subscription_(std::string entity_id, optional<std::string> attribute,
528 std::function<void(const std::string &)> &&f, bool once) {
529 // Wrap callback to convert StringRef -> std::string, then delegate
530 this->add_state_subscription_(std::move(entity_id), std::move(attribute),
531 std::function<void(StringRef)>([f = std::move(f)](StringRef state) { f(state.str()); }),
532 once);
533}
534
535// Legacy std::string overload (for custom_api_device.h - converts StringRef to std::string)
536void APIServer::subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
537 std::function<void(const std::string &)> &&f) {
538 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), false);
539}
540
541void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
542 std::function<void(const std::string &)> &&f) {
543 this->add_state_subscription_(std::move(entity_id), std::move(attribute), std::move(f), true);
544}
545
546const std::vector<APIServer::HomeAssistantStateSubscription> &APIServer::get_state_subs() const {
547 return this->state_subs_;
548}
549#endif
550
551uint16_t APIServer::get_port() const { return this->port_; }
552
553void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
554
555#ifdef USE_API_NOISE
556bool APIServer::update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg,
557 const LogString *fail_log_msg, bool make_active) {
558 if (!this->noise_pref_.save(&new_psk)) {
559 ESP_LOGW(TAG, "%s", LOG_STR_ARG(fail_log_msg));
560 return false;
561 }
562 // ensure it's written immediately
563 if (!global_preferences->sync()) {
564 ESP_LOGW(TAG, "Failed to sync preferences");
565 return false;
566 }
567 ESP_LOGD(TAG, "%s", LOG_STR_ARG(save_log_msg));
568 if (make_active) {
569 this->set_timeout(100, [this]() {
570 // Re-read the PSK from preferences rather than capturing the 32-byte array
571 // in the lambda (which would exceed std::function SBO and heap-allocate).
572 if (!this->load_and_apply_noise_psk_()) {
573 ESP_LOGW(TAG, "Failed to load saved PSK for activation");
574 return;
575 }
576 ESP_LOGW(TAG, "Disconnecting all clients to reset PSK");
577 for (auto &c : this->active_clients()) {
579 c->send_message(req);
580 }
581 });
582 }
583 return true;
584}
585
587 SavedNoisePsk saved{};
588 if (!this->noise_pref_.load(&saved))
589 return false;
590 this->set_noise_psk(saved.psk);
591 return true;
592}
593
594bool APIServer::save_noise_psk(psk_t psk, bool make_active) {
595#ifdef USE_API_NOISE_PSK_FROM_YAML
596 // When PSK is set from YAML, this function should never be called
597 // but if it is, reject the change
598 ESP_LOGW(TAG, "Key set in YAML");
599 return false;
600#else
601 auto &old_psk = this->noise_ctx_.get_psk();
602 if (std::equal(old_psk.begin(), old_psk.end(), psk.begin())) {
603 ESP_LOGW(TAG, "New PSK matches old");
604 return true;
605 }
606
607 SavedNoisePsk new_saved_psk{psk};
608 bool result = this->update_noise_psk_(new_saved_psk, LOG_STR("Noise PSK saved"), LOG_STR("Failed to save Noise PSK"),
609 make_active);
610#ifdef USE_PROVISIONING
611 // The device now has a key; report provisioned so the provisioning window is
612 // satisfied and the reboot timeout resumes normal operation.
613 if (result && provisioning::global_provisioning_manager != nullptr) {
615 }
616#endif
617 return result;
618#endif
619}
620bool APIServer::clear_noise_psk(bool make_active) {
621#ifdef USE_API_NOISE_PSK_FROM_YAML
622 // When PSK is set from YAML, this function should never be called
623 // but if it is, reject the change
624 ESP_LOGW(TAG, "Key set in YAML");
625 return false;
626#else
627 SavedNoisePsk empty_psk{};
628 bool result = this->update_noise_psk_(empty_psk, LOG_STR("Noise PSK cleared"), LOG_STR("Failed to clear Noise PSK"),
629 make_active);
630#ifdef USE_PROVISIONING
631 // The key was cleared; report unprovisioned so a subsequent reboot reopens the
632 // provisioning window.
633 if (result && provisioning::global_provisioning_manager != nullptr) {
635 }
636#endif
637 return result;
638#endif
639}
640#endif
641
642#ifdef USE_HOMEASSISTANT_TIME
644 for (auto &client : this->active_clients()) {
645 if (!client->flags_.remove && client->is_authenticated()) {
646 client->send_time_request();
647 return; // Only request from one client to avoid clock conflicts
648 }
649 }
650}
651#endif
652
654 for (uint8_t i = 0; i < this->api_connection_count_; i++) {
655 if (this->clients_[i]->flags_.state_subscription) {
656 return true;
657 }
658 }
659 return false;
660}
661
662#ifdef USE_LOGGER
663void APIServer::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
664 if (this->shutting_down_) {
665 // Don't try to send logs during shutdown
666 // as it could result in a recursion and
667 // we would be filling a buffer we are trying to clear
668 return;
669 }
670 for (auto &c : this->active_clients()) {
671 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
672 c->try_send_log_message(level, tag, message, message_len);
673 }
674}
675#endif
676
677#ifdef USE_CAMERA
678void APIServer::on_camera_image(const std::shared_ptr<camera::CameraImage> &image) {
679 for (auto &c : this->active_clients()) {
680 if (!c->flags_.remove)
681 c->set_camera_state(image);
682 }
683}
684#endif
685
687 this->shutting_down_ = true;
688
689 // Close the listening socket to prevent new connections
690 this->destroy_socket_();
691
692 // Change batch delay to 5ms for quick flushing during shutdown
693 this->batch_delay_ = 5;
694
695 // Send disconnect requests to all connected clients
696 for (auto &c : this->active_clients()) {
698 if (!c->send_message(req)) {
699 // If we can't send the disconnect request directly (tx_buffer full),
700 // schedule it at the front of the batch so it will be sent with priority
701 c->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
702 }
703 }
704}
705
707 // If network is disconnected, no point trying to flush buffers
708 if (!network::is_connected()) {
709 return true;
710 }
711 this->loop();
712
713 // Return true only when all clients have been torn down
714 return this->api_connection_count_ == 0;
715}
716
717#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
718// Timeout for action calls - matches aioesphomeapi client timeout (default 30s)
719// Can be overridden via USE_API_ACTION_CALL_TIMEOUT_MS define for testing
720#ifndef USE_API_ACTION_CALL_TIMEOUT_MS
721#define USE_API_ACTION_CALL_TIMEOUT_MS 30000 // NOLINT
722#endif
723
725 uint32_t action_call_id = this->next_action_call_id_++;
726 // Handle wraparound (skip 0 as it means "no call")
727 if (this->next_action_call_id_ == 0) {
728 this->next_action_call_id_ = 1;
729 }
730 this->active_action_calls_.push_back({action_call_id, client_call_id, conn});
731
732 // Schedule automatic cleanup after timeout (client will have given up by then)
733 // Uses numeric ID overload to avoid heap allocation from str_sprintf
734 this->set_timeout(action_call_id, USE_API_ACTION_CALL_TIMEOUT_MS, [this, action_call_id]() {
735 ESP_LOGD(TAG, "Action call %" PRIu32 " timed out", action_call_id);
736 this->unregister_active_action_call(action_call_id);
737 });
738
739 return action_call_id;
740}
741
743 // Cancel the timeout for this action call (uses numeric ID overload)
744 this->cancel_timeout(action_call_id);
745
746 // Swap-and-pop is more efficient than remove_if for unordered vectors
747 for (size_t i = 0; i < this->active_action_calls_.size(); i++) {
748 if (this->active_action_calls_[i].action_call_id == action_call_id) {
749 std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
750 this->active_action_calls_.pop_back();
751 return;
752 }
753 }
754}
755
757 // Remove all active action calls for disconnected connection using swap-and-pop
758 for (size_t i = 0; i < this->active_action_calls_.size();) {
759 if (this->active_action_calls_[i].connection == conn) {
760 // Cancel the timeout for this action call (uses numeric ID overload)
761 this->cancel_timeout(this->active_action_calls_[i].action_call_id);
762
763 std::swap(this->active_action_calls_[i], this->active_action_calls_.back());
764 this->active_action_calls_.pop_back();
765 // Don't increment i - need to check the swapped element
766 } else {
767 i++;
768 }
769 }
770}
771
772void APIServer::send_action_response(uint32_t action_call_id, bool success, StringRef error_message) {
773 for (auto &call : this->active_action_calls_) {
774 if (call.action_call_id == action_call_id) {
775 call.connection->send_execute_service_response(call.client_call_id, success, error_message);
776 return;
777 }
778 }
779 ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %" PRIu32, action_call_id);
780}
781#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
782void APIServer::send_action_response(uint32_t action_call_id, bool success, StringRef error_message,
783 const uint8_t *response_data, size_t response_data_len) {
784 for (auto &call : this->active_action_calls_) {
785 if (call.action_call_id == action_call_id) {
786 call.connection->send_execute_service_response(call.client_call_id, success, error_message, response_data,
787 response_data_len);
788 return;
789 }
790 }
791 ESP_LOGW(TAG, "Cannot send response: no active call found for action_call_id %" PRIu32, action_call_id);
792}
793#endif // USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
794#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
795
796} // namespace esphome::api
797#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
const psk_t & get_psk() const
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:311
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 set_port(uint16_t port)
void dump_config() override
void unregister_active_action_calls_for_connection(APIConnection *conn)
void handle_disconnect(APIConnection *conn)
void set_batch_delay(uint16_t batch_delay)
void set_reboot_timeout(uint32_t reboot_timeout)
void send_action_response(uint32_t action_call_id, bool success, StringRef error_message)
bool save_noise_psk(psk_t psk, bool make_active=true)
void setup() override
bool teardown() override
APINoiseContext noise_ctx_
Definition api_server.h:357
void unregister_active_action_call(uint32_t action_call_id)
void send_homeassistant_action(const HomeassistantActionRequest &call)
socket::ListenSocket * socket_
Definition api_server.h:298
void on_event(event::Event *obj) override
void on_update(update::UpdateEntity *obj) override
std::vector< PendingActionResponse > action_response_callbacks_
Definition api_server.h:340
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:142
bool provisioning_pending_() const
Definition api_server.h:266
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:358
Trigger< std::string, std::string > client_disconnected_trigger_
Definition api_server.h:303
std::vector< HomeAssistantStateSubscription > state_subs_
Definition api_server.h:319
bool clear_noise_psk(bool make_active=true)
ActiveClientsView active_clients() const
Definition api_server.h:209
uint16_t get_port() const
std::vector< ActiveActionCall > active_action_calls_
Definition api_server.h:331
void set_noise_psk(psk_t psk)
Definition api_server.h:78
float get_setup_priority() const override
uint32_t register_active_action_call(uint32_t client_call_id, APIConnection *conn)
void on_shutdown() override
void on_zwave_proxy_request(const ZWaveProxyRequest &msg)
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:436
static constexpr uint8_t ESTIMATED_SIZE
Definition api_pb2.h:437
enums::DisconnectReason reason
Definition api_pb2.h:441
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
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:16
APIServer * global_api_server
API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor) API_DISPATCH_UPDATE(cover
std::array< uint8_t, 32 > psk_t
Logger * global_logger
Definition logger.cpp:279
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:25
ProvisioningManager * global_provisioning_manager
constexpr float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.h:55
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
const char * tag
Definition log.h:74
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:32
std::unique_ptr< std::string > entity_id_dynamic_storage
Definition api_server.h:222
std::unique_ptr< std::string > attribute_dynamic_storage
Definition api_server.h:223
SemaphoreHandle_t lock