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#ifdef ESPHOME_THREAD_MULTI_ATOMICS
122 item->remove.store(
false, std::memory_order_relaxed);
124 item->remove =
false;
126 item->is_retry = is_retry;
128#ifndef ESPHOME_THREAD_SINGLE
131 if (
delay == 0 &&
type == SchedulerItem::TIMEOUT) {
136 this->defer_queue_.push_back(std::move(item));
142 if (
type == SchedulerItem::INTERVAL) {
143 item->interval =
delay;
147 item->set_next_execution(now + offset);
148 ESP_LOGV(TAG,
"Scheduler interval for %s is %" PRIu32
"ms, offset %" PRIu32
"ms", name_cstr ? name_cstr :
"",
delay,
152 item->set_next_execution(now +
delay);
155#ifdef ESPHOME_DEBUG_SCHEDULER
157 if (is_static_string && name_cstr !=
nullptr) {
158 validate_static_string(name_cstr);
162 const char *type_str = (
type == SchedulerItem::TIMEOUT) ?
"timeout" :
"interval";
163 if (
type == SchedulerItem::TIMEOUT) {
164 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
165 name_cstr ? name_cstr :
"(null)", type_str,
delay);
167 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
", offset=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
168 name_cstr ? name_cstr :
"(null)", type_str,
delay,
169 static_cast<uint32_t>(item->get_next_execution() - now));
174 if (is_retry && name_cstr !=
nullptr &&
type == SchedulerItem::TIMEOUT &&
175 (has_cancelled_timeout_in_container_(this->items_,
component, name_cstr,
true) ||
176 has_cancelled_timeout_in_container_(this->to_add_,
component, name_cstr,
true))) {
178#ifdef ESPHOME_DEBUG_SCHEDULER
179 ESP_LOGD(TAG,
"Skipping retry '%s' - found cancelled item", name_cstr);
191 this->to_add_.push_back(std::move(item));
194void HOT Scheduler::set_timeout(Component *
component,
const char *name, uint32_t timeout, std::function<
void()> func) {
195 this->set_timer_common_(
component, SchedulerItem::TIMEOUT,
true, name, timeout, std::move(func));
198void HOT Scheduler::set_timeout(Component *
component,
const std::string &name, uint32_t timeout,
199 std::function<
void()> func) {
200 this->set_timer_common_(
component, SchedulerItem::TIMEOUT,
false, &name, timeout, std::move(func));
202bool HOT Scheduler::cancel_timeout(Component *
component,
const std::string &name) {
203 return this->cancel_item_(
component,
false, &name, SchedulerItem::TIMEOUT);
205bool HOT Scheduler::cancel_timeout(Component *
component,
const char *name) {
206 return this->cancel_item_(
component,
true, name, SchedulerItem::TIMEOUT);
208void HOT Scheduler::set_interval(Component *
component,
const std::string &name, uint32_t interval,
209 std::function<
void()> func) {
210 this->set_timer_common_(
component, SchedulerItem::INTERVAL,
false, &name, interval, std::move(func));
213void HOT Scheduler::set_interval(Component *
component,
const char *name, uint32_t interval,
214 std::function<
void()> func) {
215 this->set_timer_common_(
component, SchedulerItem::INTERVAL,
true, name, interval, std::move(func));
217bool HOT Scheduler::cancel_interval(Component *
component,
const std::string &name) {
218 return this->cancel_item_(
component,
false, &name, SchedulerItem::INTERVAL);
220bool HOT Scheduler::cancel_interval(Component *
component,
const char *name) {
221 return this->cancel_item_(
component,
true, name, SchedulerItem::INTERVAL);
226 uint8_t retry_countdown;
230 float backoff_increase_factor;
231 Scheduler *scheduler;
235 RetryResult const retry_result = args->func(--args->retry_countdown);
239 args->scheduler->set_timer_common_(
240 args->component, Scheduler::SchedulerItem::TIMEOUT,
false, &args->name, args->current_interval,
241 [args]() { retry_handler(args); },
true);
243 args->current_interval *= args->backoff_increase_factor;
246void HOT Scheduler::set_retry_common_(Component *
component,
bool is_static_string,
const void *name_ptr,
247 uint32_t initial_wait_time, uint8_t max_attempts,
248 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
249 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
251 if (name_cstr !=
nullptr)
252 this->cancel_retry(
component, name_cstr);
254 if (initial_wait_time == SCHEDULER_DONT_RUN)
257 ESP_LOGVV(TAG,
"set_retry(name='%s', initial_wait_time=%" PRIu32
", max_attempts=%u, backoff_factor=%0.1f)",
258 name_cstr ? name_cstr :
"", initial_wait_time, max_attempts, backoff_increase_factor);
260 if (backoff_increase_factor < 0.0001) {
261 ESP_LOGE(TAG,
"backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor, name_cstr ? name_cstr :
"");
262 backoff_increase_factor = 1;
265 auto args = std::make_shared<RetryArgs>();
266 args->func = std::move(func);
267 args->retry_countdown = max_attempts;
268 args->current_interval = initial_wait_time;
270 args->name = name_cstr ? name_cstr :
"";
271 args->backoff_increase_factor = backoff_increase_factor;
272 args->scheduler =
this;
275 this->set_timer_common_(
276 component, SchedulerItem::TIMEOUT,
false, &args->name, 0, [args]() { retry_handler(args); },
280void HOT Scheduler::set_retry(Component *
component,
const std::string &name, uint32_t initial_wait_time,
281 uint8_t max_attempts, std::function<
RetryResult(uint8_t)> func,
282 float backoff_increase_factor) {
283 this->set_retry_common_(
component,
false, &name, initial_wait_time, max_attempts, std::move(func),
284 backoff_increase_factor);
287void HOT Scheduler::set_retry(Component *
component,
const char *name, uint32_t initial_wait_time, uint8_t max_attempts,
288 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
289 this->set_retry_common_(
component,
true, name, initial_wait_time, max_attempts, std::move(func),
290 backoff_increase_factor);
292bool HOT Scheduler::cancel_retry(Component *
component,
const std::string &name) {
293 return this->cancel_retry(
component, name.c_str());
296bool HOT Scheduler::cancel_retry(Component *
component,
const char *name) {
298 LockGuard guard{this->lock_};
299 return this->cancel_item_locked_(
component, name, SchedulerItem::TIMEOUT,
true);
302optional<uint32_t> HOT Scheduler::next_schedule_in(uint32_t now) {
308 if (this->cleanup_() == 0)
311 auto &item = this->items_[0];
313 const auto now_64 = this->millis_64_(now);
314 const uint64_t next_exec = item->get_next_execution();
315 if (next_exec < now_64)
317 return next_exec - now_64;
319void HOT Scheduler::call(uint32_t now) {
320#ifndef ESPHOME_THREAD_SINGLE
333 while (!this->defer_queue_.empty()) {
337 std::unique_ptr<SchedulerItem> item;
339 LockGuard lock(this->lock_);
340 item = std::move(this->defer_queue_.front());
341 this->defer_queue_.pop_front();
346 if (!this->should_skip_item_(item.get())) {
347 now = this->execute_item_(item.get(), now);
350 this->recycle_item_(std::move(item));
355 const auto now_64 = this->millis_64_(now);
356 this->process_to_add();
359 bool has_added_items =
false;
361#ifdef ESPHOME_DEBUG_SCHEDULER
362 static uint64_t last_print = 0;
364 if (now_64 - last_print > 2000) {
366 std::vector<std::unique_ptr<SchedulerItem>> old_items;
367#ifdef ESPHOME_THREAD_MULTI_ATOMICS
368 const auto last_dbg = this->last_millis_.load(std::memory_order_relaxed);
369 const auto major_dbg = this->millis_major_.load(std::memory_order_relaxed);
370 ESP_LOGD(TAG,
"Items: count=%zu, pool=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(),
371 this->scheduler_item_pool_.size(), now_64, major_dbg, last_dbg);
373 ESP_LOGD(TAG,
"Items: count=%zu, pool=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(),
374 this->scheduler_item_pool_.size(), now_64, this->millis_major_, this->last_millis_);
378 while (!this->items_.empty()) {
379 std::unique_ptr<SchedulerItem> item;
381 LockGuard guard{this->lock_};
382 item = std::move(this->items_[0]);
386 const char *name = item->get_name();
387 bool is_cancelled = is_item_removed_(item.get());
388 ESP_LOGD(TAG,
" %s '%s/%s' interval=%" PRIu32
" next_execution in %" PRIu64
"ms at %" PRIu64
"%s",
389 item->get_type_str(), LOG_STR_ARG(item->get_source()), name ? name :
"(null)", item->interval,
390 item->get_next_execution() - now_64, item->get_next_execution(), is_cancelled ?
" [CANCELLED]" :
"");
392 old_items.push_back(std::move(item));
397 LockGuard guard{this->lock_};
398 this->items_ = std::move(old_items);
400 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
411 if (this->to_remove_ >= MAX_LOGICALLY_DELETED_ITEMS) {
417 LockGuard guard{this->lock_};
419 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
422 for (
auto &item : this->items_) {
423 if (!is_item_removed_(item.get())) {
424 valid_items.push_back(std::move(item));
427 this->recycle_item_(std::move(item));
432 this->items_ = std::move(valid_items);
434 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
435 this->to_remove_ = 0;
437 while (!this->items_.empty()) {
439 auto &item = this->items_[0];
440 if (item->get_next_execution() > now_64) {
445 if (item->component !=
nullptr && item->component->is_failed()) {
446 LockGuard guard{this->lock_};
455#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
458 LockGuard guard{this->lock_};
459 if (is_item_removed_(item.get())) {
467 if (is_item_removed_(item.get())) {
468 LockGuard guard{this->lock_};
475#ifdef ESPHOME_DEBUG_SCHEDULER
476 const char *item_name = item->get_name();
477 ESP_LOGV(TAG,
"Running %s '%s/%s' with interval=%" PRIu32
" next_execution=%" PRIu64
" (now=%" PRIu64
")",
478 item->get_type_str(), LOG_STR_ARG(item->get_source()), item_name ? item_name :
"(null)", item->interval,
479 item->get_next_execution(), now_64);
485 now = this->execute_item_(item.get(), now);
487 LockGuard guard{this->lock_};
489 auto executed_item = std::move(this->items_[0]);
494 if (executed_item->remove) {
500 if (executed_item->type == SchedulerItem::INTERVAL) {
501 executed_item->set_next_execution(now_64 + executed_item->interval);
504 this->to_add_.push_back(std::move(executed_item));
507 this->recycle_item_(std::move(executed_item));
510 has_added_items |= !this->to_add_.empty();
513 if (has_added_items) {
514 this->process_to_add();
517void HOT Scheduler::process_to_add() {
518 LockGuard guard{this->lock_};
519 for (
auto &it : this->to_add_) {
520 if (is_item_removed_(it.get())) {
522 this->recycle_item_(std::move(it));
526 this->items_.push_back(std::move(it));
527 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
529 this->to_add_.clear();
531size_t HOT Scheduler::cleanup_() {
539 if (this->to_remove_ == 0)
540 return this->items_.size();
550 LockGuard guard{this->lock_};
551 while (!this->items_.empty()) {
552 auto &item = this->items_[0];
558 return this->items_.size();
560void HOT Scheduler::pop_raw_() {
561 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
564 this->recycle_item_(std::move(this->items_.back()));
566 this->items_.pop_back();
570uint32_t HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
572 WarnIfComponentBlockingGuard guard{item->component, now};
574 return guard.finish();
578bool HOT Scheduler::cancel_item_(Component *
component,
bool is_static_string,
const void *name_ptr,
579 SchedulerItem::Type
type) {
581 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
584 LockGuard guard{this->lock_};
585 return this->cancel_item_locked_(
component, name_cstr,
type);
589bool HOT Scheduler::cancel_item_locked_(Component *
component,
const char *name_cstr, SchedulerItem::Type
type,
592 if (name_cstr ==
nullptr) {
596 size_t total_cancelled = 0;
599#ifndef ESPHOME_THREAD_SINGLE
601 if (
type == SchedulerItem::TIMEOUT) {
602 total_cancelled += this->mark_matching_items_removed_(this->defer_queue_,
component, name_cstr,
type, match_retry);
609 if (!this->items_.empty()) {
610 auto &last_item = this->items_.back();
611 if (this->matches_item_(last_item,
component, name_cstr,
type, match_retry)) {
612 this->recycle_item_(std::move(this->items_.back()));
613 this->items_.pop_back();
617 size_t heap_cancelled = this->mark_matching_items_removed_(this->items_,
component, name_cstr,
type, match_retry);
618 total_cancelled += heap_cancelled;
619 this->to_remove_ += heap_cancelled;
623 total_cancelled += this->mark_matching_items_removed_(this->to_add_,
component, name_cstr,
type, match_retry);
625 return total_cancelled > 0;
628uint64_t Scheduler::millis_64_(uint32_t now) {
642#ifdef ESPHOME_THREAD_SINGLE
648 uint16_t major = this->millis_major_;
652 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);
662 this->last_millis_ = now;
666 return now + (
static_cast<uint64_t
>(major) << 32);
668#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
676 uint16_t major = this->millis_major_;
681 static const uint32_t ROLLOVER_WINDOW = 10000;
684 bool near_rollover = (last > (std::numeric_limits<uint32_t>::max() - ROLLOVER_WINDOW)) || (now < ROLLOVER_WINDOW);
686 if (near_rollover || (now < last && (last - now) > HALF_MAX_UINT32)) {
688 LockGuard guard{this->lock_};
690 last = this->last_millis_;
692 if (now < last && (last - now) > HALF_MAX_UINT32) {
694 this->millis_major_++;
696#ifdef ESPHOME_DEBUG_SCHEDULER
697 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
701 this->last_millis_ = now;
702 }
else if (now > last) {
709 this->last_millis_ = now;
715 return now + (
static_cast<uint64_t
>(major) << 32);
717#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
728 uint16_t major = this->millis_major_.load(std::memory_order_acquire);
736 uint32_t last = this->last_millis_.load(std::memory_order_acquire);
740 if (now < last && (last - now) > HALF_MAX_UINT32) {
742 LockGuard guard{this->lock_};
744 last = this->last_millis_.load(std::memory_order_relaxed);
746 if (now < last && (last - now) > HALF_MAX_UINT32) {
748 this->millis_major_.fetch_add(1, std::memory_order_relaxed);
750#ifdef ESPHOME_DEBUG_SCHEDULER
751 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
759 this->last_millis_.store(now, std::memory_order_release);
763 while (now > last && (now - last) < HALF_MAX_UINT32) {
764 if (this->last_millis_.compare_exchange_weak(last, now,
765 std::memory_order_release,
766 std::memory_order_relaxed)) {
773 uint16_t major_end = this->millis_major_.load(std::memory_order_relaxed);
774 if (major_end == major)
775 return now + (
static_cast<uint64_t
>(major) << 32);
778 __builtin_unreachable();
782 "No platform threading model defined. One of ESPHOME_THREAD_SINGLE, ESPHOME_THREAD_MULTI_NO_ATOMICS, or ESPHOME_THREAD_MULTI_ATOMICS must be defined."
786bool HOT Scheduler::SchedulerItem::cmp(
const std::unique_ptr<SchedulerItem> &a,
787 const std::unique_ptr<SchedulerItem> &b) {
790 return (a->next_execution_high_ == b->next_execution_high_) ? (a->next_execution_low_ > b->next_execution_low_)
791 : (a->next_execution_high_ > b->next_execution_high_);
794void Scheduler::recycle_item_(std::unique_ptr<SchedulerItem> item) {
798 if (this->scheduler_item_pool_.size() < MAX_POOL_SIZE) {
800 item->callback =
nullptr;
802 item->clear_dynamic_name();
803 this->scheduler_item_pool_.push_back(std::move(item));
804#ifdef ESPHOME_DEBUG_SCHEDULER
805 ESP_LOGD(TAG,
"Recycled item to pool (pool size now: %zu)", this->scheduler_item_pool_.size());
808#ifdef ESPHOME_DEBUG_SCHEDULER
809 ESP_LOGD(TAG,
"Pool full (size: %zu), deleting item", this->scheduler_item_pool_.size());
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.