15static const char *
const TAG =
"scheduler";
24static constexpr size_t MAX_POOL_SIZE = 5;
29static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
31static constexpr uint32_t HALF_MAX_UINT32 = std::numeric_limits<uint32_t>::max() / 2;
33static constexpr uint32_t MAX_INTERVAL_DELAY = 5000;
38#ifdef ESPHOME_DEBUG_SCHEDULER
40static void validate_static_string(
const char *name) {
46 uintptr_t addr =
reinterpret_cast<uintptr_t
>(name);
50 uintptr_t stack_addr =
reinterpret_cast<uintptr_t
>(&stack_var);
54 if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
56 "WARNING: Scheduler name '%s' at %p appears to be on the stack - this is unsafe!\n"
57 " Stack reference at %p",
58 name, name, &stack_var);
63 static const char *static_str =
"test";
64 uintptr_t static_addr =
reinterpret_cast<uintptr_t
>(static_str);
67 if (addr > static_addr + 0x100000 || (static_addr > 0x100000 && addr < static_addr - 0x100000)) {
68 ESP_LOGW(TAG,
"WARNING: Scheduler name '%s' at %p might be on heap (static ref at %p)", name, name, static_str);
79void HOT Scheduler::set_timer_common_(Component *
component, SchedulerItem::Type
type,
bool is_static_string,
80 const void *name_ptr, uint32_t
delay, std::function<
void()> func,
bool is_retry,
83 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
85 if (
delay == SCHEDULER_DONT_RUN) {
88 LockGuard guard{this->lock_};
95 const uint64_t now = this->millis_64_(
millis());
98 LockGuard guard{this->lock_};
101 std::unique_ptr<SchedulerItem> item;
102 if (!this->scheduler_item_pool_.empty()) {
104 item = std::move(this->scheduler_item_pool_.back());
105 this->scheduler_item_pool_.pop_back();
106#ifdef ESPHOME_DEBUG_SCHEDULER
107 ESP_LOGD(TAG,
"Reused item from pool (pool size now: %zu)", this->scheduler_item_pool_.size());
111 item = make_unique<SchedulerItem>();
112#ifdef ESPHOME_DEBUG_SCHEDULER
113 ESP_LOGD(TAG,
"Allocated new item (pool empty)");
117 item->set_name(name_cstr, !is_static_string);
119 item->callback = std::move(func);
121 this->set_item_removed_(item.get(),
false);
122 item->is_retry = is_retry;
124#ifndef ESPHOME_THREAD_SINGLE
127 if (
delay == 0 &&
type == SchedulerItem::TIMEOUT) {
132 this->defer_queue_.push_back(std::move(item));
138 if (
type == SchedulerItem::INTERVAL) {
139 item->interval =
delay;
143 item->set_next_execution(now + offset);
144 ESP_LOGV(TAG,
"Scheduler interval for %s is %" PRIu32
"ms, offset %" PRIu32
"ms", name_cstr ? name_cstr :
"",
delay,
148 item->set_next_execution(now +
delay);
151#ifdef ESPHOME_DEBUG_SCHEDULER
152 this->debug_log_timer_(item.get(), is_static_string, name_cstr,
type,
delay, now);
156 if (is_retry && name_cstr !=
nullptr &&
type == SchedulerItem::TIMEOUT &&
157 (has_cancelled_timeout_in_container_(this->items_,
component, name_cstr,
true) ||
158 has_cancelled_timeout_in_container_(this->to_add_,
component, name_cstr,
true))) {
160#ifdef ESPHOME_DEBUG_SCHEDULER
161 ESP_LOGD(TAG,
"Skipping retry '%s' - found cancelled item", name_cstr);
173 this->to_add_.push_back(std::move(item));
176void HOT Scheduler::set_timeout(Component *
component,
const char *name, uint32_t timeout, std::function<
void()> func) {
177 this->set_timer_common_(
component, SchedulerItem::TIMEOUT,
true, name, timeout, std::move(func));
180void HOT Scheduler::set_timeout(Component *
component,
const std::string &name, uint32_t timeout,
181 std::function<
void()> func) {
182 this->set_timer_common_(
component, SchedulerItem::TIMEOUT,
false, &name, timeout, std::move(func));
184bool HOT Scheduler::cancel_timeout(Component *
component,
const std::string &name) {
185 return this->cancel_item_(
component,
false, &name, SchedulerItem::TIMEOUT);
187bool HOT Scheduler::cancel_timeout(Component *
component,
const char *name) {
188 return this->cancel_item_(
component,
true, name, SchedulerItem::TIMEOUT);
190void HOT Scheduler::set_interval(Component *
component,
const std::string &name, uint32_t interval,
191 std::function<
void()> func) {
192 this->set_timer_common_(
component, SchedulerItem::INTERVAL,
false, &name, interval, std::move(func));
195void HOT Scheduler::set_interval(Component *
component,
const char *name, uint32_t interval,
196 std::function<
void()> func) {
197 this->set_timer_common_(
component, SchedulerItem::INTERVAL,
true, name, interval, std::move(func));
199bool HOT Scheduler::cancel_interval(Component *
component,
const std::string &name) {
200 return this->cancel_item_(
component,
false, &name, SchedulerItem::INTERVAL);
202bool HOT Scheduler::cancel_interval(Component *
component,
const char *name) {
203 return this->cancel_item_(
component,
true, name, SchedulerItem::INTERVAL);
208 uint8_t retry_countdown;
212 float backoff_increase_factor;
213 Scheduler *scheduler;
217 RetryResult const retry_result = args->func(--args->retry_countdown);
221 args->scheduler->set_timer_common_(
222 args->component, Scheduler::SchedulerItem::TIMEOUT,
false, &args->name, args->current_interval,
223 [args]() { retry_handler(args); },
true);
225 args->current_interval *= args->backoff_increase_factor;
228void HOT Scheduler::set_retry_common_(Component *
component,
bool is_static_string,
const void *name_ptr,
229 uint32_t initial_wait_time, uint8_t max_attempts,
230 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
231 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
233 if (name_cstr !=
nullptr)
234 this->cancel_retry(
component, name_cstr);
236 if (initial_wait_time == SCHEDULER_DONT_RUN)
239 ESP_LOGVV(TAG,
"set_retry(name='%s', initial_wait_time=%" PRIu32
", max_attempts=%u, backoff_factor=%0.1f)",
240 name_cstr ? name_cstr :
"", initial_wait_time, max_attempts, backoff_increase_factor);
242 if (backoff_increase_factor < 0.0001) {
243 ESP_LOGE(TAG,
"backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor, name_cstr ? name_cstr :
"");
244 backoff_increase_factor = 1;
247 auto args = std::make_shared<RetryArgs>();
248 args->func = std::move(func);
249 args->retry_countdown = max_attempts;
250 args->current_interval = initial_wait_time;
252 args->name = name_cstr ? name_cstr :
"";
253 args->backoff_increase_factor = backoff_increase_factor;
254 args->scheduler =
this;
257 this->set_timer_common_(
258 component, SchedulerItem::TIMEOUT,
false, &args->name, 0, [args]() { retry_handler(args); },
262void HOT Scheduler::set_retry(Component *
component,
const std::string &name, uint32_t initial_wait_time,
263 uint8_t max_attempts, std::function<
RetryResult(uint8_t)> func,
264 float backoff_increase_factor) {
265 this->set_retry_common_(
component,
false, &name, initial_wait_time, max_attempts, std::move(func),
266 backoff_increase_factor);
269void HOT Scheduler::set_retry(Component *
component,
const char *name, uint32_t initial_wait_time, uint8_t max_attempts,
270 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
271 this->set_retry_common_(
component,
true, name, initial_wait_time, max_attempts, std::move(func),
272 backoff_increase_factor);
274bool HOT Scheduler::cancel_retry(Component *
component,
const std::string &name) {
275 return this->cancel_retry(
component, name.c_str());
278bool HOT Scheduler::cancel_retry(Component *
component,
const char *name) {
280 LockGuard guard{this->lock_};
281 return this->cancel_item_locked_(
component, name, SchedulerItem::TIMEOUT,
true);
284optional<uint32_t> HOT Scheduler::next_schedule_in(uint32_t now) {
290 if (this->cleanup_() == 0)
293 auto &item = this->items_[0];
295 const auto now_64 = this->millis_64_(now);
296 const uint64_t next_exec = item->get_next_execution();
297 if (next_exec < now_64)
299 return next_exec - now_64;
302void Scheduler::full_cleanup_removed_items_() {
308 LockGuard guard{this->lock_};
310 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
313 for (
auto &item : this->items_) {
314 if (!is_item_removed_(item.get())) {
315 valid_items.push_back(std::move(item));
318 this->recycle_item_(std::move(item));
323 this->items_ = std::move(valid_items);
325 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
326 this->to_remove_ = 0;
329void HOT Scheduler::call(uint32_t now) {
330#ifndef ESPHOME_THREAD_SINGLE
331 this->process_defer_queue_(now);
335 const auto now_64 = this->millis_64_(now);
336 this->process_to_add();
339 bool has_added_items =
false;
341#ifdef ESPHOME_DEBUG_SCHEDULER
342 static uint64_t last_print = 0;
344 if (now_64 - last_print > 2000) {
346 std::vector<std::unique_ptr<SchedulerItem>> old_items;
347#ifdef ESPHOME_THREAD_MULTI_ATOMICS
348 const auto last_dbg = this->last_millis_.load(std::memory_order_relaxed);
349 const auto major_dbg = this->millis_major_.load(std::memory_order_relaxed);
350 ESP_LOGD(TAG,
"Items: count=%zu, pool=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(),
351 this->scheduler_item_pool_.size(), now_64, major_dbg, last_dbg);
353 ESP_LOGD(TAG,
"Items: count=%zu, pool=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(),
354 this->scheduler_item_pool_.size(), now_64, this->millis_major_, this->last_millis_);
358 while (!this->items_.empty()) {
359 std::unique_ptr<SchedulerItem> item;
361 LockGuard guard{this->lock_};
362 item = std::move(this->items_[0]);
366 const char *name = item->get_name();
367 bool is_cancelled = is_item_removed_(item.get());
368 ESP_LOGD(TAG,
" %s '%s/%s' interval=%" PRIu32
" next_execution in %" PRIu64
"ms at %" PRIu64
"%s",
369 item->get_type_str(), LOG_STR_ARG(item->get_source()), name ? name :
"(null)", item->interval,
370 item->get_next_execution() - now_64, item->get_next_execution(), is_cancelled ?
" [CANCELLED]" :
"");
372 old_items.push_back(std::move(item));
377 LockGuard guard{this->lock_};
378 this->items_ = std::move(old_items);
380 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
391 if (this->to_remove_ >= MAX_LOGICALLY_DELETED_ITEMS) {
392 this->full_cleanup_removed_items_();
394 while (!this->items_.empty()) {
396 auto &item = this->items_[0];
397 if (item->get_next_execution() > now_64) {
402 if (item->component !=
nullptr && item->component->is_failed()) {
403 LockGuard guard{this->lock_};
412#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
415 LockGuard guard{this->lock_};
416 if (is_item_removed_(item.get())) {
424 if (is_item_removed_(item.get())) {
425 LockGuard guard{this->lock_};
432#ifdef ESPHOME_DEBUG_SCHEDULER
433 const char *item_name = item->get_name();
434 ESP_LOGV(TAG,
"Running %s '%s/%s' with interval=%" PRIu32
" next_execution=%" PRIu64
" (now=%" PRIu64
")",
435 item->get_type_str(), LOG_STR_ARG(item->get_source()), item_name ? item_name :
"(null)", item->interval,
436 item->get_next_execution(), now_64);
442 now = this->execute_item_(item.get(), now);
444 LockGuard guard{this->lock_};
446 auto executed_item = std::move(this->items_[0]);
451 if (executed_item->remove) {
457 if (executed_item->type == SchedulerItem::INTERVAL) {
458 executed_item->set_next_execution(now_64 + executed_item->interval);
461 this->to_add_.push_back(std::move(executed_item));
464 this->recycle_item_(std::move(executed_item));
467 has_added_items |= !this->to_add_.empty();
470 if (has_added_items) {
471 this->process_to_add();
474void HOT Scheduler::process_to_add() {
475 LockGuard guard{this->lock_};
476 for (
auto &it : this->to_add_) {
477 if (is_item_removed_(it.get())) {
479 this->recycle_item_(std::move(it));
483 this->items_.push_back(std::move(it));
484 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
486 this->to_add_.clear();
488size_t HOT Scheduler::cleanup_() {
496 if (this->to_remove_ == 0)
497 return this->items_.size();
507 LockGuard guard{this->lock_};
508 while (!this->items_.empty()) {
509 auto &item = this->items_[0];
515 return this->items_.size();
517void HOT Scheduler::pop_raw_() {
518 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
521 this->recycle_item_(std::move(this->items_.back()));
523 this->items_.pop_back();
527uint32_t HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
529 WarnIfComponentBlockingGuard guard{item->component, now};
531 return guard.finish();
535bool HOT Scheduler::cancel_item_(Component *
component,
bool is_static_string,
const void *name_ptr,
536 SchedulerItem::Type
type) {
538 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
541 LockGuard guard{this->lock_};
542 return this->cancel_item_locked_(
component, name_cstr,
type);
546bool HOT Scheduler::cancel_item_locked_(Component *
component,
const char *name_cstr, SchedulerItem::Type
type,
549 if (name_cstr ==
nullptr) {
553 size_t total_cancelled = 0;
556#ifndef ESPHOME_THREAD_SINGLE
558 if (
type == SchedulerItem::TIMEOUT) {
559 total_cancelled += this->mark_matching_items_removed_(this->defer_queue_,
component, name_cstr,
type, match_retry);
566 if (!this->items_.empty()) {
567 auto &last_item = this->items_.back();
568 if (this->matches_item_(last_item,
component, name_cstr,
type, match_retry)) {
569 this->recycle_item_(std::move(this->items_.back()));
570 this->items_.pop_back();
574 size_t heap_cancelled = this->mark_matching_items_removed_(this->items_,
component, name_cstr,
type, match_retry);
575 total_cancelled += heap_cancelled;
576 this->to_remove_ += heap_cancelled;
580 total_cancelled += this->mark_matching_items_removed_(this->to_add_,
component, name_cstr,
type, match_retry);
582 return total_cancelled > 0;
585uint64_t Scheduler::millis_64_(uint32_t now) {
599#ifdef ESPHOME_THREAD_SINGLE
605 uint16_t major = this->millis_major_;
609 if (now < last && (last - now) > HALF_MAX_UINT32) {
610 this->millis_major_++;
612#ifdef ESPHOME_DEBUG_SCHEDULER
613 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
619 this->last_millis_ = now;
623 return now + (
static_cast<uint64_t
>(major) << 32);
625#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
633 uint16_t major = this->millis_major_;
638 static const uint32_t ROLLOVER_WINDOW = 10000;
641 bool near_rollover = (last > (std::numeric_limits<uint32_t>::max() - ROLLOVER_WINDOW)) || (now < ROLLOVER_WINDOW);
643 if (near_rollover || (now < last && (last - now) > HALF_MAX_UINT32)) {
645 LockGuard guard{this->lock_};
647 last = this->last_millis_;
649 if (now < last && (last - now) > HALF_MAX_UINT32) {
651 this->millis_major_++;
653#ifdef ESPHOME_DEBUG_SCHEDULER
654 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
658 this->last_millis_ = now;
659 }
else if (now > last) {
666 this->last_millis_ = now;
672 return now + (
static_cast<uint64_t
>(major) << 32);
674#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
685 uint16_t major = this->millis_major_.load(std::memory_order_acquire);
693 uint32_t last = this->last_millis_.load(std::memory_order_acquire);
697 if (now < last && (last - now) > HALF_MAX_UINT32) {
699 LockGuard guard{this->lock_};
701 last = this->last_millis_.load(std::memory_order_relaxed);
703 if (now < last && (last - now) > HALF_MAX_UINT32) {
705 this->millis_major_.fetch_add(1, std::memory_order_relaxed);
707#ifdef ESPHOME_DEBUG_SCHEDULER
708 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
716 this->last_millis_.store(now, std::memory_order_release);
720 while (now > last && (now - last) < HALF_MAX_UINT32) {
721 if (this->last_millis_.compare_exchange_weak(last, now,
722 std::memory_order_release,
723 std::memory_order_relaxed)) {
730 uint16_t major_end = this->millis_major_.load(std::memory_order_relaxed);
731 if (major_end == major)
732 return now + (
static_cast<uint64_t
>(major) << 32);
735 __builtin_unreachable();
739 "No platform threading model defined. One of ESPHOME_THREAD_SINGLE, ESPHOME_THREAD_MULTI_NO_ATOMICS, or ESPHOME_THREAD_MULTI_ATOMICS must be defined."
743bool HOT Scheduler::SchedulerItem::cmp(
const std::unique_ptr<SchedulerItem> &a,
744 const std::unique_ptr<SchedulerItem> &b) {
747 return (a->next_execution_high_ == b->next_execution_high_) ? (a->next_execution_low_ > b->next_execution_low_)
748 : (a->next_execution_high_ > b->next_execution_high_);
751void Scheduler::recycle_item_(std::unique_ptr<SchedulerItem> item) {
755 if (this->scheduler_item_pool_.size() < MAX_POOL_SIZE) {
757 item->callback =
nullptr;
759 item->clear_dynamic_name();
760 this->scheduler_item_pool_.push_back(std::move(item));
761#ifdef ESPHOME_DEBUG_SCHEDULER
762 ESP_LOGD(TAG,
"Recycled item to pool (pool size now: %zu)", this->scheduler_item_pool_.size());
765#ifdef ESPHOME_DEBUG_SCHEDULER
766 ESP_LOGD(TAG,
"Pool full (size: %zu), deleting item", this->scheduler_item_pool_.size());
772#ifdef ESPHOME_DEBUG_SCHEDULER
773void Scheduler::debug_log_timer_(
const SchedulerItem *item,
bool is_static_string,
const char *name_cstr,
774 SchedulerItem::Type
type, uint32_t
delay, uint64_t now) {
776 if (is_static_string && name_cstr !=
nullptr) {
777 validate_static_string(name_cstr);
781 const char *type_str = (
type == SchedulerItem::TIMEOUT) ?
"timeout" :
"interval";
782 if (
type == SchedulerItem::TIMEOUT) {
783 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
784 name_cstr ? name_cstr :
"(null)", type_str,
delay);
786 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
", offset=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
787 name_cstr ? name_cstr :
"(null)", type_str,
delay,
788 static_cast<uint32_t>(item->get_next_execution() - now));
void set_current_component(Component *component)
const 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.