ESPHome 2026.5.2
Loading...
Searching...
No Matches
application.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <ctime>
5#include <limits>
6#include <span>
7#include <string>
8#include <type_traits>
9#include <vector>
12
13#if defined(USE_LWIP_FAST_SELECT) && defined(ESPHOME_THREAD_MULTI_ATOMICS)
14#include <atomic> // for std::atomic_thread_fence in Application::loop()
15#endif
16#include "esphome/core/hal.h"
23
24#ifdef USE_ESP32
25#include <sdkconfig.h> // for CONFIG_ESP_TASK_WDT_TIMEOUT_S (drives WDT_FEED_INTERVAL_MS)
26#endif
27
28#ifdef USE_DEVICES
29#include "esphome/core/device.h"
30#endif
31#ifdef USE_AREAS
32#include "esphome/core/area.h"
33#endif
34
35#ifdef USE_RUNTIME_STATS
37#endif
38#include "esphome/core/wake.h"
40
41#ifdef USE_RUNTIME_STATS
42namespace esphome::runtime_stats {
43class RuntimeStatsCollector;
44} // namespace esphome::runtime_stats
45#endif
46
47// Forward declarations for friend access from codegen-generated setup()
48void setup(); // NOLINT(readability-redundant-declaration) - may be declared in Arduino.h
49void original_setup(); // NOLINT(readability-redundant-declaration) - used by cpp unit tests
50
51namespace esphome {
52
56template<typename T, typename = void> struct HasLoopOverride : std::true_type {};
57template<typename T>
58struct HasLoopOverride<T, std::void_t<decltype(&T::loop)>>
59 : std::bool_constant<!std::is_same_v<decltype(&T::loop), decltype(&Component::loop)>> {};
60
61// Teardown timeout constant (in milliseconds)
62// For reboots, it's more important to shut down quickly than disconnect cleanly
63// since we're not entering deep sleep. The only consequence of not shutting down
64// cleanly is a warning in the log.
65static constexpr uint32_t TEARDOWN_TIMEOUT_REBOOT_MS = 1000; // 1 second for quick reboot
66
68 public:
69#ifdef ESPHOME_NAME_ADD_MAC_SUFFIX
70 // Called before Logger::pre_setup() — must not log (global_logger is not yet set).
72 void pre_setup(char *name, size_t name_len, char *friendly_name, size_t friendly_name_len) {
73 arch_init();
74 this->name_add_mac_suffix_ = true;
75 // MAC address suffix length (last 6 characters of 12-char MAC address string)
76 constexpr size_t mac_address_suffix_len = 6;
77 char mac_addr[MAC_ADDRESS_BUFFER_SIZE];
79 // Overwrite the placeholder suffix in the mutable static buffers with actual MAC
80 // name is always non-empty (validated by validate_hostname in Python config)
81 memcpy(name + name_len - mac_address_suffix_len, mac_addr + mac_address_suffix_len, mac_address_suffix_len);
82 if (friendly_name_len > 0) {
83 memcpy(friendly_name + friendly_name_len - mac_address_suffix_len, mac_addr + mac_address_suffix_len,
84 mac_address_suffix_len);
85 }
86 this->name_ = StringRef(name, name_len);
87 this->friendly_name_ = StringRef(friendly_name, friendly_name_len);
88 }
89#else
90 // Called before Logger::pre_setup() — must not log (global_logger is not yet set).
92 void pre_setup(const char *name, size_t name_len, const char *friendly_name, size_t friendly_name_len) {
93 arch_init();
94 this->name_add_mac_suffix_ = false;
95 this->name_ = StringRef(name, name_len);
96 this->friendly_name_ = StringRef(friendly_name, friendly_name_len);
97 }
98#endif
99
100#ifdef USE_DEVICES
101 void register_device(Device *device) { this->devices_.push_back(device); }
102#endif
103#ifdef USE_AREAS
104 void register_area(Area *area) { this->areas_.push_back(area); }
105#endif
106
109
110// Entity register methods (generated from entity_types.h).
111// Each entity type gets two overloads:
112// - register_<entity>(obj) — bare push_back
113// - register_<entity>(obj, name, hash, fields) — configure_entity_ + push_back
114// The 4-arg form lets codegen collapse `App.register_<entity>(obj); obj->configure_entity_(...);`
115// into a single call site, saving flash and a `main.cpp` line per entity.
116// NOLINTBEGIN(bugprone-macro-parentheses)
117#define ENTITY_TYPE_(type, singular, plural, count, upper) \
118 void register_##singular(type *obj) { this->plural##_.push_back(obj); } \
119 void register_##singular(type *obj, const char *name, uint32_t object_id_hash, uint32_t entity_fields) { \
120 obj->configure_entity_(name, object_id_hash, entity_fields); \
121 this->plural##_.push_back(obj); \
122 }
123#define ENTITY_CONTROLLER_TYPE_(type, singular, plural, count, upper, callback) \
124 ENTITY_TYPE_(type, singular, plural, count, upper)
126#undef ENTITY_TYPE_
127#undef ENTITY_CONTROLLER_TYPE_
128 // NOLINTEND(bugprone-macro-parentheses)
129
130#ifdef USE_SERIAL_PROXY
132 proxy->set_instance_index(this->serial_proxies_.size());
133 this->serial_proxies_.push_back(proxy);
134 }
135#endif
136
138
140 void setup();
141
143 inline void ESPHOME_ALWAYS_INLINE loop();
144
146 const StringRef &get_name() const { return this->name_; }
147
149 const StringRef &get_friendly_name() const { return this->friendly_name_; }
150
152 const char *get_area() const {
153#ifdef USE_AREAS
154 // If we have areas registered, return the name of the first one (which is the top-level area)
155 if (!this->areas_.empty() && this->areas_[0] != nullptr) {
156 return this->areas_[0]->get_name();
157 }
158#endif
159 return "";
160 }
161
163 static constexpr size_t ESPHOME_COMMENT_SIZE_MAX = 256;
164
166 void get_comment_string(std::span<char, ESPHOME_COMMENT_SIZE_MAX> buffer);
167
169 std::string get_comment() {
170 char buffer[ESPHOME_COMMENT_SIZE_MAX];
171 this->get_comment_string(buffer);
172 return std::string(buffer);
173 }
174
176
178 static constexpr size_t BUILD_TIME_STR_SIZE = 26;
179
182
185
187 time_t get_build_time();
188
191 void get_build_time_string(std::span<char, BUILD_TIME_STR_SIZE> buffer);
192
194 // Remove before 2026.7.0
195 ESPDEPRECATED("Use get_build_time_string() instead. Removed in 2026.7.0", "2026.1.0")
196 std::string get_compilation_time() {
197 char buf[BUILD_TIME_STR_SIZE];
198 this->get_build_time_string(buf);
199 return std::string(buf);
200 }
201
203 inline uint32_t IRAM_ATTR HOT get_loop_component_start_time() const { return this->loop_component_start_time_; }
204
221 void set_loop_interval(uint32_t loop_interval) {
222 this->loop_interval_ = std::min(loop_interval, static_cast<uint32_t>(std::numeric_limits<uint16_t>::max()));
223 }
224
225 uint32_t get_loop_interval() const { return static_cast<uint32_t>(this->loop_interval_); }
226
228
240#ifdef USE_BK72XX
241 // BDK busy-waits 200us per WDT reload (sctrl_dpll_delay200us). LibreTiny
242 // sets HW WDT to 10s; 2000ms keeps ~5x margin. See wdt_ctrl WCMD_RELOAD_PERIOD:
243 // https://github.com/libretiny-eu/framework-beken-bdk/blob/44800e7451ea30fbcbd3bb6e905315de59349fee/beken378/driver/wdt/wdt.c#L75-L87
244 static constexpr uint32_t WDT_FEED_INTERVAL_MS = 2000;
245#elif defined(USE_ESP32)
246 // Auto-scale to 1/5 of the configured ESP32 task WDT timeout so the safety
247 // margin stays constant when the user raises esp32.watchdog_timeout (default
248 // 5 s → 1000 ms feed; 10 s → 2000 ms; 60 s → 12000 ms). The esp32 component
249 // writes CONFIG_ESP_TASK_WDT_TIMEOUT_S into sdkconfig (range is validated
250 // to ≥ 5 s in esp32/__init__.py), giving us the value at compile time.
251 // esp_task_wdt_reset() takes a spinlock and walks the WDT task list, so
252 // each call costs tens of microseconds; longer intervals materially reduce
253 // the main-loop's wdt bucket. Component loops and scheduler items still
254 // feed after every op, so any op exceeding this threshold triggers a real
255 // feed naturally regardless of the rate-limit.
256 static_assert(CONFIG_ESP_TASK_WDT_TIMEOUT_S >= 5,
257 "CONFIG_ESP_TASK_WDT_TIMEOUT_S must be at least 5s for a safe WDT feed interval");
258 static constexpr uint32_t WDT_FEED_INTERVAL_MS = (CONFIG_ESP_TASK_WDT_TIMEOUT_S * 1000U) / 5U;
259#elif defined(USE_ESP8266)
260 // ESP8266 needs a tighter feed cadence than the other targets: the soft WDT
261 // is ~1.6 s and the HW WDT ~6 s, but a single long iteration (mDNS reply,
262 // wifi scan, OTA verify, lwIP TCP retransmit storm) can push the loop past
263 // a few hundred ms without giving the SDK a chance to feed. 100 ms keeps a
264 // ~16x margin to the soft WDT and ~60x to the HW WDT while still avoiding
265 // the per-iteration arch_feed_wdt() cost (this is the rate limit; component
266 // loops and scheduler items still feed after every op).
267 static constexpr uint32_t WDT_FEED_INTERVAL_MS = 100;
268#else
269 static constexpr uint32_t WDT_FEED_INTERVAL_MS = 300;
270#endif
271
274 void feed_wdt();
275
276#ifdef USE_STATUS_LED
284#endif
285
294 void ESPHOME_ALWAYS_INLINE feed_wdt_with_time(uint32_t time) {
295 if (static_cast<uint32_t>(time - this->last_wdt_feed_) > WDT_FEED_INTERVAL_MS) [[unlikely]] {
296 this->feed_wdt_slow_(time);
297 }
298#ifdef USE_STATUS_LED
299 if (static_cast<uint32_t>(time - this->last_status_led_service_) > STATUS_LED_DISPATCH_INTERVAL_MS) [[unlikely]] {
300 this->service_status_led_slow_(time);
301 }
302#endif
303 }
304
305 void reboot();
306
307 void safe_reboot();
308
310
311 void run_powerdown_hooks();
312
317 void teardown_components(uint32_t timeout_ms);
318
322 uint8_t get_app_state() const { return this->app_state_ & ~APP_STATE_SETUP_COMPLETE; }
323
330 bool is_setup_complete() const { return (this->app_state_ & APP_STATE_SETUP_COMPLETE) != 0; }
331
332// Helper macro for entity getter method declarations
333#ifdef USE_DEVICES
334#define GET_ENTITY_METHOD(entity_type, entity_name, entities_member) \
335 entity_type *get_##entity_name##_by_key(uint32_t key, uint32_t device_id, bool include_internal = false) { \
336 for (auto *obj : this->entities_member##_) { \
337 if (obj->get_object_id_hash() == key && obj->get_device_id() == device_id && \
338 (include_internal || !obj->is_internal())) \
339 return obj; \
340 } \
341 return nullptr; \
342 }
343 const auto &get_devices() { return this->devices_; }
344#else
345#define GET_ENTITY_METHOD(entity_type, entity_name, entities_member) \
346 entity_type *get_##entity_name##_by_key(uint32_t key, bool include_internal = false) { \
347 for (auto *obj : this->entities_member##_) { \
348 if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) \
349 return obj; \
350 } \
351 return nullptr; \
352 }
353#endif // USE_DEVICES
354#ifdef USE_AREAS
355 const auto &get_areas() { return this->areas_; }
356#endif
357// Entity getter methods (generated from entity_types.h)
358// NOLINTBEGIN(bugprone-macro-parentheses)
359#define ENTITY_TYPE_(type, singular, plural, count, upper) \
360 auto &get_##plural() const { return this->plural##_; } \
361 GET_ENTITY_METHOD(type, singular, plural)
362#define ENTITY_CONTROLLER_TYPE_(type, singular, plural, count, upper, callback) \
363 ENTITY_TYPE_(type, singular, plural, count, upper)
365#undef ENTITY_TYPE_
366#undef ENTITY_CONTROLLER_TYPE_
367 // NOLINTEND(bugprone-macro-parentheses)
368
369#ifdef USE_SERIAL_PROXY
370 auto &get_serial_proxies() const { return this->serial_proxies_; }
371#endif
372
374
378
379#if defined(USE_ESP32) || defined(USE_LIBRETINY)
381 static void IRAM_ATTR wake_loop_isrsafe(BaseType_t *px) { esphome::wake_loop_isrsafe(px); }
382#elif defined(USE_ESP8266)
384 static void IRAM_ATTR ESPHOME_ALWAYS_INLINE wake_loop_isrsafe() { esphome::wake_loop_isrsafe(); }
385#elif defined(USE_ZEPHYR)
388#endif
389
392
393 protected:
394 friend Component;
395 friend class Scheduler;
396#ifdef USE_RUNTIME_STATS
398#endif
399 friend void ::setup();
400 friend void ::original_setup();
401
404
409 bool any_component_has_status_flag_(uint8_t flag) const;
410
415 template<typename T> void register_component_(T *comp, uint8_t source_index = 0) {
416 if (source_index != 0)
417 comp->set_component_source_(source_index);
419 }
420
421 void register_component_impl_(Component *comp, bool has_loop);
422
424 // FixedVector capacity was pre-initialized by codegen with the exact count
425 // of components that override loop(), computed at C++ compile time.
426
427 // Add all components with loop override that aren't already LOOP_DONE
428 // Some components (like logger) may call disable_loop() during initialization
429 // before setup runs, so we need to respect their LOOP_DONE state
432 // Then add any components that are already LOOP_DONE to the inactive section
433 // This handles components that called disable_loop() during initialization
435 }
436 void add_looping_components_by_state_(bool match_loop_done);
437
438 // These methods are called by Component::disable_loop() and Component::enable_loop()
439 // Components should not call these directly - use this->disable_loop() or this->enable_loop()
440 // to ensure component state is properly updated along with the loop partition
444 void activate_looping_component_(uint16_t index);
445 inline uint32_t ESPHOME_ALWAYS_INLINE scheduler_tick_(uint32_t now);
446
447 // RAII guard for a component loop phase. Constructor processes any pending
448 // enable_loop requests from ISRs and marks in_loop_ so reentrant
449 // modifications during component.loop() are safe; destructor clears in_loop_.
451 public:
452 inline ESPHOME_ALWAYS_INLINE explicit ComponentPhaseGuard(Application &app);
453 inline ESPHOME_ALWAYS_INLINE ~ComponentPhaseGuard() { this->app_.in_loop_ = false; }
456
457 private:
458 Application &app_;
459 };
460
464 void __attribute__((noinline)) process_dump_config_();
465
471 void feed_wdt_slow_(uint32_t time);
472
473#ifdef USE_STATUS_LED
479#endif
480
481 // === Member variables ordered by size to minimize padding ===
482
483 // Pointer-sized members first
485
486 // std::vector (3 pointers each: begin, end, capacity)
487 // Partitioned vector design for looping components
488 // =================================================
489 // Components are partitioned into [active | inactive] sections:
490 //
491 // looping_components_: [A, B, C, D | E, F]
492 // ^
493 // looping_components_active_end_ (4)
494 //
495 // - Components A,B,C,D are active and will be called in loop()
496 // - Components E,F are inactive (disabled/failed) and won't be called
497 // - No flag checking needed during iteration - just loop 0 to active_end_
498 // - When a component is disabled, it's swapped with the last active component
499 // and active_end_ is decremented
500 // - When a component is enabled, it's swapped with the first inactive component
501 // and active_end_ is incremented
502 // - This eliminates branch mispredictions from flag checking in the hot loop
504
505 // StringRef members (8 bytes each: pointer + size)
508
509 // 4-byte members
512 uint32_t last_wdt_feed_{0}; // millis() of most recent arch_feed_wdt(); rate-limits feed_wdt() hot path
513#ifdef USE_STATUS_LED
514 // millis() of most recent status_led dispatch; rate-limits independently of last_wdt_feed_
516#endif
517
518 // 2-byte members (grouped together for alignment)
519 uint16_t dump_config_at_{std::numeric_limits<uint16_t>::max()}; // Index into components_ for dump_config progress
520 uint16_t loop_interval_{16}; // Loop interval in ms (max 65535ms = 65.5 seconds)
521 uint16_t looping_components_active_end_{0}; // Index marking end of active components in looping_components_
522 uint16_t current_loop_index_{0}; // For safe reentrant modifications during iteration
523
524 // 1-byte members (grouped together to minimize padding)
525 uint8_t app_state_{0};
527 bool in_loop_{false};
529
530 // StaticVectors (largest members - contain actual array data inline)
532
533#ifdef USE_DEVICES
535#endif
536#ifdef USE_AREAS
538#endif
539// Entity StaticVector fields (generated from entity_types.h)
540// NOLINTBEGIN(bugprone-macro-parentheses)
541#define ENTITY_TYPE_(type, singular, plural, count, upper) StaticVector<type *, count> plural##_{};
542#define ENTITY_CONTROLLER_TYPE_(type, singular, plural, count, upper, callback) \
543 ENTITY_TYPE_(type, singular, plural, count, upper)
545#undef ENTITY_TYPE_
546#undef ENTITY_CONTROLLER_TYPE_
547 // NOLINTEND(bugprone-macro-parentheses)
548
549#ifdef USE_SERIAL_PROXY
551#endif
552};
553
555extern Application App; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
556
557// Phase A: drain wake notifications and run the scheduler. Invoked on every
558// Application::loop() tick regardless of whether a component phase runs, so
559// scheduler items fire at their requested cadence even when the caller has
560// raised loop_interval_ for power savings (see Application::loop()).
561// Returns the timestamp of the last scheduler item that ran (or `now`
562// unchanged if none ran), so the caller's WDT feed stays monotonic with the
563// per-item feeds inside scheduler.call() without an extra millis().
564inline uint32_t ESPHOME_ALWAYS_INLINE Application::scheduler_tick_(uint32_t now) {
565#ifdef USE_HOST
566 // Drain wake notifications first to clear socket for next wake.
568#endif
569 return this->scheduler.call(now);
570}
571
572// Phase B entry: only invoked when a component loop phase is about to run.
573// Processes pending enable_loop requests from ISRs and marks in_loop_ so
574// reentrant modifications during component.loop() are safe.
575inline ESPHOME_ALWAYS_INLINE Application::ComponentPhaseGuard::ComponentPhaseGuard(Application &app) : app_(app) {
576 // Process any pending enable_loop requests from ISRs
577 // This must be done before marking in_loop_ = true to avoid race conditions
578 if (this->app_.has_pending_enable_loop_requests_) {
579 // Clear flag BEFORE processing to avoid race condition
580 // If ISR sets it during processing, we'll catch it next loop iteration
581 // This is safe because:
582 // 1. Each component has its own pending_enable_loop_ flag that we check
583 // 2. If we can't process a component (wrong state), enable_pending_loops_()
584 // will set this flag back to true
585 // 3. Any new ISR requests during processing will set the flag again
586 this->app_.has_pending_enable_loop_requests_ = false;
587 this->app_.enable_pending_loops_();
588 }
589
590 // Mark that we're in the loop for safe reentrant modifications
591 this->app_.in_loop_ = true;
592}
593
594inline void ESPHOME_ALWAYS_INLINE Application::loop() {
595#if defined(USE_LWIP_FAST_SELECT) && defined(ESPHOME_THREAD_MULTI_ATOMICS)
596 // Pairs with the TCP/IP thread's SYS_ARCH_UNPROTECT release on rcvevent so
597 // subsequent Socket::ready() checks in this iter observe the published state
598 // without a per-call memw. Wake is independent (xTaskNotifyGive/
599 // ulTaskNotifyTake), so non-losing. Skipped on MULTI_NO_ATOMICS (e.g.
600 // BK72xx) — that path keeps `volatile` in esphome_lwip_socket_has_data()
601 // instead.
602 std::atomic_thread_fence(std::memory_order_acquire);
603#endif
604#ifdef USE_RUNTIME_STATS
605 // Capture the start of the active (non-sleeping) portion of this iteration.
606 // Used to derive main-loop overhead = active time − Σ(component time) −
607 // before/tail splits recorded below.
608 uint32_t loop_active_start_us = micros();
609 // Snapshot the cumulative component-recorded time so we can subtract the
610 // slice that the scheduler spends inside its own WarnIfComponentBlockingGuard
611 // (scheduler.cpp) — that time is already counted in per-component stats,
612 // so charging it again to "before" would double-count.
613 uint64_t loop_recorded_snap = ComponentRuntimeStats::global_recorded_us;
614#endif
615 // Phase A: always service the scheduler. Decouples scheduler cadence from
616 // loop_interval_ so raised intervals (for power savings) don't drag scheduled
617 // items forward. A tick that only runs the scheduler is cheap.
618 // scheduler_tick_ returns the timestamp of the last scheduler item that ran
619 // (advanced by its per-item feeds) or `now` unchanged. We adopt it as `now`
620 // so the gate check and WDT feed both reflect actual elapsed time after
621 // scheduler dispatch, without an extra millis() call.
622 uint32_t now = this->scheduler_tick_(MillisInternal::get());
623 // Guarantee one WDT feed per tick even when the scheduler had nothing to
624 // dispatch and the component phase is gated out — covers configs with no
625 // looping components and no scheduler work (setup() has its own
626 // per-component feed_wdt calls, so only do this here, not in scheduler_tick_).
627 this->feed_wdt_with_time(now);
628
629#ifdef USE_RUNTIME_STATS
630 uint32_t loop_before_end_us = micros();
631 uint64_t loop_before_scheduled_us = ComponentRuntimeStats::global_recorded_us - loop_recorded_snap;
632 // Only meaningful when do_component_phase is true; initialized to 0 so the
633 // tail bucket receives 0 on Phase A-only ticks (no component tail happened,
634 // the gate-check / stats-prefix overhead belongs to "residual", not "tail").
635 uint32_t loop_tail_start_us = 0;
636#endif
637
638 // Gate the component phase on loop_interval_, an active high-frequency
639 // request, or an explicit wake from a background producer. A scheduler-only
640 // wake (e.g. set_interval firing under a raised loop_interval_) leaves the
641 // component phase gated; an external producer that called wake_loop_*
642 // (MQTT RX, USB RX, BLE event, etc.) needs the component phase to actually
643 // run so its component's loop() can drain the queued work — that is the
644 // long-standing semantic of wake_loop_threadsafe(), and the wake_request
645 // flag preserves it. wake_request_take() exchange-clears the flag; wakes
646 // that arrive during Phase B re-set it and run Phase B again on the next
647 // iteration.
648 //
649 // wake_request_take() must always be called first since it does an
650 // atomic exchange to clear the flag, and we want to run the component phase
651 // if either the flag was set or the scheduler requested a high-frequency loop.
652 const bool do_component_phase = esphome::wake_request_take() || HighFrequencyLoopRequester::is_high_frequency() ||
653 (now - this->last_loop_ >= this->loop_interval_);
654
655 if (do_component_phase) {
656 ComponentPhaseGuard phase_guard{*this};
657
658 uint32_t last_op_end_time = now;
660 this->current_loop_index_++) {
662
663 // Update the cached time before each component runs
664 this->loop_component_start_time_ = last_op_end_time;
665
666 {
667 this->set_current_component(component);
668 WarnIfComponentBlockingGuard guard{component, last_op_end_time};
669 component->loop();
670 // Use the finish method to get the current time as the end time
671 last_op_end_time = guard.finish();
672 }
673 this->feed_wdt_with_time(last_op_end_time);
674 }
675
676#ifdef USE_RUNTIME_STATS
677 loop_tail_start_us = micros();
678#endif
679 this->last_loop_ = last_op_end_time;
680 now = last_op_end_time;
681 // phase_guard destructor clears in_loop_ at scope exit
682 }
683
684#ifdef USE_RUNTIME_STATS
685 // Record per-tick timing on every loop, not just component-phase ticks.
686 // record_loop_active is a small accumulator; process_pending_stats is an
687 // inline gate check that early-outs unless now >= next_log_time_.
688 if (global_runtime_stats != nullptr) {
689 uint32_t loop_now_us = micros();
690 // Subtract scheduled-component time from the "before" bucket so it is
691 // not double-counted (it is already attributed to per-component stats).
692 uint32_t loop_before_wall_us = loop_before_end_us - loop_active_start_us;
693 uint32_t loop_before_overhead_us = loop_before_wall_us > loop_before_scheduled_us
694 ? loop_before_wall_us - static_cast<uint32_t>(loop_before_scheduled_us)
695 : 0;
696 // tail_us is only defined when Phase B ran; 0 on Phase A-only ticks so the
697 // stats bucket keeps its "component-phase trailing overhead" meaning.
698 uint32_t loop_tail_us = do_component_phase ? (loop_now_us - loop_tail_start_us) : 0;
699 global_runtime_stats->record_loop_active(loop_now_us - loop_active_start_us, loop_before_overhead_us, loop_tail_us);
701 }
702#endif
703
704 // Compute sleep: bounded by time-until-next-component-phase and the
705 // scheduler's next deadline. When a scheduler timer fires it re-enters
706 // loop(), Phase A services it, and the component phase stays gated by
707 // loop_interval_. When a background producer calls wake_loop_threadsafe()
708 // it sets the wake_request flag and wakes select() / the task notification;
709 // the gate above sees the flag and runs Phase B too so the producer's
710 // component can drain its queued work without waiting up to loop_interval_.
711 //
712 // Re-read HighFrequencyLoopRequester::is_high_frequency() here instead of
713 // reusing the cached `high_frequency` captured above: a component calling
714 // HighFrequencyLoopRequester::start() from within its loop() would
715 // otherwise sit under the stale value and sleep for up to loop_interval_
716 // before the request took effect. That was fine pre-decoupling (the old
717 // main loop also called the function fresh at the sleep point) but now
718 // matters much more — loop_interval_ is a power-saving knob documented
719 // to accept multi-second values, so the stale path could add seconds of
720 // latency on an HF request. The call is a trivial atomic read.
721 uint32_t delay_time = 0;
723 const uint32_t elapsed_since_phase = now - this->last_loop_;
724 const uint32_t until_phase =
725 (elapsed_since_phase >= this->loop_interval_) ? 0 : (this->loop_interval_ - elapsed_since_phase);
726 const uint32_t until_sched = this->scheduler.next_schedule_in(now).value_or(until_phase);
727 delay_time = std::min(until_phase, until_sched);
728 }
729 // All platforms route loop yields through the platform wake primitive.
730 // On host this drains the loopback wake socket via select(); on FreeRTOS
731 // targets it uses task notifications; on ESP8266/RP2040 it uses esp_delay/WFE.
733
734 if (this->dump_config_at_ < this->components_.size()) {
735 this->process_dump_config_();
736 }
737}
738
739} // namespace esphome
void original_setup()
void setup()
ComponentPhaseGuard & operator=(const ComponentPhaseGuard &)=delete
ESPHOME_ALWAYS_INLINE ComponentPhaseGuard(Application &app)
ESPHOME_ALWAYS_INLINE ~ComponentPhaseGuard()
ComponentPhaseGuard(const ComponentPhaseGuard &)=delete
void set_loop_component_start_time_(uint32_t now)
Freshen the cached loop component start time. Called by Scheduler before each dispatch.
uint32_t ESPHOME_ALWAYS_INLINE scheduler_tick_(uint32_t now)
void setup()
Reserve space for components to avoid memory fragmentation.
uint32_t get_loop_interval() const
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
void ESPHOME_ALWAYS_INLINE feed_wdt_with_time(uint32_t time)
Feed the task watchdog, hot entry.
const auto & get_areas()
uint16_t looping_components_active_end_
void pre_setup(char *name, size_t name_len, char *friendly_name, size_t friendly_name_len)
Pre-setup with MAC suffix: overwrites placeholder in mutable static buffers with actual MAC.
Definition application.h:72
void service_status_led_slow_(uint32_t time)
Slow path for the status_led dispatch rate limit.
void set_current_component(Component *component)
Component * get_current_component()
void register_serial_proxy(serial_proxy::SerialProxy *proxy)
static void IRAM_ATTR wake_loop_any_context()
Wake from any context (ISR, thread, callback).
static void IRAM_ATTR ESPHOME_ALWAYS_INLINE wake_loop_isrsafe()
Wake from ISR (ESP8266). No task_woken arg — no FreeRTOS. Caller must be IRAM_ATTR.
static constexpr size_t BUILD_TIME_STR_SIZE
Size of buffer required for build time string (including null terminator)
void __attribute__((noinline)) process_dump_config_()
Process dump_config output one component per loop iteration.
StaticVector< Area *, ESPHOME_AREA_COUNT > areas_
std::string get_comment()
Get the comment of this Application as a string.
uint32_t get_config_hash()
Get the config hash as a 32-bit integer.
void register_component_(T *comp, uint8_t source_index=0)
Register a component, detecting loop() override at compile time.
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
void pre_setup(const char *name, size_t name_len, const char *friendly_name, size_t friendly_name_len)
Pre-setup without MAC suffix: StringRef points directly at const string literals in flash.
Definition application.h:92
void set_loop_interval(uint32_t loop_interval)
Set the target interval with which to run the loop() calls.
StaticVector< Component *, ESPHOME_COMPONENT_COUNT > components_
bool any_component_has_status_flag_(uint8_t flag) const
Walk all registered components looking for any whose component_state_ has the given flag set.
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 register_area(Area *area)
Component * current_component_
static void wake_loop_isrsafe()
Wake from ISR (Zephyr). No task_woken arg — k_sem_give() handles ISR scheduling internally.
void enable_component_loop_(Component *component)
uint32_t loop_component_start_time_
void feed_wdt()
Feed the task watchdog.
void disable_component_loop_(Component *component)
const char * get_area() const
Get the area of this Application set by pre_setup().
bool is_name_add_mac_suffix_enabled() const
void activate_looping_component_(uint16_t index)
const auto & get_devices()
uint32_t last_status_led_service_
ESPDEPRECATED("Use get_build_time_string() instead. Removed in 2026.7.0", "2026.1.0") std
Get the build time as a string (deprecated, use get_build_time_string() instead)
void teardown_components(uint32_t timeout_ms)
Teardown all components with a timeout.
static constexpr size_t ESPHOME_COMMENT_SIZE_MAX
Maximum size of the comment buffer (including null terminator)
FixedVector< Component * > looping_components_
auto & get_serial_proxies() const
void add_looping_components_by_state_(bool match_loop_done)
volatile bool has_pending_enable_loop_requests_
void get_comment_string(std::span< char, ESPHOME_COMMENT_SIZE_MAX > buffer)
Copy the comment string into the provided buffer.
static void IRAM_ATTR wake_loop_isrsafe(BaseType_t *px)
Wake from ISR (ESP32 and LibreTiny).
void feed_wdt_slow_(uint32_t time)
Slow path for feed_wdt(): actually calls arch_feed_wdt() and updates last_wdt_feed_.
uint16_t current_loop_index_
static constexpr uint32_t WDT_FEED_INTERVAL_MS
Minimum interval between real arch_feed_wdt() calls.
void ESPHOME_ALWAYS_INLINE loop()
Make a loop iteration. Call this in your loop() function.
time_t get_build_time()
Get the build time as a Unix timestamp.
StaticVector< serial_proxy::SerialProxy *, SERIAL_PROXY_COUNT > serial_proxies_
bool is_setup_complete() const
True once Application::setup() has finished walking all components and finalized the initial status f...
void register_device(Device *device)
static constexpr uint32_t STATUS_LED_DISPATCH_INTERVAL_MS
Dispatch interval for the status LED update.
uint32_t get_config_version_hash()
Get the config hash extended with ESPHome version.
StaticVector< Device *, ESPHOME_DEVICE_COUNT > devices_
void calculate_looping_components_()
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void register_component_impl_(Component *comp, bool has_loop)
uint8_t get_app_state() const
Return the public app state status bits (STATUS_LED_* only).
friend class Scheduler
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:529
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.h:2001
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:217
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
void ESPHOME_ALWAYS_INLINE process_pending_stats(uint32_t current_time)
void record_loop_active(uint32_t active_us, uint32_t before_us, uint32_t tail_us)
void set_instance_index(uint32_t index)
Set the instance index (called by Application::register_serial_proxy)
const Component * component
Definition component.cpp:34
void ESPHOME_ALWAYS_INLINE wakeable_delay(uint32_t ms)
Host wakeable_delay uses select() over the registered fds — defined in wake_host.cpp.
runtime_stats::RuntimeStatsCollector * global_runtime_stats
void wake_loop_threadsafe()
Non-ISR: always inline.
void arch_init()
Definition hal.cpp:47
constexpr uint8_t APP_STATE_SETUP_COMPLETE
Definition component.h:96
void ESPHOME_ALWAYS_INLINE wake_drain_notifications()
Definition wake_host.h:48
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
void get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Definition helpers.cpp:745
Application App
Global storage of Application pointer - only one Application can exist.
void ESPHOME_ALWAYS_INLINE wake_loop_isrsafe()
ISR-safe: no task_woken arg because ESP8266 has no FreeRTOS. Caller must be IRAM_ATTR.
void IRAM_ATTR wake_loop_any_context()
IRAM_ATTR entry point for ISR callers — defined in wake_esp8266.cpp.
static void uint32_t
static uint64_t global_recorded_us
Definition component.h:124
SFINAE helper: detects whether T overrides Component::loop().
Definition application.h:56
Platform-specific main loop wake primitives.