ESPHome 2025.10.0-dev
Loading...
Searching...
No Matches
application.cpp
Go to the documentation of this file.
2#include "esphome/core/log.h"
4#include "esphome/core/hal.h"
5#include <algorithm>
6#include <ranges>
7#ifdef USE_RUNTIME_STATS
9#endif
10
11#ifdef USE_STATUS_LED
13#endif
14
15#ifdef USE_SOCKET_SELECT_SUPPORT
16#include <cerrno>
17
18#ifdef USE_SOCKET_IMPL_LWIP_SOCKETS
19// LWIP sockets implementation
20#include <lwip/sockets.h>
21#elif defined(USE_SOCKET_IMPL_BSD_SOCKETS)
22// BSD sockets implementation
23#ifdef USE_ESP32
24// ESP32 "BSD sockets" are actually LWIP under the hood
25#include <lwip/sockets.h>
26#else
27// True BSD sockets (e.g., host platform)
28#include <sys/select.h>
29#endif
30#endif
31#endif
32
33namespace esphome {
34
35static const char *const TAG = "app";
36
37// Helper function for insertion sort of components by priority
38// Using insertion sort instead of std::stable_sort saves ~1.3KB of flash
39// by avoiding template instantiations (std::rotate, std::stable_sort, lambdas)
40// IMPORTANT: This sort is stable (preserves relative order of equal elements),
41// which is necessary to maintain user-defined component order for same priority
42template<typename Iterator, float (Component::*GetPriority)() const>
43static void insertion_sort_by_priority(Iterator first, Iterator last) {
44 for (auto it = first + 1; it != last; ++it) {
45 auto key = *it;
46 float key_priority = (key->*GetPriority)();
47 auto j = it - 1;
48
49 // Using '<' (not '<=') ensures stability - equal priority components keep their order
50 while (j >= first && ((*j)->*GetPriority)() < key_priority) {
51 *(j + 1) = *j;
52 j--;
53 }
54 *(j + 1) = key;
55 }
56}
57
59 if (comp == nullptr) {
60 ESP_LOGW(TAG, "Tried to register null component!");
61 return;
62 }
63
64 for (auto *c : this->components_) {
65 if (comp == c) {
66 ESP_LOGW(TAG, "Component %s already registered! (%p)", LOG_STR_ARG(c->get_component_log_str()), c);
67 return;
68 }
69 }
70 this->components_.push_back(comp);
71}
73 ESP_LOGI(TAG, "Running through setup()");
74 ESP_LOGV(TAG, "Sorting components by setup priority");
75
76 // Sort by setup priority using our helper function
77 insertion_sort_by_priority<decltype(this->components_.begin()), &Component::get_actual_setup_priority>(
78 this->components_.begin(), this->components_.end());
79
80 // Initialize looping_components_ early so enable_pending_loops_() works during setup
82
83 for (uint32_t i = 0; i < this->components_.size(); i++) {
84 Component *component = this->components_[i];
85
86 // Update loop_component_start_time_ before calling each component during setup
88 component->call();
89 this->scheduler.process_to_add();
90 this->feed_wdt();
91 if (component->can_proceed())
92 continue;
93
94 // Sort components 0 through i by loop priority
95 insertion_sort_by_priority<decltype(this->components_.begin()), &Component::get_loop_priority>(
96 this->components_.begin(), this->components_.begin() + i + 1);
97
98 do {
99 uint8_t new_app_state = STATUS_LED_WARNING;
100 uint32_t now = millis();
101
102 // Process pending loop enables to handle GPIO interrupts during setup
103 this->before_loop_tasks_(now);
104
105 for (uint32_t j = 0; j <= i; j++) {
106 // Update loop_component_start_time_ right before calling each component
108 this->components_[j]->call();
109 new_app_state |= this->components_[j]->get_component_state();
110 this->app_state_ |= new_app_state;
111 this->feed_wdt();
112 }
113
114 this->after_loop_tasks_();
115 this->app_state_ = new_app_state;
116 yield();
117 } while (!component->can_proceed());
118 }
119
120 ESP_LOGI(TAG, "setup() finished successfully!");
121
122 // Clear setup priority overrides to free memory
124
125 this->schedule_dump_config();
126}
128 uint8_t new_app_state = 0;
129
130 // Get the initial loop time at the start
131 uint32_t last_op_end_time = millis();
132
133 this->before_loop_tasks_(last_op_end_time);
134
136 this->current_loop_index_++) {
137 Component *component = this->looping_components_[this->current_loop_index_];
138
139 // Update the cached time before each component runs
140 this->loop_component_start_time_ = last_op_end_time;
141
142 {
143 this->set_current_component(component);
144 WarnIfComponentBlockingGuard guard{component, last_op_end_time};
145 component->call();
146 // Use the finish method to get the current time as the end time
147 last_op_end_time = guard.finish();
148 }
149 new_app_state |= component->get_component_state();
150 this->app_state_ |= new_app_state;
151 this->feed_wdt(last_op_end_time);
152 }
153
154 this->after_loop_tasks_();
155 this->app_state_ = new_app_state;
156
157#ifdef USE_RUNTIME_STATS
158 // Process any pending runtime stats printing after all components have run
159 // This ensures stats printing doesn't affect component timing measurements
160 if (global_runtime_stats != nullptr) {
162 }
163#endif
164
165 // Use the last component's end time instead of calling millis() again
166 auto elapsed = last_op_end_time - this->last_loop_;
168 // Even if we overran the loop interval, we still need to select()
169 // to know if any sockets have data ready
170 this->yield_with_select_(0);
171 } else {
172 uint32_t delay_time = this->loop_interval_ - elapsed;
173 uint32_t next_schedule = this->scheduler.next_schedule_in(last_op_end_time).value_or(delay_time);
174 // next_schedule is max 0.5*delay_time
175 // otherwise interval=0 schedules result in constant looping with almost no sleep
176 next_schedule = std::max(next_schedule, delay_time / 2);
177 delay_time = std::min(next_schedule, delay_time);
178
179 this->yield_with_select_(delay_time);
180 }
181 this->last_loop_ = last_op_end_time;
182
183 if (this->dump_config_at_ < this->components_.size()) {
184 if (this->dump_config_at_ == 0) {
185 ESP_LOGI(TAG, "ESPHome version " ESPHOME_VERSION " compiled on %s", this->compilation_time_);
186#ifdef ESPHOME_PROJECT_NAME
187 ESP_LOGI(TAG, "Project " ESPHOME_PROJECT_NAME " version " ESPHOME_PROJECT_VERSION);
188#endif
189 }
190
191 this->components_[this->dump_config_at_]->call_dump_config();
192 this->dump_config_at_++;
193 }
194}
195
196void IRAM_ATTR HOT Application::feed_wdt(uint32_t time) {
197 static uint32_t last_feed = 0;
198 // Use provided time if available, otherwise get current time
199 uint32_t now = time ? time : millis();
200 // Compare in milliseconds (3ms threshold)
201 if (now - last_feed > 3) {
203 last_feed = now;
204#ifdef USE_STATUS_LED
205 if (status_led::global_status_led != nullptr) {
207 }
208#endif
209 }
210}
212 ESP_LOGI(TAG, "Forcing a reboot");
213 for (auto &component : std::ranges::reverse_view(this->components_)) {
214 component->on_shutdown();
215 }
216 arch_restart();
217}
219 ESP_LOGI(TAG, "Rebooting safely");
221 teardown_components(TEARDOWN_TIMEOUT_REBOOT_MS);
223 arch_restart();
224}
225
227 for (auto &component : std::ranges::reverse_view(this->components_)) {
228 component->on_safe_shutdown();
229 }
230 for (auto &component : std::ranges::reverse_view(this->components_)) {
231 component->on_shutdown();
232 }
233}
234
236 for (auto &component : std::ranges::reverse_view(this->components_)) {
237 component->on_powerdown();
238 }
239}
240
241void Application::teardown_components(uint32_t timeout_ms) {
242 uint32_t start_time = millis();
243
244 // Use a StaticVector instead of std::vector to avoid heap allocation
245 // since we know the actual size at compile time
247
248 // Copy all components in reverse order
249 // Reverse order matches the behavior of run_safe_shutdown_hooks() above and ensures
250 // components are torn down in the opposite order of their setup_priority (which is
251 // used to sort components during Application::setup())
252 size_t num_components = this->components_.size();
253 for (size_t i = 0; i < num_components; ++i) {
254 pending_components[i] = this->components_[num_components - 1 - i];
255 }
256
257 uint32_t now = start_time;
258 size_t pending_count = num_components;
259
260 // Teardown Algorithm
261 // ==================
262 // We iterate through pending components, calling teardown() on each.
263 // Components that return false (need more time) are copied forward
264 // in the array. Components that return true (finished) are skipped.
265 //
266 // The compaction happens in-place during iteration:
267 // - still_pending tracks the write position (where to put next pending component)
268 // - i tracks the read position (which component we're testing)
269 // - When teardown() returns false, we copy component[i] to component[still_pending]
270 // - When teardown() returns true, we just skip it (don't increment still_pending)
271 //
272 // Example with 4 components where B can teardown immediately:
273 //
274 // Start:
275 // pending_components: [A, B, C, D]
276 // pending_count: 4 ^----------^
277 //
278 // Iteration 1:
279 // i=0: A needs more time → keep at pos 0 (no copy needed)
280 // i=1: B finished → skip
281 // i=2: C needs more time → copy to pos 1
282 // i=3: D needs more time → copy to pos 2
283 //
284 // After iteration 1:
285 // pending_components: [A, C, D | D]
286 // pending_count: 3 ^--------^
287 //
288 // Iteration 2:
289 // i=0: A finished → skip
290 // i=1: C needs more time → copy to pos 0
291 // i=2: D finished → skip
292 //
293 // After iteration 2:
294 // pending_components: [C | C, D, D] (positions 1-3 have old values)
295 // pending_count: 1 ^--^
296
297 while (pending_count > 0 && (now - start_time) < timeout_ms) {
298 // Feed watchdog during teardown to prevent triggering
299 this->feed_wdt(now);
300
301 // Process components and compact the array, keeping only those still pending
302 size_t still_pending = 0;
303 for (size_t i = 0; i < pending_count; ++i) {
304 if (!pending_components[i]->teardown()) {
305 // Component still needs time, copy it forward
306 if (still_pending != i) {
307 pending_components[still_pending] = pending_components[i];
308 }
309 ++still_pending;
310 }
311 // Component finished teardown, skip it (don't increment still_pending)
312 }
313 pending_count = still_pending;
314
315 // Give some time for I/O operations if components are still pending
316 if (pending_count > 0) {
317 this->yield_with_select_(1);
318 }
319
320 // Update time for next iteration
321 now = millis();
322 }
323
324 if (pending_count > 0) {
325 // Note: At this point, connections are either disconnected or in a bad state,
326 // so this warning will only appear via serial rather than being transmitted to clients
327 for (size_t i = 0; i < pending_count; ++i) {
328 ESP_LOGW(TAG, "%s did not complete teardown within %" PRIu32 " ms",
329 LOG_STR_ARG(pending_components[i]->get_component_log_str()), timeout_ms);
330 }
331 }
332}
333
335 // Count total components that need looping
336 size_t total_looping = 0;
337 for (auto *obj : this->components_) {
338 if (obj->has_overridden_loop()) {
339 total_looping++;
340 }
341 }
342
343 // Pre-reserve vector to avoid reallocations
344 this->looping_components_.reserve(total_looping);
345
346 // Add all components with loop override that aren't already LOOP_DONE
347 // Some components (like logger) may call disable_loop() during initialization
348 // before setup runs, so we need to respect their LOOP_DONE state
350
352
353 // Then add any components that are already LOOP_DONE to the inactive section
354 // This handles components that called disable_loop() during initialization
356}
357
359 for (auto *obj : this->components_) {
360 if (obj->has_overridden_loop() &&
361 ((obj->get_component_state() & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP_DONE) == match_loop_done) {
362 this->looping_components_.push_back(obj);
363 }
364 }
365}
366
368 // This method must be reentrant - components can disable themselves during their own loop() call
369 // Linear search to find component in active section
370 // Most configs have 10-30 looping components (30 is on the high end)
371 // O(n) is acceptable here as we optimize for memory, not complexity
372 for (uint16_t i = 0; i < this->looping_components_active_end_; i++) {
373 if (this->looping_components_[i] == component) {
374 // Move last active component to this position
375 this->looping_components_active_end_--;
376 if (i != this->looping_components_active_end_) {
377 std::swap(this->looping_components_[i], this->looping_components_[this->looping_components_active_end_]);
378
379 // If we're currently iterating and just swapped the current position
380 if (this->in_loop_ && i == this->current_loop_index_) {
381 // Decrement so we'll process the swapped component next
382 this->current_loop_index_--;
383 // Update the loop start time to current time so the swapped component
384 // gets correct timing instead of inheriting stale timing.
385 // This prevents integer underflow in timing calculations by ensuring
386 // the swapped component starts with a fresh timing reference, avoiding
387 // errors caused by stale or wrapped timing values.
389 }
390 }
391 return;
392 }
393 }
394}
395
397 // Helper to move component from inactive to active section
398 if (index != this->looping_components_active_end_) {
399 std::swap(this->looping_components_[index], this->looping_components_[this->looping_components_active_end_]);
400 }
402}
403
405 // This method is only called when component state is LOOP_DONE, so we know
406 // the component must be in the inactive section (if it exists in looping_components_)
407 // Only search the inactive portion for better performance
408 // With typical 0-5 inactive components, O(k) is much faster than O(n)
409 const uint16_t size = this->looping_components_.size();
410 for (uint16_t i = this->looping_components_active_end_; i < size; i++) {
411 if (this->looping_components_[i] == component) {
412 // Found in inactive section - move to active
414 return;
415 }
416 }
417 // Component not found in looping_components_ - this is normal for components
418 // that don't have loop() or were not included in the partitioned vector
419}
420
422 // Process components that requested enable_loop from ISR context
423 // Only iterate through inactive looping_components_ (typically 0-5) instead of all components
424 //
425 // Race condition handling:
426 // 1. We check if component is already in LOOP state first - if so, just clear the flag
427 // This handles reentrancy where enable_loop() was called between ISR and processing
428 // 2. We only clear pending_enable_loop_ after checking state, preventing lost requests
429 // 3. If any components aren't in LOOP_DONE state, we set has_pending_enable_loop_requests_
430 // back to true to ensure we check again next iteration
431 // 4. ISRs can safely set flags at any time - worst case is we process them next iteration
432 // 5. The global flag (has_pending_enable_loop_requests_) is cleared before this method,
433 // so any ISR that fires during processing will be caught in the next loop
434 const uint16_t size = this->looping_components_.size();
435 bool has_pending = false;
436
437 for (uint16_t i = this->looping_components_active_end_; i < size; i++) {
438 Component *component = this->looping_components_[i];
439 if (!component->pending_enable_loop_) {
440 continue; // Skip components without pending requests
441 }
442
443 // Check current state
444 uint8_t state = component->component_state_ & COMPONENT_STATE_MASK;
445
446 // If already in LOOP state, nothing to do - clear flag and continue
448 component->pending_enable_loop_ = false;
449 continue;
450 }
451
452 // If not in LOOP_DONE state, can't enable yet - keep flag set
454 has_pending = true; // Keep tracking this component
455 continue; // Keep the flag set - try again next iteration
456 }
457
458 // Clear the pending flag and enable the loop
459 component->pending_enable_loop_ = false;
460 ESP_LOGVV(TAG, "%s loop enabled from ISR", LOG_STR_ARG(component->get_component_log_str()));
461 component->component_state_ &= ~COMPONENT_STATE_MASK;
463
464 // Move to active section
466 }
467
468 // If we couldn't process some requests, ensure we check again next iteration
469 if (has_pending) {
471 }
472}
473
474void Application::before_loop_tasks_(uint32_t loop_start_time) {
475 // Process scheduled tasks
476 this->scheduler.call(loop_start_time);
477
478 // Feed the watchdog timer
479 this->feed_wdt(loop_start_time);
480
481 // Process any pending enable_loop requests from ISRs
482 // This must be done before marking in_loop_ = true to avoid race conditions
484 // Clear flag BEFORE processing to avoid race condition
485 // If ISR sets it during processing, we'll catch it next loop iteration
486 // This is safe because:
487 // 1. Each component has its own pending_enable_loop_ flag that we check
488 // 2. If we can't process a component (wrong state), enable_pending_loops_()
489 // will set this flag back to true
490 // 3. Any new ISR requests during processing will set the flag again
492 this->enable_pending_loops_();
493 }
494
495 // Mark that we're in the loop for safe reentrant modifications
496 this->in_loop_ = true;
497}
498
500 // Clear the in_loop_ flag to indicate we're done processing components
501 this->in_loop_ = false;
502}
503
504#ifdef USE_SOCKET_SELECT_SUPPORT
506 // WARNING: This function is NOT thread-safe and must only be called from the main loop
507 // It modifies socket_fds_ and related variables without locking
508 if (fd < 0)
509 return false;
510
511#ifndef USE_ESP32
512 // Only check on non-ESP32 platforms
513 // On ESP32 (both Arduino and ESP-IDF), CONFIG_LWIP_MAX_SOCKETS is always <= FD_SETSIZE by design
514 // (LWIP_SOCKET_OFFSET = FD_SETSIZE - CONFIG_LWIP_MAX_SOCKETS per lwipopts.h)
515 // Other platforms may not have this guarantee
516 if (fd >= FD_SETSIZE) {
517 ESP_LOGE(TAG, "fd %d exceeds FD_SETSIZE %d", fd, FD_SETSIZE);
518 return false;
519 }
520#endif
521
522 this->socket_fds_.push_back(fd);
523 this->socket_fds_changed_ = true;
524
525 if (fd > this->max_fd_) {
526 this->max_fd_ = fd;
527 }
528
529 return true;
530}
531
533 // WARNING: This function is NOT thread-safe and must only be called from the main loop
534 // It modifies socket_fds_ and related variables without locking
535 if (fd < 0)
536 return;
537
538 for (size_t i = 0; i < this->socket_fds_.size(); i++) {
539 if (this->socket_fds_[i] != fd)
540 continue;
541
542 // Swap with last element and pop - O(1) removal since order doesn't matter
543 if (i < this->socket_fds_.size() - 1)
544 this->socket_fds_[i] = this->socket_fds_.back();
545 this->socket_fds_.pop_back();
546 this->socket_fds_changed_ = true;
547
548 // Only recalculate max_fd if we removed the current max
549 if (fd == this->max_fd_) {
550 this->max_fd_ = -1;
551 for (int sock_fd : this->socket_fds_) {
552 if (sock_fd > this->max_fd_)
553 this->max_fd_ = sock_fd;
554 }
555 }
556 return;
557 }
558}
559
561 // This function is thread-safe for reading the result of select()
562 // However, it should only be called after select() has been executed in the main loop
563 // The read_fds_ is only modified by select() in the main loop
564 if (fd < 0 || fd >= FD_SETSIZE)
565 return false;
566
567 return FD_ISSET(fd, &this->read_fds_);
568}
569#endif
570
571void Application::yield_with_select_(uint32_t delay_ms) {
572 // Delay while monitoring sockets. When delay_ms is 0, always yield() to ensure other tasks run
573 // since select() with 0 timeout only polls without yielding.
574#ifdef USE_SOCKET_SELECT_SUPPORT
575 if (!this->socket_fds_.empty()) {
576 // Update fd_set if socket list has changed
577 if (this->socket_fds_changed_) {
578 FD_ZERO(&this->base_read_fds_);
579 for (int fd : this->socket_fds_) {
580 if (fd >= 0 && fd < FD_SETSIZE) {
581 FD_SET(fd, &this->base_read_fds_);
582 }
583 }
584 this->socket_fds_changed_ = false;
585 }
586
587 // Copy base fd_set before each select
588 this->read_fds_ = this->base_read_fds_;
589
590 // Convert delay_ms to timeval
591 struct timeval tv;
592 tv.tv_sec = delay_ms / 1000;
593 tv.tv_usec = (delay_ms - tv.tv_sec * 1000) * 1000;
594
595 // Call select with timeout
596#if defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || (defined(USE_ESP32) && defined(USE_SOCKET_IMPL_BSD_SOCKETS))
597 int ret = lwip_select(this->max_fd_ + 1, &this->read_fds_, nullptr, nullptr, &tv);
598#else
599 int ret = ::select(this->max_fd_ + 1, &this->read_fds_, nullptr, nullptr, &tv);
600#endif
601
602 // Process select() result:
603 // ret < 0: error (except EINTR which is normal)
604 // ret > 0: socket(s) have data ready - normal and expected
605 // ret == 0: timeout occurred - normal and expected
606 if (ret < 0 && errno != EINTR) {
607 // Actual error - log and fall back to delay
608 ESP_LOGW(TAG, "select() failed with errno %d", errno);
609 delay(delay_ms);
610 }
611 // When delay_ms is 0, we need to yield since select(0) doesn't yield
612 if (delay_ms == 0) {
613 yield();
614 }
615 } else {
616 // No sockets registered, use regular delay
617 delay(delay_ms);
618 }
619#else
620 // No select support, use regular delay
621 delay(delay_ms);
622#endif
623}
624
625Application App; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
626
627} // namespace esphome
void setup()
Set up all the registered components. Call this at the end of your setup() function.
uint16_t looping_components_active_end_
void set_current_component(Component *component)
bool is_socket_ready(int fd) const
Check if there's data available on a socket without blocking This function is thread-safe for reading...
std::vector< int > socket_fds_
StaticVector< Component *, ESPHOME_COMPONENT_COUNT > components_
void enable_component_loop_(Component *component)
uint32_t loop_component_start_time_
void disable_component_loop_(Component *component)
void activate_looping_component_(uint16_t index)
void teardown_components(uint32_t timeout_ms)
Teardown all components with a timeout.
void add_looping_components_by_state_(bool match_loop_done)
volatile bool has_pending_enable_loop_requests_
const char * compilation_time_
std::vector< Component * > looping_components_
uint16_t current_loop_index_
void feed_wdt(uint32_t time=0)
void before_loop_tasks_(uint32_t loop_start_time)
void loop()
Make a loop iteration. Call this in your loop() function.
void unregister_socket_fd(int fd)
bool register_socket_fd(int fd)
Register/unregister a socket file descriptor to be monitored for read events.
void calculate_looping_components_()
void yield_with_select_(uint32_t delay_ms)
Perform a delay while also monitoring socket file descriptors for readiness.
void register_component_(Component *comp)
float get_actual_setup_priority() const
const LogString * get_component_log_str() const
Get the integration where this component was declared as a LogString for logging.
uint8_t get_component_state() const
volatile bool pending_enable_loop_
ISR-safe flag for enable_loop_soon_any_context.
Definition component.h:420
virtual bool can_proceed()
virtual float get_loop_priority() const
priority of loop().
Definition component.cpp:80
uint8_t component_state_
State of this component - each bit has a purpose: Bits 0-2: Component state (0x00=CONSTRUCTION,...
Definition component.h:419
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:588
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:110
size_t size() const
Definition helpers.h:130
void process_pending_stats(uint32_t current_time)
bool state
Definition fan.h:0
const char *const TAG
Definition spi.cpp:8
StatusLED * global_status_led
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
runtime_stats::RuntimeStatsCollector * global_runtime_stats
const uint8_t COMPONENT_STATE_MASK
Definition component.cpp:63
const uint8_t COMPONENT_STATE_LOOP
Definition component.cpp:66
void clear_setup_priority_overrides()
void IRAM_ATTR HOT yield()
Definition core.cpp:27
void IRAM_ATTR HOT arch_feed_wdt()
Definition core.cpp:56
const uint8_t STATUS_LED_WARNING
Definition component.cpp:72
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
void arch_restart()
Definition core.cpp:32
Application App
Global storage of Application pointer - only one Application can exist.
const uint8_t COMPONENT_STATE_LOOP_DONE
Definition component.cpp:68