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);
68 const void *name_ptr, uint32_t
delay, std::function<
void()> func,
bool is_retry) {
70 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
72 if (
delay == SCHEDULER_DONT_RUN) {
75 this->cancel_item_locked_(component, name_cstr,
type);
80 auto item = make_unique<SchedulerItem>();
81 item->component = component;
82 item->set_name(name_cstr, !is_static_string);
84 item->callback = std::move(func);
86 item->is_retry = is_retry;
88#ifndef ESPHOME_THREAD_SINGLE
94 this->cancel_item_locked_(component, name_cstr,
type);
95 this->defer_queue_.push_back(std::move(item));
105 item->interval =
delay;
108 uint32_t offset = (uint32_t) (std::min(
delay / 2, MAX_INTERVAL_DELAY) *
random_float());
109 item->next_execution_ = now + offset;
110 ESP_LOGV(TAG,
"Scheduler interval for %s is %" PRIu32
"ms, offset %" PRIu32
"ms", name_cstr ? name_cstr :
"",
delay,
114 item->next_execution_ = now +
delay;
117#ifdef ESPHOME_DEBUG_SCHEDULER
119 if (is_static_string && name_cstr !=
nullptr) {
120 validate_static_string(name_cstr);
126 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
")", type_str, item->get_source(),
127 name_cstr ? name_cstr :
"(null)", type_str,
delay);
129 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
", offset=%" PRIu32
")", type_str, item->get_source(),
130 name_cstr ? name_cstr :
"(null)", type_str,
delay,
static_cast<uint32_t
>(item->next_execution_ - now));
138 (has_cancelled_timeout_in_container_(this->items_, component, name_cstr,
true) ||
139 has_cancelled_timeout_in_container_(this->to_add_, component, name_cstr,
true))) {
141#ifdef ESPHOME_DEBUG_SCHEDULER
142 ESP_LOGD(TAG,
"Skipping retry '%s' - found cancelled item", name_cstr);
149 this->cancel_item_locked_(component, name_cstr,
type);
152 this->to_add_.push_back(std::move(item));
160 std::function<
void()> func) {
170 std::function<
void()> func) {
175 std::function<
void()> func) {
187 uint8_t retry_countdown;
188 uint32_t current_interval;
191 float backoff_increase_factor;
196 RetryResult const retry_result = args->func(--args->retry_countdown);
200 args->scheduler->set_timer_common_(
202 [args]() { retry_handler(args); },
true);
204 args->current_interval *= args->backoff_increase_factor;
208 uint32_t initial_wait_time, uint8_t max_attempts,
209 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
210 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
212 if (name_cstr !=
nullptr)
215 if (initial_wait_time == SCHEDULER_DONT_RUN)
218 ESP_LOGVV(TAG,
"set_retry(name='%s', initial_wait_time=%" PRIu32
", max_attempts=%u, backoff_factor=%0.1f)",
219 name_cstr ? name_cstr :
"", initial_wait_time, max_attempts, backoff_increase_factor);
221 if (backoff_increase_factor < 0.0001) {
222 ESP_LOGE(TAG,
"backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor, name_cstr ? name_cstr :
"");
223 backoff_increase_factor = 1;
226 auto args = std::make_shared<RetryArgs>();
227 args->func = std::move(func);
228 args->retry_countdown = max_attempts;
229 args->current_interval = initial_wait_time;
230 args->component = component;
231 args->name = name_cstr ? name_cstr :
"";
232 args->backoff_increase_factor = backoff_increase_factor;
233 args->scheduler =
this;
242 uint8_t max_attempts, std::function<
RetryResult(uint8_t)> func,
243 float backoff_increase_factor) {
244 this->
set_retry_common_(component,
false, &name, initial_wait_time, max_attempts, std::move(func),
245 backoff_increase_factor);
249 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
250 this->
set_retry_common_(component,
true, name, initial_wait_time, max_attempts, std::move(func),
251 backoff_increase_factor);
272 auto &item = this->items_[0];
275 if (item->next_execution_ < now_64)
277 return item->next_execution_ - now_64;
280#ifndef ESPHOME_THREAD_SINGLE
293 while (!this->defer_queue_.empty()) {
297 std::unique_ptr<SchedulerItem> item;
300 item = std::move(this->defer_queue_.front());
301 this->defer_queue_.pop_front();
306 if (!this->should_skip_item_(item.get())) {
307 this->execute_item_(item.get(), now);
316#ifdef ESPHOME_DEBUG_SCHEDULER
317 static uint64_t last_print = 0;
319 if (now_64 - last_print > 2000) {
321 std::vector<std::unique_ptr<SchedulerItem>> old_items;
322#ifdef ESPHOME_THREAD_MULTI_ATOMICS
323 const auto last_dbg = this->last_millis_.load(std::memory_order_relaxed);
324 const auto major_dbg = this->millis_major_.load(std::memory_order_relaxed);
325 ESP_LOGD(TAG,
"Items: count=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(), now_64,
326 major_dbg, last_dbg);
328 ESP_LOGD(TAG,
"Items: count=%zu, now=%" PRIu64
" (%" PRIu16
", %" PRIu32
")", this->items_.size(), now_64,
329 this->millis_major_, this->last_millis_);
333 while (!this->items_.empty()) {
334 std::unique_ptr<SchedulerItem> item;
337 item = std::move(this->items_[0]);
341 const char *name = item->get_name();
342 ESP_LOGD(TAG,
" %s '%s/%s' interval=%" PRIu32
" next_execution in %" PRIu64
"ms at %" PRIu64,
343 item->get_type_str(), item->get_source(), name ? name :
"(null)", item->interval,
344 item->next_execution_ - now_64, item->next_execution_);
346 old_items.push_back(std::move(item));
352 this->items_ = std::move(old_items);
360 if (this->to_remove_ > MAX_LOGICALLY_DELETED_ITEMS) {
368 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
371 for (
auto &item : this->items_) {
373 valid_items.push_back(std::move(item));
378 this->items_ = std::move(valid_items);
381 this->to_remove_ = 0;
386 while (!this->items_.empty()) {
390 auto &item = this->items_[0];
391 if (item->next_execution_ > now_64) {
396 if (item->component !=
nullptr && item->component->is_failed()) {
401#ifdef ESPHOME_DEBUG_SCHEDULER
402 const char *item_name = item->get_name();
403 ESP_LOGV(TAG,
"Running %s '%s/%s' with interval=%" PRIu32
" next_execution=%" PRIu64
" (now=%" PRIu64
")",
404 item->get_type_str(), item->get_source(), item_name ? item_name :
"(null)", item->interval,
405 item->next_execution_, now_64);
411 this->execute_item_(item.get(), now);
418 auto item = std::move(this->items_[0]);
430 item->next_execution_ = now_64 + item->interval;
433 this->to_add_.push_back(std::move(item));
442 for (
auto &it : this->to_add_) {
447 this->items_.push_back(std::move(it));
450 this->to_add_.clear();
460 if (this->to_remove_ == 0)
461 return this->items_.size();
472 while (!this->items_.empty()) {
473 auto &item = this->items_[0];
479 return this->items_.size();
483 this->items_.pop_back();
487void HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
495bool HOT Scheduler::cancel_item_(Component *component,
bool is_static_string,
const void *name_ptr,
496 SchedulerItem::Type
type) {
498 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
501 LockGuard guard{this->lock_};
502 return this->cancel_item_locked_(component, name_cstr,
type);
506bool HOT Scheduler::cancel_item_locked_(Component *component,
const char *name_cstr, SchedulerItem::Type
type,
509 if (name_cstr ==
nullptr) {
513 size_t total_cancelled = 0;
516#ifndef ESPHOME_THREAD_SINGLE
519 for (
auto &item : this->defer_queue_) {
520 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
529 for (
auto &item : this->items_) {
530 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
538 for (
auto &item : this->to_add_) {
539 if (this->matches_item_(item, component, name_cstr,
type, match_retry)) {
546 return total_cancelled > 0;
563#ifdef ESPHOME_THREAD_SINGLE
569 uint16_t major = this->millis_major_;
570 uint32_t last = this->last_millis_;
573 if (now < last && (last - now) > HALF_MAX_UINT32) {
574 this->millis_major_++;
576#ifdef ESPHOME_DEBUG_SCHEDULER
577 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
583 this->last_millis_ = now;
587 return now + (
static_cast<uint64_t
>(major) << 32);
589#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
597 uint16_t major = this->millis_major_;
598 uint32_t last = this->last_millis_;
602 static const uint32_t ROLLOVER_WINDOW = 10000;
605 bool near_rollover = (last > (std::numeric_limits<uint32_t>::max() - ROLLOVER_WINDOW)) || (now < ROLLOVER_WINDOW);
607 if (near_rollover || (now < last && (last - now) > HALF_MAX_UINT32)) {
611 last = this->last_millis_;
613 if (now < last && (last - now) > HALF_MAX_UINT32) {
615 this->millis_major_++;
617#ifdef ESPHOME_DEBUG_SCHEDULER
618 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
622 this->last_millis_ = now;
623 }
else if (now > last) {
630 this->last_millis_ = now;
636 return now + (
static_cast<uint64_t
>(major) << 32);
638#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
649 uint16_t major = this->millis_major_.load(std::memory_order_acquire);
657 uint32_t last = this->last_millis_.load(std::memory_order_acquire);
661 if (now < last && (last - now) > HALF_MAX_UINT32) {
665 last = this->last_millis_.load(std::memory_order_relaxed);
667 if (now < last && (last - now) > HALF_MAX_UINT32) {
669 this->millis_major_.fetch_add(1, std::memory_order_relaxed);
671#ifdef ESPHOME_DEBUG_SCHEDULER
672 ESP_LOGD(TAG,
"Detected true 32-bit rollover at %" PRIu32
"ms (was %" PRIu32
")", now, last);
680 this->last_millis_.store(now, std::memory_order_release);
684 while (now > last && (now - last) < HALF_MAX_UINT32) {
685 if (this->last_millis_.compare_exchange_weak(last, now,
686 std::memory_order_release,
687 std::memory_order_relaxed)) {
694 uint16_t major_end = this->millis_major_.load(std::memory_order_relaxed);
695 if (major_end == major)
696 return now + (
static_cast<uint64_t
>(major) << 32);
699 __builtin_unreachable();
703 "No platform threading model defined. One of ESPHOME_THREAD_SINGLE, ESPHOME_THREAD_MULTI_NO_ATOMICS, or ESPHOME_THREAD_MULTI_ATOMICS must be defined."
708 const std::unique_ptr<SchedulerItem> &b) {
709 return a->next_execution_ > b->next_execution_;
void set_current_component(Component *component)
Helper class that wraps a mutex with a RAII-style API.
void set_retry_common_(Component *component, bool is_static_string, const void *name_ptr, uint32_t initial_wait_time, uint8_t max_attempts, std::function< RetryResult(uint8_t)> func, float backoff_increase_factor)
bool cancel_retry(Component *component, const std::string &name)
void set_timer_common_(Component *component, SchedulerItem::Type type, bool is_static_string, const void *name_ptr, uint32_t delay, std::function< void()> func, bool is_retry=false)
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)
bool cancel_interval(Component *component, const std::string &name)
void set_timeout(Component *component, const std::string &name, uint32_t timeout, std::function< void()> func)
void set_interval(Component *component, const std::string &name, uint32_t interval, std::function< void()> func)
uint64_t millis_64_(uint32_t now)
optional< uint32_t > next_schedule_in(uint32_t now)
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.
static bool cmp(const std::unique_ptr< SchedulerItem > &a, const std::unique_ptr< SchedulerItem > &b)