ESPHome 2025.12.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 <vector>
13#include <forward_list>
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 auto f = std::bind(&DelayAction<Ts...>::play_next_, this, x...);
182 this->num_running_++;
183
184 // If num_running_ > 1, we have multiple instances running in parallel
185 // In single/restart/queued modes, only one instance runs at a time
186 // Parallel mode uses skip_cancel=true to allow multiple delays to coexist
187 // WARNING: This can accumulate delays if scripts are triggered faster than they complete!
188 // Users should set max_runs on parallel scripts to limit concurrent executions.
189 // Issue #10264: This is a workaround for parallel script delays interfering with each other.
190 App.scheduler.set_timer_common_(this, Scheduler::SchedulerItem::TIMEOUT,
191 /* is_static_string= */ true, "delay", this->delay_.value(x...), std::move(f),
192 /* is_retry= */ false, /* skip_cancel= */ this->num_running_ > 1);
193 }
194 float get_setup_priority() const override { return setup_priority::HARDWARE; }
195
196 void play(const Ts &...x) override { /* ignore - see play_complex */
197 }
198
199 void stop() override { this->cancel_timeout("delay"); }
200};
201
202template<typename... Ts> class LambdaAction : public Action<Ts...> {
203 public:
204 explicit LambdaAction(std::function<void(Ts...)> &&f) : f_(std::move(f)) {}
205
206 void play(const Ts &...x) override { this->f_(x...); }
207
208 protected:
209 std::function<void(Ts...)> f_;
210};
211
215template<typename... Ts> class StatelessLambdaAction : public Action<Ts...> {
216 public:
217 explicit StatelessLambdaAction(void (*f)(Ts...)) : f_(f) {}
218
219 void play(const Ts &...x) override { this->f_(x...); }
220
221 protected:
222 void (*f_)(Ts...);
223};
224
228template<typename... Ts> class ContinuationAction : public Action<Ts...> {
229 public:
230 explicit ContinuationAction(Action<Ts...> *parent) : parent_(parent) {}
231
232 void play(const Ts &...x) override { this->parent_->play_next_(x...); }
233
234 protected:
236};
237
238// Forward declaration for WhileLoopContinuation
239template<typename... Ts> class WhileAction;
240
243template<typename... Ts> class WhileLoopContinuation : public Action<Ts...> {
244 public:
245 explicit WhileLoopContinuation(WhileAction<Ts...> *parent) : parent_(parent) {}
246
247 void play(const Ts &...x) override;
248
249 protected:
251};
252
253template<typename... Ts> class IfAction : public Action<Ts...> {
254 public:
255 explicit IfAction(Condition<Ts...> *condition) : condition_(condition) {}
256
257 void add_then(const std::initializer_list<Action<Ts...> *> &actions) {
258 this->then_.add_actions(actions);
260 }
261
262 void add_else(const std::initializer_list<Action<Ts...> *> &actions) {
263 this->else_.add_actions(actions);
265 }
266
267 void play_complex(const Ts &...x) override {
268 this->num_running_++;
269 bool res = this->condition_->check(x...);
270 if (res) {
271 if (this->then_.empty()) {
272 this->play_next_(x...);
273 } else if (this->num_running_ > 0) {
274 this->then_.play(x...);
275 }
276 } else {
277 if (this->else_.empty()) {
278 this->play_next_(x...);
279 } else if (this->num_running_ > 0) {
280 this->else_.play(x...);
281 }
282 }
283 }
284
285 void play(const Ts &...x) override { /* ignore - see play_complex */
286 }
287
288 void stop() override {
289 this->then_.stop();
290 this->else_.stop();
291 }
292
293 protected:
297};
298
299template<typename... Ts> class WhileAction : public Action<Ts...> {
300 public:
301 WhileAction(Condition<Ts...> *condition) : condition_(condition) {}
302
303 void add_then(const std::initializer_list<Action<Ts...> *> &actions) {
304 this->then_.add_actions(actions);
306 }
307
308 friend class WhileLoopContinuation<Ts...>;
309
310 void play_complex(const Ts &...x) override {
311 this->num_running_++;
312 // Initial condition check
313 if (!this->condition_->check(x...)) {
314 // If new condition check failed, stop loop if running
315 this->then_.stop();
316 this->play_next_(x...);
317 return;
318 }
319
320 if (this->num_running_ > 0) {
321 this->then_.play(x...);
322 }
323 }
324
325 void play(const Ts &...x) override { /* ignore - see play_complex */
326 }
327
328 void stop() override { this->then_.stop(); }
329
330 protected:
333};
334
335// Implementation of WhileLoopContinuation::play
336template<typename... Ts> void WhileLoopContinuation<Ts...>::play(const Ts &...x) {
337 if (this->parent_->num_running_ > 0 && this->parent_->condition_->check(x...)) {
338 // play again
339 this->parent_->then_.play(x...);
340 } else {
341 // condition false, play next
342 this->parent_->play_next_(x...);
343 }
344}
345
346// Forward declaration for RepeatLoopContinuation
347template<typename... Ts> class RepeatAction;
348
351template<typename... Ts> class RepeatLoopContinuation : public Action<uint32_t, Ts...> {
352 public:
354
355 void play(const uint32_t &iteration, const Ts &...x) override;
356
357 protected:
359};
360
361template<typename... Ts> class RepeatAction : public Action<Ts...> {
362 public:
363 TEMPLATABLE_VALUE(uint32_t, count)
364
365 void add_then(const std::initializer_list<Action<uint32_t, Ts...> *> &actions) {
366 this->then_.add_actions(actions);
368 }
369
370 friend class RepeatLoopContinuation<Ts...>;
371
372 void play_complex(const Ts &...x) override {
373 this->num_running_++;
374 if (this->count_.value(x...) > 0) {
375 this->then_.play(0, x...);
376 } else {
377 this->play_next_(x...);
378 }
379 }
380
381 void play(const Ts &...x) override { /* ignore - see play_complex */
382 }
383
384 void stop() override { this->then_.stop(); }
385
386 protected:
387 ActionList<uint32_t, Ts...> then_;
388};
389
390// Implementation of RepeatLoopContinuation::play
391template<typename... Ts> void RepeatLoopContinuation<Ts...>::play(const uint32_t &iteration, const Ts &...x) {
392 uint32_t next_iteration = iteration + 1;
393 if (next_iteration >= this->parent_->count_.value(x...)) {
394 this->parent_->play_next_(x...);
395 } else {
396 this->parent_->then_.play(next_iteration, x...);
397 }
398}
399
407template<typename... Ts> class WaitUntilAction : public Action<Ts...>, public Component {
408 public:
409 WaitUntilAction(Condition<Ts...> *condition) : condition_(condition) {}
410
411 TEMPLATABLE_VALUE(uint32_t, timeout_value)
412
413 void setup() override {
414 // Start with loop disabled - only enable when there's work to do
415 // IMPORTANT: Only disable if num_running_ is 0, otherwise play_complex() was already
416 // called before our setup() (e.g., from on_boot trigger at same priority level)
417 // and we must not undo its enable_loop() call
418 if (this->num_running_ == 0) {
419 this->disable_loop();
420 }
421 }
422
423 void play_complex(const Ts &...x) override {
424 this->num_running_++;
425 // Check if we can continue immediately.
426 if (this->condition_->check(x...)) {
427 if (this->num_running_ > 0) {
428 this->play_next_(x...);
429 }
430 return;
431 }
432
433 // Store for later processing
434 auto now = millis();
435 auto timeout = this->timeout_value_.optional_value(x...);
436 this->var_queue_.emplace_front(now, timeout, std::make_tuple(x...));
437
438 // Do immediate check with fresh timestamp
439 if (this->process_queue_(now)) {
440 // Only enable loop if we still have pending items
441 this->enable_loop();
442 }
443 }
444
445 void loop() override {
446 // Safe to use cached time - only called from Application::loop()
448 // If queue is now empty, disable loop until next play_complex
449 this->disable_loop();
450 }
451 }
452
453 void stop() override {
454 this->var_queue_.clear();
455 this->disable_loop();
456 }
457
458 float get_setup_priority() const override { return setup_priority::DATA; }
459
460 void play(const Ts &...x) override { /* ignore - see play_complex */
461 }
462
463 protected:
464 // Helper: Process queue, triggering completed items and removing them
465 // Returns true if queue still has pending items
466 bool process_queue_(uint32_t now) {
467 // Process each queued wait_until and remove completed ones
468 this->var_queue_.remove_if([&](auto &queued) {
469 auto start = std::get<uint32_t>(queued);
470 auto timeout = std::get<optional<uint32_t>>(queued);
471 auto &var = std::get<std::tuple<Ts...>>(queued);
472
473 // Check if timeout has expired
474 auto expired = timeout && (now - start) >= *timeout;
475
476 // Keep waiting if not expired and condition not met
477 if (!expired && !this->condition_->check_tuple(var)) {
478 return false;
479 }
480
481 // Condition met or timed out - trigger next action
482 this->play_next_tuple_(var);
483 return true;
484 });
485
486 return !this->var_queue_.empty();
487 }
488
490 std::forward_list<std::tuple<uint32_t, optional<uint32_t>, std::tuple<Ts...>>> var_queue_{};
491};
492
493template<typename... Ts> class UpdateComponentAction : public Action<Ts...> {
494 public:
496
497 void play(const Ts &...x) override {
498 if (!this->component_->is_ready())
499 return;
500 this->component_->update();
501 }
502
503 protected:
505};
506
507template<typename... Ts> class SuspendComponentAction : public Action<Ts...> {
508 public:
510
511 void play(const Ts &...x) override {
512 if (!this->component_->is_ready())
513 return;
514 this->component_->stop_poller();
515 }
516
517 protected:
519};
520
521template<typename... Ts> class ResumeComponentAction : public Action<Ts...> {
522 public:
524 TEMPLATABLE_VALUE(uint32_t, update_interval)
525
526 void play(const Ts &...x) override {
527 if (!this->component_->is_ready()) {
528 return;
529 }
530 optional<uint32_t> update_interval = this->update_interval_.optional_value(x...);
531 if (update_interval.has_value()) {
532 this->component_->set_update_interval(update_interval.value());
533 }
534 this->component_->start_poller();
535 }
536
537 protected:
539};
540
541} // namespace esphome
void play_next_tuple_(const std::tuple< Ts... > &tuple, seq< S... >)
Definition automation.h:234
void play_next_(const Ts &...x)
Definition automation.h:226
virtual void play(const Ts &...x)=0
virtual void play_complex(const Ts &...x)
Definition automation.h:197
void add_action(Action< Ts... > *action)
Definition automation.h:263
void play(const Ts &...x)
Definition automation.h:276
bool empty() const
Definition automation.h:285
void add_actions(const std::initializer_list< Action< Ts... > * > &actions)
Definition automation.h:271
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.
Definition component.cpp:94
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:148
bool check_tuple(const std::tuple< Ts... > &tuple)
Call check with a tuple of values as parameter.
Definition automation.h:154
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:437
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:169
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
std::forward_list< std::tuple< uint32_t, optional< uint32_t >, std::tuple< Ts... > > > var_queue_
void play(const Ts &...x) override
bool process_queue_(uint32_t now)
Condition< Ts... > * condition_
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:59
const float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.cpp:58
const float PROCESSOR
For components that use data from sensors like displays.
Definition component.cpp:60
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