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