15static const char *
const TAG =
"scheduler";
17static const uint32_t MAX_LOGICALLY_DELETED_ITEMS = 10;
19static constexpr uint32_t HALF_MAX_UINT32 = std::numeric_limits<uint32_t>::max() / 2;
21static constexpr uint32_t MAX_INTERVAL_DELAY = 5000;
26#ifdef ESPHOME_DEBUG_SCHEDULER
28static void validate_static_string(
const char *name) {
34 uintptr_t addr =
reinterpret_cast<uintptr_t
>(name);
38 uintptr_t stack_addr =
reinterpret_cast<uintptr_t
>(&stack_var);
42 if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
44 "WARNING: Scheduler name '%s' at %p appears to be on the stack - this is unsafe!\n"
45 " Stack reference at %p",
46 name, name, &stack_var);
51 static const char *static_str =
"test";
52 uintptr_t static_addr =
reinterpret_cast<uintptr_t
>(static_str);
55 if (addr > static_addr + 0x100000 || (static_addr > 0x100000 && addr < static_addr - 0x100000)) {
56 ESP_LOGW(TAG,
"WARNING: Scheduler name '%s' at %p might be on heap (static ref at %p)", name, name, static_str);
67void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
type,
bool is_static_string,
68 const void *name_ptr, uint32_t
delay, std::function<
void()> func,
bool is_retry,
71 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
73 if (
delay == SCHEDULER_DONT_RUN) {
76 LockGuard guard{this->lock_};
77 this->cancel_item_locked_(component, name_cstr,
type);
83 auto item = make_unique<SchedulerItem>();
84 item->component = component;
85 item->set_name(name_cstr, !is_static_string);
87 item->callback = std::move(func);
90#ifdef ESPHOME_THREAD_MULTI_ATOMICS
91 item->remove.store(
false, std::memory_order_relaxed);
95 item->is_retry = is_retry;
97#ifndef ESPHOME_THREAD_SINGLE
100 if (
delay == 0 &&
type == SchedulerItem::TIMEOUT) {
102 LockGuard guard{this->lock_};
104 this->cancel_item_locked_(component, name_cstr,
type);
106 this->defer_queue_.push_back(std::move(item));
112 const auto now = this->millis_64_(
millis());
115 if (
type == SchedulerItem::INTERVAL) {
116 item->interval =
delay;
120 item->next_execution_ = now + offset;
121 ESP_LOGV(TAG,
"Scheduler interval for %s is %" PRIu32
"ms, offset %" PRIu32
"ms", name_cstr ? name_cstr :
"",
delay,
125 item->next_execution_ = now +
delay;
128#ifdef ESPHOME_DEBUG_SCHEDULER
130 if (is_static_string && name_cstr !=
nullptr) {
131 validate_static_string(name_cstr);
135 const char *type_str = (
type == SchedulerItem::TIMEOUT) ?
"timeout" :
"interval";
136 if (
type == SchedulerItem::TIMEOUT) {
137 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
")", type_str, item->get_source(),
138 name_cstr ? name_cstr :
"(null)", type_str,
delay);
140 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
", offset=%" PRIu32
")", type_str, item->get_source(),
141 name_cstr ? name_cstr :
"(null)", type_str,
delay,
static_cast<uint32_t>(item->next_execution_ - now));
145 LockGuard guard{this->lock_};
148 if (is_retry && name_cstr !=
nullptr &&
type == SchedulerItem::TIMEOUT &&
149 (has_cancelled_timeout_in_container_(this->items_, component, name_cstr,
true) ||
150 has_cancelled_timeout_in_container_(this->to_add_, component, name_cstr,
true))) {
152#ifdef ESPHOME_DEBUG_SCHEDULER
153 ESP_LOGD(TAG,
"Skipping retry '%s' - found cancelled item", name_cstr);
161 this->cancel_item_locked_(component, name_cstr,
type);
165 this->to_add_.push_back(std::move(item));
168void HOT Scheduler::set_timeout(Component *component,
const char *name, uint32_t timeout, std::function<
void()> func) {
169 this->set_timer_common_(component, SchedulerItem::TIMEOUT,
true, name, timeout, std::move(func));
172void HOT Scheduler::set_timeout(Component *component,
const std::string &name, uint32_t timeout,
173 std::function<
void()> func) {
174 this->set_timer_common_(component, SchedulerItem::TIMEOUT,
false, &name, timeout, std::move(func));
176bool HOT Scheduler::cancel_timeout(Component *component,
const std::string &name) {
177 return this->cancel_item_(component,
false, &name, SchedulerItem::TIMEOUT);
179bool HOT Scheduler::cancel_timeout(Component *component,
const char *name) {
180 return this->cancel_item_(component,
true, name, SchedulerItem::TIMEOUT);
182void HOT Scheduler::set_interval(Component *component,
const std::string &name, uint32_t interval,
183 std::function<
void()> func) {
184 this->set_timer_common_(component, SchedulerItem::INTERVAL,
false, &name, interval, std::move(func));
187void HOT Scheduler::set_interval(Component *component,
const char *name, uint32_t interval,
188 std::function<
void()> func) {
189 this->set_timer_common_(component, SchedulerItem::INTERVAL,
true, name, interval, std::move(func));
191bool HOT Scheduler::cancel_interval(Component *component,
const std::string &name) {
192 return this->cancel_item_(component,
false, &name, SchedulerItem::INTERVAL);
194bool HOT Scheduler::cancel_interval(Component *component,
const char *name) {
195 return this->cancel_item_(component,
true, name, SchedulerItem::INTERVAL);
200 uint8_t retry_countdown;
202 Component *component;
204 float backoff_increase_factor;
205 Scheduler *scheduler;
209 RetryResult const retry_result = args->func(--args->retry_countdown);
213 args->scheduler->set_timer_common_(
214 args->component, Scheduler::SchedulerItem::TIMEOUT,
false, &args->name, args->current_interval,
215 [args]() { retry_handler(args); },
true);
217 args->current_interval *= args->backoff_increase_factor;
220void HOT Scheduler::set_retry_common_(Component *component,
bool is_static_string,
const void *name_ptr,
221 uint32_t initial_wait_time, uint8_t max_attempts,
222 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
223 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
225 if (name_cstr !=
nullptr)
226 this->cancel_retry(component, name_cstr);
228 if (initial_wait_time == SCHEDULER_DONT_RUN)
231 ESP_LOGVV(TAG,
"set_retry(name='%s', initial_wait_time=%" PRIu32
", max_attempts=%u, backoff_factor=%0.1f)",
232 name_cstr ? name_cstr :
"", initial_wait_time, max_attempts, backoff_increase_factor);
234 if (backoff_increase_factor < 0.0001) {
235 ESP_LOGE(TAG,
"backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor, name_cstr ? name_cstr :
"");
236 backoff_increase_factor = 1;
239 auto args = std::make_shared<RetryArgs>();
240 args->func = std::move(func);
241 args->retry_countdown = max_attempts;
242 args->current_interval = initial_wait_time;
243 args->component = component;
244 args->name = name_cstr ? name_cstr :
"";
245 args->backoff_increase_factor = backoff_increase_factor;
246 args->scheduler =
this;
249 this->set_timer_common_(
250 component, SchedulerItem::TIMEOUT,
false, &args->name, 0, [args]() { retry_handler(args); },
254void HOT Scheduler::set_retry(Component *component,
const std::string &name, uint32_t initial_wait_time,
255 uint8_t max_attempts, std::function<
RetryResult(uint8_t)> func,
256 float backoff_increase_factor) {
257 this->set_retry_common_(component,
false, &name, initial_wait_time, max_attempts, std::move(func),
258 backoff_increase_factor);
261void HOT Scheduler::set_retry(Component *component,
const char *name, uint32_t initial_wait_time, uint8_t max_attempts,
262 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
263 this->set_retry_common_(component,
true, name, initial_wait_time, max_attempts, std::move(func),
264 backoff_increase_factor);
266bool HOT Scheduler::cancel_retry(Component *component,
const std::string &name) {
267 return this->cancel_retry(component, name.c_str());
270bool HOT Scheduler::cancel_retry(Component *component,
const char *name) {
272 LockGuard guard{this->lock_};
273 return this->cancel_item_locked_(component, name, SchedulerItem::TIMEOUT,
true);
276optional<uint32_t> HOT Scheduler::next_schedule_in(uint32_t now) {
282 if (this->cleanup_() == 0)
285 auto &item = this->items_[0];
287 const auto now_64 = this->millis_64_(now);
288 if (item->next_execution_ < now_64)
290 return item->next_execution_ - now_64;
292void HOT Scheduler::call(uint32_t now) {
293#ifndef ESPHOME_THREAD_SINGLE
306 while (!this->defer_queue_.empty()) {
310 std::unique_ptr<SchedulerItem> item;
312 LockGuard lock(this->lock_);
313 item = std::move(this->defer_queue_.front());
314 this->defer_queue_.pop_front();
319 if (!this->should_skip_item_(item.get())) {
320 this->execute_item_(item.get(), now);
326 const auto now_64 = this->millis_64_(now);
327 this->process_to_add();
329#ifdef ESPHOME_DEBUG_SCHEDULER
330 static uint64_t last_print = 0;
332 if (now_64 - last_print > 2000) {
334 std::vector<std::unique_ptr<SchedulerItem>> old_items;
335#ifdef ESPHOME_THREAD_MULTI_ATOMICS
336 const auto last_dbg = this->last_millis_.load(std::memory_order_relaxed);
337 const auto major_dbg = this->millis_major_.load(std::memory_order_relaxed);
338 ESP_LOGD(TAG,
"Items: count=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(), now_64,
339 major_dbg, last_dbg);
341 ESP_LOGD(TAG,
"Items: count=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(), now_64,
342 this->millis_major_, this->last_millis_);
346 while (!this->items_.empty()) {
347 std::unique_ptr<SchedulerItem> item;
349 LockGuard guard{this->lock_};
350 item = std::move(this->items_[0]);
354 const char *name = item->get_name();
355 ESP_LOGD(TAG,
" %s '%s/%s' interval=%" PRIu32
" next_execution in %" PRIu64
"ms at %" PRIu64,
356 item->get_type_str(), item->get_source(), name ? name :
"(null)", item->interval,
357 item->next_execution_ - now_64, item->next_execution_);
359 old_items.push_back(std::move(item));
364 LockGuard guard{this->lock_};
365 this->items_ = std::move(old_items);
367 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
373 if (this->to_remove_ > MAX_LOGICALLY_DELETED_ITEMS) {
379 LockGuard guard{this->lock_};
381 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
384 for (
auto &item : this->items_) {
386 valid_items.push_back(std::move(item));
391 this->items_ = std::move(valid_items);
393 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
394 this->to_remove_ = 0;
399 while (!this->items_.empty()) {
403 auto &item = this->items_[0];
404 if (item->next_execution_ > now_64) {
409 if (item->component !=
nullptr && item->component->is_failed()) {
410 LockGuard guard{this->lock_};
419#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
422 LockGuard guard{this->lock_};
423 if (is_item_removed_(item.get())) {
431 if (is_item_removed_(item.get())) {
432 LockGuard guard{this->lock_};
439#ifdef ESPHOME_DEBUG_SCHEDULER
440 const char *item_name = item->get_name();
441 ESP_LOGV(TAG,
"Running %s '%s/%s' with interval=%" PRIu32
" next_execution=%" PRIu64
" (now=%" PRIu64
")",
442 item->get_type_str(), item->get_source(), item_name ? item_name :
"(null)", item->interval,
443 item->next_execution_, now_64);
449 this->execute_item_(item.get(), now);
453 LockGuard guard{this->lock_};
456 auto item = std::move(this->items_[0]);
467 if (item->type == SchedulerItem::INTERVAL) {
468 item->next_execution_ = now_64 + item->interval;
471 this->to_add_.push_back(std::move(item));
476 this->process_to_add();
478void HOT Scheduler::process_to_add() {
479 LockGuard guard{this->lock_};
480 for (
auto &it : this->to_add_) {
485 this->items_.push_back(std::move(it));
486 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
488 this->to_add_.clear();
490size_t HOT Scheduler::cleanup_() {
498 if (this->to_remove_ == 0)
499 return this->items_.size();
509 LockGuard guard{this->lock_};
510 while (!this->items_.empty()) {
511 auto &item = this->items_[0];
517 return this->items_.size();
519void HOT Scheduler::pop_raw_() {
520 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
521 this->items_.pop_back();
525void HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
527 WarnIfComponentBlockingGuard guard{item->component, now};
533bool HOT Scheduler::cancel_item_(Component *component,
bool is_static_string,
const void *name_ptr,
534 SchedulerItem::Type
type) {
536 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
539 LockGuard guard{this->lock_};
540 return this->cancel_item_locked_(component, name_cstr,
type);
544bool HOT Scheduler::cancel_item_locked_(Component *component,
const char *name_cstr, SchedulerItem::Type
type,
547 if (name_cstr ==
nullptr) {
551 size_t total_cancelled = 0;
554#ifndef ESPHOME_THREAD_SINGLE
556 if (
type == SchedulerItem::TIMEOUT) {
557 for (
auto &item : this->defer_queue_) {
558 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
559 this->mark_item_removed_(item.get());
567 for (
auto &item : this->items_) {
568 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
569 this->mark_item_removed_(item.get());
576 for (
auto &item : this->to_add_) {
577 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
578 this->mark_item_removed_(item.get());
584 return total_cancelled > 0;
587uint64_t Scheduler::millis_64_(uint32_t now) {
601#ifdef ESPHOME_THREAD_SINGLE
607 uint16_t major = this->millis_major_;
611 if (now < last && (last - now) > HALF_MAX_UINT32) {
612 this->millis_major_++;
614#ifdef ESPHOME_DEBUG_SCHEDULER
615 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
621 this->last_millis_ = now;
625 return now + (
static_cast<uint64_t
>(major) << 32);
627#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
635 uint16_t major = this->millis_major_;
640 static const uint32_t ROLLOVER_WINDOW = 10000;
643 bool near_rollover = (last > (std::numeric_limits<uint32_t>::max() - ROLLOVER_WINDOW)) || (now < ROLLOVER_WINDOW);
645 if (near_rollover || (now < last && (last - now) > HALF_MAX_UINT32)) {
647 LockGuard guard{this->lock_};
649 last = this->last_millis_;
651 if (now < last && (last - now) > HALF_MAX_UINT32) {
653 this->millis_major_++;
655#ifdef ESPHOME_DEBUG_SCHEDULER
656 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
660 this->last_millis_ = now;
661 }
else if (now > last) {
668 this->last_millis_ = now;
674 return now + (
static_cast<uint64_t
>(major) << 32);
676#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
687 uint16_t major = this->millis_major_.load(std::memory_order_acquire);
695 uint32_t last = this->last_millis_.load(std::memory_order_acquire);
699 if (now < last && (last - now) > HALF_MAX_UINT32) {
701 LockGuard guard{this->lock_};
703 last = this->last_millis_.load(std::memory_order_relaxed);
705 if (now < last && (last - now) > HALF_MAX_UINT32) {
707 this->millis_major_.fetch_add(1, std::memory_order_relaxed);
709#ifdef ESPHOME_DEBUG_SCHEDULER
710 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
718 this->last_millis_.store(now, std::memory_order_release);
722 while (now > last && (now - last) < HALF_MAX_UINT32) {
723 if (this->last_millis_.compare_exchange_weak(last, now,
724 std::memory_order_release,
725 std::memory_order_relaxed)) {
732 uint16_t major_end = this->millis_major_.load(std::memory_order_relaxed);
733 if (major_end == major)
734 return now + (
static_cast<uint64_t
>(major) << 32);
737 __builtin_unreachable();
741 "No platform threading model defined. One of ESPHOME_THREAD_SINGLE, ESPHOME_THREAD_MULTI_NO_ATOMICS, or ESPHOME_THREAD_MULTI_ATOMICS must be defined."
745bool HOT Scheduler::SchedulerItem::cmp(
const std::unique_ptr<SchedulerItem> &a,
746 const std::unique_ptr<SchedulerItem> &b) {
747 return a->next_execution_ > b->next_execution_;
void set_current_component(Component *component)
Providing packet encoding functions for exchanging data with a remote host.
float random_float()
Return a random float between 0 and 1.
void retry_handler(const std::shared_ptr< RetryArgs > &args)
void IRAM_ATTR HOT delay(uint32_t ms)
uint32_t IRAM_ATTR HOT millis()
Application App
Global storage of Application pointer - only one Application can exist.