ESPHome 2026.5.0-dev
Loading...
Searching...
No Matches
base_automation.h
Go to the documentation of this file.
1#pragma once
2
5#include "esphome/core/hal.h"
11
12#include <array>
13#include <list>
14#include <vector>
15
16namespace esphome {
17
18template<size_t N, typename... Ts> class AndCondition : public Condition<Ts...> {
19 public:
20 explicit AndCondition(std::initializer_list<Condition<Ts...> *> conditions) {
21 init_array_from(this->conditions_, conditions);
22 }
23 bool check(const Ts &...x) override {
24 for (auto *condition : this->conditions_) {
25 if (!condition->check(x...))
26 return false;
27 }
28
29 return true;
30 }
31
32 protected:
33 std::array<Condition<Ts...> *, N> conditions_{};
34};
35
36template<size_t N, typename... Ts> class OrCondition : public Condition<Ts...> {
37 public:
38 explicit OrCondition(std::initializer_list<Condition<Ts...> *> conditions) {
39 init_array_from(this->conditions_, conditions);
40 }
41 bool check(const Ts &...x) override {
42 for (auto *condition : this->conditions_) {
43 if (condition->check(x...))
44 return true;
45 }
46
47 return false;
48 }
49
50 protected:
51 std::array<Condition<Ts...> *, N> conditions_{};
52};
53
54template<typename... Ts> class NotCondition : public Condition<Ts...> {
55 public:
56 explicit NotCondition(Condition<Ts...> *condition) : condition_(condition) {}
57 bool check(const Ts &...x) override { return !this->condition_->check(x...); }
58
59 protected:
61};
62
63template<size_t N, typename... Ts> class XorCondition : public Condition<Ts...> {
64 public:
65 explicit XorCondition(std::initializer_list<Condition<Ts...> *> conditions) {
66 init_array_from(this->conditions_, conditions);
67 }
68 bool check(const Ts &...x) override {
69 size_t result = 0;
70 for (auto *condition : this->conditions_) {
71 result += condition->check(x...);
72 }
73
74 return result == 1;
75 }
76
77 protected:
78 std::array<Condition<Ts...> *, N> conditions_{};
79};
80
81template<typename... Ts> class LambdaCondition : public Condition<Ts...> {
82 public:
83 explicit LambdaCondition(std::function<bool(Ts...)> &&f) : f_(std::move(f)) {}
84 bool check(const Ts &...x) override { return this->f_(x...); }
85
86 protected:
87 std::function<bool(Ts...)> f_;
88};
89
93template<typename... Ts> class StatelessLambdaCondition : public Condition<Ts...> {
94 public:
95 explicit StatelessLambdaCondition(bool (*f)(Ts...)) : f_(f) {}
96 bool check(const Ts &...x) override { return this->f_(x...); }
97
98 protected:
99 bool (*f_)(Ts...);
100};
101
102template<typename... Ts> class ForCondition : public Condition<Ts...>, public Component {
103 public:
104 explicit ForCondition(Condition<> *condition) : condition_(condition) {}
105
107
108 void loop() override {
109 // Safe to use cached time - only called from Application::loop()
111 }
112
113 float get_setup_priority() const override { return setup_priority::DATA; }
114
115 bool check(const Ts &...x) override {
116 auto now = millis();
117 if (!this->check_internal_(now))
118 return false;
119 return now - this->last_inactive_ >= this->time_.value(x...);
120 }
121
122 protected:
124 bool cond = this->condition_->check();
125 if (!cond)
126 this->last_inactive_ = now;
127 return cond;
128 }
129
132};
133
134class StartupTrigger : public Trigger<>, public Component {
135 public:
136 explicit StartupTrigger(float setup_priority) : setup_priority_(setup_priority) {}
137 void setup() override { this->trigger(); }
138 float get_setup_priority() const override { return this->setup_priority_; }
139
140 protected:
142};
143
144class ShutdownTrigger : public Trigger<>, public Component {
145 public:
146 explicit ShutdownTrigger(float setup_priority) : setup_priority_(setup_priority) {}
147 void on_shutdown() override { this->trigger(); }
148 float get_setup_priority() const override { return this->setup_priority_; }
149
150 protected:
152};
153
154class LoopTrigger : public Trigger<>, public Component {
155 public:
156 void loop() override { this->trigger(); }
157 float get_setup_priority() const override { return setup_priority::DATA; }
158};
159
160#ifdef ESPHOME_PROJECT_NAME
161class ProjectUpdateTrigger : public Trigger<std::string>, public Component {
162 public:
163 void setup() override {
164 uint32_t hash = fnv1_hash(ESPHOME_PROJECT_NAME);
165 ESPPreferenceObject pref = global_preferences->make_preference<char[30]>(hash, true);
166 char previous_version[30];
167 char current_version[30] = ESPHOME_PROJECT_VERSION_30;
168 if (pref.load(&previous_version)) {
169 int cmp = strcmp(previous_version, current_version);
170 if (cmp < 0) {
171 this->trigger(previous_version);
172 }
173 }
174 pref.save(&current_version);
176 }
177 float get_setup_priority() const override { return setup_priority::PROCESSOR; }
178};
179#endif
180
181template<typename... Ts> class DelayAction : public Action<Ts...>, public Component {
182 public:
183 explicit DelayAction() = default;
184
186
187 void play_complex(const Ts &...x) override {
188 this->num_running_++;
189
190 // If num_running_ > 1, we have multiple instances running in parallel
191 // In single/restart/queued modes, only one instance runs at a time
192 // Parallel mode uses skip_cancel=true to allow multiple delays to coexist
193 // WARNING: This can accumulate delays if scripts are triggered faster than they complete!
194 // Users should set max_runs on parallel scripts to limit concurrent executions.
195 // Issue #10264: This is a workaround for parallel script delays interfering with each other.
196
197 // Optimization: For no-argument delays (most common case), use direct lambda
198 // to avoid overhead from capturing arguments by value
199 if constexpr (sizeof...(Ts) == 0) {
200 App.scheduler.set_timer_common_(
201 this, Scheduler::SchedulerItem::TIMEOUT, Scheduler::NameType::NUMERIC_ID_INTERNAL, nullptr,
202 static_cast<uint32_t>(InternalSchedulerID::DELAY_ACTION), this->delay_.value(),
203 [this]() { this->play_next_(); },
204 /* is_retry= */ false, /* skip_cancel= */ this->num_running_ > 1);
205 } else {
206 // For delays with arguments, capture by value to preserve argument values
207 // Arguments must be copied because original references may be invalid after delay
208 auto f = [this, x...]() { this->play_next_(x...); };
209 App.scheduler.set_timer_common_(this, Scheduler::SchedulerItem::TIMEOUT, Scheduler::NameType::NUMERIC_ID_INTERNAL,
210 nullptr, static_cast<uint32_t>(InternalSchedulerID::DELAY_ACTION),
211 this->delay_.value(x...), std::move(f),
212 /* is_retry= */ false, /* skip_cancel= */ this->num_running_ > 1);
213 }
214 }
215 float get_setup_priority() const override { return setup_priority::HARDWARE; }
216
217 void play(const Ts &...x) override { /* ignore - see play_complex */
218 }
219
221};
222
223template<typename... Ts> class LambdaAction : public Action<Ts...> {
224 public:
225 explicit LambdaAction(std::function<void(Ts...)> &&f) : f_(std::move(f)) {}
226
227 void play(const Ts &...x) override { this->f_(x...); }
228
229 protected:
230 std::function<void(Ts...)> f_;
231};
232
236template<typename... Ts> class StatelessLambdaAction : public Action<Ts...> {
237 public:
238 explicit StatelessLambdaAction(void (*f)(Ts...)) : f_(f) {}
239
240 void play(const Ts &...x) override { this->f_(x...); }
241
242 protected:
243 void (*f_)(Ts...);
244};
245
249template<typename... Ts> class ContinuationAction : public Action<Ts...> {
250 public:
251 explicit ContinuationAction(Action<Ts...> *parent) : parent_(parent) {}
252
253 void play(const Ts &...x) override { this->parent_->play_next_(x...); }
254
255 protected:
257};
258
259// Forward declaration for WhileLoopContinuation
260template<typename... Ts> class WhileAction;
261
264template<typename... Ts> class WhileLoopContinuation : public Action<Ts...> {
265 public:
266 explicit WhileLoopContinuation(WhileAction<Ts...> *parent) : parent_(parent) {}
267
268 void play(const Ts &...x) override;
269
270 protected:
272};
273
274template<bool HasElse, typename... Ts> class IfAction : public Action<Ts...> {
275 public:
276 explicit IfAction(Condition<Ts...> *condition) : condition_(condition) {}
277
278 void add_then(const std::initializer_list<Action<Ts...> *> &actions) {
279 this->then_.add_actions(actions);
281 }
282
283 void add_else(const std::initializer_list<Action<Ts...> *> &actions) requires(HasElse) {
284 this->else_.add_actions(actions);
285 this->else_.add_action(new ContinuationAction<Ts...>(this));
286 }
287
288 void play_complex(const Ts &...x) override {
289 this->num_running_++;
290 if (this->condition_->check(x...)) {
291 if (!this->then_.empty() && this->num_running_ > 0) {
292 this->then_.play(x...);
293 return;
294 }
295 } else if constexpr (HasElse) {
296 if (!this->else_.empty() && this->num_running_ > 0) {
297 this->else_.play(x...);
298 return;
299 }
300 }
301 this->play_next_(x...);
302 }
303
304 void play(const Ts &...x) override { /* ignore - see play_complex */
305 }
306
307 void stop() override {
308 this->then_.stop();
309 if constexpr (HasElse) {
310 this->else_.stop();
311 }
312 }
313
314 protected:
317 struct NoElse {};
318 [[no_unique_address]] std::conditional_t<HasElse, ActionList<Ts...>, NoElse> else_;
319};
320
321template<typename... Ts> class WhileAction : public Action<Ts...> {
322 public:
323 WhileAction(Condition<Ts...> *condition) : condition_(condition) {}
324
325 void add_then(const std::initializer_list<Action<Ts...> *> &actions) {
326 this->then_.add_actions(actions);
328 }
329
330 friend class WhileLoopContinuation<Ts...>;
331
332 void play_complex(const Ts &...x) override {
333 this->num_running_++;
334 // Initial condition check
335 if (!this->condition_->check(x...)) {
336 // If new condition check failed, stop loop if running
337 this->then_.stop();
338 this->play_next_(x...);
339 return;
340 }
341
342 if (this->num_running_ > 0) {
343 this->then_.play(x...);
344 }
345 }
346
347 void play(const Ts &...x) override { /* ignore - see play_complex */
348 }
349
350 void stop() override { this->then_.stop(); }
351
352 protected:
355};
356
357// Implementation of WhileLoopContinuation::play
358template<typename... Ts> void WhileLoopContinuation<Ts...>::play(const Ts &...x) {
359 if (this->parent_->num_running_ > 0 && this->parent_->condition_->check(x...)) {
360 // play again
361 this->parent_->then_.play(x...);
362 } else {
363 // condition false, play next
364 this->parent_->play_next_(x...);
365 }
366}
367
368// Forward declaration for RepeatLoopContinuation
369template<typename... Ts> class RepeatAction;
370
373template<typename... Ts> class RepeatLoopContinuation : public Action<uint32_t, Ts...> {
374 public:
376
377 void play(const uint32_t &iteration, const Ts &...x) override;
378
379 protected:
381};
382
383template<typename... Ts> class RepeatAction : public Action<Ts...> {
384 public:
386
387 void add_then(const std::initializer_list<Action<uint32_t, Ts...> *> &actions) {
388 this->then_.add_actions(actions);
390 }
391
392 friend class RepeatLoopContinuation<Ts...>;
393
394 void play_complex(const Ts &...x) override {
395 this->num_running_++;
396 if (this->count_.value(x...) > 0) {
397 this->then_.play(0, x...);
398 } else {
399 this->play_next_(x...);
400 }
401 }
402
403 void play(const Ts &...x) override { /* ignore - see play_complex */
404 }
405
406 void stop() override { this->then_.stop(); }
407
408 protected:
410};
411
412// Implementation of RepeatLoopContinuation::play
413template<typename... Ts> void RepeatLoopContinuation<Ts...>::play(const uint32_t &iteration, const Ts &...x) {
414 uint32_t next_iteration = iteration + 1;
415 if (next_iteration >= this->parent_->count_.value(x...)) {
416 this->parent_->play_next_(x...);
417 } else {
418 this->parent_->then_.play(next_iteration, x...);
419 }
420}
421
429template<typename... Ts> class WaitUntilAction : public Action<Ts...>, public Component {
430 public:
431 WaitUntilAction(Condition<Ts...> *condition) : condition_(condition) {}
432
434
435 void setup() override {
436 // Start with loop disabled - only enable when there's work to do
437 // IMPORTANT: Only disable if num_running_ is 0, otherwise play_complex() was already
438 // called before our setup() (e.g., from on_boot trigger at same priority level)
439 // and we must not undo its enable_loop() call
440 if (this->num_running_ == 0) {
441 this->disable_loop();
442 }
443 }
444
445 void play_complex(const Ts &...x) override {
446 this->num_running_++;
447 // Check if we can continue immediately.
448 if (this->condition_->check(x...)) {
449 if (this->num_running_ > 0) {
450 this->play_next_(x...);
451 }
452 return;
453 }
454
455 // Store for later processing
456 auto now = millis();
457 auto timeout = this->timeout_value_.optional_value(x...);
458 this->var_queue_.emplace_back(now, timeout, std::make_tuple(x...));
459
460 // Do immediate check with fresh timestamp - don't call loop() synchronously!
461 // Let the event loop call it to avoid reentrancy issues
462 if (this->process_queue_(now)) {
463 // Only enable loop if we still have pending items
464 this->enable_loop();
465 }
466 }
467
468 void loop() override {
469 // Safe to use cached time - only called from Application::loop()
471 // If queue is now empty, disable loop until next play_complex
472 this->disable_loop();
473 }
474 }
475
476 void stop() override {
477 this->var_queue_.clear();
478 this->disable_loop();
479 }
480
481 float get_setup_priority() const override { return setup_priority::DATA; }
482
483 void play(const Ts &...x) override { /* ignore - see play_complex */
484 }
485
486 protected:
487 // Helper: Process queue, triggering completed items and removing them
488 // Returns true if queue still has pending items
490 // Process each queued wait_until and remove completed ones
491 this->var_queue_.remove_if([&](auto &queued) {
492 auto start = std::get<uint32_t>(queued);
493 auto timeout = std::get<optional<uint32_t>>(queued);
494 auto &var = std::get<std::tuple<Ts...>>(queued);
495
496 // Check if timeout has expired
497 auto expired = timeout && (now - start) >= *timeout;
498
499 // Keep waiting if not expired and condition not met
500 if (!expired && !this->condition_->check_tuple(var)) {
501 return false;
502 }
503
504 // Condition met or timed out - trigger next action
505 this->play_next_tuple_(var);
506 return true;
507 });
508
509 return !this->var_queue_.empty();
510 }
511
513 std::list<std::tuple<uint32_t, optional<uint32_t>, std::tuple<Ts...>>> var_queue_{};
514};
515
516template<typename... Ts> class UpdateComponentAction : public Action<Ts...> {
517 public:
519
520 void play(const Ts &...x) override {
521 if (!this->component_->is_ready())
522 return;
523 this->component_->update();
524 }
525
526 protected:
528};
529
530template<typename... Ts> class SuspendComponentAction : public Action<Ts...> {
531 public:
533
534 void play(const Ts &...x) override {
535 if (!this->component_->is_ready())
536 return;
537 this->component_->stop_poller();
538 }
539
540 protected:
542};
543
544template<typename... Ts> class ResumeComponentAction : public Action<Ts...> {
545 public:
547 TEMPLATABLE_VALUE(uint32_t, update_interval)
548
549 void play(const Ts &...x) override {
550 if (!this->component_->is_ready()) {
551 return;
552 }
553 optional<uint32_t> update_interval = this->update_interval_.optional_value(x...);
554 if (update_interval.has_value()) {
555 this->component_->set_update_interval(update_interval.value());
556 }
557 this->component_->start_poller();
558 }
559
560 protected:
562};
563
564} // namespace esphome
void play_next_(const Ts &...x)
Definition automation.h:539
virtual void play(const Ts &...x)=0
void play_next_tuple_(const std::tuple< Ts... > &tuple, std::index_sequence< S... >)
Definition automation.h:547
virtual void play_complex(const Ts &...x)
Definition automation.h:510
void add_action(Action< Ts... > *action)
Definition automation.h:576
bool empty() const
Definition automation.h:606
void add_actions(const std::initializer_list< Action< Ts... > * > &actions)
Definition automation.h:583
void play(const Ts &...x) ESPHOME_ALWAYS_INLINE
Definition automation.h:595
AndCondition(std::initializer_list< Condition< Ts... > * > conditions)
bool check(const Ts &...x) override
std::array< Condition< Ts... > *, N > conditions_
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.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:89
bool is_ready() const
void enable_loop()
Enable this component's loop.
Definition component.h:258
void disable_loop()
Disable this component's loop.
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") bool cancel_timeout(const std boo cancel_timeout)(const char *name)
Cancel a timeout function.
Definition component.h:532
ESPDEPRECATED("set_retry is deprecated and will be removed in 2026.8.0. Use set_timeout or set_interval instead.", "2026.2.0") void set_retry(const std uint32_t uint8_t std::function< RetryResult(uint8_t)> && f
Definition component.h:454
Base class for all automation conditions.
Definition automation.h:459
bool check_tuple(const std::tuple< Ts... > &tuple)
Call check with a tuple of values as parameter.
Definition automation.h:465
virtual bool check(const Ts &...x)=0
Check whether this condition passes. This condition check must be instant, and not cause any delays.
Simple continuation action that calls play_next_ on a parent action.
void play(const Ts &...x) override
ContinuationAction(Action< Ts... > *parent)
void play(const Ts &...x) override
TEMPLATABLE_VALUE(uint32_t, delay) void play_complex(const Ts &...x) override
float get_setup_priority() const override
bool check_internal_(uint32_t now)
ForCondition(Condition<> *condition)
float get_setup_priority() const override
bool check(const Ts &...x) override
TEMPLATABLE_VALUE(uint32_t, time)
ActionList< Ts... > then_
Condition< Ts... > * condition_
void play(const Ts &...x) override
void add_then(const std::initializer_list< Action< Ts... > * > &actions)
void play_complex(const Ts &...x) override
void stop() override
std::conditional_t< HasElse, ActionList< Ts... >, NoElse > else_
IfAction(Condition< Ts... > *condition)
void add_else(const std::initializer_list< Action< Ts... > * > &actions)
LambdaAction(std::function< void(Ts...)> &&f)
void play(const Ts &...x) override
std::function< void(Ts...)> f_
bool check(const Ts &...x) override
LambdaCondition(std::function< bool(Ts...)> &&f)
std::function< bool(Ts...)> f_
float get_setup_priority() const override
Condition< Ts... > * condition_
bool check(const Ts &...x) override
NotCondition(Condition< Ts... > *condition)
OrCondition(std::initializer_list< Condition< Ts... > * > conditions)
bool check(const Ts &...x) override
std::array< Condition< Ts... > *, N > conditions_
This class simplifies creating components that periodically check a state.
Definition component.h:602
void set_update_interval(uint32_t update_interval)
Manually set the update interval in ms for this polling object.
Definition component.h:616
virtual void update()=0
float get_setup_priority() const override
ActionList< uint32_t, Ts... > then_
TEMPLATABLE_VALUE(uint32_t, count) void add_then(const std
void play_complex(const Ts &...x) override
void play(const Ts &...x) override
Loop continuation for RepeatAction that increments iteration and repeats or continues.
RepeatLoopContinuation(RepeatAction< Ts... > *parent)
RepeatAction< Ts... > * parent_
void play(const uint32_t &iteration, const Ts &...x) override
ResumeComponentAction(PollingComponent *component)
TEMPLATABLE_VALUE(uint32_t, update_interval) void play(const Ts &...x) override
ShutdownTrigger(float setup_priority)
float get_setup_priority() const override
float get_setup_priority() const override
StartupTrigger(float setup_priority)
Optimized lambda action for stateless lambdas (no capture).
void play(const Ts &...x) override
Optimized lambda condition for stateless lambdas (no capture).
bool check(const Ts &...x) override
SuspendComponentAction(PollingComponent *component)
void play(const Ts &...x) override
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Definition automation.h:482
void play(const Ts &...x) override
UpdateComponentAction(PollingComponent *component)
Wait until a condition is true to continue execution.
WaitUntilAction(Condition< Ts... > *condition)
TEMPLATABLE_VALUE(uint32_t, timeout_value) void setup() override
void play_complex(const Ts &...x) override
void play(const Ts &...x) override
bool process_queue_(uint32_t now)
Condition< Ts... > * condition_
std::list< std::tuple< uint32_t, optional< uint32_t >, std::tuple< Ts... > > > var_queue_
float get_setup_priority() const override
void add_then(const std::initializer_list< Action< Ts... > * > &actions)
WhileAction(Condition< Ts... > *condition)
void play(const Ts &...x) override
void play_complex(const Ts &...x) override
Condition< Ts... > * condition_
ActionList< Ts... > then_
Loop continuation for WhileAction that checks condition and repeats or continues.
WhileLoopContinuation(WhileAction< Ts... > *parent)
void play(const Ts &...x) override
WhileAction< Ts... > * parent_
std::array< Condition< Ts... > *, N > conditions_
bool check(const Ts &...x) override
XorCondition(std::initializer_list< Condition< Ts... > * > conditions)
const Component * component
Definition component.cpp:34
constexpr float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.h:40
constexpr float DATA
For components that import data from directly connected sensors like DHT.
Definition component.h:42
constexpr float PROCESSOR
For components that use data from sensors like displays.
Definition component.h:44
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
ESPPreferences * global_preferences
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:161
void init_array_from(std::array< T, N > &dest, std::initializer_list< T > src)
Initialize a std::array from an initializer_list.
Definition helpers.h:505
void HOT delay(uint32_t ms)
Definition core.cpp:28
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:26
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
bool sync()
Commit pending writes to flash.
Definition preferences.h:32
uint16_t x
Definition tt21100.cpp:5