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