ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
component.cpp
Go to the documentation of this file.
2
3#include <cinttypes>
4#include <limits>
5#include <memory>
6#include <utility>
7#include <vector>
9#include "esphome/core/hal.h"
11#include "esphome/core/log.h"
12
13namespace esphome {
14
15static const char *const TAG = "component";
16
17// Global vectors for component data that doesn't belong in every instance.
18// Using vector instead of unordered_map for both because:
19// - Much lower memory overhead (8 bytes per entry vs 20+ for unordered_map)
20// - Linear search is fine for small n (typically < 5 entries)
21// - These are rarely accessed (setup only or error cases only)
22
23// Component error messages - only stores messages for failed components
24// Lazy allocated since most configs have zero failures
25// Note: We don't clear this vector because:
26// 1. Components are never destroyed in ESPHome
27// 2. Failed components remain failed (no recovery mechanism)
28// 3. Memory usage is minimal (only failures with custom messages are stored)
29
30// Using namespace-scope static to avoid guard variables (saves 16 bytes total)
31// This is safe because ESPHome is single-threaded during initialization
32namespace {
33struct ComponentErrorMessage {
34 const Component *component;
35 const LogString *message;
36};
37
38#ifdef USE_SETUP_PRIORITY_OVERRIDE
39struct ComponentPriorityOverride {
40 const Component *component;
41 float priority;
42};
43
44// Setup priority overrides - freed after setup completes
45// Using raw pointer instead of unique_ptr to avoid global constructor/destructor overhead
46// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
47std::vector<ComponentPriorityOverride> *setup_priority_overrides = nullptr;
48#endif
49
50// Error messages for failed components
51// Using raw pointer instead of unique_ptr to avoid global constructor/destructor overhead
52// This is never freed as error messages persist for the lifetime of the device
53// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
54std::vector<ComponentErrorMessage> *component_error_messages = nullptr;
55
56// Helper to store error messages
57void store_component_error_message(const Component *component, const LogString *message) {
58 // Lazy allocate the error messages vector if needed
59 if (!component_error_messages) {
60 component_error_messages = new std::vector<ComponentErrorMessage>();
61 }
62 // Check if this component already has an error message
63 for (auto &entry : *component_error_messages) {
64 if (entry.component == component) {
65 entry.message = message;
66 return;
67 }
68 }
69 // Add new error message
70 component_error_messages->emplace_back(ComponentErrorMessage{component, message});
71}
72} // namespace
73
74// setup_priority, component state, and status LED constants are now
75// constexpr in component.h
76
77static constexpr uint16_t WARN_IF_BLOCKING_INCREMENT_MS =
78 10U;
79// Threshold in ms (computed from centiseconds constant in component.h)
80static constexpr uint32_t WARN_IF_BLOCKING_OVER_MS = static_cast<uint32_t>(WARN_IF_BLOCKING_OVER_CS) * 10U;
81
83
85
87
88void Component::set_interval(const char *name, uint32_t interval, std::function<void()> &&f) { // NOLINT
89 App.scheduler.set_interval(this, name, interval, std::move(f));
90}
91
92bool Component::cancel_interval(const char *name) { // NOLINT
93 return App.scheduler.cancel_interval(this, name);
94}
95
96void Component::set_timeout(const char *name, uint32_t timeout, std::function<void()> &&f) { // NOLINT
97 App.scheduler.set_timeout(this, name, timeout, std::move(f));
98}
99
100bool Component::cancel_timeout(const char *name) { // NOLINT
101 return App.scheduler.cancel_timeout(this, name);
102}
103
104// uint32_t (numeric ID) overloads - zero heap allocation
105void Component::set_timeout(uint32_t id, uint32_t timeout, std::function<void()> &&f) { // NOLINT
106 App.scheduler.set_timeout(this, id, timeout, std::move(f));
107}
108
109bool Component::cancel_timeout(uint32_t id) { return App.scheduler.cancel_timeout(this, id); }
110
111void Component::set_timeout(InternalSchedulerID id, uint32_t timeout, std::function<void()> &&f) { // NOLINT
112 App.scheduler.set_timeout(this, id, timeout, std::move(f));
113}
114
115bool Component::cancel_timeout(InternalSchedulerID id) { return App.scheduler.cancel_timeout(this, id); }
116
117void Component::set_interval(uint32_t id, uint32_t interval, std::function<void()> &&f) { // NOLINT
118 App.scheduler.set_interval(this, id, interval, std::move(f));
119}
120
121bool Component::cancel_interval(uint32_t id) { return App.scheduler.cancel_interval(this, id); }
122
123void Component::set_interval(InternalSchedulerID id, uint32_t interval, std::function<void()> &&f) { // NOLINT
124 App.scheduler.set_interval(this, id, interval, std::move(f));
125}
126
127bool Component::cancel_interval(InternalSchedulerID id) { return App.scheduler.cancel_interval(this, id); }
128
129void Component::call_setup() { this->setup(); }
131 this->dump_config();
132 if (this->is_failed()) {
133 // Look up error message from global vector
134 const LogString *error_msg = nullptr;
135 if (component_error_messages) {
136 for (const auto &entry : *component_error_messages) {
137 if (entry.component == this) {
138 error_msg = entry.message;
139 break;
140 }
141 }
142 }
143 ESP_LOGE(TAG, " %s is marked FAILED: %s", LOG_STR_ARG(this->get_component_log_str()),
144 error_msg ? LOG_STR_ARG(error_msg) : LOG_STR_LITERAL("unspecified"));
145 }
146}
147
150 switch (state) {
152 // State Construction: Call setup and set state to setup
154 ESP_LOGV(TAG, "Setup %s", LOG_STR_ARG(this->get_component_log_str()));
155#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
156 uint32_t start_time = millis();
157#endif
158 this->call_setup();
159#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
160 uint32_t setup_time = millis() - start_time;
161 // Only log at CONFIG level if setup took longer than the blocking threshold
162 // to avoid spamming the log and blocking the event loop
163 if (setup_time >= WARN_IF_BLOCKING_OVER_MS) {
164 ESP_LOGCONFIG(TAG, "Setup %s took %ums", LOG_STR_ARG(this->get_component_log_str()), (unsigned) setup_time);
165 } else {
166 ESP_LOGV(TAG, "Setup %s took %ums", LOG_STR_ARG(this->get_component_log_str()), (unsigned) setup_time);
167 }
168#endif
169 break;
170 }
172 // State setup: Call first loop and set state to loop
174 this->loop();
175 break;
177 // State loop: Call loop
178 this->loop();
179 break;
181 // State failed: Do nothing
183 // State loop done: Do nothing, component has finished its work
184 default:
185 break;
186 }
187}
188bool Component::should_warn_of_blocking(uint32_t blocking_time, uint32_t &threshold_ms_out) {
189 // Convert centisecond threshold to milliseconds for comparison
190 uint32_t threshold_ms = static_cast<uint32_t>(this->warn_if_blocking_over_) * 10U;
191 // Report the threshold that was exceeded (before any ratcheting below) so the warning is accurate.
192 threshold_ms_out = threshold_ms;
193 if (blocking_time > threshold_ms) {
194 // Set new threshold: blocking_time + increment, converted back to centiseconds
195 uint32_t new_threshold_ms = blocking_time + WARN_IF_BLOCKING_INCREMENT_MS;
196 uint32_t new_cs = new_threshold_ms / 10U;
197 // Saturate at uint8_t max (255 = 2550ms)
198 this->warn_if_blocking_over_ = static_cast<uint8_t>(new_cs > 255U ? 255U : new_cs);
199 return true;
200 }
201 return false;
202}
204 ESP_LOGE(TAG, "%s was marked as failed", LOG_STR_ARG(this->get_component_log_str()));
206 this->status_set_error();
207 // Also remove from loop since failed components shouldn't loop
209}
212 ESP_LOGVV(TAG, "%s loop disabled", LOG_STR_ARG(this->get_component_log_str()));
215 }
216}
218 ESP_LOGVV(TAG, "%s loop enabled", LOG_STR_ARG(this->get_component_log_str()));
221}
223 // This method is thread and ISR-safe because:
224 // 1. Only performs simple assignments to volatile variables (atomic on all platforms)
225 // 2. No read-modify-write operations that could be interrupted
226 // 3. No memory allocation or object construction; on ESP32 the only call (wake_loop_any_context) is ISR-safe
227 // 4. IRAM_ATTR ensures code is in IRAM, not flash (required for ISR execution)
228 // 5. Components are never destroyed, so no use-after-free concerns
229 // 6. App is guaranteed to be initialized before any ISR could fire
230 // 7. Multiple ISR/thread calls are safe - just sets the same flags to true
231 // 8. Race condition with main loop is handled by clearing flag before processing
232 this->pending_enable_loop_ = true;
234 // Wake the main loop from sleep. Without this, the main loop would not
235 // wake until the select/delay timeout expires (~16ms).
237}
240 ESP_LOGI(TAG, "%s is being reset to construction state", LOG_STR_ARG(this->get_component_log_str()));
242 // Clear error status when resetting
243 this->status_clear_error();
244 }
245}
246void Component::defer(std::function<void()> &&f) { // NOLINT
247 App.scheduler.set_timeout(this, static_cast<const char *>(nullptr), 0, std::move(f));
248}
249bool Component::cancel_defer(const char *name) { // NOLINT
250 return App.scheduler.cancel_timeout(this, name);
251}
252void Component::defer(const char *name, std::function<void()> &&f) { // NOLINT
253 App.scheduler.set_timeout(this, name, 0, std::move(f));
254}
255void Component::defer(uint32_t id, std::function<void()> &&f) { // NOLINT
256 App.scheduler.set_timeout(this, id, 0, std::move(f));
257}
258bool Component::cancel_defer(uint32_t id) { return App.scheduler.cancel_timeout(this, id); }
259void Component::set_timeout(uint32_t timeout, std::function<void()> &&f) { // NOLINT
260 App.scheduler.set_timeout(this, static_cast<const char *>(nullptr), timeout, std::move(f));
261}
262void Component::set_interval(uint32_t interval, std::function<void()> &&f) { // NOLINT
263 App.scheduler.set_interval(this, static_cast<const char *>(nullptr), interval, std::move(f));
264}
266 // Bitmask check: valid states are SETUP(1), LOOP(2), LOOP_DONE(4)
267 // (1 << state) & 0b10110 checks membership in one instruction
268 return ((1u << (this->component_state_ & COMPONENT_STATE_MASK)) &
269 ((1u << COMPONENT_STATE_SETUP) | (1u << COMPONENT_STATE_LOOP) | (1u << COMPONENT_STATE_LOOP_DONE))) != 0;
270}
271bool Component::can_proceed() { return true; }
272bool Component::set_status_flag_(uint8_t flag) {
273 if ((this->component_state_ & flag) != 0)
274 return false;
275 this->component_state_ |= flag;
276 App.app_state_ |= flag;
277 return true;
278}
279
280void Component::status_set_warning() { this->status_set_warning((const LogString *) nullptr); }
283 return;
284 ESP_LOGW(TAG, "%s set Warning flag: %s", LOG_STR_ARG(this->get_component_log_str()),
285 message ? message : LOG_STR_LITERAL("unspecified"));
286}
289 return;
290 ESP_LOGW(TAG, "%s set Warning flag: %s", LOG_STR_ARG(this->get_component_log_str()),
291 message ? LOG_STR_ARG(message) : LOG_STR_LITERAL("unspecified"));
292}
293void Component::status_set_error() { this->status_set_error((const LogString *) nullptr); }
294void Component::status_set_error(const LogString *message) {
296 return;
297 ESP_LOGE(TAG, "%s set Error flag: %s", LOG_STR_ARG(this->get_component_log_str()),
298 message ? LOG_STR_ARG(message) : LOG_STR_LITERAL("unspecified"));
299 if (message != nullptr) {
300 store_component_error_message(this, message);
301 }
302}
304 this->component_state_ &= ~STATUS_LED_WARNING;
305 // Clear the app-wide STATUS_LED_WARNING bit only if setup has finished
306 // AND no other component still has it set. During setup the forced
307 // STATUS_LED_WARNING (from the slow-setup busy-wait) must not be wiped
308 // by a transient component clear — Application::setup() reconciles
309 // the warning bit once at the end before setting APP_STATE_SETUP_COMPLETE.
310 // The set path is unchanged (set_status_flag_ still writes directly).
312 App.app_state_ &= ~STATUS_LED_WARNING;
313 ESP_LOGW(TAG, "%s cleared Warning flag", LOG_STR_ARG(this->get_component_log_str()));
314}
316 this->component_state_ &= ~STATUS_LED_ERROR;
317 // STATUS_LED_ERROR is never artificially forced — it only ever lands
318 // in app_state_ via a real set_status_flag_ call. So the walk-and-clear
319 // path is always safe, including during setup.
321 App.app_state_ &= ~STATUS_LED_ERROR;
322 ESP_LOGE(TAG, "%s cleared Error flag", LOG_STR_ARG(this->get_component_log_str()));
323}
325 this->status_set_warning();
326 this->set_timeout(name, length, [this]() { this->status_clear_warning(); });
327}
329 this->status_set_error();
330 this->set_timeout(name, length, [this]() { this->status_clear_error(); });
331}
333
334// Function implementation of LOG_UPDATE_INTERVAL macro to reduce code size
336 uint32_t update_interval = component->get_update_interval();
337 if (update_interval == SCHEDULER_DONT_RUN) {
338 ESP_LOGCONFIG(tag, " Update Interval: never");
339 } else if (update_interval < 100) {
340 ESP_LOGCONFIG(tag, " Update Interval: %.3fs", update_interval / 1000.0f);
341 } else {
342 ESP_LOGCONFIG(tag, " Update Interval: %.1fs", update_interval / 1000.0f);
343 }
344}
346#ifdef USE_SETUP_PRIORITY_OVERRIDE
347 // Check if there's an override in the global vector
348 if (setup_priority_overrides) {
349 // Linear search is fine for small n (typically < 5 overrides)
350 for (const auto &entry : *setup_priority_overrides) {
351 if (entry.component == this) {
352 return entry.priority;
353 }
354 }
355 }
356#endif
357 return this->get_setup_priority();
358}
359#ifdef USE_SETUP_PRIORITY_OVERRIDE
361 // Lazy allocate the vector if needed
362 if (!setup_priority_overrides) {
363 setup_priority_overrides = new std::vector<ComponentPriorityOverride>();
364 }
365
366 // Check if this component already has an override
367 for (auto &entry : *setup_priority_overrides) {
368 if (entry.component == this) {
369 entry.priority = priority;
370 return;
371 }
372 }
373
374 // Add new override
375 setup_priority_overrides->emplace_back(ComponentPriorityOverride{this, priority});
376}
377#endif
378
379PollingComponent::PollingComponent(uint32_t update_interval) : update_interval_(update_interval) {}
380
382 // init the poller before calling setup, allowing setup to cancel it if desired
383 this->start_poller();
384 // Let the polling component subclass setup their HW.
385 this->setup();
386}
387
389 // Register interval.
390 this->set_interval(InternalSchedulerID::POLLING_UPDATE, this->get_update_interval(), [this]() { this->update(); });
391}
392
394 // Clear the interval to suspend component
396}
397
399
400#ifdef USE_RUNTIME_STATS
401uint64_t ComponentRuntimeStats::global_recorded_us = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
402#endif
403
404void __attribute__((noinline, cold)) LoopBlockingGuard::warn_blocking(uint32_t blocking_time) {
405 // Identity is published on App by the caller before the guard is built; read it back here.
407 // Component-less path always warns (the caller already checked the constant threshold).
408 uint32_t threshold_ms = WARN_IF_BLOCKING_OVER_MS;
409 if (component != nullptr && !component->should_warn_of_blocking(blocking_time, threshold_ms)) {
410 return; // Component's (possibly ratcheted) threshold not exceeded yet
411 }
412 // Component name if any, else the published source (owning script), else a generic label.
413 const LogString *name;
414 if (component != nullptr) {
415 name = component->get_component_log_str();
416 } else {
417 name = App.get_current_source();
418 if (name == nullptr)
419 name = LOG_STR("a scheduled task");
420 }
421 ESP_LOGW(TAG, "%s took a long time for an operation (%" PRIu32 " ms), max is %" PRIu32 " ms", LOG_STR_ARG(name),
422 blocking_time, threshold_ms);
423}
424
425#ifdef USE_SETUP_PRIORITY_OVERRIDE
427 // Free the setup priority map completely
428 delete setup_priority_overrides;
429 setup_priority_overrides = nullptr;
430}
431#endif
432
433// Weak default for component_source_lookup - overridden by generated code
434__attribute__((weak)) const LogString *component_source_lookup(uint8_t) { return LOG_STR("<unknown>"); }
435
436} // namespace esphome
Component * get_current_component()
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 enable_component_loop_(Component *component)
void disable_component_loop_(Component *component)
const LogString * get_current_source()
volatile bool has_pending_enable_loop_requests_
bool is_setup_complete() const
True once Application::setup() has finished walking all components and finalized the initial status f...
void mark_failed()
Mark this component as failed.
void status_momentary_error(const char *name, uint32_t length=5000)
Set error status flag and automatically clear it after a timeout.
virtual float get_setup_priority() const
priority of setup().
Definition component.cpp:82
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
float get_actual_setup_priority() const
bool set_status_flag_(uint8_t flag)
Helper to set a status LED flag on both this component and the app.
bool is_failed() const
Definition component.h:272
void enable_loop_slow_path_()
volatile bool pending_enable_loop_
ISR-safe flag for enable_loop_soon_any_context.
Definition component.h:496
virtual bool can_proceed()
bool cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
void status_clear_error()
Definition component.h:295
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
uint8_t component_state_
State of this component - each bit has a purpose: Bits 0-2: Component state (0x00=CONSTRUCTION,...
Definition component.h:495
bool should_warn_of_blocking(uint32_t blocking_time, uint32_t &threshold_ms_out)
bool cancel_timeout(const char *name)
Cancel a timeout function.
void status_momentary_warning(const char *name, uint32_t length=5000)
Set warning status flag and automatically clear it after a timeout.
bool is_ready() const
virtual void dump_config()
const LogString * get_component_log_str() const ESPHOME_ALWAYS_INLINE
Get the integration where this component was declared as a LogString for logging.
Definition component.h:325
void status_clear_warning_slow_path_()
void set_component_state_(uint8_t state)
Helper to set component state (clears state bits and sets new state)
Definition component.h:349
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
void status_clear_error_slow_path_()
void disable_loop()
Disable this component's loop.
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
virtual void loop()
This method will be called repeatedly.
Definition component.cpp:86
void reset_to_construction_state()
Reset this component back to the construction state to allow setup to run again.
uint8_t warn_if_blocking_over_
Warn threshold in centiseconds (max 2550ms)
Definition component.h:488
void set_setup_priority(float priority)
bool cancel_defer(const char *name)
Cancel a defer callback using the specified name, name must not be empty.
void status_clear_warning()
Definition component.h:289
virtual void call_setup()
This class simplifies creating components that periodically check a state.
Definition component.h:510
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
void call_setup() override
virtual void update()=0
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:32
const Component * component
Definition component.cpp:34
const LogString * message
Definition component.cpp:35
uint8_t priority
bool state
Definition fan.h:2
constexpr float DATA
For components that import data from directly connected sensors like DHT.
Definition component.h:45
const char *const TAG
Definition spi.cpp:7
const char * tag
Definition log.h:74
constexpr uint8_t COMPONENT_STATE_FAILED
Definition component.h:85
constexpr uint8_t WARN_IF_BLOCKING_OVER_CS
Definition component.h:100
InternalSchedulerID
Type-safe scheduler IDs for core base classes.
Definition component.h:68
constexpr uint8_t COMPONENT_STATE_LOOP
Definition component.h:84
constexpr uint8_t STATUS_LED_WARNING
Definition component.h:90
constexpr uint8_t COMPONENT_STATE_MASK
Definition component.h:81
void log_update_interval(const char *tag, PollingComponent *component)
void clear_setup_priority_overrides()
const LogString * component_source_lookup(uint8_t index)
Lookup component source name by index (1-based).
constexpr uint8_t COMPONENT_STATE_LOOP_DONE
Definition component.h:86
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint8_t COMPONENT_STATE_SETUP
Definition component.h:83
constexpr uint8_t COMPONENT_STATE_CONSTRUCTION
Definition component.h:82
constexpr uint8_t STATUS_LED_ERROR
Definition component.h:91
constexpr uint32_t SCHEDULER_DONT_RUN
Definition component.h:63
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
uint16_t length
Definition tt21100.cpp:0