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