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_};
89 this->cancel_item_locked_(component, name_cstr,
type);
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)");
116 item->component = component;
117 item->set_name(name_cstr, !is_static_string);
119 item->callback = std::move(func);
122#ifdef ESPHOME_THREAD_MULTI_ATOMICS
123 item->remove.store(
false, std::memory_order_relaxed);
125 item->remove =
false;
127 item->is_retry = is_retry;
129#ifndef ESPHOME_THREAD_SINGLE
132 if (
delay == 0 &&
type == SchedulerItem::TIMEOUT) {
135 this->cancel_item_locked_(component, name_cstr,
type);
137 this->defer_queue_.push_back(std::move(item));
143 if (
type == SchedulerItem::INTERVAL) {
144 item->interval =
delay;
148 item->set_next_execution(now + offset);
149 ESP_LOGV(TAG,
"Scheduler interval for %s is %" PRIu32
"ms, offset %" PRIu32
"ms", name_cstr ? name_cstr :
"",
delay,
153 item->set_next_execution(now +
delay);
156#ifdef ESPHOME_DEBUG_SCHEDULER
158 if (is_static_string && name_cstr !=
nullptr) {
159 validate_static_string(name_cstr);
163 const char *type_str = (
type == SchedulerItem::TIMEOUT) ?
"timeout" :
"interval";
164 if (
type == SchedulerItem::TIMEOUT) {
165 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
166 name_cstr ? name_cstr :
"(null)", type_str,
delay);
168 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
", offset=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
169 name_cstr ? name_cstr :
"(null)", type_str,
delay,
170 static_cast<uint32_t>(item->get_next_execution() - now));
175 if (is_retry && name_cstr !=
nullptr &&
type == SchedulerItem::TIMEOUT &&
176 (has_cancelled_timeout_in_container_(this->items_, component, name_cstr,
true) ||
177 has_cancelled_timeout_in_container_(this->to_add_, component, name_cstr,
true))) {
179#ifdef ESPHOME_DEBUG_SCHEDULER
180 ESP_LOGD(TAG,
"Skipping retry '%s' - found cancelled item", name_cstr);
188 this->cancel_item_locked_(component, name_cstr,
type);
192 this->to_add_.push_back(std::move(item));
195void HOT Scheduler::set_timeout(Component *component,
const char *name, uint32_t timeout, std::function<
void()> func) {
196 this->set_timer_common_(component, SchedulerItem::TIMEOUT,
true, name, timeout, std::move(func));
199void HOT Scheduler::set_timeout(Component *component,
const std::string &name, uint32_t timeout,
200 std::function<
void()> func) {
201 this->set_timer_common_(component, SchedulerItem::TIMEOUT,
false, &name, timeout, std::move(func));
203bool HOT Scheduler::cancel_timeout(Component *component,
const std::string &name) {
204 return this->cancel_item_(component,
false, &name, SchedulerItem::TIMEOUT);
206bool HOT Scheduler::cancel_timeout(Component *component,
const char *name) {
207 return this->cancel_item_(component,
true, name, SchedulerItem::TIMEOUT);
209void HOT Scheduler::set_interval(Component *component,
const std::string &name, uint32_t interval,
210 std::function<
void()> func) {
211 this->set_timer_common_(component, SchedulerItem::INTERVAL,
false, &name, interval, std::move(func));
214void HOT Scheduler::set_interval(Component *component,
const char *name, uint32_t interval,
215 std::function<
void()> func) {
216 this->set_timer_common_(component, SchedulerItem::INTERVAL,
true, name, interval, std::move(func));
218bool HOT Scheduler::cancel_interval(Component *component,
const std::string &name) {
219 return this->cancel_item_(component,
false, &name, SchedulerItem::INTERVAL);
221bool HOT Scheduler::cancel_interval(Component *component,
const char *name) {
222 return this->cancel_item_(component,
true, name, SchedulerItem::INTERVAL);
227 uint8_t retry_countdown;
229 Component *component;
231 float backoff_increase_factor;
232 Scheduler *scheduler;
236 RetryResult const retry_result = args->func(--args->retry_countdown);
240 args->scheduler->set_timer_common_(
241 args->component, Scheduler::SchedulerItem::TIMEOUT,
false, &args->name, args->current_interval,
242 [args]() { retry_handler(args); },
true);
244 args->current_interval *= args->backoff_increase_factor;
247void HOT Scheduler::set_retry_common_(Component *component,
bool is_static_string,
const void *name_ptr,
248 uint32_t initial_wait_time, uint8_t max_attempts,
249 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
250 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
252 if (name_cstr !=
nullptr)
253 this->cancel_retry(component, name_cstr);
255 if (initial_wait_time == SCHEDULER_DONT_RUN)
258 ESP_LOGVV(TAG,
"set_retry(name='%s', initial_wait_time=%" PRIu32
", max_attempts=%u, backoff_factor=%0.1f)",
259 name_cstr ? name_cstr :
"", initial_wait_time, max_attempts, backoff_increase_factor);
261 if (backoff_increase_factor < 0.0001) {
262 ESP_LOGE(TAG,
"backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor, name_cstr ? name_cstr :
"");
263 backoff_increase_factor = 1;
266 auto args = std::make_shared<RetryArgs>();
267 args->func = std::move(func);
268 args->retry_countdown = max_attempts;
269 args->current_interval = initial_wait_time;
270 args->component = component;
271 args->name = name_cstr ? name_cstr :
"";
272 args->backoff_increase_factor = backoff_increase_factor;
273 args->scheduler =
this;
276 this->set_timer_common_(
277 component, SchedulerItem::TIMEOUT,
false, &args->name, 0, [args]() { retry_handler(args); },
281void HOT Scheduler::set_retry(Component *component,
const std::string &name, uint32_t initial_wait_time,
282 uint8_t max_attempts, std::function<
RetryResult(uint8_t)> func,
283 float backoff_increase_factor) {
284 this->set_retry_common_(component,
false, &name, initial_wait_time, max_attempts, std::move(func),
285 backoff_increase_factor);
288void HOT Scheduler::set_retry(Component *component,
const char *name, uint32_t initial_wait_time, uint8_t max_attempts,
289 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
290 this->set_retry_common_(component,
true, name, initial_wait_time, max_attempts, std::move(func),
291 backoff_increase_factor);
293bool HOT Scheduler::cancel_retry(Component *component,
const std::string &name) {
294 return this->cancel_retry(component, name.c_str());
297bool HOT Scheduler::cancel_retry(Component *component,
const char *name) {
299 LockGuard guard{this->lock_};
300 return this->cancel_item_locked_(component, name, SchedulerItem::TIMEOUT,
true);
303optional<uint32_t> HOT Scheduler::next_schedule_in(uint32_t now) {
309 if (this->cleanup_() == 0)
312 auto &item = this->items_[0];
314 const auto now_64 = this->millis_64_(now);
315 const uint64_t next_exec = item->get_next_execution();
316 if (next_exec < now_64)
318 return next_exec - now_64;
320void HOT Scheduler::call(uint32_t now) {
321#ifndef ESPHOME_THREAD_SINGLE
334 while (!this->defer_queue_.empty()) {
338 std::unique_ptr<SchedulerItem> item;
340 LockGuard lock(this->lock_);
341 item = std::move(this->defer_queue_.front());
342 this->defer_queue_.pop_front();
347 if (!this->should_skip_item_(item.get())) {
348 now = this->execute_item_(item.get(), now);
351 this->recycle_item_(std::move(item));
356 const auto now_64 = this->millis_64_(now);
357 this->process_to_add();
360 bool has_added_items =
false;
362#ifdef ESPHOME_DEBUG_SCHEDULER
363 static uint64_t last_print = 0;
365 if (now_64 - last_print > 2000) {
367 std::vector<std::unique_ptr<SchedulerItem>> old_items;
368#ifdef ESPHOME_THREAD_MULTI_ATOMICS
369 const auto last_dbg = this->last_millis_.load(std::memory_order_relaxed);
370 const auto major_dbg = this->millis_major_.load(std::memory_order_relaxed);
371 ESP_LOGD(TAG,
"Items: count=%zu, pool=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(),
372 this->scheduler_item_pool_.size(), now_64, major_dbg, last_dbg);
374 ESP_LOGD(TAG,
"Items: count=%zu, pool=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(),
375 this->scheduler_item_pool_.size(), now_64, this->millis_major_, this->last_millis_);
379 while (!this->items_.empty()) {
380 std::unique_ptr<SchedulerItem> item;
382 LockGuard guard{this->lock_};
383 item = std::move(this->items_[0]);
387 const char *name = item->get_name();
388 bool is_cancelled = is_item_removed_(item.get());
389 ESP_LOGD(TAG,
" %s '%s/%s' interval=%" PRIu32
" next_execution in %" PRIu64
"ms at %" PRIu64
"%s",
390 item->get_type_str(), LOG_STR_ARG(item->get_source()), name ? name :
"(null)", item->interval,
391 item->get_next_execution() - now_64, item->get_next_execution(), is_cancelled ?
" [CANCELLED]" :
"");
393 old_items.push_back(std::move(item));
398 LockGuard guard{this->lock_};
399 this->items_ = std::move(old_items);
401 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
412 if (this->to_remove_ >= MAX_LOGICALLY_DELETED_ITEMS) {
418 LockGuard guard{this->lock_};
420 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
423 for (
auto &item : this->items_) {
424 if (!is_item_removed_(item.get())) {
425 valid_items.push_back(std::move(item));
428 this->recycle_item_(std::move(item));
433 this->items_ = std::move(valid_items);
435 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
436 this->to_remove_ = 0;
438 while (!this->items_.empty()) {
440 auto &item = this->items_[0];
441 if (item->get_next_execution() > now_64) {
446 if (item->component !=
nullptr && item->component->is_failed()) {
447 LockGuard guard{this->lock_};
456#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
459 LockGuard guard{this->lock_};
460 if (is_item_removed_(item.get())) {
468 if (is_item_removed_(item.get())) {
469 LockGuard guard{this->lock_};
476#ifdef ESPHOME_DEBUG_SCHEDULER
477 const char *item_name = item->get_name();
478 ESP_LOGV(TAG,
"Running %s '%s/%s' with interval=%" PRIu32
" next_execution=%" PRIu64
" (now=%" PRIu64
")",
479 item->get_type_str(), LOG_STR_ARG(item->get_source()), item_name ? item_name :
"(null)", item->interval,
480 item->get_next_execution(), now_64);
486 now = this->execute_item_(item.get(), now);
488 LockGuard guard{this->lock_};
490 auto executed_item = std::move(this->items_[0]);
495 if (executed_item->remove) {
501 if (executed_item->type == SchedulerItem::INTERVAL) {
502 executed_item->set_next_execution(now_64 + executed_item->interval);
505 this->to_add_.push_back(std::move(executed_item));
508 this->recycle_item_(std::move(executed_item));
511 has_added_items |= !this->to_add_.empty();
514 if (has_added_items) {
515 this->process_to_add();
518void HOT Scheduler::process_to_add() {
519 LockGuard guard{this->lock_};
520 for (
auto &it : this->to_add_) {
521 if (is_item_removed_(it.get())) {
523 this->recycle_item_(std::move(it));
527 this->items_.push_back(std::move(it));
528 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
530 this->to_add_.clear();
532size_t HOT Scheduler::cleanup_() {
540 if (this->to_remove_ == 0)
541 return this->items_.size();
551 LockGuard guard{this->lock_};
552 while (!this->items_.empty()) {
553 auto &item = this->items_[0];
559 return this->items_.size();
561void HOT Scheduler::pop_raw_() {
562 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
565 this->recycle_item_(std::move(this->items_.back()));
567 this->items_.pop_back();
571uint32_t HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
573 WarnIfComponentBlockingGuard guard{item->component, now};
575 return guard.finish();
579bool HOT Scheduler::cancel_item_(Component *component,
bool is_static_string,
const void *name_ptr,
580 SchedulerItem::Type
type) {
582 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
585 LockGuard guard{this->lock_};
586 return this->cancel_item_locked_(component, name_cstr,
type);
590bool HOT Scheduler::cancel_item_locked_(Component *component,
const char *name_cstr, SchedulerItem::Type
type,
593 if (name_cstr ==
nullptr) {
597 size_t total_cancelled = 0;
600#ifndef ESPHOME_THREAD_SINGLE
602 if (
type == SchedulerItem::TIMEOUT) {
603 for (
auto &item : this->defer_queue_) {
604 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
605 this->mark_item_removed_(item.get());
615 if (!this->items_.empty()) {
616 auto &last_item = this->items_.back();
617 if (this->matches_item_(last_item, component, name_cstr,
type, match_retry)) {
618 this->recycle_item_(std::move(this->items_.back()));
619 this->items_.pop_back();
623 for (
auto &item : this->items_) {
624 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
625 this->mark_item_removed_(item.get());
633 for (
auto &item : this->to_add_) {
634 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
635 this->mark_item_removed_(item.get());
641 return total_cancelled > 0;
644uint64_t Scheduler::millis_64_(uint32_t now) {
658#ifdef ESPHOME_THREAD_SINGLE
664 uint16_t major = this->millis_major_;
668 if (now < last && (last - now) > HALF_MAX_UINT32) {
669 this->millis_major_++;
671#ifdef ESPHOME_DEBUG_SCHEDULER
672 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
678 this->last_millis_ = now;
682 return now + (
static_cast<uint64_t
>(major) << 32);
684#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
692 uint16_t major = this->millis_major_;
697 static const uint32_t ROLLOVER_WINDOW = 10000;
700 bool near_rollover = (last > (std::numeric_limits<uint32_t>::max() - ROLLOVER_WINDOW)) || (now < ROLLOVER_WINDOW);
702 if (near_rollover || (now < last && (last - now) > HALF_MAX_UINT32)) {
704 LockGuard guard{this->lock_};
706 last = this->last_millis_;
708 if (now < last && (last - now) > HALF_MAX_UINT32) {
710 this->millis_major_++;
712#ifdef ESPHOME_DEBUG_SCHEDULER
713 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
717 this->last_millis_ = now;
718 }
else if (now > last) {
725 this->last_millis_ = now;
731 return now + (
static_cast<uint64_t
>(major) << 32);
733#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
744 uint16_t major = this->millis_major_.load(std::memory_order_acquire);
752 uint32_t last = this->last_millis_.load(std::memory_order_acquire);
756 if (now < last && (last - now) > HALF_MAX_UINT32) {
758 LockGuard guard{this->lock_};
760 last = this->last_millis_.load(std::memory_order_relaxed);
762 if (now < last && (last - now) > HALF_MAX_UINT32) {
764 this->millis_major_.fetch_add(1, std::memory_order_relaxed);
766#ifdef ESPHOME_DEBUG_SCHEDULER
767 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
775 this->last_millis_.store(now, std::memory_order_release);
779 while (now > last && (now - last) < HALF_MAX_UINT32) {
780 if (this->last_millis_.compare_exchange_weak(last, now,
781 std::memory_order_release,
782 std::memory_order_relaxed)) {
789 uint16_t major_end = this->millis_major_.load(std::memory_order_relaxed);
790 if (major_end == major)
791 return now + (
static_cast<uint64_t
>(major) << 32);
794 __builtin_unreachable();
798 "No platform threading model defined. One of ESPHOME_THREAD_SINGLE, ESPHOME_THREAD_MULTI_NO_ATOMICS, or ESPHOME_THREAD_MULTI_ATOMICS must be defined."
802bool HOT Scheduler::SchedulerItem::cmp(
const std::unique_ptr<SchedulerItem> &a,
803 const std::unique_ptr<SchedulerItem> &b) {
806 return (a->next_execution_high_ == b->next_execution_high_) ? (a->next_execution_low_ > b->next_execution_low_)
807 : (a->next_execution_high_ > b->next_execution_high_);
810void Scheduler::recycle_item_(std::unique_ptr<SchedulerItem> item) {
814 if (this->scheduler_item_pool_.size() < MAX_POOL_SIZE) {
816 item->callback =
nullptr;
818 item->clear_dynamic_name();
819 this->scheduler_item_pool_.push_back(std::move(item));
820#ifdef ESPHOME_DEBUG_SCHEDULER
821 ESP_LOGD(TAG,
"Recycled item to pool (pool size now: %zu)", this->scheduler_item_pool_.size());
824#ifdef ESPHOME_DEBUG_SCHEDULER
825 ESP_LOGD(TAG,
"Pool full (size: %zu), deleting item", this->scheduler_item_pool_.size());
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.