ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
script.h
Go to the documentation of this file.
1#pragma once
2
3#include <list>
4#include <memory>
5#include <tuple>
10#include "esphome/core/log.h"
12
13namespace esphome::script {
14
16 protected:
17 void esp_logw_(int line, ProgmemStr format, const char *param) {
18 esp_log_(ESPHOME_LOG_LEVEL_WARN, line, format, param);
19 }
20 void esp_logd_(int line, ProgmemStr format, const char *param) {
21 esp_log_(ESPHOME_LOG_LEVEL_DEBUG, line, format, param);
22 }
23 void esp_log_(int level, int line, ProgmemStr format, const char *param);
24};
25
27template<typename... Ts> class Script : public ScriptLogger, public Trigger<Ts...> {
28 public:
33 virtual void execute(Ts...) = 0;
35 virtual bool is_running() { return this->is_action_running(); }
36#ifdef USE_SCRIPT_ON_STOP
38 virtual void stop() {
39 if (this->is_action_running())
40 this->stop_running_();
41 }
42
44#else
46 virtual void stop() { this->stop_action(); }
47#endif
48
49 // Internal function to give scripts readable names.
50 void set_name(const LogString *name) { name_ = name; }
51
52 protected:
53 // Run the action chain with this script's name published as the current source (RAII save/restore,
54 // so nesting composes), so deferred work inside the script is attributed to it in blocking
55 // warnings. Force-inlined to fold into the always-inlined trigger chain (no extra stack frame).
56 inline void run_actions_(const Ts &...x) ESPHOME_ALWAYS_INLINE {
57 ScopedSourceGuard source_guard{this->name_};
58 this->trigger(x...);
59 }
60
61 // Stop the running actions early and fire the on_stop trigger.
63 this->stop_action();
64#ifdef USE_SCRIPT_ON_STOP
65 this->stop_trigger_.trigger();
66#endif
67 }
68
69 const LogString *name_{nullptr};
70#ifdef USE_SCRIPT_ON_STOP
72#endif
73};
74
80template<typename... Ts> class SingleScript : public Script<Ts...> {
81 public:
82 void execute(Ts... x) override {
83 if (this->is_action_running()) {
84 this->esp_logw_(__LINE__, ESPHOME_LOG_FORMAT("Script '%s' is already running! (mode: single)"),
85 LOG_STR_ARG(this->name_));
86 return;
87 }
88
89 this->run_actions_(x...);
90 }
91};
92
98template<typename... Ts> class RestartScript : public Script<Ts...> {
99 public:
100 void execute(Ts... x) override {
101 if (this->is_action_running()) {
102 this->esp_logd_(__LINE__, ESPHOME_LOG_FORMAT("Script '%s' restarting (mode: restart)"), LOG_STR_ARG(this->name_));
103 this->stop_running_();
104#ifdef USE_SCRIPT_ON_STOP
105 // on_stop may have executed this script again; only the newest run may continue
106 if (this->is_action_running())
107 this->stop_action();
108#endif
109 }
110
111 this->run_actions_(x...);
112 }
113};
114
129template<typename... Ts> class QueueingScript : public Script<Ts...>, public Component {
130 public:
131 void execute(Ts... x) override {
132 if (this->is_action_running() || this->num_queued_ > 0) {
133 // num_queued_ is the number of *queued* instances (waiting, not including currently running)
134 // max_runs_ is the maximum *total* instances (running + queued)
135 // So we reject when num_queued_ + 1 >= max_runs_ (queued + running >= max)
136 if (this->num_queued_ + 1 >= this->max_runs_) {
137 this->esp_logw_(__LINE__, ESPHOME_LOG_FORMAT("Script '%s' max instances (running + queued) reached!"),
138 LOG_STR_ARG(this->name_));
139 return;
140 }
141
142 // Initialize queue on first queued item (after capacity check)
143 this->lazy_init_queue_();
144
145 this->esp_logd_(__LINE__, ESPHOME_LOG_FORMAT("Script '%s' queueing new instance (mode: queued)"),
146 LOG_STR_ARG(this->name_));
147 // Ring buffer: write to (queue_front_ + num_queued_) % queue_capacity
148 const size_t queue_capacity = static_cast<size_t>(this->max_runs_ - 1);
149 size_t write_pos = (this->queue_front_ + this->num_queued_) % queue_capacity;
150 // Use std::make_unique to replace the unique_ptr
151 this->var_queue_[write_pos] = std::make_unique<std::tuple<Ts...>>(x...);
152 this->num_queued_++;
153 // Enable loop now that there is something to dequeue - don't call loop()
154 // synchronously! Let the event loop call it to avoid reentrancy issues
155 this->enable_loop();
156 return;
157 }
158
159 this->run_actions_(x...);
160 // Check if the trigger was immediate and we can continue right away.
161 this->loop();
162 }
163
164 void stop() override {
165#ifdef USE_SCRIPT_ON_STOP
166 // Queued runs are unfinished work too, even between two runs when nothing is running
167 const bool stopping = this->is_action_running() || this->num_queued_ != 0;
168#endif
169 // Clear all queued items to free memory immediately
170 // Resetting the array automatically destroys all unique_ptrs and their contents
171 this->var_queue_.reset();
172 this->num_queued_ = 0;
173 this->queue_front_ = 0;
174#ifdef USE_SCRIPT_ON_STOP
175 if (stopping)
176 this->stop_running_();
177#else
179#endif
180 }
181
182 void loop() override {
183 if (this->num_queued_ != 0 && !this->is_action_running()) {
184 // Dequeue: decrement count, move tuple out (frees slot), advance read position
185 this->num_queued_--;
186 const size_t queue_capacity = static_cast<size_t>(this->max_runs_ - 1);
187 auto tuple_ptr = std::move(this->var_queue_[this->queue_front_]);
188 this->queue_front_ = (this->queue_front_ + 1) % queue_capacity;
189 this->trigger_tuple_(*tuple_ptr, std::make_index_sequence<sizeof...(Ts)>{});
190 }
191 if (this->num_queued_ == 0 && !this->is_idle()) {
192 // Queue is now empty - disable loop until the next execute() queues an
193 // instance. The inline is_idle() check skips the out-of-line call when
194 // the loop is already disabled (execute() calls loop() synchronously).
195 // This can run before this component's setup() (execute() from on_boot),
196 // which leaves the state machine in LOOP_DONE and skips call_setup();
197 // this class therefore must not rely on a setup() override.
198 this->disable_loop();
199 }
200 }
201
202 void set_max_runs(int max_runs) { max_runs_ = max_runs; }
203
204 protected:
205 // Lazy init queue on first use - avoids setup() ordering issues and saves memory
206 // if script is never executed during this boot cycle
207 inline void lazy_init_queue_() {
208 if (!this->var_queue_) {
209 // Allocate array of max_runs_ - 1 slots for queued items (running item is separate)
210 // unique_ptr array is zero-initialized, so all slots start as nullptr
211 this->var_queue_ = std::make_unique<std::unique_ptr<std::tuple<Ts...>>[]>(this->max_runs_ - 1);
212 }
213 }
214
215 template<size_t... S> void trigger_tuple_(const std::tuple<Ts...> &tuple, std::index_sequence<S...> /*unused*/) {
216 this->run_actions_(std::get<S>(tuple)...);
217 }
218
219 int num_queued_ = 0; // Number of queued instances (not including currently running)
220 int max_runs_ = 0; // Maximum total instances (running + queued)
221 size_t queue_front_ = 0; // Ring buffer read position (next item to execute)
222 std::unique_ptr<std::unique_ptr<std::tuple<Ts...>>[]> var_queue_; // Ring buffer of queued parameters
223};
224
230template<typename... Ts> class ParallelScript : public Script<Ts...> {
231 public:
232 void execute(Ts... x) override {
233 if (this->max_runs_ != 0 && this->automation_parent_->num_running() >= this->max_runs_) {
234 this->esp_logw_(__LINE__, ESPHOME_LOG_FORMAT("Script '%s' maximum number of parallel runs exceeded!"),
235 LOG_STR_ARG(this->name_));
236 return;
237 }
238 this->run_actions_(x...);
239 }
240 void set_max_runs(int max_runs) { max_runs_ = max_runs; }
241
242 protected:
243 int max_runs_ = 0;
244};
245
253template<class C, typename... Ts> class ScriptWaitAction final : public Action<Ts...>, public Component {
254 public:
255 ScriptWaitAction(C *script) : script_(script) {}
256
257 void setup() override {
258 // Start with loop disabled - only enable when there's work to do
259 // IMPORTANT: Only disable if num_running_ is 0, otherwise play_complex() was already
260 // called before our setup() (e.g., from on_boot trigger at same priority level)
261 // and we must not undo its enable_loop() call
262 if (this->num_running_ == 0) {
263 this->disable_loop();
264 }
265 }
266
267 void play_complex(const Ts &...x) override {
268 this->num_running_++;
269 // Check if we can continue immediately.
270 if (!this->script_->is_running()) {
271 this->play_next_(x...);
272 return;
273 }
274
275 // Store parameters for later execution
276 this->param_queue_.emplace_back(x...);
277 // Enable loop now that we have work to do - don't call loop() synchronously!
278 // Let the event loop call it to avoid reentrancy issues
279 this->enable_loop();
280 }
281
282 void loop() override {
283 if (this->num_running_ == 0) {
284 // Nothing left to wait for, e.g. once the last queued item has run
285 this->disable_loop();
286 return;
287 }
288
289 if (this->script_->is_running())
290 return;
291
292 // Only process ONE queued item per loop iteration
293 // Processing all items in a while loop causes infinite loops because
294 // play_next_() can trigger more items to be queued
295 if (!this->param_queue_.empty()) {
296 // Take the item out first: the chain may call stop(), which clears the queue
297 auto params = std::move(this->param_queue_.front());
298 this->param_queue_.pop_front();
299 std::apply([this](auto &...args) { this->play_next_(args...); }, params);
300 } else {
301 // Queue is now empty - disable loop until next play_complex
302 this->disable_loop();
303 }
304 }
305
306 void play(const Ts &...x) override { /* ignore - see play_complex */ }
307
308 void stop() override {
309 this->param_queue_.clear();
310 this->disable_loop();
311 }
312
313 protected:
315 std::list<std::tuple<stored_trigger_arg_t<Ts>...>> param_queue_;
316};
317
318} // namespace esphome::script
void play_next_(const Ts &...x)
Definition automation.h:614
int num_running()
Return the number of actions in the action part of this automation that are currently running.
Definition automation.h:751
void enable_loop()
Enable this component's loop.
Definition component.h:261
void disable_loop()
Disable this component's loop.
bool is_idle() const
Check if this component is idle.
Definition component.h:217
RAII guard that publishes a current source (e.g.
Automation< Ts... > * automation_parent_
Definition automation.h:578
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Definition automation.h:557
A script type that executes new instances in parallel.
Definition script.h:230
void execute(Ts... x) override
Definition script.h:232
void set_max_runs(int max_runs)
Definition script.h:240
A script type that queues new instances that are created.
Definition script.h:129
void trigger_tuple_(const std::tuple< Ts... > &tuple, std::index_sequence< S... >)
Definition script.h:215
void execute(Ts... x) override
Definition script.h:131
void set_max_runs(int max_runs)
Definition script.h:202
std::unique_ptr< std::unique_ptr< std::tuple< Ts... > >[]> var_queue_
Definition script.h:222
A script type that restarts scripts from the beginning when a new instance is started.
Definition script.h:98
void execute(Ts... x) override
Definition script.h:100
The abstract base class for all script types.
Definition script.h:27
virtual bool is_running()
Check if any instance of this script is currently running.
Definition script.h:35
virtual void execute(Ts...)=0
Execute a new instance of this script.
Trigger * get_stop_trigger()
Definition script.h:43
virtual void stop()
Stop all instances of this script. Fires the on_stop trigger once if any instance was running.
Definition script.h:38
void run_actions_(const Ts &...x) ESPHOME_ALWAYS_INLINE
Definition script.h:56
void set_name(const LogString *name)
Definition script.h:50
const LogString * name_
Definition script.h:69
void esp_logw_(int line, ProgmemStr format, const char *param)
Definition script.h:17
void esp_logd_(int line, ProgmemStr format, const char *param)
Definition script.h:20
void esp_log_(int level, int line, ProgmemStr format, const char *param)
Definition script.cpp:8
Wait for a script to finish before continuing.
Definition script.h:253
void play(const Ts &...x) override
Definition script.h:306
std::list< std::tuple< stored_trigger_arg_t< Ts >... > > param_queue_
Definition script.h:315
void play_complex(const Ts &...x) override
Definition script.h:267
A script type for which only a single instance at a time is allowed.
Definition script.h:80
void execute(Ts... x) override
Definition script.h:82
const char * format
const __FlashStringHelper * ProgmemStr
Definition progmem.h:31
uint16_t x
Definition tt21100.cpp:5