ESPHome 2026.11.0b6
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 // Runs after Logger::pre_setup() (emitted at EARLY_INIT priority), so the app name is not set yet there.
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 // Runs after Logger::pre_setup() (emitted at EARLY_INIT priority), so the app name is not set yet there.
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
108
109 // Owning script of the action chain currently executing (nullptr when none); used to attribute
110 // blocking warnings for deferred work to the script that scheduled it.
111 void set_current_source(const LogString *source) { this->current_source_ = source; }
112 const LogString *get_current_source() { return this->current_source_; }
113
114// Entity register methods (generated from entity_types.h).
115// Each entity type gets two overloads:
116// - register_<entity>(obj) — bare push_back
117// - register_<entity>(obj, name, hash, fields) — configure_entity_ + push_back
118// The 4-arg form lets codegen collapse `App.register_<entity>(obj); obj->configure_entity_(...);`
119// into a single call site, saving flash and a `main.cpp` line per entity.
120// NOLINTBEGIN(bugprone-macro-parentheses)
121#define ENTITY_TYPE_(type, singular, plural, count, upper) \
122 void register_##singular(type *obj) { this->plural##_.push_back(obj); } \
123 void register_##singular(type *obj, const char *name, uint32_t object_id_hash, uint32_t entity_fields) { \
124 obj->configure_entity_(name, object_id_hash, entity_fields); \
125 this->plural##_.push_back(obj); \
126 }
127#define ENTITY_CONTROLLER_TYPE_(type, singular, plural, count, upper, callback) \
128 ENTITY_TYPE_(type, singular, plural, count, upper)
130#undef ENTITY_TYPE_
131#undef ENTITY_CONTROLLER_TYPE_
132 // NOLINTEND(bugprone-macro-parentheses)
133
134#ifdef USE_SERIAL_PROXY
136 proxy->set_instance_index(this->serial_proxies_.size());
137 this->serial_proxies_.push_back(proxy);
138 }
139#endif
140
142
144 void setup();
145
147 inline void ESPHOME_ALWAYS_INLINE loop();
148
150 const StringRef &get_name() const { return this->name_; }
151
153 const StringRef &get_friendly_name() const { return this->friendly_name_; }
154
156 const char *get_area() const {
157#ifdef USE_AREAS
158 // If we have areas registered, return the name of the first one (which is the top-level area)
159 if (!this->areas_.empty() && this->areas_[0] != nullptr) {
160 return this->areas_[0]->get_name();
161 }
162#endif
163 return "";
164 }
165
167 static constexpr size_t ESPHOME_COMMENT_SIZE_MAX = 256;
168
170 void get_comment_string(std::span<char, ESPHOME_COMMENT_SIZE_MAX> buffer);
171
173 std::string get_comment() {
175 this->get_comment_string(buffer);
176 return std::string(buffer);
177 }
178
180
182 static constexpr size_t BUILD_TIME_STR_SIZE = 26;
183
186
189
191 time_t get_build_time();
192
195 void get_build_time_string(std::span<char, BUILD_TIME_STR_SIZE> buffer);
196
198 inline uint32_t IRAM_ATTR HOT get_loop_component_start_time() const { return this->loop_component_start_time_; }
199
216 void set_loop_interval(uint32_t loop_interval) {
217 this->loop_interval_ = std::min(loop_interval, static_cast<uint32_t>(std::numeric_limits<uint16_t>::max()));
218 }
219
220 uint32_t get_loop_interval() const { return static_cast<uint32_t>(this->loop_interval_); }
221
223
236#ifdef USE_BK72XX
237 // BDK busy-waits 200us per WDT reload (sctrl_dpll_delay200us). LibreTiny
238 // sets HW WDT to 10s; 2000ms keeps ~5x margin. See wdt_ctrl WCMD_RELOAD_PERIOD:
239 // https://github.com/libretiny-eu/framework-beken-bdk/blob/44800e7451ea30fbcbd3bb6e905315de59349fee/beken378/driver/wdt/wdt.c#L75-L87
240 static constexpr uint32_t WDT_FEED_INTERVAL_MS = 2000;
241#elif defined(USE_ESP32)
242 // Auto-scale to 1/5 of the configured ESP32 task WDT timeout so the safety
243 // margin stays constant when the user raises esp32.watchdog_timeout (default
244 // 5 s → 1000 ms feed; 10 s → 2000 ms; 60 s → 12000 ms). The esp32 component
245 // writes CONFIG_ESP_TASK_WDT_TIMEOUT_S into sdkconfig (range is validated
246 // to ≥ 5 s in esp32/__init__.py), giving us the value at compile time.
247 // esp_task_wdt_reset() takes a spinlock and walks the WDT task list, so
248 // each call costs tens of microseconds; longer intervals materially reduce
249 // the main-loop's wdt bucket. Component loops and scheduler items still
250 // feed after every op, so any op exceeding this threshold triggers a real
251 // feed naturally regardless of the rate-limit.
252 static_assert(CONFIG_ESP_TASK_WDT_TIMEOUT_S >= 5,
253 "CONFIG_ESP_TASK_WDT_TIMEOUT_S must be at least 5s for a safe WDT feed interval");
254 static constexpr uint32_t WDT_FEED_INTERVAL_MS = (CONFIG_ESP_TASK_WDT_TIMEOUT_S * 1000U) / 5U;
255#elif defined(USE_ESP8266)
256 // ESP8266 needs a tighter feed cadence than the other targets: the soft WDT
257 // is ~1.6 s and the HW WDT ~6 s, but a single long iteration (mDNS reply,
258 // wifi scan, OTA verify, lwIP TCP retransmit storm) can push the loop past
259 // a few hundred ms without giving the SDK a chance to feed. 100 ms keeps a
260 // ~16x margin to the soft WDT and ~60x to the HW WDT while still avoiding
261 // the per-iteration arch_feed_wdt() cost (this is the rate limit; component
262 // loops and scheduler items still feed after every op).
263 static constexpr uint32_t WDT_FEED_INTERVAL_MS = 100;
264#else
265 static constexpr uint32_t WDT_FEED_INTERVAL_MS = 300;
266#endif
267
270 void feed_wdt();
271
272#ifdef USE_STATUS_LED
280#endif
281
290 void ESPHOME_ALWAYS_INLINE feed_wdt_with_time(uint32_t time) {
291 if (static_cast<uint32_t>(time - this->last_wdt_feed_) > WDT_FEED_INTERVAL_MS) [[unlikely]] {
292 this->feed_wdt_slow_(time);
293 }
294#ifdef USE_STATUS_LED
295 if (static_cast<uint32_t>(time - this->last_status_led_service_) > STATUS_LED_DISPATCH_INTERVAL_MS) [[unlikely]] {
296 this->service_status_led_slow_(time);
297 }
298#endif
299 }
300
301 void reboot();
302
303 void safe_reboot();
304
306 void safe_shutdown(uint32_t timeout_ms);
307
309
310 void run_powerdown_hooks();
311
316 void teardown_components(uint32_t timeout_ms);
317
321 uint8_t get_app_state() const { return this->app_state_ & ~APP_STATE_SETUP_COMPLETE; }
322
329 bool is_setup_complete() const { return (this->app_state_ & APP_STATE_SETUP_COMPLETE) != 0; }
330
331// Helper macro for entity getter method declarations
332#ifdef USE_DEVICES
333#define GET_ENTITY_METHOD(entity_type, entity_name, entities_member) \
334 entity_type *get_##entity_name##_by_key(uint32_t key, uint32_t device_id, bool include_internal = false) { \
335 for (auto *obj : this->entities_member##_) { \
336 if (obj->get_object_id_hash() == key && obj->get_device_id() == device_id && \
337 (include_internal || !obj->is_internal())) \
338 return obj; \
339 } \
340 return nullptr; \
341 }
342 const auto &get_devices() { return this->devices_; }
343#else
344#define GET_ENTITY_METHOD(entity_type, entity_name, entities_member) \
345 entity_type *get_##entity_name##_by_key(uint32_t key, bool include_internal = false) { \
346 for (auto *obj : this->entities_member##_) { \
347 if (obj->get_object_id_hash() == key && (include_internal || !obj->is_internal())) \
348 return obj; \
349 } \
350 return nullptr; \
351 }
352#endif // USE_DEVICES
353#ifdef USE_AREAS
354 const auto &get_areas() { return this->areas_; }
355#endif
356// Entity getter methods (generated from entity_types.h)
357// NOLINTBEGIN(bugprone-macro-parentheses)
358#define ENTITY_TYPE_(type, singular, plural, count, upper) \
359 auto &get_##plural() const { return this->plural##_; } \
360 GET_ENTITY_METHOD(type, singular, plural)
361#define ENTITY_CONTROLLER_TYPE_(type, singular, plural, count, upper, callback) \
362 ENTITY_TYPE_(type, singular, plural, count, upper)
364#undef ENTITY_TYPE_
365#undef ENTITY_CONTROLLER_TYPE_
366 // NOLINTEND(bugprone-macro-parentheses)
367
368#ifdef USE_SERIAL_PROXY
369 auto &get_serial_proxies() const { return this->serial_proxies_; }
370#endif
371
373
377
378#if defined(USE_ESP32) || defined(USE_LIBRETINY)
380 static void IRAM_ATTR wake_loop_isrsafe(BaseType_t *px) { esphome::wake_loop_isrsafe(px); }
381#elif defined(USE_ESP8266)
383 static void IRAM_ATTR ESPHOME_ALWAYS_INLINE wake_loop_isrsafe() { esphome::wake_loop_isrsafe(); }
384#elif defined(USE_ZEPHYR)
387#endif
388
391
392 protected:
393 friend Component;
394 friend class Scheduler;
395 friend class LoopBlockingGuard;
397#ifdef USE_RUNTIME_STATS
399#endif
400 friend void ::setup();
401 friend void ::original_setup();
402
405
406 // Publish the running unit's identity (component + source) and dispatch time together, so a
407 // dispatch site can't set one without the others. Friend-only (Scheduler).
408 void set_current_execution_context_(Component *component, const LogString *source, uint32_t now) {
410 this->current_source_ = source;
412 }
413
418 bool any_component_has_status_flag_(uint8_t flag) const;
419
424 template<typename T> void register_component_(T *comp, uint8_t source_index = 0) {
425 if (source_index != 0)
426 comp->set_component_source_(source_index);
428 }
429
430 void register_component_impl_(Component *comp, bool has_loop);
431
433 // FixedVector capacity was pre-initialized by codegen with the exact count
434 // of components that override loop(), computed at C++ compile time.
435
436 // Add all components with loop override that aren't already LOOP_DONE or FAILED
437 // Some components (like logger) may call disable_loop() during initialization,
438 // and some call mark_failed() from their constructor, before setup runs
441 // Then add any components that are already LOOP_DONE or FAILED to the inactive section
443 }
444 void add_looping_components_by_state_(bool inactive);
445
446 // These methods are called by Component::disable_loop() and Component::enable_loop()
447 // Components should not call these directly - use this->disable_loop() or this->enable_loop()
448 // to ensure component state is properly updated along with the loop partition
452 void activate_looping_component_(uint16_t index);
453 inline uint32_t ESPHOME_ALWAYS_INLINE scheduler_tick_(uint32_t now);
454
455 // RAII guard for a component loop phase. Constructor processes any pending
456 // enable_loop requests from ISRs and marks in_loop_ so reentrant
457 // modifications during component.loop() are safe; destructor clears in_loop_.
459 public:
460 inline ESPHOME_ALWAYS_INLINE explicit ComponentPhaseGuard(Application &app);
461 inline ESPHOME_ALWAYS_INLINE ~ComponentPhaseGuard() { this->app_.in_loop_ = false; }
464
465 private:
466 Application &app_;
467 };
468
472 void __attribute__((noinline)) process_dump_config_();
473
479 void feed_wdt_slow_(uint32_t time);
480
481#ifdef USE_STATUS_LED
487#endif
488
489 // === Member variables ordered by size to minimize padding ===
490
491 // Pointer-sized members first
493 const LogString *current_source_{nullptr};
494
495 // std::vector (3 pointers each: begin, end, capacity)
496 // Partitioned vector design for looping components
497 // =================================================
498 // Components are partitioned into [active | inactive] sections:
499 //
500 // looping_components_: [A, B, C, D | E, F]
501 // ^
502 // looping_components_active_end_ (4)
503 //
504 // - Components A,B,C,D are active and will be called in loop()
505 // - Components E,F are inactive (disabled/failed) and won't be called
506 // - No flag checking needed during iteration - just loop 0 to active_end_
507 // - When a component is disabled, it's swapped with the last active component
508 // and active_end_ is decremented
509 // - When a component is enabled, it's swapped with the first inactive component
510 // and active_end_ is incremented
511 // - This eliminates branch mispredictions from flag checking in the hot loop
513
514 // StringRef members (8 bytes each: pointer + size)
517
518 // 4-byte members
521 uint32_t last_wdt_feed_{0}; // millis() of most recent arch_feed_wdt(); rate-limits feed_wdt() hot path
522#ifdef USE_STATUS_LED
523 // millis() of most recent status_led dispatch; rate-limits independently of last_wdt_feed_
525#endif
526
527 // 2-byte members (grouped together for alignment)
528 uint16_t dump_config_at_{std::numeric_limits<uint16_t>::max()}; // Index into components_ for dump_config progress
529 uint16_t loop_interval_{16}; // Loop interval in ms (max 65535ms = 65.5 seconds)
530 uint16_t looping_components_active_end_{0}; // Index marking end of active components in looping_components_
531 uint16_t current_loop_index_{0}; // For safe reentrant modifications during iteration
532
533 // 1-byte members (grouped together to minimize padding)
534 uint8_t app_state_{0};
536 bool in_loop_{false};
538
539 // StaticVectors (largest members - contain actual array data inline)
541
542#ifdef USE_DEVICES
544#endif
545#ifdef USE_AREAS
547#endif
548// Entity StaticVector fields (generated from entity_types.h)
549// NOLINTBEGIN(bugprone-macro-parentheses)
550#define ENTITY_TYPE_(type, singular, plural, count, upper) StaticVector<type *, count> plural##_{};
551#define ENTITY_CONTROLLER_TYPE_(type, singular, plural, count, upper, callback) \
552 ENTITY_TYPE_(type, singular, plural, count, upper)
554#undef ENTITY_TYPE_
555#undef ENTITY_CONTROLLER_TYPE_
556 // NOLINTEND(bugprone-macro-parentheses)
557
558#ifdef USE_SERIAL_PROXY
560#endif
561};
562
564extern Application App; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
565
569 public:
570 explicit ScopedSourceGuard(const LogString *source) : prev_(App.get_current_source()) {
571 App.set_current_source(source);
572 }
576
577 private:
578 const LogString *prev_;
579};
580
581// Times one unit of work (a component loop() or a scheduled callback) and warns if it blocks the
582// main loop too long. The constructor publishes the unit's identity + dispatch time to App;
583// finish()/the cold warning path read them back, so the guard stores no copy.
584//
585// Guards must not nest: the constructor publishes to App but never restores on destruction, so a
586// nested guard would clobber the outer's context. Safe because the two dispatch sites (component
587// loop phase, execute_item_) run strictly sequentially and aren't re-entered from a timed callback.
589 public:
590 // Publish the unit's identity + dispatch time, then start timing. The millis start lives in App,
591 // so only the runtime-stats micros stamp is kept here.
592 LoopBlockingGuard(Component *component, const LogString *source, uint32_t now) {
594#ifdef USE_RUNTIME_STATS
595 this->started_us_ = micros();
596#endif
597 }
598
599 // Finish the timing operation and return the current time (millis)
600 // Inlined: the fast path is just millis() + subtract + compare
601 inline uint32_t HOT finish() {
602#ifdef USE_RUNTIME_STATS
603 uint32_t elapsed_us = micros() - this->started_us_;
604 // Delays have no component; accumulate into the global counter so loop() can subtract them.
606 if (component != nullptr) {
607 component->runtime_stats_.record_time(elapsed_us);
608 } else {
610 }
611#endif
612 uint32_t curr_time = MillisInternal::get();
613#ifndef USE_BENCHMARK
614 // Fast path: compare against constant threshold in ms (computed at compile time from centiseconds)
615 static constexpr uint32_t WARN_IF_BLOCKING_OVER_MS = static_cast<uint32_t>(WARN_IF_BLOCKING_OVER_CS) * 10U;
616 uint32_t blocking_time = curr_time - App.get_loop_component_start_time();
617 if (blocking_time > WARN_IF_BLOCKING_OVER_MS) [[unlikely]] {
618 warn_blocking(blocking_time);
619 // Exclude synchronous warning-log time from the next operation.
620 curr_time = MillisInternal::get();
621 }
622#endif
623 return curr_time;
624 }
625
627
628#ifdef USE_RUNTIME_STATS
629 protected:
631#endif
632
633 private:
634 // Cold path; defined in component.cpp. Reads the current component/source from App to name the culprit.
635 static void __attribute__((noinline, cold)) warn_blocking(uint32_t blocking_time);
636};
637
654 public:
655 UnavoidableBlockingScope() : started_(MillisInternal::get()), pass_start_(App.get_loop_component_start_time()) {}
657 // Move the pass start seen at entry forward by the time spent here, clamped to now
658 const uint32_t now = MillisInternal::get();
659 const uint32_t moved = this->pass_start_ + (now - this->started_);
660 App.set_loop_component_start_time_(static_cast<int32_t>(now - moved) < 0 ? now : moved);
661 }
664
665 private:
666 uint32_t started_;
667 uint32_t pass_start_;
668};
669
670// Phase A: drain wake notifications and run the scheduler. Invoked on every
671// Application::loop() tick regardless of whether a component phase runs, so
672// scheduler items fire at their requested cadence even when the caller has
673// raised loop_interval_ for power savings (see Application::loop()).
674// Returns the timestamp of the last scheduler item that ran (or `now`
675// unchanged if none ran), so the caller's WDT feed stays monotonic with the
676// per-item feeds inside scheduler.call() without an extra millis().
677inline uint32_t ESPHOME_ALWAYS_INLINE Application::scheduler_tick_(uint32_t now) {
678#ifdef USE_HOST
679 // Drain wake notifications first to clear socket for next wake.
681#endif
682 return this->scheduler.call(now);
683}
684
685// Phase B entry: only invoked when a component loop phase is about to run.
686// Processes pending enable_loop requests from ISRs and marks in_loop_ so
687// reentrant modifications during component.loop() are safe.
688inline ESPHOME_ALWAYS_INLINE Application::ComponentPhaseGuard::ComponentPhaseGuard(Application &app) : app_(app) {
689 // Process any pending enable_loop requests from ISRs
690 // This must be done before marking in_loop_ = true to avoid race conditions
691 if (this->app_.has_pending_enable_loop_requests_) {
692 // Clear flag BEFORE processing to avoid race condition
693 // If ISR sets it during processing, we'll catch it next loop iteration
694 // This is safe because:
695 // 1. Each component has its own pending_enable_loop_ flag that we check
696 // 2. If we can't process a component (wrong state), enable_pending_loops_()
697 // will set this flag back to true
698 // 3. Any new ISR requests during processing will set the flag again
699 this->app_.has_pending_enable_loop_requests_ = false;
700 this->app_.enable_pending_loops_();
701 }
702
703 // Mark that we're in the loop for safe reentrant modifications
704 this->app_.in_loop_ = true;
705}
706
707inline void ESPHOME_ALWAYS_INLINE Application::loop() {
708#if defined(USE_LWIP_FAST_SELECT) && defined(ESPHOME_THREAD_MULTI_ATOMICS)
709 // Pairs with the TCP/IP thread's SYS_ARCH_UNPROTECT release on rcvevent so
710 // subsequent Socket::ready() checks in this iter observe the published state
711 // without a per-call memw. Wake is independent (esphome_main_task_notify/
712 // esphome_main_task_wait), so non-losing. Skipped on MULTI_NO_ATOMICS (e.g.
713 // BK72xx) — that path keeps `volatile` in esphome_lwip_socket_has_data()
714 // instead.
715 std::atomic_thread_fence(std::memory_order_acquire);
716#endif
717#ifdef USE_RUNTIME_STATS
718 // Capture the start of the active (non-sleeping) portion of this iteration.
719 // Used to derive main-loop overhead = active time − Σ(component time) −
720 // before/tail splits recorded below.
721 uint32_t loop_active_start_us = micros();
722 // Snapshot the cumulative component-recorded time so we can subtract the
723 // slice that the scheduler spends inside its own LoopBlockingGuard
724 // (scheduler.cpp) — that time is already counted in per-component stats,
725 // so charging it again to "before" would double-count.
726 uint64_t loop_recorded_snap = ComponentRuntimeStats::global_recorded_us;
727#endif
728 // Phase A: always service the scheduler. Decouples scheduler cadence from
729 // loop_interval_ so raised intervals (for power savings) don't drag scheduled
730 // items forward. A tick that only runs the scheduler is cheap.
731 // scheduler_tick_ returns the timestamp of the last scheduler item that ran
732 // (advanced by its per-item feeds) or `now` unchanged. We adopt it as `now`
733 // so the gate check and WDT feed both reflect actual elapsed time after
734 // scheduler dispatch, without an extra millis() call.
735 uint32_t now = this->scheduler_tick_(MillisInternal::get());
736 // Guarantee one WDT feed per tick even when the scheduler had nothing to
737 // dispatch and the component phase is gated out — covers configs with no
738 // looping components and no scheduler work (setup() has its own
739 // per-component feed_wdt calls, so only do this here, not in scheduler_tick_).
740 this->feed_wdt_with_time(now);
741
742#ifdef USE_RUNTIME_STATS
743 uint32_t loop_before_end_us = micros();
744 uint64_t loop_before_scheduled_us = ComponentRuntimeStats::global_recorded_us - loop_recorded_snap;
745 // Only meaningful when do_component_phase is true; initialized to 0 so the
746 // tail bucket receives 0 on Phase A-only ticks (no component tail happened,
747 // the gate-check / stats-prefix overhead belongs to "residual", not "tail").
748 uint32_t loop_tail_start_us = 0;
749#endif
750
751 // Gate the component phase on loop_interval_, an active high-frequency
752 // request, or an explicit wake from a background producer. A scheduler-only
753 // wake (e.g. set_interval firing under a raised loop_interval_) leaves the
754 // component phase gated; an external producer that called wake_loop_*
755 // (MQTT RX, USB RX, BLE event, etc.) needs the component phase to actually
756 // run so its component's loop() can drain the queued work — that is the
757 // long-standing semantic of wake_loop_threadsafe(), and the wake_request
758 // flag preserves it. wake_request_take() exchange-clears the flag; wakes
759 // that arrive during Phase B re-set it and run Phase B again on the next
760 // iteration.
761 //
762 // wake_request_take() must always be called first since it does an
763 // atomic exchange to clear the flag, and we want to run the component phase
764 // if either the flag was set or the scheduler requested a high-frequency loop.
765 const bool do_component_phase = esphome::wake_request_take() || HighFrequencyLoopRequester::is_high_frequency() ||
766 (now - this->last_loop_ >= this->loop_interval_);
767
768 if (do_component_phase) {
769 ComponentPhaseGuard phase_guard{*this};
770
771 uint32_t last_op_end_time = now;
773 this->current_loop_index_++) {
775
776 {
777 // Guard publishes this component (no script source) + dispatch time, then times loop().
778 LoopBlockingGuard guard{component, nullptr, last_op_end_time};
779 component->loop();
780 // Use the finish method to get the current time as the end time
781 last_op_end_time = guard.finish();
782 }
783 this->feed_wdt_with_time(last_op_end_time);
784 }
785
786#ifdef USE_RUNTIME_STATS
787 loop_tail_start_us = micros();
788#endif
789 // process scheduler items added in component phase
790 this->scheduler.process_to_add();
791 this->last_loop_ = last_op_end_time;
792 now = last_op_end_time;
793 // phase_guard destructor clears in_loop_ at scope exit
794 }
795
796#ifdef USE_RUNTIME_STATS
797 // Record per-tick timing on every loop, not just component-phase ticks.
798 // record_loop_active is a small accumulator; process_pending_stats is an
799 // inline gate check that early-outs unless now >= next_log_time_.
800 if (global_runtime_stats != nullptr) {
801 uint32_t loop_now_us = micros();
802 // Subtract scheduled-component time from the "before" bucket so it is
803 // not double-counted (it is already attributed to per-component stats).
804 uint32_t loop_before_wall_us = loop_before_end_us - loop_active_start_us;
805 uint32_t loop_before_overhead_us = loop_before_wall_us > loop_before_scheduled_us
806 ? loop_before_wall_us - static_cast<uint32_t>(loop_before_scheduled_us)
807 : 0;
808 // tail_us is only defined when Phase B ran; 0 on Phase A-only ticks so the
809 // stats bucket keeps its "component-phase trailing overhead" meaning.
810 uint32_t loop_tail_us = do_component_phase ? (loop_now_us - loop_tail_start_us) : 0;
811 global_runtime_stats->record_loop_active(loop_now_us - loop_active_start_us, loop_before_overhead_us, loop_tail_us);
813 }
814#endif
815
816 // Compute sleep: bounded by time-until-next-component-phase if there are
817 // components with loop enabled and the scheduler's next deadline. When a scheduler timer fires it re-enters
818 // loop(), Phase A services it, and the component phase stays gated by
819 // loop_interval_. When a background producer calls wake_loop_threadsafe()
820 // it sets the wake_request flag and wakes select() / the task notification;
821 // the gate above sees the flag and runs Phase B too so the producer's
822 // component can drain its queued work without waiting up to loop_interval_.
823 //
824 // Re-read HighFrequencyLoopRequester::is_high_frequency() here instead of
825 // reusing the cached `high_frequency` captured above: a component calling
826 // HighFrequencyLoopRequester::start() from within its loop() would
827 // otherwise sit under the stale value and sleep for up to loop_interval_
828 // before the request took effect. That was fine pre-decoupling (the old
829 // main loop also called the function fresh at the sleep point) but now
830 // matters much more — loop_interval_ is a power-saving knob documented
831 // to accept multi-second values, so the stale path could add seconds of
832 // latency on an HF request. The call is a trivial atomic read.
833 uint32_t delay_time = 0;
835 const uint32_t elapsed_since_phase = now - this->last_loop_;
836#ifdef ESPHOME_SUSPEND_LOOP
837 const bool has_loop_work =
838 this->looping_components_active_end_ > 0 || this->dump_config_at_ < this->components_.size();
839 uint32_t until_phase = std::numeric_limits<uint32_t>::max();
840 if (has_loop_work) {
841 until_phase = (elapsed_since_phase >= this->loop_interval_) ? 0 : (this->loop_interval_ - elapsed_since_phase);
842 }
843#else
844 uint32_t until_phase =
845 (elapsed_since_phase >= this->loop_interval_) ? 0 : (this->loop_interval_ - elapsed_since_phase);
846#endif
847 const uint32_t until_sched = this->scheduler.next_schedule_in(now).value_or(until_phase);
848 delay_time = std::min(until_phase, until_sched);
849 }
850 // All platforms route loop yields through the platform wake primitive.
851 // On host this drains the loopback wake socket via select(); on FreeRTOS
852 // targets it uses task notifications; on ESP8266/RP2040 it uses esp_delay/WFE.
853 // Cap the sleep so the WDT feed and status-LED dispatch rate limits still get
854 // exercised even when loop_interval is raised or the scheduler and component
855 // phases are gated out for a long sleep. Waking every 2*WDT_FEED_INTERVAL_MS
856 // clears the feed rate limit on every wake, so the WDT is fed at least that
857 // often -- well inside every platform's timeout.
858#if defined(USE_ESP8266)
859 // SDK os_timer_arm() accepts at most 0x68D7A3 ms without system_timer_reinit();
860 // the SDK feeds both watchdogs while the cont task is suspended, so no WDT cap needed.
861 static constexpr uint32_t MAX_SLEEP_BASE = 0x68D7A3;
862#elif defined(USE_HOST)
863 // arch_feed_wdt() is a no-op on host and ESPHOME_SUSPEND_LOOP is rejected by
864 // the config validator, so delay_time is already bounded by loop_interval_.
865 static constexpr uint32_t MAX_SLEEP_BASE = std::numeric_limits<uint32_t>::max();
866#else
867 static constexpr uint32_t MAX_SLEEP_BASE = WDT_FEED_INTERVAL_MS * 2;
868#endif
869 uint32_t max_sleep = MAX_SLEEP_BASE;
870#ifdef USE_STATUS_LED
871 if ((this->app_state_ & STATUS_LED_MASK) != 0) {
872 max_sleep = std::min(max_sleep, STATUS_LED_DISPATCH_INTERVAL_MS);
873 }
874#endif
875
876 esphome::internal::wakeable_delay(std::min(delay_time, max_sleep));
877 if (this->dump_config_at_ < this->components_.size()) {
878 this->process_dump_config_();
879 }
880}
881
882} // 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()
const LogString * current_source_
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 set_current_execution_context_(Component *component, const LogString *source, uint32_t now)
void service_status_led_slow_(uint32_t time)
Slow path for the status_led dispatch rate limit.
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_
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
const LogString * get_current_source()
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_.
void add_looping_components_by_state_(bool inactive)
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_
void safe_shutdown(uint32_t timeout_ms)
Run the safe shutdown hooks, give components up to timeout_ms to tear down, then run the powerdown ho...
bool is_setup_complete() const
True once Application::setup() has finished walking all components and finalized the initial status f...
void set_current_source(const LogString *source)
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 - sized once through init() or try_init(); push_back never reallocates This avo...
Definition helpers.h:669
static bool is_high_frequency()
Check whether the loop is running continuously.
Definition helpers.h:2337
LoopBlockingGuard(Component *component, const LogString *source, uint32_t now)
RAII guard that publishes a current source (e.g.
ScopedSourceGuard(const ScopedSourceGuard &)=delete
ScopedSourceGuard(const LogString *source)
ScopedSourceGuard & operator=(const ScopedSourceGuard &)=delete
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:304
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
Leaves a stretch of the current loop pass out of the blocking warning.
UnavoidableBlockingScope & operator=(const UnavoidableBlockingScope &)=delete
UnavoidableBlockingScope(const UnavoidableBlockingScope &)=delete
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)
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
const Component * component
Definition component.cpp:34
uint32_t buffer
Definition gif.cpp:50
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
constexpr uint8_t WARN_IF_BLOCKING_OVER_CS
Definition component.h:102
void wake_loop_threadsafe()
Non-ISR: always inline.
constexpr uint8_t STATUS_LED_MASK
Definition component.h:90
void arch_init()
Definition hal.cpp:44
constexpr uint8_t APP_STATE_SETUP_COMPLETE
Definition component.h:100
void ESPHOME_ALWAYS_INLINE wake_drain_notifications()
Definition wake_host.h:49
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:848
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.
STL namespace.
static void uint32_t
static uint64_t global_recorded_us
Definition component.h:126
SFINAE helper: detects whether T overrides Component::loop().
Definition application.h:56
Platform-specific main loop wake primitives.