ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
automation.h
Go to the documentation of this file.
1#pragma once
2
9#include <concepts>
10#include <functional>
11#include <span>
12#include <type_traits>
13#include <utility>
14#include <vector>
15
16namespace esphome {
17
21template<typename T, typename... X> class TemplatableFn {
22 public:
23 constexpr TemplatableFn() = default;
24 TemplatableFn(std::nullptr_t) = delete;
25
26 // Exact return type match — direct function pointer storage
27 // constexpr so codegen can place arrays of these in flash.
28 template<typename F>
29 constexpr TemplatableFn(F f)
30 requires std::convertible_to<F, T (*)(X...)>
31 : f_(f) {}
32
33 // Convertible return type (e.g., int -> uint8_t) — casting trampoline.
34 // Stateless lambdas are default-constructible in C++20, so F{} recreates the lambda inside
35 // the trampoline without capturing. This compiles to the same code as a direct call + cast.
36 // Deprecated: codegen should use the correct output type to avoid the trampoline.
37 template<typename F>
38 [[deprecated("Lambda return type does not match TemplatableFn<T> — use the correct type in "
39 "codegen")]] TemplatableFn(F)
40 requires(!std::convertible_to<F, T (*)(X...)>) && std::invocable<F, X...> &&
41 std::convertible_to<std::invoke_result_t<F, X...>, T> && std::is_empty_v<F> && std::default_initializable<F>
42 : f_([](X... x) -> T { return static_cast<T>(F{}(x...)); }) {}
43
44 // Reject any callable that didn't match the above (stateful lambdas or inconvertible return types)
45 template<typename F>
47 requires std::invocable<F, X...> && (!std::convertible_to<F, T (*)(X...)>) &&
48 (!std::is_empty_v<F> || !std::convertible_to<std::invoke_result_t<F, X...>, T> ||
49 !std::default_initializable<F>)
50 = delete;
51
52 // Reject raw (non-callable) values with a helpful diagnostic pointing at the Python-side fix.
53 // TemplatableFn stores only a function pointer (4 bytes), so constants must be wrapped in a
54 // stateless lambda by codegen. External components hitting this error should use
55 // `cg.templatable(value, args, type)` in their Python __init__.py before passing to the setter.
56 template<typename V>
58 requires(!std::invocable<V, X...>) && (!std::convertible_to<V, T (*)(X...)>)
59 {
60 static_assert(sizeof(V) == 0, "Missing cg.templatable(...) in Python codegen for this TEMPLATABLE_VALUE "
61 "field. The wrapper was always required; it worked by accident because the old "
62 "TemplatableValue implicitly converted raw constants. TemplatableFn cannot. See "
63 "https://developers.esphome.io/blog/2026/04/09/"
64 "templatablefn-4-byte-templatable-storage-for-trivially-copyable-types/");
65 }
66
67 bool has_value() const { return this->f_ != nullptr; }
68
69 T value(X... x) const { return this->f_ ? this->f_(x...) : T{}; }
70
71 optional<T> optional_value(X... x) const {
72 if (!this->f_)
73 return {};
74 return this->f_(x...);
75 }
76
77 T value_or(X... x, T default_value) const { return this->f_ ? this->f_(x...) : default_value; }
78
79 protected:
80 T (*f_)(X...){nullptr};
81};
82
85template<typename... Ts> class TemplatableBytes {
86 public:
87 void set_template(std::vector<uint8_t> (*func)(Ts...)) {
88 this->code_.func = func;
89 this->len_ = -1;
90 }
91 void set_static(const uint8_t *data, uint16_t len) {
92 this->code_.data = data;
93 this->len_ = len;
94 }
95 bool is_static() const { return this->len_ >= 0; }
97 const uint8_t *data() const { return this->code_.data; }
99 size_t size() const { return static_cast<size_t>(this->len_); }
100 std::vector<uint8_t> value(const Ts &...x) const {
101 if (this->len_ < 0)
102 return this->code_.func(x...);
103 return to_vector(this->code_.data, this->size());
104 }
107 template<size_t N = 64, typename F> void visit(F &&fn, const Ts &...x) const {
108 if (this->len_ < 0) {
109 const std::vector<uint8_t> bytes = this->code_.func(x...);
110 fn(bytes.data(), bytes.size());
111 return;
112 }
113#ifdef USE_ESP8266
114 SmallBufferWithHeapFallback<N> buf(this->size());
115 if (this->len_ != 0)
116 progmem_memcpy(buf.get(), this->code_.data, this->size());
117 fn(buf.get(), this->size());
118#else
119 fn(this->code_.data, this->size());
120#endif
121 }
122
123 protected:
124 static std::vector<uint8_t> to_vector(const uint8_t *data, size_t len) {
125 std::vector<uint8_t> out(len);
126 // An empty payload is (nullptr, 0), and memcpy from nullptr is undefined even for zero bytes.
127 if (len != 0)
128 progmem_memcpy(out.data(), data, len); // byte loads from flash fault on ESP8266
129 return out;
130 }
131
132 union {
133 std::vector<uint8_t> (*func)(Ts...);
134 const uint8_t *data;
135 } code_{};
136 int32_t len_{-1}; // -1: lambda, otherwise the length of the static table
137};
138
139#define TEMPLATABLE_BYTES(name) \
140 protected: \
141 TemplatableBytes<Ts...> name##_{}; \
142\
143 public: \
144 void set_##name##_template(std::vector<uint8_t> (*func)(Ts...)) { this->name##_.set_template(func); } \
145 void set_##name##_static(const uint8_t *data, uint16_t len) { this->name##_.set_static(data, len); }
146
147// Forward declaration for TemplatableValue (string specialization needs it)
148template<typename T, typename... X> class TemplatableValue;
149
153template<typename T, typename... X>
155 std::conditional_t<std::is_trivially_copyable_v<T>, TemplatableFn<T, X...>, TemplatableValue<T, X...>>;
156
157#define TEMPLATABLE_VALUE_(type, name) \
158 protected: \
159 TemplatableStorage<type, Ts...> name##_{}; \
160\
161 public: \
162 template<typename V> void set_##name(V name) { this->name##_ = name; }
163
164#define TEMPLATABLE_VALUE(type, name) TEMPLATABLE_VALUE_(type, name)
165
169template<typename T, typename... X> class TemplatableValue {
170 public:
171 TemplatableValue() = default;
172 TemplatableValue(std::nullptr_t) = delete;
173
174 // Accept raw constants
175 template<typename V>
177 requires(!std::invocable<V, X...>)
178 : tag_(VALUE) {
179 new (&this->storage_.value_) T(static_cast<T>(std::move(value)));
180 }
181
182 // Accept stateless lambdas (convertible to function pointer)
183 template<typename F>
185 requires std::convertible_to<F, T (*)(X...)>
186 : tag_(FN) {
187 this->storage_.f_ = f;
188 }
189
190 // Convertible return type (e.g., int -> uint8_t) — casting trampoline
191 template<typename F>
192 [[deprecated("Lambda return type does not match TemplatableValue<T> — use the correct type in "
193 "codegen")]] TemplatableValue(F)
194 requires(!std::convertible_to<F, T (*)(X...)>) && std::invocable<F, X...> &&
195 std::convertible_to<std::invoke_result_t<F, X...>, T> && std::is_empty_v<F> && std::default_initializable<F>
196 : tag_(FN) {
197 this->storage_.f_ = [](X... x) -> T { return static_cast<T>(F{}(x...)); };
198 }
199
200 // Reject any callable that didn't match the above
201 template<typename F>
203 requires std::invocable<F, X...> && (!std::convertible_to<F, T (*)(X...)>) &&
204 (!std::is_empty_v<F> || !std::convertible_to<std::invoke_result_t<F, X...>, T> ||
205 !std::default_initializable<F>)
206 = delete;
207
208 TemplatableValue(const TemplatableValue &other) : tag_(other.tag_) {
209 if (this->tag_ == VALUE) {
210 new (&this->storage_.value_) T(other.storage_.value_);
211 } else if (this->tag_ == FN) {
212 this->storage_.f_ = other.storage_.f_;
213 }
214 }
215
216 TemplatableValue(TemplatableValue &&other) noexcept : tag_(other.tag_) {
217 if (this->tag_ == VALUE) {
218 new (&this->storage_.value_) T(std::move(other.storage_.value_));
219 other.destroy_();
220 } else if (this->tag_ == FN) {
221 this->storage_.f_ = other.storage_.f_;
222 }
223 other.tag_ = NONE;
224 }
225
227 if (this != &other) {
228 this->destroy_();
229 this->tag_ = other.tag_;
230 if (this->tag_ == VALUE) {
231 new (&this->storage_.value_) T(other.storage_.value_);
232 } else if (this->tag_ == FN) {
233 this->storage_.f_ = other.storage_.f_;
234 }
235 }
236 return *this;
237 }
238
240 if (this != &other) {
241 this->destroy_();
242 this->tag_ = other.tag_;
243 if (this->tag_ == VALUE) {
244 new (&this->storage_.value_) T(std::move(other.storage_.value_));
245 other.destroy_();
246 } else if (this->tag_ == FN) {
247 this->storage_.f_ = other.storage_.f_;
248 }
249 other.tag_ = NONE;
250 }
251 return *this;
252 }
253
254 ~TemplatableValue() { this->destroy_(); }
255
256 bool has_value() const { return this->tag_ != NONE; }
257
258 T value(X... x) const {
259 if (this->tag_ == FN)
260 return this->storage_.f_(x...);
261 if (this->tag_ == VALUE)
262 return this->storage_.value_;
263 return T{};
264 }
265
266 optional<T> optional_value(X... x) const {
267 if (this->tag_ == NONE)
268 return {};
269 return this->value(x...);
270 }
271
272 T value_or(X... x, T default_value) const {
273 if (this->tag_ == NONE)
274 return default_value;
275 return this->value(x...);
276 }
277
278 protected:
279 void destroy_() {
280 if constexpr (!std::is_trivially_destructible_v<T>) {
281 if (this->tag_ == VALUE)
282 this->storage_.value_.~T();
283 }
284 }
285
286 enum Tag : uint8_t { NONE, VALUE, FN } tag_{NONE};
287 // Union with explicit ctor/dtor to support non-trivially-constructible/destructible T
288 // (e.g., std::vector<uint8_t>). Lifetime of value_ is managed externally via
289 // placement new and destroy_().
290 union Storage {
291 constexpr Storage() : f_(nullptr) {}
292 constexpr ~Storage() {}
294 T (*f_)(X...);
295 } storage_;
296};
297
300template<typename... X> class TemplatableValue<std::string, X...> {
301 public:
302 TemplatableValue() : type_(NONE) {}
303
304 // For const char*: store pointer directly, no heap allocation.
305 // String remains in flash and is only converted to std::string when value() is called.
306 TemplatableValue(const char *str) : type_(STATIC_STRING) { this->static_str_ = str; }
307
308#ifdef USE_ESP8266
309 // On ESP8266, __FlashStringHelper* is a distinct type from const char*.
310 // ESPHOME_F(s) expands to F(s) which returns __FlashStringHelper* pointing to PROGMEM.
311 // Store as FLASH_STRING — value()/is_empty()/ref_or_copy_to() use _P functions.
312 TemplatableValue(const __FlashStringHelper *str) : type_(FLASH_STRING) {
313 this->static_str_ = reinterpret_cast<const char *>(str);
314 }
315#endif
316
317 template<typename F>
319 requires(!std::invocable<F, X...>)
320 : type_(VALUE) {
321 this->value_ = new std::string(std::move(value));
322 }
323
324 // For stateless lambdas (convertible to function pointer): use function pointer
325 template<typename F>
327 requires std::invocable<F, X...> && std::convertible_to<F, std::string (*)(X...)>
328 : type_(STATELESS_LAMBDA) {
329 this->stateless_f_ = f; // Implicit conversion to function pointer
330 }
331
332 // For stateful lambdas (not convertible to function pointer): use std::function
333 template<typename F>
335 requires std::invocable<F, X...> && (!std::convertible_to<F, std::string (*)(X...)>)
336 : type_(LAMBDA) {
337 this->f_ = new std::function<std::string(X...)>(std::move(f));
338 }
339
340 // Copy constructor
341 TemplatableValue(const TemplatableValue &other) : type_(other.type_) {
342 if (this->type_ == VALUE) {
343 this->value_ = new std::string(*other.value_);
344 } else if (this->type_ == LAMBDA) {
345 this->f_ = new std::function<std::string(X...)>(*other.f_);
346 } else if (this->type_ == STATELESS_LAMBDA) {
347 this->stateless_f_ = other.stateless_f_;
348 } else if (this->type_ == STATIC_STRING || this->type_ == FLASH_STRING) {
349 this->static_str_ = other.static_str_;
350 }
351 }
352
353 // Move constructor
354 TemplatableValue(TemplatableValue &&other) noexcept : type_(other.type_) {
355 if (this->type_ == VALUE) {
356 this->value_ = other.value_;
357 other.value_ = nullptr;
358 } else if (this->type_ == LAMBDA) {
359 this->f_ = other.f_;
360 other.f_ = nullptr;
361 } else if (this->type_ == STATELESS_LAMBDA) {
362 this->stateless_f_ = other.stateless_f_;
363 } else if (this->type_ == STATIC_STRING || this->type_ == FLASH_STRING) {
364 this->static_str_ = other.static_str_;
365 }
366 other.type_ = NONE;
367 }
368
369 // Assignment operators
371 if (this != &other) {
372 this->~TemplatableValue();
373 new (this) TemplatableValue(other);
374 }
375 return *this;
376 }
377
379 if (this != &other) {
380 this->~TemplatableValue();
381 new (this) TemplatableValue(std::move(other));
382 }
383 return *this;
384 }
385
387 if (this->type_ == VALUE) {
388 delete this->value_;
389 } else if (this->type_ == LAMBDA) {
390 delete this->f_;
391 }
392 // STATELESS_LAMBDA/STATIC_STRING/FLASH_STRING/NONE: no cleanup needed (pointers, not heap-allocated)
393 }
394
395 bool has_value() const { return this->type_ != NONE; }
397 bool is_lambda() const { return this->type_ == LAMBDA || this->type_ == STATELESS_LAMBDA; }
398
399 std::string value(X... x) const {
400 switch (this->type_) {
401 case STATELESS_LAMBDA:
402 return this->stateless_f_(x...); // Direct function pointer call
403 case LAMBDA:
404 return (*this->f_)(x...); // std::function call
405 case VALUE:
406 return *this->value_;
407 case STATIC_STRING:
408 return std::string(this->static_str_);
409#ifdef USE_ESP8266
410 case FLASH_STRING:
411 return progmem_string(reinterpret_cast<ProgmemStr>(this->static_str_));
412#endif
413 case NONE:
414 default:
415 return {};
416 }
417 }
418
419 optional<std::string> optional_value(X... x) const {
420 if (!this->has_value())
421 return {};
422 return this->value(x...);
423 }
424
425 std::string value_or(X... x, std::string default_value) const {
426 if (!this->has_value())
427 return default_value;
428 return this->value(x...);
429 }
430
434 // Remove before 2027.4.0
435 ESPDEPRECATED("Read the value with ref_or_copy_to() instead. Removed in 2027.4.0", "2026.10.0")
436 bool is_static_string() const { return this->type_ == STATIC_STRING; }
437
440 // Remove before 2027.4.0
441 ESPDEPRECATED("Use ref_or_copy_to() instead. Removed in 2027.4.0", "2026.10.0")
442 const char *get_static_string() const { return this->static_str_; }
443
447 bool is_empty() const {
448 switch (this->type_) {
449 case NONE:
450 return true;
451 case STATIC_STRING:
452 return this->static_str_ == nullptr || this->static_str_[0] == '\0';
453#ifdef USE_ESP8266
454 case FLASH_STRING:
455 // PROGMEM pointer — must use progmem_read_byte on ESP8266
456 return this->static_str_ == nullptr ||
457 progmem_read_byte(reinterpret_cast<const uint8_t *>(this->static_str_)) == '\0';
458#endif
459 case VALUE:
460 return this->value_->empty();
461 default: // LAMBDA/STATELESS_LAMBDA - must call value()
462 return this->value().empty();
463 }
464 }
465
473 StringRef ref_or_copy_to(char *lambda_buf, size_t lambda_buf_size) const {
474 switch (this->type_) {
475 case NONE:
476 return StringRef();
477 case STATIC_STRING:
478 if (this->static_str_ == nullptr)
479 return StringRef();
480 return StringRef(this->static_str_, strlen(this->static_str_));
481#ifdef USE_ESP8266
482 case FLASH_STRING:
483 if (this->static_str_ == nullptr)
484 return StringRef();
485 {
486 // PROGMEM pointer — copy to buffer via _P functions
487 size_t len = strlen_P(this->static_str_);
488 size_t copy_len = std::min(len, lambda_buf_size - 1);
489 memcpy_P(lambda_buf, this->static_str_, copy_len);
490 lambda_buf[copy_len] = '\0';
491 return StringRef(lambda_buf, copy_len);
492 }
493#endif
494 case VALUE:
495 return StringRef(this->value_->data(), this->value_->size());
496 default: { // LAMBDA/STATELESS_LAMBDA - must call value() and copy
497 std::string result = this->value();
498 size_t copy_len = std::min(result.size(), lambda_buf_size - 1);
499 memcpy(lambda_buf, result.data(), copy_len);
500 lambda_buf[copy_len] = '\0';
501 return StringRef(lambda_buf, copy_len);
502 }
503 }
504 }
505
506 protected:
507 enum : uint8_t {
512 STATIC_STRING, // For const char* — avoids heap allocation
513 FLASH_STRING, // PROGMEM pointer on ESP8266; never set on other platforms
514 } type_;
515 union {
516 std::string *value_; // Heap-allocated string (VALUE)
517 std::function<std::string(X...)> *f_; // Heap-allocated std::function (LAMBDA)
518 std::string (*stateless_f_)(X...); // Function pointer (STATELESS_LAMBDA)
519 const char *static_str_; // For STATIC_STRING and FLASH_STRING types
520 };
521};
522
526template<typename T>
528 std::conditional_t<std::is_copy_constructible_v<std::remove_cvref_t<T>>, std::remove_cvref_t<T>, T>;
529
534template<typename... Ts> class Condition {
535 public:
537 virtual bool check(const Ts &...x) = 0;
538
540 bool check_tuple(const std::tuple<Ts...> &tuple) {
541 return this->check_tuple_(tuple, std::make_index_sequence<sizeof...(Ts)>{});
542 }
543
544 protected:
545 template<size_t... S> bool check_tuple_(const std::tuple<Ts...> &tuple, std::index_sequence<S...> /*unused*/) {
546 return this->check(std::get<S>(tuple)...);
547 }
548};
549
550template<typename... Ts> class Automation;
551
552template<typename... Ts> class Trigger {
553 public:
555 // Force-inline: collapses the Trigger→Automation→ActionList forwarding
556 // chain into a single frame, reducing automation call stack depth.
557 inline void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE {
558 if (this->automation_parent_ == nullptr)
559 return;
560 this->automation_parent_->trigger(x...);
561 }
562 void set_automation_parent(Automation<Ts...> *automation_parent) { this->automation_parent_ = automation_parent; }
563
565 void stop_action() {
566 if (this->automation_parent_ == nullptr)
567 return;
568 this->automation_parent_->stop();
569 }
572 if (this->automation_parent_ == nullptr)
573 return false;
574 return this->automation_parent_->is_running();
575 }
576
577 protected:
578 Automation<Ts...> *automation_parent_{nullptr};
579};
580
581template<typename... Ts> class ActionList;
582
583template<typename... Ts> class Action {
584 public:
585 virtual void play_complex(const Ts &...x) {
586 this->num_running_++;
587 this->play(x...);
588 this->play_next_(x...);
589 }
591 if (num_running_) {
592 this->stop();
593 this->num_running_ = 0;
594 }
595 this->stop_next_();
596 }
598 bool is_running() { return this->num_running_ > 0 || this->is_running_next_(); }
599
603 int total = this->num_running_;
604 if (Action *next = this->chain_next_())
605 total += next->num_running_total();
606 return total;
607 }
608
609 protected:
610 friend ActionList<Ts...>;
611
613 virtual void play(const Ts &...x) = 0;
614 void play_next_(const Ts &...x) {
615 if (this->num_running_ > 0) {
616 this->num_running_--;
617 if (this->next_is_owner_()) {
618 this->owner_()->play(x...);
619 } else if (this->next_ != nullptr) {
620 this->next_->play_complex(x...);
621 }
622 }
623 }
624 template<size_t... S> void play_next_tuple_(const std::tuple<Ts...> &tuple, std::index_sequence<S...> /*unused*/) {
625 this->play_next_(std::get<S>(tuple)...);
626 }
627 void play_next_tuple_(const std::tuple<Ts...> &tuple) {
628 this->play_next_tuple_(tuple, std::make_index_sequence<sizeof...(Ts)>{});
629 }
630
631 virtual void stop() {}
632 void stop_next_() {
633 if (Action *next = this->chain_next_())
634 next->stop_complex();
635 }
636
638 Action *next = this->chain_next_();
639 return next != nullptr && next->is_running();
640 }
641
642 // A branch's last action points at its owner with the low bit set. Only Action objects are
643 // tagged, never function pointers, which use that bit on ARM Thumb (#9283).
644 static constexpr uintptr_t OWNER_TAG = 1;
645 bool next_is_owner_() const { return reinterpret_cast<uintptr_t>(this->next_) & OWNER_TAG; }
647 Action *owner_() const { return reinterpret_cast<Action *>(reinterpret_cast<char *>(this->next_) - OWNER_TAG); }
648 Action *chain_next_() const { return this->next_is_owner_() ? nullptr : this->next_; }
649 static Action *tag_owner(Action *owner) {
650 return reinterpret_cast<Action *>(reinterpret_cast<char *>(owner) + OWNER_TAG);
651 }
652
653 Action<Ts...> *next_{nullptr};
654
657 int num_running_{0};
658};
659
660// The vtable pointer gives every instantiation this alignment.
661static_assert(alignof(Action<>) >= 2, "the owner tag needs a free low bit in Action object pointers");
662
663template<typename... Ts> class ActionList {
664 public:
665 void add_action(Action<Ts...> *action) {
666 // Walk to end of chain - action lists are short and only built during setup()
667 *this->tail_() = action;
668 }
669 void add_actions(const std::initializer_list<Action<Ts...> *> &actions) {
670 // Find tail once, then append all actions in a single pass
671 Action<Ts...> **tail = this->tail_();
672 for (auto *action : actions) {
673 *tail = action;
674 tail = &action->next_;
675 }
676 }
679 // Nothing to tag in an empty list
680 if (this->actions_ == nullptr)
681 return;
682 *this->tail_() = Action<Ts...>::tag_owner(owner);
683 }
684 // Force-inline: part of the Trigger→Automation→ActionList forwarding
685 // chain collapsed to reduce automation call stack depth.
686 inline void play(const Ts &...x) ESPHOME_ALWAYS_INLINE {
687 if (this->actions_ != nullptr)
688 this->actions_->play_complex(x...);
689 }
690 void play_tuple(const std::tuple<Ts...> &tuple) {
691 this->play_tuple_(tuple, std::make_index_sequence<sizeof...(Ts)>{});
692 }
693 void stop() {
694 if (this->actions_ != nullptr)
695 this->actions_->stop_complex();
696 }
697 bool empty() const { return this->actions_ == nullptr; }
698
700 bool is_running() {
701 if (this->actions_ == nullptr)
702 return false;
703 return this->actions_->is_running();
704 }
707 if (this->actions_ == nullptr)
708 return 0;
709 return this->actions_->num_running_total();
710 }
711
712 protected:
713 template<size_t... S> void play_tuple_(const std::tuple<Ts...> &tuple, std::index_sequence<S...> /*unused*/) {
714 this->play(std::get<S>(tuple)...);
715 }
716 // Lists with an owner are complete; never append after set_owner()
717 Action<Ts...> **tail_() {
718 Action<Ts...> **tail = &this->actions_;
719 while (*tail != nullptr) {
720 // Not checked in release builds: only automation.py builds these lists, appending each action and
721 // then finishing the branch once, so appending after set_owner() would be a codegen bug.
722 ESPHOME_DEBUG_ASSERT(!(*tail)->next_is_owner_());
723 tail = &(*tail)->next_;
724 }
725 return tail;
726 }
727
728 Action<Ts...> *actions_{nullptr};
729};
730
731template<typename... Ts> class Automation {
732 public:
734 // User provided, not "= default": `new(p) Automation()` would zero-fill .bss that is already zero.
735 // constexpr and noexcept keep the rest of the implicit constructor's contract.
736 constexpr Automation() noexcept {}
737 explicit Automation(Trigger<Ts...> *trigger) { trigger->set_automation_parent(this); }
738
739 void add_action(Action<Ts...> *action) { this->actions_.add_action(action); }
740 void add_actions(const std::initializer_list<Action<Ts...> *> &actions) { this->actions_.add_actions(actions); }
741
742 void stop() { this->actions_.stop(); }
743
744 // Force-inline: part of the Trigger→Automation→ActionList forwarding
745 // chain collapsed to reduce automation call stack depth.
746 inline void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE { this->actions_.play(x...); }
747
748 bool is_running() { return this->actions_.is_running(); }
749
751 int num_running() { return this->actions_.num_running(); }
752
753 protected:
755};
756
758template<typename... Ts>
759void trigger_automations(std::span<Automation<Ts...> *const> automations, const std::type_identity_t<Ts> &...x) {
760 for (auto *automation : automations)
761 automation->trigger(x...);
762}
763
765template<size_t N, typename... Ts> class AutomationList {
766 public:
767 void add(Automation<Ts...> *automation) { this->automations_.push_back(automation); }
768 bool empty() const { return this->automations_.empty(); }
770 template<typename... Args> void trigger(Args &&...x) {
771 if (this->automations_.empty())
772 return;
773 trigger_automations<Ts...>(std::span<Automation<Ts...> *const>(this->automations_), x...);
774 }
775
776 protected:
778};
779
783template<typename... Ts> struct TriggerForwarder {
785 void operator()(const Ts &...args) const { this->automation->trigger(args...); }
786};
787
792 void operator()(bool state) const {
793 if (state)
794 this->automation->trigger();
795 }
796};
797
802 void operator()(bool state) const {
803 if (!state)
804 this->automation->trigger();
805 }
806};
807
808// Ensure forwarders fit in Callback::ctx_ (pointer-sized inline storage).
809// If these fail, the forwarder would heap-allocate in Callback::create().
810static_assert(sizeof(TriggerForwarder<>) <= sizeof(void *));
811static_assert(sizeof(TriggerOnTrueForwarder) <= sizeof(void *));
812static_assert(sizeof(TriggerOnFalseForwarder) <= sizeof(void *));
813static_assert(std::is_trivially_copyable_v<TriggerForwarder<>>);
814static_assert(std::is_trivially_copyable_v<TriggerOnTrueForwarder>);
815static_assert(std::is_trivially_copyable_v<TriggerOnFalseForwarder>);
816
817} // namespace esphome
bool is_running()
Check if this or any of the following actions are currently running.
Definition automation.h:598
Action * chain_next_() const
Definition automation.h:648
void stop_complex()
Definition automation.h:590
Action * owner_() const
Only valid when next_is_owner_().
Definition automation.h:647
static Action * tag_owner(Action *owner)
Definition automation.h:649
void play_next_(const Ts &...x)
Definition automation.h:614
virtual void play(const Ts &...x)=0
For a branch owner (if, while), play() runs when the branch finishes.
void play_next_tuple_(const std::tuple< Ts... > &tuple)
Definition automation.h:627
virtual void stop()
Definition automation.h:631
bool is_running_next_()
Definition automation.h:637
int num_running_total()
The total number of actions that are currently running in this plus any of the following actions in t...
Definition automation.h:602
void play_next_tuple_(const std::tuple< Ts... > &tuple, std::index_sequence< S... >)
Definition automation.h:624
bool next_is_owner_() const
Definition automation.h:645
virtual void play_complex(const Ts &...x)
Definition automation.h:585
void add_action(Action< Ts... > *action)
Definition automation.h:665
void play_tuple(const std::tuple< Ts... > &tuple)
Definition automation.h:690
bool is_running()
Check if any action in this action list is currently running.
Definition automation.h:700
bool empty() const
Definition automation.h:697
void add_actions(const std::initializer_list< Action< Ts... > * > &actions)
Definition automation.h:669
Action< Ts... > ** tail_()
Definition automation.h:717
void play_tuple_(const std::tuple< Ts... > &tuple, std::index_sequence< S... >)
Definition automation.h:713
void play(const Ts &...x) ESPHOME_ALWAYS_INLINE
Definition automation.h:686
void set_owner(Action< Ts... > *owner)
Resume owner via play() when the list finishes; call once, after adding actions.
Definition automation.h:678
int num_running()
Return the number of actions in this action list that are currently running.
Definition automation.h:706
void add_action(Action< Ts... > *action)
Definition automation.h:739
int num_running()
Return the number of actions in the action part of this automation that are currently running.
Definition automation.h:751
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Definition automation.h:746
Automation(Trigger< Ts... > *trigger)
Definition automation.h:737
void add_actions(const std::initializer_list< Action< Ts... > * > &actions)
Definition automation.h:740
ActionList< Ts... > actions_
Definition automation.h:754
constexpr Automation() noexcept
Default constructor for use with TriggerForwarder (no Trigger object needed).
Definition automation.h:736
Automations a component triggers itself, sized at codegen time (count from cg.slot_counter).
Definition automation.h:765
void trigger(Args &&...x)
Arguments convert to Ts only when the list is not empty (e.g. const char * to std::string).
Definition automation.h:770
void add(Automation< Ts... > *automation)
Definition automation.h:767
StaticVector< Automation< Ts... > *, N > automations_
Definition automation.h:777
Base class for all automation conditions.
Definition automation.h:534
bool check_tuple_(const std::tuple< Ts... > &tuple, std::index_sequence< S... >)
Definition automation.h:545
bool check_tuple(const std::tuple< Ts... > &tuple)
Call check with a tuple of values as parameter.
Definition automation.h:540
virtual bool check(const Ts &...x)=0
Check whether this condition passes. This condition check must be instant, and not cause any delays.
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
Definition helpers.h:872
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:304
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
Byte payload that is either a stateless lambda or a static table, which may be in PROGMEM.
Definition automation.h:85
static std::vector< uint8_t > to_vector(const uint8_t *data, size_t len)
Definition automation.h:124
void visit(F &&fn, const Ts &...x) const
Calls fn(const uint8_t *data, size_t len) with the payload readable from RAM: a lambda's vector,...
Definition automation.h:107
size_t size() const
Only valid when is_static().
Definition automation.h:99
void set_static(const uint8_t *data, uint16_t len)
Definition automation.h:91
void set_template(std::vector< uint8_t >(*func)(Ts...))
Definition automation.h:87
std::vector< uint8_t > value(const Ts &...x) const
Definition automation.h:100
const uint8_t * data() const
Only valid when is_static(); may point to PROGMEM, so read it with progmem_memcpy or progmem_read_byt...
Definition automation.h:97
Function-pointer-only templatable storage (4 bytes on 32-bit).
Definition automation.h:21
constexpr TemplatableFn()=default
T value_or(X... x, T default_value) const
Definition automation.h:77
bool has_value() const
Definition automation.h:67
constexpr TemplatableFn(F f)
Definition automation.h:29
TemplatableFn(std::nullptr_t)=delete
optional< T > optional_value(X... x) const
Definition automation.h:71
T value(X... x) const
Definition automation.h:69
TemplatableValue(const __FlashStringHelper *str)
Definition automation.h:312
ESPDEPRECATED("Read the value with ref_or_copy_to() instead. Removed in 2027.4.0", "2026.10.0") bool is_static_string() const
Check if this holds a static string (const char* stored without allocation) The pointer is always dir...
Definition automation.h:435
TemplatableValue(TemplatableValue &&other) noexcept
Definition automation.h:354
TemplatableValue & operator=(const TemplatableValue &other)
Definition automation.h:370
bool is_lambda() const
Whether the value comes from a lambda, so it may differ between reads.
Definition automation.h:397
bool is_empty() const
Check if the string value is empty without allocating.
Definition automation.h:447
TemplatableValue(const TemplatableValue &other)
Definition automation.h:341
TemplatableValue & operator=(TemplatableValue &&other) noexcept
Definition automation.h:378
StringRef ref_or_copy_to(char *lambda_buf, size_t lambda_buf_size) const
Get a StringRef to the string value without heap allocation when possible.
Definition automation.h:473
std::string value_or(X... x, std::string default_value) const
Definition automation.h:425
ESPDEPRECATED("Use ref_or_copy_to() instead. Removed in 2027.4.0", "2026.10.0") const char *get_static_string() const
Get the static string pointer (only valid if is_static_string() returns true) The pointer is always d...
Definition automation.h:441
optional< std::string > optional_value(X... x) const
Definition automation.h:419
std::function< std::string(X...)> * f_
Definition automation.h:517
Primary TemplatableValue: stores either a constant value or a function pointer.
Definition automation.h:169
TemplatableValue(const TemplatableValue &other)
Definition automation.h:208
TemplatableValue & operator=(TemplatableValue &&other) noexcept
Definition automation.h:239
union esphome::TemplatableValue::Storage storage_
TemplatableValue(TemplatableValue &&other) noexcept
Definition automation.h:216
T value(X... x) const
Definition automation.h:258
optional< T > optional_value(X... x) const
Definition automation.h:266
TemplatableValue & operator=(const TemplatableValue &other)
Definition automation.h:226
T value_or(X... x, T default_value) const
Definition automation.h:272
TemplatableValue(std::nullptr_t)=delete
void stop_action()
Stop any action connected to this trigger.
Definition automation.h:565
bool is_action_running()
Returns true if any action connected to this trigger is running.
Definition automation.h:571
void set_automation_parent(Automation< Ts... > *automation_parent)
Definition automation.h:562
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:557
NameCopy * next
bool state
Definition fan.h:2
std::vector< uint8_t > & out
Definition gif.cpp:49
std::string progmem_string(ProgmemStr str)
Copies a string stored with ESPHOME_F into a std::string.
Definition helpers.cpp:24
std::conditional_t< std::is_copy_constructible_v< std::remove_cvref_t< T > >, std::remove_cvref_t< T >, T > stored_trigger_arg_t
How deferring actions store a trigger argument: a copy, since a referenced object may be gone once th...
Definition automation.h:527
void progmem_memcpy(void *dst, const void *src, size_t len)
Definition hal.h:56
std::conditional_t< std::is_trivially_copyable_v< T >, TemplatableFn< T, X... >, TemplatableValue< T, X... > > TemplatableStorage
Selects TemplatableFn (4 bytes) for trivially copyable types, TemplatableValue (8 bytes) otherwise.
Definition automation.h:154
void trigger_automations(std::span< Automation< Ts... > *const > automations, const std::type_identity_t< Ts > &...x)
Triggers each automation in order; shared by every AutomationList size with the same arguments.
Definition automation.h:759
uint8_t progmem_read_byte(const uint8_t *addr)
Definition hal.h:51
STL namespace.
const __FlashStringHelper * ProgmemStr
Definition progmem.h:31
Callback forwarder that triggers an Automation directly.
Definition automation.h:783
Automation< Ts... > * automation
Definition automation.h:784
void operator()(const Ts &...args) const
Definition automation.h:785
Callback forwarder that triggers an Automation<> only when the bool arg is false.
Definition automation.h:800
void operator()(bool state) const
Definition automation.h:802
Callback forwarder that triggers an Automation<> only when the bool arg is true.
Definition automation.h:790
void operator()(bool state) const
Definition automation.h:792
uint32_t len
uint16_t x
Definition tt21100.cpp:5