ESPHome 2026.1.0-dev
Loading...
Searching...
No Matches
application.cpp
Go to the documentation of this file.
3#include "esphome/core/log.h"
5#include <cstring>
6
7#ifdef USE_ESP8266
8#include <pgmspace.h>
9#endif
11#include "esphome/core/hal.h"
12#include <algorithm>
13#include <ranges>
14#ifdef USE_RUNTIME_STATS
16#endif
17
18#ifdef USE_STATUS_LED
20#endif
21
22#if defined(USE_ESP8266) && defined(USE_SOCKET_IMPL_LWIP_TCP)
24#endif
25
26#ifdef USE_SOCKET_SELECT_SUPPORT
27#include <cerrno>
28
29#ifdef USE_SOCKET_IMPL_LWIP_SOCKETS
30// LWIP sockets implementation
31#include <lwip/sockets.h>
32#elif defined(USE_SOCKET_IMPL_BSD_SOCKETS)
33// BSD sockets implementation
34#ifdef USE_ESP32
35// ESP32 "BSD sockets" are actually LWIP under the hood
36#include <lwip/sockets.h>
37#else
38// True BSD sockets (e.g., host platform)
39#include <sys/select.h>
40#endif
41#endif
42#endif
43
44namespace esphome {
45
46static const char *const TAG = "app";
47
48// Helper function for insertion sort of components by priority
49// Using insertion sort instead of std::stable_sort saves ~1.3KB of flash
50// by avoiding template instantiations (std::rotate, std::stable_sort, lambdas)
51// IMPORTANT: This sort is stable (preserves relative order of equal elements),
52// which is necessary to maintain user-defined component order for same priority
53template<typename Iterator, float (Component::*GetPriority)() const>
54static void insertion_sort_by_priority(Iterator first, Iterator last) {
55 for (auto it = first + 1; it != last; ++it) {
56 auto key = *it;
57 float key_priority = (key->*GetPriority)();
58 auto j = it - 1;
59
60 // Using '<' (not '<=') ensures stability - equal priority components keep their order
61 while (j >= first && ((*j)->*GetPriority)() < key_priority) {
62 *(j + 1) = *j;
63 j--;
64 }
65 *(j + 1) = key;
66 }
67}
68
70 if (comp == nullptr) {
71 ESP_LOGW(TAG, "Tried to register null component!");
72 return;
73 }
74
75 for (auto *c : this->components_) {
76 if (comp == c) {
77 ESP_LOGW(TAG, "Component %s already registered! (%p)", LOG_STR_ARG(c->get_component_log_str()), c);
78 return;
79 }
80 }
81 this->components_.push_back(comp);
82}
84 ESP_LOGI(TAG, "Running through setup()");
85 ESP_LOGV(TAG, "Sorting components by setup priority");
86
87 // Sort by setup priority using our helper function
88 insertion_sort_by_priority<decltype(this->components_.begin()), &Component::get_actual_setup_priority>(
89 this->components_.begin(), this->components_.end());
90
91 // Initialize looping_components_ early so enable_pending_loops_() works during setup
93
94 for (uint32_t i = 0; i < this->components_.size(); i++) {
96
97 // Update loop_component_start_time_ before calling each component during setup
99 component->call();
100 this->scheduler.process_to_add();
101 this->feed_wdt();
102 if (component->can_proceed())
103 continue;
104
105 // Sort components 0 through i by loop priority
106 insertion_sort_by_priority<decltype(this->components_.begin()), &Component::get_loop_priority>(
107 this->components_.begin(), this->components_.begin() + i + 1);
108
109 do {
110 uint8_t new_app_state = STATUS_LED_WARNING;
111 uint32_t now = millis();
112
113 // Process pending loop enables to handle GPIO interrupts during setup
114 this->before_loop_tasks_(now);
115
116 for (uint32_t j = 0; j <= i; j++) {
117 // Update loop_component_start_time_ right before calling each component
119 this->components_[j]->call();
120 new_app_state |= this->components_[j]->get_component_state();
121 this->app_state_ |= new_app_state;
122 this->feed_wdt();
123 }
124
125 this->after_loop_tasks_();
126 this->app_state_ = new_app_state;
127 yield();
128 } while (!component->can_proceed());
129 }
130
131 ESP_LOGI(TAG, "setup() finished successfully!");
132
133 // Clear setup priority overrides to free memory
135
136#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
137 // Set up wake socket for waking main loop from tasks
139#endif
140
141 this->schedule_dump_config();
142}
144 uint8_t new_app_state = 0;
145
146 // Get the initial loop time at the start
147 uint32_t last_op_end_time = millis();
148
149 this->before_loop_tasks_(last_op_end_time);
150
152 this->current_loop_index_++) {
154
155 // Update the cached time before each component runs
156 this->loop_component_start_time_ = last_op_end_time;
157
158 {
159 this->set_current_component(component);
160 WarnIfComponentBlockingGuard guard{component, last_op_end_time};
161 component->call();
162 // Use the finish method to get the current time as the end time
163 last_op_end_time = guard.finish();
164 }
165 new_app_state |= component->get_component_state();
166 this->app_state_ |= new_app_state;
167 this->feed_wdt(last_op_end_time);
168 }
169
170 this->after_loop_tasks_();
171 this->app_state_ = new_app_state;
172
173#ifdef USE_RUNTIME_STATS
174 // Process any pending runtime stats printing after all components have run
175 // This ensures stats printing doesn't affect component timing measurements
176 if (global_runtime_stats != nullptr) {
178 }
179#endif
180
181 // Use the last component's end time instead of calling millis() again
182 auto elapsed = last_op_end_time - this->last_loop_;
184 // Even if we overran the loop interval, we still need to select()
185 // to know if any sockets have data ready
186 this->yield_with_select_(0);
187 } else {
188 uint32_t delay_time = this->loop_interval_ - elapsed;
189 uint32_t next_schedule = this->scheduler.next_schedule_in(last_op_end_time).value_or(delay_time);
190 // next_schedule is max 0.5*delay_time
191 // otherwise interval=0 schedules result in constant looping with almost no sleep
192 next_schedule = std::max(next_schedule, delay_time / 2);
193 delay_time = std::min(next_schedule, delay_time);
194
195 this->yield_with_select_(delay_time);
196 }
197 this->last_loop_ = last_op_end_time;
198
199 if (this->dump_config_at_ < this->components_.size()) {
200 if (this->dump_config_at_ == 0) {
201 char build_time_str[Application::BUILD_TIME_STR_SIZE];
202 this->get_build_time_string(build_time_str);
203 ESP_LOGI(TAG, "ESPHome version " ESPHOME_VERSION " compiled on %s", build_time_str);
204#ifdef ESPHOME_PROJECT_NAME
205 ESP_LOGI(TAG, "Project " ESPHOME_PROJECT_NAME " version " ESPHOME_PROJECT_VERSION);
206#endif
207 }
208
209 this->components_[this->dump_config_at_]->call_dump_config();
210 this->dump_config_at_++;
211 }
212}
213
214void IRAM_ATTR HOT Application::feed_wdt(uint32_t time) {
215 static uint32_t last_feed = 0;
216 // Use provided time if available, otherwise get current time
217 uint32_t now = time ? time : millis();
218 // Compare in milliseconds (3ms threshold)
219 if (now - last_feed > 3) {
221 last_feed = now;
222#ifdef USE_STATUS_LED
223 if (status_led::global_status_led != nullptr) {
225 }
226#endif
227 }
228}
230 ESP_LOGI(TAG, "Forcing a reboot");
231 for (auto &component : std::ranges::reverse_view(this->components_)) {
232 component->on_shutdown();
233 }
234 arch_restart();
235}
237 ESP_LOGI(TAG, "Rebooting safely");
239 teardown_components(TEARDOWN_TIMEOUT_REBOOT_MS);
241 arch_restart();
242}
243
245 for (auto &component : std::ranges::reverse_view(this->components_)) {
246 component->on_safe_shutdown();
247 }
248 for (auto &component : std::ranges::reverse_view(this->components_)) {
249 component->on_shutdown();
250 }
251}
252
254 for (auto &component : std::ranges::reverse_view(this->components_)) {
255 component->on_powerdown();
256 }
257}
258
259void Application::teardown_components(uint32_t timeout_ms) {
260 uint32_t start_time = millis();
261
262 // Use a StaticVector instead of std::vector to avoid heap allocation
263 // since we know the actual size at compile time
265
266 // Copy all components in reverse order
267 // Reverse order matches the behavior of run_safe_shutdown_hooks() above and ensures
268 // components are torn down in the opposite order of their setup_priority (which is
269 // used to sort components during Application::setup())
270 size_t num_components = this->components_.size();
271 for (size_t i = 0; i < num_components; ++i) {
272 pending_components[i] = this->components_[num_components - 1 - i];
273 }
274
275 uint32_t now = start_time;
276 size_t pending_count = num_components;
277
278 // Teardown Algorithm
279 // ==================
280 // We iterate through pending components, calling teardown() on each.
281 // Components that return false (need more time) are copied forward
282 // in the array. Components that return true (finished) are skipped.
283 //
284 // The compaction happens in-place during iteration:
285 // - still_pending tracks the write position (where to put next pending component)
286 // - i tracks the read position (which component we're testing)
287 // - When teardown() returns false, we copy component[i] to component[still_pending]
288 // - When teardown() returns true, we just skip it (don't increment still_pending)
289 //
290 // Example with 4 components where B can teardown immediately:
291 //
292 // Start:
293 // pending_components: [A, B, C, D]
294 // pending_count: 4 ^----------^
295 //
296 // Iteration 1:
297 // i=0: A needs more time → keep at pos 0 (no copy needed)
298 // i=1: B finished → skip
299 // i=2: C needs more time → copy to pos 1
300 // i=3: D needs more time → copy to pos 2
301 //
302 // After iteration 1:
303 // pending_components: [A, C, D | D]
304 // pending_count: 3 ^--------^
305 //
306 // Iteration 2:
307 // i=0: A finished → skip
308 // i=1: C needs more time → copy to pos 0
309 // i=2: D finished → skip
310 //
311 // After iteration 2:
312 // pending_components: [C | C, D, D] (positions 1-3 have old values)
313 // pending_count: 1 ^--^
314
315 while (pending_count > 0 && (now - start_time) < timeout_ms) {
316 // Feed watchdog during teardown to prevent triggering
317 this->feed_wdt(now);
318
319 // Process components and compact the array, keeping only those still pending
320 size_t still_pending = 0;
321 for (size_t i = 0; i < pending_count; ++i) {
322 if (!pending_components[i]->teardown()) {
323 // Component still needs time, copy it forward
324 if (still_pending != i) {
325 pending_components[still_pending] = pending_components[i];
326 }
327 ++still_pending;
328 }
329 // Component finished teardown, skip it (don't increment still_pending)
330 }
331 pending_count = still_pending;
332
333 // Give some time for I/O operations if components are still pending
334 if (pending_count > 0) {
335 this->yield_with_select_(1);
336 }
337
338 // Update time for next iteration
339 now = millis();
340 }
341
342 if (pending_count > 0) {
343 // Note: At this point, connections are either disconnected or in a bad state,
344 // so this warning will only appear via serial rather than being transmitted to clients
345 for (size_t i = 0; i < pending_count; ++i) {
346 ESP_LOGW(TAG, "%s did not complete teardown within %" PRIu32 " ms",
347 LOG_STR_ARG(pending_components[i]->get_component_log_str()), timeout_ms);
348 }
349 }
350}
351
353 // Count total components that need looping
354 size_t total_looping = 0;
355 for (auto *obj : this->components_) {
356 if (obj->has_overridden_loop()) {
357 total_looping++;
358 }
359 }
360
361 // Initialize FixedVector with exact size - no reallocation possible
362 this->looping_components_.init(total_looping);
363
364 // Add all components with loop override that aren't already LOOP_DONE
365 // Some components (like logger) may call disable_loop() during initialization
366 // before setup runs, so we need to respect their LOOP_DONE state
368
370
371 // Then add any components that are already LOOP_DONE to the inactive section
372 // This handles components that called disable_loop() during initialization
374}
375
377 for (auto *obj : this->components_) {
378 if (obj->has_overridden_loop() &&
379 ((obj->get_component_state() & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP_DONE) == match_loop_done) {
380 this->looping_components_.push_back(obj);
381 }
382 }
383}
384
386 // This method must be reentrant - components can disable themselves during their own loop() call
387 // Linear search to find component in active section
388 // Most configs have 10-30 looping components (30 is on the high end)
389 // O(n) is acceptable here as we optimize for memory, not complexity
390 for (uint16_t i = 0; i < this->looping_components_active_end_; i++) {
391 if (this->looping_components_[i] == component) {
392 // Move last active component to this position
393 this->looping_components_active_end_--;
394 if (i != this->looping_components_active_end_) {
395 std::swap(this->looping_components_[i], this->looping_components_[this->looping_components_active_end_]);
396
397 // If we're currently iterating and just swapped the current position
398 if (this->in_loop_ && i == this->current_loop_index_) {
399 // Decrement so we'll process the swapped component next
400 this->current_loop_index_--;
401 // Update the loop start time to current time so the swapped component
402 // gets correct timing instead of inheriting stale timing.
403 // This prevents integer underflow in timing calculations by ensuring
404 // the swapped component starts with a fresh timing reference, avoiding
405 // errors caused by stale or wrapped timing values.
407 }
408 }
409 return;
410 }
411 }
412}
413
415 // Helper to move component from inactive to active section
416 if (index != this->looping_components_active_end_) {
417 std::swap(this->looping_components_[index], this->looping_components_[this->looping_components_active_end_]);
418 }
420}
421
423 // This method is only called when component state is LOOP_DONE, so we know
424 // the component must be in the inactive section (if it exists in looping_components_)
425 // Only search the inactive portion for better performance
426 // With typical 0-5 inactive components, O(k) is much faster than O(n)
427 const uint16_t size = this->looping_components_.size();
428 for (uint16_t i = this->looping_components_active_end_; i < size; i++) {
429 if (this->looping_components_[i] == component) {
430 // Found in inactive section - move to active
432 return;
433 }
434 }
435 // Component not found in looping_components_ - this is normal for components
436 // that don't have loop() or were not included in the partitioned vector
437}
438
440 // Process components that requested enable_loop from ISR context
441 // Only iterate through inactive looping_components_ (typically 0-5) instead of all components
442 //
443 // Race condition handling:
444 // 1. We check if component is already in LOOP state first - if so, just clear the flag
445 // This handles reentrancy where enable_loop() was called between ISR and processing
446 // 2. We only clear pending_enable_loop_ after checking state, preventing lost requests
447 // 3. If any components aren't in LOOP_DONE state, we set has_pending_enable_loop_requests_
448 // back to true to ensure we check again next iteration
449 // 4. ISRs can safely set flags at any time - worst case is we process them next iteration
450 // 5. The global flag (has_pending_enable_loop_requests_) is cleared before this method,
451 // so any ISR that fires during processing will be caught in the next loop
452 const uint16_t size = this->looping_components_.size();
453 bool has_pending = false;
454
455 for (uint16_t i = this->looping_components_active_end_; i < size; i++) {
457 if (!component->pending_enable_loop_) {
458 continue; // Skip components without pending requests
459 }
460
461 // Check current state
463
464 // If already in LOOP state, nothing to do - clear flag and continue
466 component->pending_enable_loop_ = false;
467 continue;
468 }
469
470 // If not in LOOP_DONE state, can't enable yet - keep flag set
472 has_pending = true; // Keep tracking this component
473 continue; // Keep the flag set - try again next iteration
474 }
475
476 // Clear the pending flag and enable the loop
477 component->pending_enable_loop_ = false;
478 ESP_LOGVV(TAG, "%s loop enabled from ISR", LOG_STR_ARG(component->get_component_log_str()));
479 component->component_state_ &= ~COMPONENT_STATE_MASK;
480 component->component_state_ |= COMPONENT_STATE_LOOP;
481
482 // Move to active section
484 }
485
486 // If we couldn't process some requests, ensure we check again next iteration
487 if (has_pending) {
489 }
490}
491
492void Application::before_loop_tasks_(uint32_t loop_start_time) {
493#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
494 // Drain wake notifications first to clear socket for next wake
496#endif
497
498 // Process scheduled tasks
499 this->scheduler.call(loop_start_time);
500
501 // Feed the watchdog timer
502 this->feed_wdt(loop_start_time);
503
504 // Process any pending enable_loop requests from ISRs
505 // This must be done before marking in_loop_ = true to avoid race conditions
507 // Clear flag BEFORE processing to avoid race condition
508 // If ISR sets it during processing, we'll catch it next loop iteration
509 // This is safe because:
510 // 1. Each component has its own pending_enable_loop_ flag that we check
511 // 2. If we can't process a component (wrong state), enable_pending_loops_()
512 // will set this flag back to true
513 // 3. Any new ISR requests during processing will set the flag again
515 this->enable_pending_loops_();
516 }
517
518 // Mark that we're in the loop for safe reentrant modifications
519 this->in_loop_ = true;
520}
521
523 // Clear the in_loop_ flag to indicate we're done processing components
524 this->in_loop_ = false;
525}
526
527#ifdef USE_SOCKET_SELECT_SUPPORT
529 // WARNING: This function is NOT thread-safe and must only be called from the main loop
530 // It modifies socket_fds_ and related variables without locking
531 if (fd < 0)
532 return false;
533
534#ifndef USE_ESP32
535 // Only check on non-ESP32 platforms
536 // On ESP32 (both Arduino and ESP-IDF), CONFIG_LWIP_MAX_SOCKETS is always <= FD_SETSIZE by design
537 // (LWIP_SOCKET_OFFSET = FD_SETSIZE - CONFIG_LWIP_MAX_SOCKETS per lwipopts.h)
538 // Other platforms may not have this guarantee
539 if (fd >= FD_SETSIZE) {
540 ESP_LOGE(TAG, "fd %d exceeds FD_SETSIZE %d", fd, FD_SETSIZE);
541 return false;
542 }
543#endif
544
545 this->socket_fds_.push_back(fd);
546 this->socket_fds_changed_ = true;
547
548 if (fd > this->max_fd_) {
549 this->max_fd_ = fd;
550 }
551
552 return true;
553}
554
556 // WARNING: This function is NOT thread-safe and must only be called from the main loop
557 // It modifies socket_fds_ and related variables without locking
558 if (fd < 0)
559 return;
560
561 for (size_t i = 0; i < this->socket_fds_.size(); i++) {
562 if (this->socket_fds_[i] != fd)
563 continue;
564
565 // Swap with last element and pop - O(1) removal since order doesn't matter
566 if (i < this->socket_fds_.size() - 1)
567 this->socket_fds_[i] = this->socket_fds_.back();
568 this->socket_fds_.pop_back();
569 this->socket_fds_changed_ = true;
570
571 // Only recalculate max_fd if we removed the current max
572 if (fd == this->max_fd_) {
573 this->max_fd_ = -1;
574 for (int sock_fd : this->socket_fds_) {
575 if (sock_fd > this->max_fd_)
576 this->max_fd_ = sock_fd;
577 }
578 }
579 return;
580 }
581}
582
584 // This function is thread-safe for reading the result of select()
585 // However, it should only be called after select() has been executed in the main loop
586 // The read_fds_ is only modified by select() in the main loop
587 if (fd < 0 || fd >= FD_SETSIZE)
588 return false;
589
590 return FD_ISSET(fd, &this->read_fds_);
591}
592#endif
593
594void Application::yield_with_select_(uint32_t delay_ms) {
595 // Delay while monitoring sockets. When delay_ms is 0, always yield() to ensure other tasks run
596 // since select() with 0 timeout only polls without yielding.
597#ifdef USE_SOCKET_SELECT_SUPPORT
598 if (!this->socket_fds_.empty()) {
599 // Update fd_set if socket list has changed
600 if (this->socket_fds_changed_) {
601 FD_ZERO(&this->base_read_fds_);
602 // fd bounds are already validated in register_socket_fd() or guaranteed by platform design:
603 // - ESP32: LwIP guarantees fd < FD_SETSIZE by design (LWIP_SOCKET_OFFSET = FD_SETSIZE - CONFIG_LWIP_MAX_SOCKETS)
604 // - Other platforms: register_socket_fd() validates fd < FD_SETSIZE
605 for (int fd : this->socket_fds_) {
606 FD_SET(fd, &this->base_read_fds_);
607 }
608 this->socket_fds_changed_ = false;
609 }
610
611 // Copy base fd_set before each select
612 this->read_fds_ = this->base_read_fds_;
613
614 // Convert delay_ms to timeval
615 struct timeval tv;
616 tv.tv_sec = delay_ms / 1000;
617 tv.tv_usec = (delay_ms - tv.tv_sec * 1000) * 1000;
618
619 // Call select with timeout
620#if defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || (defined(USE_ESP32) && defined(USE_SOCKET_IMPL_BSD_SOCKETS))
621 int ret = lwip_select(this->max_fd_ + 1, &this->read_fds_, nullptr, nullptr, &tv);
622#else
623 int ret = ::select(this->max_fd_ + 1, &this->read_fds_, nullptr, nullptr, &tv);
624#endif
625
626 // Process select() result:
627 // ret < 0: error (except EINTR which is normal)
628 // ret > 0: socket(s) have data ready - normal and expected
629 // ret == 0: timeout occurred - normal and expected
630 if (ret < 0 && errno != EINTR) {
631 // Actual error - log and fall back to delay
632 ESP_LOGW(TAG, "select() failed with errno %d", errno);
633 delay(delay_ms);
634 }
635 // When delay_ms is 0, we need to yield since select(0) doesn't yield
636 if (delay_ms == 0) {
637 yield();
638 }
639 } else {
640 // No sockets registered, use regular delay
641 delay(delay_ms);
642 }
643#elif defined(USE_ESP8266) && defined(USE_SOCKET_IMPL_LWIP_TCP)
644 // No select support but can wake on socket activity via esp_schedule()
645 socket::socket_delay(delay_ms);
646#else
647 // No select support, use regular delay
648 delay(delay_ms);
649#endif
650}
651
652Application App; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
653
654#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
656 // Create UDP socket for wake notifications
657 this->wake_socket_fd_ = lwip_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
658 if (this->wake_socket_fd_ < 0) {
659 ESP_LOGW(TAG, "Wake socket create failed: %d", errno);
660 return;
661 }
662
663 // Bind to loopback with auto-assigned port
664 struct sockaddr_in addr = {};
665 addr.sin_family = AF_INET;
666 addr.sin_addr.s_addr = lwip_htonl(INADDR_LOOPBACK);
667 addr.sin_port = 0; // Auto-assign port
668
669 if (lwip_bind(this->wake_socket_fd_, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
670 ESP_LOGW(TAG, "Wake socket bind failed: %d", errno);
671 lwip_close(this->wake_socket_fd_);
672 this->wake_socket_fd_ = -1;
673 return;
674 }
675
676 // Get the assigned address and connect to it
677 // Connecting a UDP socket allows using send() instead of sendto() for better performance
678 struct sockaddr_in wake_addr;
679 socklen_t len = sizeof(wake_addr);
680 if (lwip_getsockname(this->wake_socket_fd_, (struct sockaddr *) &wake_addr, &len) < 0) {
681 ESP_LOGW(TAG, "Wake socket address failed: %d", errno);
682 lwip_close(this->wake_socket_fd_);
683 this->wake_socket_fd_ = -1;
684 return;
685 }
686
687 // Connect to self (loopback) - allows using send() instead of sendto()
688 // After connect(), no need to store wake_addr - the socket remembers it
689 if (lwip_connect(this->wake_socket_fd_, (struct sockaddr *) &wake_addr, sizeof(wake_addr)) < 0) {
690 ESP_LOGW(TAG, "Wake socket connect failed: %d", errno);
691 lwip_close(this->wake_socket_fd_);
692 this->wake_socket_fd_ = -1;
693 return;
694 }
695
696 // Set non-blocking mode
697 int flags = lwip_fcntl(this->wake_socket_fd_, F_GETFL, 0);
698 lwip_fcntl(this->wake_socket_fd_, F_SETFL, flags | O_NONBLOCK);
699
700 // Register with application's select() loop
701 if (!this->register_socket_fd(this->wake_socket_fd_)) {
702 ESP_LOGW(TAG, "Wake socket register failed");
703 lwip_close(this->wake_socket_fd_);
704 this->wake_socket_fd_ = -1;
705 return;
706 }
707}
708
710 // Called from FreeRTOS task context when events need immediate processing
711 // Wakes up lwip_select() in main loop by writing to connected loopback socket
712 if (this->wake_socket_fd_ >= 0) {
713 const char dummy = 1;
714 // Non-blocking send - if it fails (unlikely), select() will wake on timeout anyway
715 // No error checking needed: we control both ends of this loopback socket.
716 // This is safe to call from FreeRTOS tasks - send() is thread-safe in lwip
717 // Socket is already connected to loopback address, so send() is faster than sendto()
718 lwip_send(this->wake_socket_fd_, &dummy, 1, 0);
719 }
720}
721#endif // defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
722
723void Application::get_build_time_string(std::span<char, BUILD_TIME_STR_SIZE> buffer) {
724 ESPHOME_strncpy_P(buffer.data(), ESPHOME_BUILD_TIME_STR, buffer.size());
725 buffer[buffer.size() - 1] = '\0';
726}
727
728} // namespace esphome
void setup()
Set up all the registered components. Call this at the end of your setup() function.
void wake_loop_threadsafe()
Wake the main event loop from a FreeRTOS task Thread-safe, can be called from task context to immedia...
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...
static constexpr size_t BUILD_TIME_STR_SIZE
Size of buffer required for build time string (including null terminator)
std::vector< int > socket_fds_
StaticVector< Component *, ESPHOME_COMPONENT_COUNT > components_
void get_build_time_string(std::span< char, BUILD_TIME_STR_SIZE > buffer)
Copy the build time string into the provided buffer Buffer must be BUILD_TIME_STR_SIZE bytes (compile...
void drain_wake_notifications_()
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.
FixedVector< Component * > looping_components_
void add_looping_components_by_state_(bool match_loop_done)
volatile bool has_pending_enable_loop_requests_
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
uint8_t get_component_state() const
virtual bool can_proceed()
virtual float get_loop_priority() const
priority of loop().
uint8_t component_state_
State of this component - each bit has a purpose: Bits 0-2: Component state (0x00=CONSTRUCTION,...
Definition component.h:464
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.cpp:689
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:132
size_t size() const
Definition helpers.h:162
void process_pending_stats(uint32_t current_time)
const Component * component
Definition component.cpp:37
uint16_t flags
bool state
Definition fan.h:0
uint32_t socklen_t
Definition headers.h:97
void socket_delay(uint32_t ms)
Delay that can be woken early by socket activity.
const char *const TAG
Definition spi.cpp:7
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:95
std::string size_t len
Definition helpers.h:533
const uint8_t COMPONENT_STATE_LOOP
Definition component.cpp:98
void clear_setup_priority_overrides()
void IRAM_ATTR HOT yield()
Definition core.cpp:24
void IRAM_ATTR HOT arch_feed_wdt()
Definition core.cpp:47
const uint8_t STATUS_LED_WARNING
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:26
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
void arch_restart()
Definition core.cpp:29
Application App
Global storage of Application pointer - only one Application can exist.
const uint8_t COMPONENT_STATE_LOOP_DONE
struct in_addr sin_addr
Definition headers.h:65
sa_family_t sin_family
Definition headers.h:63
in_port_t sin_port
Definition headers.h:64