ESPHome 2025.10.1
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#ifdef USE_RUNTIME_STATS
14#endif
15
16namespace esphome {
17
18static const char *const TAG = "component";
19
20// Global vectors for component data that doesn't belong in every instance.
21// Using vector instead of unordered_map for both because:
22// - Much lower memory overhead (8 bytes per entry vs 20+ for unordered_map)
23// - Linear search is fine for small n (typically < 5 entries)
24// - These are rarely accessed (setup only or error cases only)
25
26// Component error messages - only stores messages for failed components
27// Lazy allocated since most configs have zero failures
28// Note: We don't clear this vector because:
29// 1. Components are never destroyed in ESPHome
30// 2. Failed components remain failed (no recovery mechanism)
31// 3. Memory usage is minimal (only failures with custom messages are stored)
32
33// Using namespace-scope static to avoid guard variables (saves 16 bytes total)
34// This is safe because ESPHome is single-threaded during initialization
35namespace {
36struct ComponentErrorMessage {
37 const Component *component;
38 const char *message;
39};
40
41struct ComponentPriorityOverride {
42 const Component *component;
43 float priority;
44};
45
46// Error messages for failed components
47// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
48std::unique_ptr<std::vector<ComponentErrorMessage>> component_error_messages;
49// Setup priority overrides - freed after setup completes
50// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
51std::unique_ptr<std::vector<ComponentPriorityOverride>> setup_priority_overrides;
52} // namespace
53
54namespace setup_priority {
55
56const float BUS = 1000.0f;
57const float IO = 900.0f;
58const float HARDWARE = 800.0f;
59const float DATA = 600.0f;
60const float PROCESSOR = 400.0;
61const float BLUETOOTH = 350.0f;
62const float AFTER_BLUETOOTH = 300.0f;
63const float WIFI = 250.0f;
64const float ETHERNET = 250.0f;
65const float BEFORE_CONNECTION = 220.0f;
66const float AFTER_WIFI = 200.0f;
67const float AFTER_CONNECTION = 100.0f;
68const float LATE = -100.0f;
69
70} // namespace setup_priority
71
72// Component state uses bits 0-2 (8 states, 5 used)
73const uint8_t COMPONENT_STATE_MASK = 0x07;
74const uint8_t COMPONENT_STATE_CONSTRUCTION = 0x00;
75const uint8_t COMPONENT_STATE_SETUP = 0x01;
76const uint8_t COMPONENT_STATE_LOOP = 0x02;
77const uint8_t COMPONENT_STATE_FAILED = 0x03;
78const uint8_t COMPONENT_STATE_LOOP_DONE = 0x04;
79// Status LED uses bits 3-4
80const uint8_t STATUS_LED_MASK = 0x18;
81const uint8_t STATUS_LED_OK = 0x00;
82const uint8_t STATUS_LED_WARNING = 0x08; // Bit 3
83const uint8_t STATUS_LED_ERROR = 0x10; // Bit 4
84
85const uint16_t WARN_IF_BLOCKING_OVER_MS = 50U;
86const uint16_t WARN_IF_BLOCKING_INCREMENT_MS = 10U;
87
88uint32_t global_state = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
89
90float Component::get_loop_priority() const { return 0.0f; }
91
93
95
97
98void Component::set_interval(const std::string &name, uint32_t interval, std::function<void()> &&f) { // NOLINT
99 App.scheduler.set_interval(this, name, interval, std::move(f));
100}
101
102void Component::set_interval(const char *name, uint32_t interval, std::function<void()> &&f) { // NOLINT
103 App.scheduler.set_interval(this, name, interval, std::move(f));
104}
105
106bool Component::cancel_interval(const std::string &name) { // NOLINT
107 return App.scheduler.cancel_interval(this, name);
108}
109
110bool Component::cancel_interval(const char *name) { // NOLINT
111 return App.scheduler.cancel_interval(this, name);
112}
113
114void Component::set_retry(const std::string &name, uint32_t initial_wait_time, uint8_t max_attempts,
115 std::function<RetryResult(uint8_t)> &&f, float backoff_increase_factor) { // NOLINT
116 App.scheduler.set_retry(this, name, initial_wait_time, max_attempts, std::move(f), backoff_increase_factor);
117}
118
119bool Component::cancel_retry(const std::string &name) { // NOLINT
120 return App.scheduler.cancel_retry(this, name);
121}
122
123void Component::set_timeout(const std::string &name, uint32_t timeout, std::function<void()> &&f) { // NOLINT
124 App.scheduler.set_timeout(this, name, timeout, std::move(f));
125}
126
127void Component::set_timeout(const char *name, uint32_t timeout, std::function<void()> &&f) { // NOLINT
128 App.scheduler.set_timeout(this, name, timeout, std::move(f));
129}
130
131bool Component::cancel_timeout(const std::string &name) { // NOLINT
132 return App.scheduler.cancel_timeout(this, name);
133}
134
135bool Component::cancel_timeout(const char *name) { // NOLINT
136 return App.scheduler.cancel_timeout(this, name);
137}
138
139void Component::call_loop() { this->loop(); }
140void Component::call_setup() { this->setup(); }
142 this->dump_config();
143 if (this->is_failed()) {
144 // Look up error message from global vector
145 const char *error_msg = nullptr;
146 if (component_error_messages) {
147 for (const auto &entry : *component_error_messages) {
148 if (entry.component == this) {
149 error_msg = entry.message;
150 break;
151 }
152 }
153 }
154 ESP_LOGE(TAG, " %s is marked FAILED: %s", LOG_STR_ARG(this->get_component_log_str()),
155 error_msg ? error_msg : LOG_STR_LITERAL("unspecified"));
156 }
157}
158
159uint8_t Component::get_component_state() const { return this->component_state_; }
162 switch (state) {
164 // State Construction: Call setup and set state to setup
165 this->set_component_state_(COMPONENT_STATE_SETUP);
166 ESP_LOGV(TAG, "Setup %s", LOG_STR_ARG(this->get_component_log_str()));
167#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
168 uint32_t start_time = millis();
169#endif
170 this->call_setup();
171#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
172 uint32_t setup_time = millis() - start_time;
173 ESP_LOGCONFIG(TAG, "Setup %s took %ums", LOG_STR_ARG(this->get_component_log_str()), (unsigned) setup_time);
174#endif
175 break;
176 }
178 // State setup: Call first loop and set state to loop
179 this->set_component_state_(COMPONENT_STATE_LOOP);
180 this->call_loop();
181 break;
183 // State loop: Call loop
184 this->call_loop();
185 break;
187 // State failed: Do nothing
189 // State loop done: Do nothing, component has finished its work
190 default:
191 break;
192 }
193}
194const LogString *Component::get_component_log_str() const {
195 return this->component_source_ == nullptr ? LOG_STR("<unknown>") : this->component_source_;
196}
197bool Component::should_warn_of_blocking(uint32_t blocking_time) {
198 if (blocking_time > this->warn_if_blocking_over_) {
199 // Prevent overflow when adding increment - if we're about to overflow, just max out
200 if (blocking_time + WARN_IF_BLOCKING_INCREMENT_MS < blocking_time ||
201 blocking_time + WARN_IF_BLOCKING_INCREMENT_MS > std::numeric_limits<uint16_t>::max()) {
202 this->warn_if_blocking_over_ = std::numeric_limits<uint16_t>::max();
203 } else {
204 this->warn_if_blocking_over_ = static_cast<uint16_t>(blocking_time + WARN_IF_BLOCKING_INCREMENT_MS);
205 }
206 return true;
207 }
208 return false;
209}
211 ESP_LOGE(TAG, "%s was marked as failed", LOG_STR_ARG(this->get_component_log_str()));
212 this->set_component_state_(COMPONENT_STATE_FAILED);
213 this->status_set_error();
214 // Also remove from loop since failed components shouldn't loop
216}
218 this->component_state_ &= ~COMPONENT_STATE_MASK;
219 this->component_state_ |= state;
220}
222 if ((this->component_state_ & COMPONENT_STATE_MASK) != COMPONENT_STATE_LOOP_DONE) {
223 ESP_LOGVV(TAG, "%s loop disabled", LOG_STR_ARG(this->get_component_log_str()));
224 this->set_component_state_(COMPONENT_STATE_LOOP_DONE);
226 }
227}
229 if ((this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP_DONE) {
230 ESP_LOGVV(TAG, "%s loop enabled", LOG_STR_ARG(this->get_component_log_str()));
231 this->set_component_state_(COMPONENT_STATE_LOOP);
233 }
234}
236 // This method is thread and ISR-safe because:
237 // 1. Only performs simple assignments to volatile variables (atomic on all platforms)
238 // 2. No read-modify-write operations that could be interrupted
239 // 3. No memory allocation, object construction, or function calls
240 // 4. IRAM_ATTR ensures code is in IRAM, not flash (required for ISR execution)
241 // 5. Components are never destroyed, so no use-after-free concerns
242 // 6. App is guaranteed to be initialized before any ISR could fire
243 // 7. Multiple ISR/thread calls are safe - just sets the same flags to true
244 // 8. Race condition with main loop is handled by clearing flag before processing
245 this->pending_enable_loop_ = true;
247}
249 if ((this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_FAILED) {
250 ESP_LOGI(TAG, "%s is being reset to construction state", LOG_STR_ARG(this->get_component_log_str()));
251 this->set_component_state_(COMPONENT_STATE_CONSTRUCTION);
252 // Clear error status when resetting
253 this->status_clear_error();
254 }
255}
257 return (this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP;
258}
259void Component::defer(std::function<void()> &&f) { // NOLINT
260 App.scheduler.set_timeout(this, static_cast<const char *>(nullptr), 0, std::move(f));
261}
262bool Component::cancel_defer(const std::string &name) { // NOLINT
263 return App.scheduler.cancel_timeout(this, name);
264}
265void Component::defer(const std::string &name, std::function<void()> &&f) { // NOLINT
266 App.scheduler.set_timeout(this, name, 0, std::move(f));
267}
268void Component::defer(const char *name, std::function<void()> &&f) { // NOLINT
269 App.scheduler.set_timeout(this, name, 0, std::move(f));
270}
271void Component::set_timeout(uint32_t timeout, std::function<void()> &&f) { // NOLINT
272 App.scheduler.set_timeout(this, static_cast<const char *>(nullptr), timeout, std::move(f));
273}
274void Component::set_interval(uint32_t interval, std::function<void()> &&f) { // NOLINT
275 App.scheduler.set_interval(this, static_cast<const char *>(nullptr), interval, std::move(f));
276}
277void Component::set_retry(uint32_t initial_wait_time, uint8_t max_attempts, std::function<RetryResult(uint8_t)> &&f,
278 float backoff_increase_factor) { // NOLINT
279 App.scheduler.set_retry(this, "", initial_wait_time, max_attempts, std::move(f), backoff_increase_factor);
280}
281bool Component::is_failed() const { return (this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_FAILED; }
283 return (this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP ||
284 (this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP_DONE ||
285 (this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_SETUP;
286}
287bool Component::can_proceed() { return true; }
290
292 // Don't spam the log. This risks missing different warning messages though.
293 if ((this->component_state_ & STATUS_LED_WARNING) != 0)
294 return;
297 ESP_LOGW(TAG, "%s set Warning flag: %s", LOG_STR_ARG(this->get_component_log_str()),
298 message ? message : LOG_STR_LITERAL("unspecified"));
299}
301 // Don't spam the log. This risks missing different warning messages though.
302 if ((this->component_state_ & STATUS_LED_WARNING) != 0)
303 return;
306 ESP_LOGW(TAG, "%s set Warning flag: %s", LOG_STR_ARG(this->get_component_log_str()),
307 message ? LOG_STR_ARG(message) : LOG_STR_LITERAL("unspecified"));
308}
310 if ((this->component_state_ & STATUS_LED_ERROR) != 0)
311 return;
314 ESP_LOGE(TAG, "%s set Error flag: %s", LOG_STR_ARG(this->get_component_log_str()),
315 message ? message : LOG_STR_LITERAL("unspecified"));
316 if (message != nullptr) {
317 // Lazy allocate the error messages vector if needed
318 if (!component_error_messages) {
319 component_error_messages = std::make_unique<std::vector<ComponentErrorMessage>>();
320 }
321 // Check if this component already has an error message
322 for (auto &entry : *component_error_messages) {
323 if (entry.component == this) {
324 entry.message = message;
325 return;
326 }
327 }
328 // Add new error message
329 component_error_messages->emplace_back(ComponentErrorMessage{this, message});
330 }
331}
333 if ((this->component_state_ & STATUS_LED_WARNING) == 0)
334 return;
335 this->component_state_ &= ~STATUS_LED_WARNING;
336 ESP_LOGW(TAG, "%s cleared Warning flag", LOG_STR_ARG(this->get_component_log_str()));
337}
339 if ((this->component_state_ & STATUS_LED_ERROR) == 0)
340 return;
341 this->component_state_ &= ~STATUS_LED_ERROR;
342 ESP_LOGE(TAG, "%s cleared Error flag", LOG_STR_ARG(this->get_component_log_str()));
343}
344void Component::status_momentary_warning(const std::string &name, uint32_t length) {
345 this->status_set_warning();
346 this->set_timeout(name, length, [this]() { this->status_clear_warning(); });
347}
348void Component::status_momentary_error(const std::string &name, uint32_t length) {
349 this->status_set_error();
350 this->set_timeout(name, length, [this]() { this->status_clear_error(); });
351}
353
354// Function implementation of LOG_UPDATE_INTERVAL macro to reduce code size
356 uint32_t update_interval = component->get_update_interval();
357 if (update_interval == SCHEDULER_DONT_RUN) {
358 ESP_LOGCONFIG(tag, " Update Interval: never");
359 } else if (update_interval < 100) {
360 ESP_LOGCONFIG(tag, " Update Interval: %.3fs", update_interval / 1000.0f);
361 } else {
362 ESP_LOGCONFIG(tag, " Update Interval: %.1fs", update_interval / 1000.0f);
363 }
364}
366 // Check if there's an override in the global vector
367 if (setup_priority_overrides) {
368 // Linear search is fine for small n (typically < 5 overrides)
369 for (const auto &entry : *setup_priority_overrides) {
370 if (entry.component == this) {
371 return entry.priority;
372 }
373 }
374 }
375 return this->get_setup_priority();
376}
378 // Lazy allocate the vector if needed
379 if (!setup_priority_overrides) {
380 setup_priority_overrides = std::make_unique<std::vector<ComponentPriorityOverride>>();
381 // Reserve some space to avoid reallocations (most configs have < 10 overrides)
382 setup_priority_overrides->reserve(10);
383 }
384
385 // Check if this component already has an override
386 for (auto &entry : *setup_priority_overrides) {
387 if (entry.component == this) {
388 entry.priority = priority;
389 return;
390 }
391 }
392
393 // Add new override
394 setup_priority_overrides->emplace_back(ComponentPriorityOverride{this, priority});
395}
396
398#if defined(USE_HOST) || defined(CLANG_TIDY)
399 bool loop_overridden = true;
400 bool call_loop_overridden = true;
401#else
402#pragma GCC diagnostic push
403#pragma GCC diagnostic ignored "-Wpmf-conversions"
404 bool loop_overridden = (void *) (this->*(&Component::loop)) != (void *) (&Component::loop);
405 bool call_loop_overridden = (void *) (this->*(&Component::call_loop)) != (void *) (&Component::call_loop);
406#pragma GCC diagnostic pop
407#endif
408 return loop_overridden || call_loop_overridden;
409}
410
411PollingComponent::PollingComponent(uint32_t update_interval) : update_interval_(update_interval) {}
412
414 // init the poller before calling setup, allowing setup to cancel it if desired
415 this->start_poller();
416 // Let the polling component subclass setup their HW.
417 this->setup();
418}
419
421 // Register interval.
422 this->set_interval("update", this->get_update_interval(), [this]() { this->update(); });
423}
424
426 // Clear the interval to suspend component
427 this->cancel_interval("update");
428}
429
431void PollingComponent::set_update_interval(uint32_t update_interval) { this->update_interval_ = update_interval; }
432
434 : started_(start_time), component_(component) {}
436 uint32_t curr_time = millis();
437
438 uint32_t blocking_time = curr_time - this->started_;
439
440#ifdef USE_RUNTIME_STATS
441 // Record component runtime stats
442 if (global_runtime_stats != nullptr) {
443 global_runtime_stats->record_component_time(this->component_, blocking_time, curr_time);
444 }
445#endif
446 bool should_warn;
447 if (this->component_ != nullptr) {
448 should_warn = this->component_->should_warn_of_blocking(blocking_time);
449 } else {
450 should_warn = blocking_time > WARN_IF_BLOCKING_OVER_MS;
451 }
452 if (should_warn) {
453 ESP_LOGW(TAG, "%s took a long time for an operation (%" PRIu32 " ms)",
454 component_ == nullptr ? LOG_STR_LITERAL("<null>") : LOG_STR_ARG(component_->get_component_log_str()),
455 blocking_time);
456 ESP_LOGW(TAG, "Components should block for at most 30 ms");
457 }
458
459 return curr_time;
460}
461
463
465 // Free the setup priority map completely
466 setup_priority_overrides.reset();
467}
468
469} // namespace esphome
void enable_component_loop_(Component *component)
void disable_component_loop_(Component *component)
volatile bool has_pending_enable_loop_requests_
virtual void mark_failed()
Mark this component as failed.
virtual void call_dump_config()
virtual float get_setup_priority() const
priority of setup().
Definition component.cpp:92
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:94
float get_actual_setup_priority() const
bool has_overridden_loop() const
const LogString * get_component_log_str() const
Get the integration where this component was declared as a LogString for logging.
const LogString * component_source_
Definition component.h:412
bool is_failed() const
uint8_t get_component_state() const
void status_set_warning(const char *message=nullptr)
void set_interval(const std::string &name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a unique name.
Definition component.cpp:98
bool should_warn_of_blocking(uint32_t blocking_time)
volatile bool pending_enable_loop_
ISR-safe flag for enable_loop_soon_any_context.
Definition component.h:420
virtual bool can_proceed()
bool cancel_timeout(const std::string &name)
Cancel a timeout function.
virtual float get_loop_priority() const
priority of loop().
Definition component.cpp:90
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
bool is_in_loop_state() const
Check if this component has completed setup and is in the loop state.
void status_momentary_error(const std::string &name, uint32_t length=5000)
uint16_t warn_if_blocking_over_
Warn if blocked for this many ms (max 65.5s)
Definition component.h:413
bool cancel_retry(const std::string &name)
Cancel a retry function.
uint8_t component_state_
State of this component - each bit has a purpose: Bits 0-2: Component state (0x00=CONSTRUCTION,...
Definition component.h:419
void status_momentary_warning(const std::string &name, uint32_t length=5000)
bool is_ready() const
virtual void dump_config()
void enable_loop()
Enable this component's loop.
void set_component_state_(uint8_t state)
Helper to set component state (clears state bits and sets new state)
bool status_has_warning() const
bool status_has_error() const
bool cancel_interval(const std::string &name)
Cancel an interval function.
void disable_loop()
Disable this component's loop.
bool cancel_defer(const std::string &name)
Cancel a defer callback using the specified name, name must not be empty.
virtual void loop()
This method will be called repeatedly.
Definition component.cpp:96
void reset_to_construction_state()
Reset this component back to the construction state to allow setup to run again.
void set_setup_priority(float priority)
void defer(const std::string &name, std::function< void()> &&f)
Defer a callback to the next loop() call.
virtual void call_loop()
void status_clear_warning()
virtual void call_setup()
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
void status_set_error(const char *message=nullptr)
void set_retry(const std::string &name, uint32_t initial_wait_time, uint8_t max_attempts, std::function< RetryResult(uint8_t)> &&f, float backoff_increase_factor=1.0f)
Set an retry function with a unique name.
This class simplifies creating components that periodically check a state.
Definition component.h:429
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
void call_setup() override
virtual void set_update_interval(uint32_t update_interval)
Manually set the update interval in ms for this polling object.
virtual void update()=0
WarnIfComponentBlockingGuard(Component *component, uint32_t start_time)
void record_component_time(Component *component, uint32_t duration_ms, uint32_t current_time)
const Component * component
Definition component.cpp:37
const char * message
Definition component.cpp:38
uint8_t priority
bool state
Definition fan.h:0
const float BUS
For communication buses like i2c/spi.
Definition component.cpp:56
const float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
Definition component.cpp:67
const float DATA
For components that import data from directly connected sensors like DHT.
Definition component.cpp:59
const float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.cpp:58
const float BEFORE_CONNECTION
For components that should be initialized after WiFi and before API is connected.
Definition component.cpp:65
const float IO
For components that represent GPIO pins like PCF8573.
Definition component.cpp:57
const float LATE
For components that should be initialized at the very end of the setup process.
Definition component.cpp:68
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.cpp:66
const float PROCESSOR
For components that use data from sensors like displays.
Definition component.cpp:60
const float AFTER_BLUETOOTH
Definition component.cpp:62
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
const uint8_t COMPONENT_STATE_SETUP
Definition component.cpp:75
const uint8_t COMPONENT_STATE_CONSTRUCTION
Definition component.cpp:74
const uint8_t STATUS_LED_MASK
Definition component.cpp:80
const uint16_t WARN_IF_BLOCKING_INCREMENT_MS
How long the blocking time must be larger to warn again.
Definition component.cpp:86
runtime_stats::RuntimeStatsCollector * global_runtime_stats
const uint8_t COMPONENT_STATE_FAILED
Definition component.cpp:77
const uint8_t COMPONENT_STATE_MASK
Definition component.cpp:73
void log_update_interval(const char *tag, PollingComponent *component)
const uint8_t COMPONENT_STATE_LOOP
Definition component.cpp:76
const uint16_t WARN_IF_BLOCKING_OVER_MS
Initial blocking time allowed without warning.
Definition component.cpp:85
void clear_setup_priority_overrides()
uint32_t global_state
Definition component.cpp:88
const uint8_t STATUS_LED_OK
Definition component.cpp:81
const uint8_t STATUS_LED_WARNING
Definition component.cpp:82
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
const uint8_t COMPONENT_STATE_LOOP_DONE
Definition component.cpp:78
const uint8_t STATUS_LED_ERROR
Definition component.cpp:83
uint16_t length
Definition tt21100.cpp:0