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