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