ESPHome 2025.9.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 setup 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> static void insertion_sort_by_setup_priority(Iterator first, Iterator last) {
43 for (auto it = first + 1; it != last; ++it) {
44 auto key = *it;
45 float key_priority = key->get_actual_setup_priority();
46 auto j = it - 1;
47
48 // Using '<' (not '<=') ensures stability - equal priority components keep their order
49 while (j >= first && (*j)->get_actual_setup_priority() < key_priority) {
50 *(j + 1) = *j;
51 j--;
52 }
53 *(j + 1) = key;
54 }
55}
56
57// Helper function for insertion sort of components by loop priority
58// IMPORTANT: This sort is stable (preserves relative order of equal elements),
59// which is required when components are re-sorted during setup() if they block
60template<typename Iterator> static void insertion_sort_by_loop_priority(Iterator first, Iterator last) {
61 for (auto it = first + 1; it != last; ++it) {
62 auto key = *it;
63 float key_priority = key->get_loop_priority();
64 auto j = it - 1;
65
66 // Using '<' (not '<=') ensures stability - equal priority components keep their order
67 while (j >= first && (*j)->get_loop_priority() < key_priority) {
68 *(j + 1) = *j;
69 j--;
70 }
71 *(j + 1) = key;
72 }
73}
74
76 if (comp == nullptr) {
77 ESP_LOGW(TAG, "Tried to register null component!");
78 return;
79 }
80
81 for (auto *c : this->components_) {
82 if (comp == c) {
83 ESP_LOGW(TAG, "Component %s already registered! (%p)", c->get_component_source(), c);
84 return;
85 }
86 }
87 this->components_.push_back(comp);
88}
90 ESP_LOGI(TAG, "Running through setup()");
91 ESP_LOGV(TAG, "Sorting components by setup priority");
92
93 // Sort by setup priority using our helper function
94 insertion_sort_by_setup_priority(this->components_.begin(), this->components_.end());
95
96 // Initialize looping_components_ early so enable_pending_loops_() works during setup
98
99 for (uint32_t i = 0; i < this->components_.size(); i++) {
100 Component *component = this->components_[i];
101
102 // Update loop_component_start_time_ before calling each component during setup
104 component->call();
105 this->scheduler.process_to_add();
106 this->feed_wdt();
107 if (component->can_proceed())
108 continue;
109
110 // Sort components 0 through i by loop priority
111 insertion_sort_by_loop_priority(this->components_.begin(), this->components_.begin() + i + 1);
112
113 do {
114 uint8_t new_app_state = STATUS_LED_WARNING;
115 uint32_t now = millis();
116
117 // Process pending loop enables to handle GPIO interrupts during setup
118 this->before_loop_tasks_(now);
119
120 for (uint32_t j = 0; j <= i; j++) {
121 // Update loop_component_start_time_ right before calling each component
123 this->components_[j]->call();
124 new_app_state |= this->components_[j]->get_component_state();
125 this->app_state_ |= new_app_state;
126 this->feed_wdt();
127 }
128
129 this->after_loop_tasks_();
130 this->app_state_ = new_app_state;
131 yield();
132 } while (!component->can_proceed());
133 }
134
135 ESP_LOGI(TAG, "setup() finished successfully!");
136
137 // Clear setup priority overrides to free memory
139
140 this->schedule_dump_config();
141}
143 uint8_t new_app_state = 0;
144
145 // Get the initial loop time at the start
146 uint32_t last_op_end_time = millis();
147
148 this->before_loop_tasks_(last_op_end_time);
149
151 this->current_loop_index_++) {
152 Component *component = this->looping_components_[this->current_loop_index_];
153
154 // Update the cached time before each component runs
155 this->loop_component_start_time_ = last_op_end_time;
156
157 {
158 this->set_current_component(component);
159 WarnIfComponentBlockingGuard guard{component, last_op_end_time};
160 component->call();
161 // Use the finish method to get the current time as the end time
162 last_op_end_time = guard.finish();
163 }
164 new_app_state |= component->get_component_state();
165 this->app_state_ |= new_app_state;
166 this->feed_wdt(last_op_end_time);
167 }
168
169 this->after_loop_tasks_();
170 this->app_state_ = new_app_state;
171
172#ifdef USE_RUNTIME_STATS
173 // Process any pending runtime stats printing after all components have run
174 // This ensures stats printing doesn't affect component timing measurements
175 if (global_runtime_stats != nullptr) {
177 }
178#endif
179
180 // Use the last component's end time instead of calling millis() again
181 auto elapsed = last_op_end_time - this->last_loop_;
183 // Even if we overran the loop interval, we still need to select()
184 // to know if any sockets have data ready
185 this->yield_with_select_(0);
186 } else {
187 uint32_t delay_time = this->loop_interval_ - elapsed;
188 uint32_t next_schedule = this->scheduler.next_schedule_in(last_op_end_time).value_or(delay_time);
189 // next_schedule is max 0.5*delay_time
190 // otherwise interval=0 schedules result in constant looping with almost no sleep
191 next_schedule = std::max(next_schedule, delay_time / 2);
192 delay_time = std::min(next_schedule, delay_time);
193
194 this->yield_with_select_(delay_time);
195 }
196 this->last_loop_ = last_op_end_time;
197
198 if (this->dump_config_at_ < this->components_.size()) {
199 if (this->dump_config_at_ == 0) {
200 ESP_LOGI(TAG, "ESPHome version " ESPHOME_VERSION " compiled on %s", this->compilation_time_);
201#ifdef ESPHOME_PROJECT_NAME
202 ESP_LOGI(TAG, "Project " ESPHOME_PROJECT_NAME " version " ESPHOME_PROJECT_VERSION);
203#endif
204 }
205
206 this->components_[this->dump_config_at_]->call_dump_config();
207 this->dump_config_at_++;
208 }
209}
210
211void IRAM_ATTR HOT Application::feed_wdt(uint32_t time) {
212 static uint32_t last_feed = 0;
213 // Use provided time if available, otherwise get current time
214 uint32_t now = time ? time : millis();
215 // Compare in milliseconds (3ms threshold)
216 if (now - last_feed > 3) {
218 last_feed = now;
219#ifdef USE_STATUS_LED
220 if (status_led::global_status_led != nullptr) {
222 }
223#endif
224 }
225}
227 ESP_LOGI(TAG, "Forcing a reboot");
228 for (auto &component : std::ranges::reverse_view(this->components_)) {
229 component->on_shutdown();
230 }
231 arch_restart();
232}
234 ESP_LOGI(TAG, "Rebooting safely");
236 teardown_components(TEARDOWN_TIMEOUT_REBOOT_MS);
238 arch_restart();
239}
240
242 for (auto &component : std::ranges::reverse_view(this->components_)) {
243 component->on_safe_shutdown();
244 }
245 for (auto &component : std::ranges::reverse_view(this->components_)) {
246 component->on_shutdown();
247 }
248}
249
251 for (auto &component : std::ranges::reverse_view(this->components_)) {
252 component->on_powerdown();
253 }
254}
255
256void Application::teardown_components(uint32_t timeout_ms) {
257 uint32_t start_time = millis();
258
259 // Copy all components in reverse order using reverse iterators
260 // Reverse order matches the behavior of run_safe_shutdown_hooks() above and ensures
261 // components are torn down in the opposite order of their setup_priority (which is
262 // used to sort components during Application::setup())
263 std::vector<Component *> pending_components(this->components_.rbegin(), this->components_.rend());
264
265 uint32_t now = start_time;
266 while (!pending_components.empty() && (now - start_time) < timeout_ms) {
267 // Feed watchdog during teardown to prevent triggering
268 this->feed_wdt(now);
269
270 // Use iterator to safely erase elements
271 for (auto it = pending_components.begin(); it != pending_components.end();) {
272 if ((*it)->teardown()) {
273 // Component finished teardown, erase it
274 it = pending_components.erase(it);
275 } else {
276 // Component still needs time
277 ++it;
278 }
279 }
280
281 // Give some time for I/O operations if components are still pending
282 if (!pending_components.empty()) {
283 this->yield_with_select_(1);
284 }
285
286 // Update time for next iteration
287 now = millis();
288 }
289
290 if (!pending_components.empty()) {
291 // Note: At this point, connections are either disconnected or in a bad state,
292 // so this warning will only appear via serial rather than being transmitted to clients
293 for (auto *component : pending_components) {
294 ESP_LOGW(TAG, "%s did not complete teardown within %" PRIu32 " ms", component->get_component_source(),
295 timeout_ms);
296 }
297 }
298}
299
301 // Count total components that need looping
302 size_t total_looping = 0;
303 for (auto *obj : this->components_) {
304 if (obj->has_overridden_loop()) {
305 total_looping++;
306 }
307 }
308
309 // Pre-reserve vector to avoid reallocations
310 this->looping_components_.reserve(total_looping);
311
312 // Add all components with loop override that aren't already LOOP_DONE
313 // Some components (like logger) may call disable_loop() during initialization
314 // before setup runs, so we need to respect their LOOP_DONE state
315 for (auto *obj : this->components_) {
316 if (obj->has_overridden_loop() &&
317 (obj->get_component_state() & COMPONENT_STATE_MASK) != COMPONENT_STATE_LOOP_DONE) {
318 this->looping_components_.push_back(obj);
319 }
320 }
321
323
324 // Then add any components that are already LOOP_DONE to the inactive section
325 // This handles components that called disable_loop() during initialization
326 for (auto *obj : this->components_) {
327 if (obj->has_overridden_loop() &&
328 (obj->get_component_state() & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP_DONE) {
329 this->looping_components_.push_back(obj);
330 }
331 }
332}
333
335 // This method must be reentrant - components can disable themselves during their own loop() call
336 // Linear search to find component in active section
337 // Most configs have 10-30 looping components (30 is on the high end)
338 // O(n) is acceptable here as we optimize for memory, not complexity
339 for (uint16_t i = 0; i < this->looping_components_active_end_; i++) {
340 if (this->looping_components_[i] == component) {
341 // Move last active component to this position
342 this->looping_components_active_end_--;
343 if (i != this->looping_components_active_end_) {
344 std::swap(this->looping_components_[i], this->looping_components_[this->looping_components_active_end_]);
345
346 // If we're currently iterating and just swapped the current position
347 if (this->in_loop_ && i == this->current_loop_index_) {
348 // Decrement so we'll process the swapped component next
349 this->current_loop_index_--;
350 // Update the loop start time to current time so the swapped component
351 // gets correct timing instead of inheriting stale timing.
352 // This prevents integer underflow in timing calculations by ensuring
353 // the swapped component starts with a fresh timing reference, avoiding
354 // errors caused by stale or wrapped timing values.
356 }
357 }
358 return;
359 }
360 }
361}
362
364 // Helper to move component from inactive to active section
365 if (index != this->looping_components_active_end_) {
366 std::swap(this->looping_components_[index], this->looping_components_[this->looping_components_active_end_]);
367 }
369}
370
372 // This method is only called when component state is LOOP_DONE, so we know
373 // the component must be in the inactive section (if it exists in looping_components_)
374 // Only search the inactive portion for better performance
375 // With typical 0-5 inactive components, O(k) is much faster than O(n)
376 const uint16_t size = this->looping_components_.size();
377 for (uint16_t i = this->looping_components_active_end_; i < size; i++) {
378 if (this->looping_components_[i] == component) {
379 // Found in inactive section - move to active
381 return;
382 }
383 }
384 // Component not found in looping_components_ - this is normal for components
385 // that don't have loop() or were not included in the partitioned vector
386}
387
389 // Process components that requested enable_loop from ISR context
390 // Only iterate through inactive looping_components_ (typically 0-5) instead of all components
391 //
392 // Race condition handling:
393 // 1. We check if component is already in LOOP state first - if so, just clear the flag
394 // This handles reentrancy where enable_loop() was called between ISR and processing
395 // 2. We only clear pending_enable_loop_ after checking state, preventing lost requests
396 // 3. If any components aren't in LOOP_DONE state, we set has_pending_enable_loop_requests_
397 // back to true to ensure we check again next iteration
398 // 4. ISRs can safely set flags at any time - worst case is we process them next iteration
399 // 5. The global flag (has_pending_enable_loop_requests_) is cleared before this method,
400 // so any ISR that fires during processing will be caught in the next loop
401 const uint16_t size = this->looping_components_.size();
402 bool has_pending = false;
403
404 for (uint16_t i = this->looping_components_active_end_; i < size; i++) {
405 Component *component = this->looping_components_[i];
406 if (!component->pending_enable_loop_) {
407 continue; // Skip components without pending requests
408 }
409
410 // Check current state
411 uint8_t state = component->component_state_ & COMPONENT_STATE_MASK;
412
413 // If already in LOOP state, nothing to do - clear flag and continue
415 component->pending_enable_loop_ = false;
416 continue;
417 }
418
419 // If not in LOOP_DONE state, can't enable yet - keep flag set
421 has_pending = true; // Keep tracking this component
422 continue; // Keep the flag set - try again next iteration
423 }
424
425 // Clear the pending flag and enable the loop
426 component->pending_enable_loop_ = false;
427 ESP_LOGVV(TAG, "%s loop enabled from ISR", component->get_component_source());
428 component->component_state_ &= ~COMPONENT_STATE_MASK;
430
431 // Move to active section
433 }
434
435 // If we couldn't process some requests, ensure we check again next iteration
436 if (has_pending) {
438 }
439}
440
441void Application::before_loop_tasks_(uint32_t loop_start_time) {
442 // Process scheduled tasks
443 this->scheduler.call(loop_start_time);
444
445 // Feed the watchdog timer
446 this->feed_wdt(loop_start_time);
447
448 // Process any pending enable_loop requests from ISRs
449 // This must be done before marking in_loop_ = true to avoid race conditions
451 // Clear flag BEFORE processing to avoid race condition
452 // If ISR sets it during processing, we'll catch it next loop iteration
453 // This is safe because:
454 // 1. Each component has its own pending_enable_loop_ flag that we check
455 // 2. If we can't process a component (wrong state), enable_pending_loops_()
456 // will set this flag back to true
457 // 3. Any new ISR requests during processing will set the flag again
459 this->enable_pending_loops_();
460 }
461
462 // Mark that we're in the loop for safe reentrant modifications
463 this->in_loop_ = true;
464}
465
467 // Clear the in_loop_ flag to indicate we're done processing components
468 this->in_loop_ = false;
469}
470
471#ifdef USE_SOCKET_SELECT_SUPPORT
473 // WARNING: This function is NOT thread-safe and must only be called from the main loop
474 // It modifies socket_fds_ and related variables without locking
475 if (fd < 0)
476 return false;
477
478 if (fd >= FD_SETSIZE) {
479 ESP_LOGE(TAG, "Cannot monitor socket fd %d: exceeds FD_SETSIZE (%d)", fd, FD_SETSIZE);
480 ESP_LOGE(TAG, "Socket will not be monitored for data - may cause performance issues!");
481 return false;
482 }
483
484 this->socket_fds_.push_back(fd);
485 this->socket_fds_changed_ = true;
486
487 if (fd > this->max_fd_) {
488 this->max_fd_ = fd;
489 }
490
491 return true;
492}
493
495 // WARNING: This function is NOT thread-safe and must only be called from the main loop
496 // It modifies socket_fds_ and related variables without locking
497 if (fd < 0)
498 return;
499
500 for (size_t i = 0; i < this->socket_fds_.size(); i++) {
501 if (this->socket_fds_[i] != fd)
502 continue;
503
504 // Swap with last element and pop - O(1) removal since order doesn't matter
505 if (i < this->socket_fds_.size() - 1)
506 this->socket_fds_[i] = this->socket_fds_.back();
507 this->socket_fds_.pop_back();
508 this->socket_fds_changed_ = true;
509
510 // Only recalculate max_fd if we removed the current max
511 if (fd == this->max_fd_) {
512 this->max_fd_ = -1;
513 for (int sock_fd : this->socket_fds_) {
514 if (sock_fd > this->max_fd_)
515 this->max_fd_ = sock_fd;
516 }
517 }
518 return;
519 }
520}
521
523 // This function is thread-safe for reading the result of select()
524 // However, it should only be called after select() has been executed in the main loop
525 // The read_fds_ is only modified by select() in the main loop
526 if (fd < 0 || fd >= FD_SETSIZE)
527 return false;
528
529 return FD_ISSET(fd, &this->read_fds_);
530}
531#endif
532
533void Application::yield_with_select_(uint32_t delay_ms) {
534 // Delay while monitoring sockets. When delay_ms is 0, always yield() to ensure other tasks run
535 // since select() with 0 timeout only polls without yielding.
536#ifdef USE_SOCKET_SELECT_SUPPORT
537 if (!this->socket_fds_.empty()) {
538 // Update fd_set if socket list has changed
539 if (this->socket_fds_changed_) {
540 FD_ZERO(&this->base_read_fds_);
541 for (int fd : this->socket_fds_) {
542 if (fd >= 0 && fd < FD_SETSIZE) {
543 FD_SET(fd, &this->base_read_fds_);
544 }
545 }
546 this->socket_fds_changed_ = false;
547 }
548
549 // Copy base fd_set before each select
550 this->read_fds_ = this->base_read_fds_;
551
552 // Convert delay_ms to timeval
553 struct timeval tv;
554 tv.tv_sec = delay_ms / 1000;
555 tv.tv_usec = (delay_ms - tv.tv_sec * 1000) * 1000;
556
557 // Call select with timeout
558#if defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || (defined(USE_ESP32) && defined(USE_SOCKET_IMPL_BSD_SOCKETS))
559 int ret = lwip_select(this->max_fd_ + 1, &this->read_fds_, nullptr, nullptr, &tv);
560#else
561 int ret = ::select(this->max_fd_ + 1, &this->read_fds_, nullptr, nullptr, &tv);
562#endif
563
564 // Process select() result:
565 // ret < 0: error (except EINTR which is normal)
566 // ret > 0: socket(s) have data ready - normal and expected
567 // ret == 0: timeout occurred - normal and expected
568 if (ret < 0 && errno != EINTR) {
569 // Actual error - log and fall back to delay
570 ESP_LOGW(TAG, "select() failed with errno %d", errno);
571 delay(delay_ms);
572 }
573 // When delay_ms is 0, we need to yield since select(0) doesn't yield
574 if (delay_ms == 0) {
575 yield();
576 }
577 } else {
578 // No sockets registered, use regular delay
579 delay(delay_ms);
580 }
581#else
582 // No select support, use regular delay
583 delay(delay_ms);
584#endif
585}
586
587Application App; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
588
589} // 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.
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)
uint8_t get_component_state() const
volatile bool pending_enable_loop_
ISR-safe flag for enable_loop_soon_any_context.
Definition component.h:416
virtual bool can_proceed()
const char * get_component_source() const
Get the integration where this component was declared as a string.
uint8_t component_state_
State of this component - each bit has a purpose: Bits 0-2: Component state (0x00=CONSTRUCTION,...
Definition component.h:415
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:576
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:64
const uint8_t COMPONENT_STATE_LOOP
Definition component.cpp:67
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:73
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:69