ESPHome 2025.5.0
Loading...
Searching...
No Matches
scheduler.cpp
Go to the documentation of this file.
1#include "scheduler.h"
2
3#include "application.h"
5#include "esphome/core/log.h"
7#include "esphome/core/hal.h"
8#include <algorithm>
9#include <cinttypes>
10
11namespace esphome {
12
13static const char *const TAG = "scheduler";
14
15static const uint32_t MAX_LOGICALLY_DELETED_ITEMS = 10;
16
17// Uncomment to debug scheduler
18// #define ESPHOME_DEBUG_SCHEDULER
19
20// A note on locking: the `lock_` lock protects the `items_` and `to_add_` containers. It must be taken when writing to
21// them (i.e. when adding/removing items, but not when changing items). As items are only deleted from the loop task,
22// iterating over them from the loop task is fine; but iterating from any other context requires the lock to be held to
23// avoid the main thread modifying the list while it is being accessed.
24
25void HOT Scheduler::set_timeout(Component *component, const std::string &name, uint32_t timeout,
26 std::function<void()> func) {
27 const auto now = this->millis_();
28
29 if (!name.empty())
30 this->cancel_timeout(component, name);
31
32 if (timeout == SCHEDULER_DONT_RUN)
33 return;
34
35 auto item = make_unique<SchedulerItem>();
36 item->component = component;
37 item->name = name;
38 item->type = SchedulerItem::TIMEOUT;
39 item->next_execution_ = now + timeout;
40 item->callback = std::move(func);
41 item->remove = false;
42#ifdef ESPHOME_DEBUG_SCHEDULER
43 ESP_LOGD(TAG, "set_timeout(name='%s/%s', timeout=%" PRIu32 ")", item->get_source(), name.c_str(), timeout);
44#endif
45 this->push_(std::move(item));
46}
47bool HOT Scheduler::cancel_timeout(Component *component, const std::string &name) {
48 return this->cancel_item_(component, name, SchedulerItem::TIMEOUT);
49}
50void HOT Scheduler::set_interval(Component *component, const std::string &name, uint32_t interval,
51 std::function<void()> func) {
52 const auto now = this->millis_();
53
54 if (!name.empty())
55 this->cancel_interval(component, name);
56
57 if (interval == SCHEDULER_DONT_RUN)
58 return;
59
60 // only put offset in lower half
61 uint32_t offset = 0;
62 if (interval != 0)
63 offset = (random_uint32() % interval) / 2;
64
65 auto item = make_unique<SchedulerItem>();
66 item->component = component;
67 item->name = name;
68 item->type = SchedulerItem::INTERVAL;
69 item->interval = interval;
70 item->next_execution_ = now + offset;
71 item->callback = std::move(func);
72 item->remove = false;
73#ifdef ESPHOME_DEBUG_SCHEDULER
74 ESP_LOGD(TAG, "set_interval(name='%s/%s', interval=%" PRIu32 ", offset=%" PRIu32 ")", item->get_source(),
75 name.c_str(), interval, offset);
76#endif
77 this->push_(std::move(item));
78}
79bool HOT Scheduler::cancel_interval(Component *component, const std::string &name) {
80 return this->cancel_item_(component, name, SchedulerItem::INTERVAL);
81}
82
83struct RetryArgs {
84 std::function<RetryResult(uint8_t)> func;
85 uint8_t retry_countdown;
86 uint32_t current_interval;
87 Component *component;
88 std::string name;
89 float backoff_increase_factor;
90 Scheduler *scheduler;
91};
92
93static void retry_handler(const std::shared_ptr<RetryArgs> &args) {
94 RetryResult const retry_result = args->func(--args->retry_countdown);
95 if (retry_result == RetryResult::DONE || args->retry_countdown <= 0)
96 return;
97 // second execution of `func` happens after `initial_wait_time`
98 args->scheduler->set_timeout(args->component, args->name, args->current_interval, [args]() { retry_handler(args); });
99 // backoff_increase_factor applied to third & later executions
100 args->current_interval *= args->backoff_increase_factor;
101}
102
103void HOT Scheduler::set_retry(Component *component, const std::string &name, uint32_t initial_wait_time,
104 uint8_t max_attempts, std::function<RetryResult(uint8_t)> func,
105 float backoff_increase_factor) {
106 if (!name.empty())
107 this->cancel_retry(component, name);
108
109 if (initial_wait_time == SCHEDULER_DONT_RUN)
110 return;
111
112 ESP_LOGVV(TAG, "set_retry(name='%s', initial_wait_time=%" PRIu32 ", max_attempts=%u, backoff_factor=%0.1f)",
113 name.c_str(), initial_wait_time, max_attempts, backoff_increase_factor);
114
115 if (backoff_increase_factor < 0.0001) {
116 ESP_LOGE(TAG,
117 "set_retry(name='%s'): backoff_factor cannot be close to zero nor negative (%0.1f). Using 1.0 instead",
118 name.c_str(), backoff_increase_factor);
119 backoff_increase_factor = 1;
120 }
121
122 auto args = std::make_shared<RetryArgs>();
123 args->func = std::move(func);
124 args->retry_countdown = max_attempts;
125 args->current_interval = initial_wait_time;
126 args->component = component;
127 args->name = "retry$" + name;
128 args->backoff_increase_factor = backoff_increase_factor;
129 args->scheduler = this;
130
131 // First execution of `func` immediately
132 this->set_timeout(component, args->name, 0, [args]() { retry_handler(args); });
133}
134bool HOT Scheduler::cancel_retry(Component *component, const std::string &name) {
135 return this->cancel_timeout(component, "retry$" + name);
136}
137
139 if (this->empty_())
140 return {};
141 auto &item = this->items_[0];
142 const auto now = this->millis_();
143 if (item->next_execution_ < now)
144 return 0;
145 return item->next_execution_ - now;
146}
147void HOT Scheduler::call() {
148 const auto now = this->millis_();
149 this->process_to_add();
150
151#ifdef ESPHOME_DEBUG_SCHEDULER
152 static uint64_t last_print = 0;
153
154 if (now - last_print > 2000) {
155 last_print = now;
156 std::vector<std::unique_ptr<SchedulerItem>> old_items;
157 ESP_LOGD(TAG, "Items: count=%u, now=%" PRIu64 " (%u, %" PRIu32 ")", this->items_.size(), now, this->millis_major_,
158 this->last_millis_);
159 while (!this->empty_()) {
160 this->lock_.lock();
161 auto item = std::move(this->items_[0]);
162 this->pop_raw_();
163 this->lock_.unlock();
164
165 ESP_LOGD(TAG, " %s '%s/%s' interval=%" PRIu32 " next_execution in %" PRIu64 "ms at %" PRIu64,
166 item->get_type_str(), item->get_source(), item->name.c_str(), item->interval,
167 item->next_execution_ - now, item->next_execution_);
168
169 old_items.push_back(std::move(item));
170 }
171 ESP_LOGD(TAG, "\n");
172
173 {
174 LockGuard guard{this->lock_};
175 this->items_ = std::move(old_items);
176 }
177 }
178#endif // ESPHOME_DEBUG_SCHEDULER
179
180 auto to_remove_was = to_remove_;
181 auto items_was = this->items_.size();
182 // If we have too many items to remove
183 if (to_remove_ > MAX_LOGICALLY_DELETED_ITEMS) {
184 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
185 while (!this->empty_()) {
186 LockGuard guard{this->lock_};
187 auto item = std::move(this->items_[0]);
188 this->pop_raw_();
189 valid_items.push_back(std::move(item));
190 }
191
192 {
193 LockGuard guard{this->lock_};
194 this->items_ = std::move(valid_items);
195 }
196
197 // The following should not happen unless I'm missing something
198 if (to_remove_ != 0) {
199 ESP_LOGW(TAG, "to_remove_ was %" PRIu32 " now: %" PRIu32 " items where %zu now %zu. Please report this",
200 to_remove_was, to_remove_, items_was, items_.size());
201 to_remove_ = 0;
202 }
203 }
204
205 while (!this->empty_()) {
206 // use scoping to indicate visibility of `item` variable
207 {
208 // Don't copy-by value yet
209 auto &item = this->items_[0];
210 if (item->next_execution_ > now) {
211 // Not reached timeout yet, done for this call
212 break;
213 }
214 // Don't run on failed components
215 if (item->component != nullptr && item->component->is_failed()) {
216 LockGuard guard{this->lock_};
217 this->pop_raw_();
218 continue;
219 }
220 App.set_current_component(item->component);
221
222#ifdef ESPHOME_DEBUG_SCHEDULER
223 ESP_LOGV(TAG, "Running %s '%s/%s' with interval=%" PRIu32 " next_execution=%" PRIu64 " (now=%" PRIu64 ")",
224 item->get_type_str(), item->get_source(), item->name.c_str(), item->interval, item->next_execution_,
225 now);
226#endif
227
228 // Warning: During callback(), a lot of stuff can happen, including:
229 // - timeouts/intervals get added, potentially invalidating vector pointers
230 // - timeouts/intervals get cancelled
231 {
232 uint32_t now_ms = millis();
233 WarnIfComponentBlockingGuard guard{item->component, now_ms};
234 item->callback();
235 // Call finish to ensure blocking time is properly calculated and reported
236 guard.finish();
237 }
238 }
239
240 {
241 this->lock_.lock();
242
243 // new scope, item from before might have been moved in the vector
244 auto item = std::move(this->items_[0]);
245
246 // Only pop after function call, this ensures we were reachable
247 // during the function call and know if we were cancelled.
248 this->pop_raw_();
249
250 this->lock_.unlock();
251
252 if (item->remove) {
253 // We were removed/cancelled in the function call, stop
254 to_remove_--;
255 continue;
256 }
257
258 if (item->type == SchedulerItem::INTERVAL) {
259 item->next_execution_ = now + item->interval;
260 this->push_(std::move(item));
261 }
262 }
263 }
264
265 this->process_to_add();
266}
268 LockGuard guard{this->lock_};
269 for (auto &it : this->to_add_) {
270 if (it->remove) {
271 continue;
272 }
273
274 this->items_.push_back(std::move(it));
275 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
276 }
277 this->to_add_.clear();
278}
280 while (!this->items_.empty()) {
281 auto &item = this->items_[0];
282 if (!item->remove)
283 return;
284
285 to_remove_--;
286
287 {
288 LockGuard guard{this->lock_};
289 this->pop_raw_();
290 }
291 }
292}
294 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
295 this->items_.pop_back();
296}
297void HOT Scheduler::push_(std::unique_ptr<Scheduler::SchedulerItem> item) {
298 LockGuard guard{this->lock_};
299 this->to_add_.push_back(std::move(item));
300}
301bool HOT Scheduler::cancel_item_(Component *component, const std::string &name, Scheduler::SchedulerItem::Type type) {
302 // obtain lock because this function iterates and can be called from non-loop task context
303 LockGuard guard{this->lock_};
304 bool ret = false;
305 for (auto &it : this->items_) {
306 if (it->component == component && it->name == name && it->type == type && !it->remove) {
307 to_remove_++;
308 it->remove = true;
309 ret = true;
310 }
311 }
312 for (auto &it : this->to_add_) {
313 if (it->component == component && it->name == name && it->type == type) {
314 it->remove = true;
315 ret = true;
316 }
317 }
318
319 return ret;
320}
322 const uint32_t now = millis();
323 if (now < this->last_millis_) {
324 this->millis_major_++;
325 ESP_LOGD(TAG, "Incrementing scheduler major at %" PRIu64 "ms",
326 now + (static_cast<uint64_t>(this->millis_major_) << 32));
327 }
328 this->last_millis_ = now;
329 return now + (static_cast<uint64_t>(this->millis_major_) << 32);
330}
331
332bool HOT Scheduler::SchedulerItem::cmp(const std::unique_ptr<SchedulerItem> &a,
333 const std::unique_ptr<SchedulerItem> &b) {
334 return a->next_execution_ > b->next_execution_;
335}
336
337} // namespace esphome
void set_current_component(Component *component)
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:585
uint32_t to_remove_
Definition scheduler.h:71
bool cancel_retry(Component *component, const std::string &name)
uint32_t last_millis_
Definition scheduler.h:69
bool cancel_item_(Component *component, const std::string &name, SchedulerItem::Type type)
void set_retry(Component *component, const std::string &name, uint32_t initial_wait_time, uint8_t max_attempts, std::function< RetryResult(uint8_t)> func, float backoff_increase_factor=1.0f)
bool cancel_timeout(Component *component, const std::string &name)
Definition scheduler.cpp:47
void push_(std::unique_ptr< SchedulerItem > item)
std::vector< std::unique_ptr< SchedulerItem > > to_add_
Definition scheduler.h:68
bool cancel_interval(Component *component, const std::string &name)
Definition scheduler.cpp:79
void set_timeout(Component *component, const std::string &name, uint32_t timeout, std::function< void()> func)
Definition scheduler.cpp:25
void set_interval(Component *component, const std::string &name, uint32_t interval, std::function< void()> func)
Definition scheduler.cpp:50
uint16_t millis_major_
Definition scheduler.h:70
optional< uint32_t > next_schedule_in()
std::vector< std::unique_ptr< SchedulerItem > > items_
Definition scheduler.h:67
uint8_t type
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::unique_ptr< T > make_unique(Args &&...args)
Definition helpers.h:85
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:196
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:27
Application App
Global storage of Application pointer - only one Application can exist.
static bool cmp(const std::unique_ptr< SchedulerItem > &a, const std::unique_ptr< SchedulerItem > &b)