12#if defined(USE_RP2) && (defined(USE_WIFI) || defined(USE_ETHERNET))
13#include <hardware/sync.h>
20#if defined(USE_RP2) && (defined(USE_WIFI) || defined(USE_ETHERNET))
23class SchedulerLockGuard {
26 ~SchedulerLockGuard() { restore_interrupts(this->state_); }
37static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
39static constexpr uint32_t MAX_INTERVAL_DELAY = 5000;
41#if defined(ESPHOME_LOG_HAS_VERBOSE) || defined(ESPHOME_DEBUG_SCHEDULER)
45struct SchedulerNameLog {
52 const char *
format(Scheduler::NameType name_type,
const char *static_name,
uint32_t hash_or_id) {
53 using NameType = Scheduler::NameType;
54 if (name_type == NameType::STATIC_STRING) {
58 ESPHOME_strncpy_P(
buffer, ESPHOME_PSTR(
"(null)"),
sizeof(
buffer));
60 }
else if (name_type == NameType::HASHED_STRING) {
61 ESPHOME_snprintf_P(
buffer,
sizeof(
buffer), ESPHOME_PSTR(
"hash:0x%08" PRIX32), hash_or_id);
63 }
else if (name_type == NameType::NUMERIC_ID) {
64 ESPHOME_snprintf_P(
buffer,
sizeof(
buffer), ESPHOME_PSTR(
"id:%" PRIu32), hash_or_id);
66 }
else if (name_type == NameType::NUMERIC_ID_INTERNAL) {
67 ESPHOME_snprintf_P(
buffer,
sizeof(
buffer), ESPHOME_PSTR(
"iid:%" PRIu32), hash_or_id);
72 ESPHOME_snprintf_P(
buffer,
sizeof(
buffer), ESPHOME_PSTR(
"self:%p"),
73 const_cast<void *
>(
static_cast<const void *
>(static_name)));
83#ifdef ESPHOME_DEBUG_SCHEDULER
85static void validate_static_string(
const char *name) {
91 uintptr_t addr =
reinterpret_cast<uintptr_t
>(name);
95 uintptr_t stack_addr =
reinterpret_cast<uintptr_t
>(&stack_var);
99 if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
101 "WARNING: Scheduler name '%s' at %p appears to be on the stack - this is unsafe!\n"
102 " Stack reference at %p",
103 name, name, &stack_var);
108 static const char *static_str =
"test";
109 uintptr_t static_addr =
reinterpret_cast<uintptr_t
>(static_str);
112 if (addr > static_addr + 0x100000 || (static_addr > 0x100000 && addr < static_addr - 0x100000)) {
113 ESP_LOGW(TAG,
"WARNING: Scheduler name '%s' at %p might be on heap (static ref at %p)", name, name, static_str);
126 uint32_t max_offset = std::min(
delay / 2, MAX_INTERVAL_DELAY);
133void HOT Scheduler::set_timer_common_(Component *
component, SchedulerItem::Type
type, NameType name_type,
135 std::function<
void()> &&func,
bool skip_cancel,
const LogString *source) {
140 this->cancel_item_locked_(
component, name_type, static_name, hash_or_id,
type,
true);
152 if (
type == SchedulerItem::INTERVAL &&
delay == 0) [[unlikely]] {
153 ESP_LOGE(TAG,
"[%s] set_interval(0) would spin main loop - coercing to 1ms (use HighFrequencyLoopRequester)",
164 SchedulerItem *item = this->get_item_from_pool_locked_();
166 if (name_type == NameType::SELF_POINTER) {
167 item->source_name = source;
171 item->set_name(name_type, static_name, hash_or_id);
178 item->callback.~function();
179 new (&item->callback) std::function<
void()>(std::move(func));
181 this->set_item_removed_(item,
false);
185 auto *target = &this->to_add_;
187#ifndef ESPHOME_THREAD_SINGLE
190 if (
delay == 0 &&
type == SchedulerItem::TIMEOUT) {
192 target = &this->defer_queue_;
200 if (
type == SchedulerItem::INTERVAL) {
201 item->interval =
delay;
203 offset = this->calculate_interval_offset_(
delay);
204 item->set_next_execution(now_64 + offset);
207 item->set_next_execution(now_64 +
delay);
210#ifdef ESPHOME_DEBUG_SCHEDULER
211 this->debug_log_timer_(item, name_type, static_name, hash_or_id,
delay, now_64);
217 if (!skip_cancel && (name_type != NameType::STATIC_STRING || static_name !=
nullptr)) {
218 this->cancel_item_locked_(
component, name_type, static_name, hash_or_id,
type,
true);
220 target->push_back(item);
221 if (target == &this->to_add_) {
222 this->to_add_count_increment_locked_();
224#ifndef ESPHOME_THREAD_SINGLE
226 this->defer_count_increment_locked_();
230#ifdef ESPHOME_LOG_HAS_VERBOSE
232 if (
type == SchedulerItem::INTERVAL) {
233 SchedulerNameLog name_log;
234 ESP_LOGV(TAG,
"Scheduler interval for %s is %" PRIu32
"ms, offset %" PRIu32
"ms",
235 name_log.format(name_type, static_name, hash_or_id),
delay, offset);
239 if (!is_main_loop_thread()) [[unlikely]]
243void HOT Scheduler::set_timeout(Component *
component,
const char *name,
uint32_t timeout,
244 std::function<
void()> &&func) {
245 this->set_timer_common_(
component, SchedulerItem::TIMEOUT, NameType::STATIC_STRING, name, 0, timeout,
250 this->set_timer_common_(
component, SchedulerItem::TIMEOUT, NameType::NUMERIC_ID,
nullptr,
id, timeout,
253bool HOT Scheduler::cancel_timeout(Component *
component,
const char *name) {
254 return this->cancel_item_(
component, NameType::STATIC_STRING, name, 0, SchedulerItem::TIMEOUT);
257 return this->cancel_item_(
component, NameType::NUMERIC_ID,
nullptr,
id, SchedulerItem::TIMEOUT);
259void HOT Scheduler::set_interval(Component *
component,
const char *name,
uint32_t interval,
260 std::function<
void()> &&func) {
261 this->set_timer_common_(
component, SchedulerItem::INTERVAL, NameType::STATIC_STRING, name, 0, interval,
265 this->set_timer_common_(
component, SchedulerItem::INTERVAL, NameType::NUMERIC_ID,
nullptr,
id, interval,
268bool HOT Scheduler::cancel_interval(Component *
component,
const char *name) {
269 return this->cancel_item_(
component, NameType::STATIC_STRING, name, 0, SchedulerItem::INTERVAL);
272 return this->cancel_item_(
component, NameType::NUMERIC_ID,
nullptr,
id, SchedulerItem::INTERVAL);
279void HOT Scheduler::set_timeout(
const void *self,
uint32_t timeout, std::function<
void()> &&func) {
280 this->set_timer_common_(
nullptr, SchedulerItem::TIMEOUT, NameType::SELF_POINTER,
static_cast<const char *
>(self), 0,
281 timeout, std::move(func));
283void HOT Scheduler::set_interval(
const void *self,
uint32_t interval, std::function<
void()> &&func) {
284 this->set_timer_common_(
nullptr, SchedulerItem::INTERVAL, NameType::SELF_POINTER,
static_cast<const char *
>(self), 0,
285 interval, std::move(func));
287bool HOT Scheduler::cancel_timeout(
const void *self) {
288 return this->cancel_item_(
nullptr, NameType::SELF_POINTER,
static_cast<const char *
>(self), 0,
289 SchedulerItem::TIMEOUT);
291bool HOT Scheduler::cancel_interval(
const void *self) {
292 return this->cancel_item_(
nullptr, NameType::SELF_POINTER,
static_cast<const char *
>(self), 0,
293 SchedulerItem::INTERVAL);
296optional<uint32_t> HOT Scheduler::next_schedule_in(
uint32_t now) {
306#ifndef ESPHOME_THREAD_SINGLE
310 if (!this->defer_empty_())
316 if (!this->to_add_empty_())
321 if (!this->cleanup_())
324 SchedulerItem *item = this->items_[0];
325 const auto now_64 = this->millis_64_from_(now);
326 const uint64_t next_exec = item->get_next_execution();
327 if (next_exec < now_64)
329 return next_exec - now_64;
332void Scheduler::full_cleanup_removed_items_() {
342 for (
size_t read = 0; read < this->items_.size(); ++read) {
343 if (!is_item_removed_locked_(this->items_[read])) {
345 this->items_[write] = this->items_[read];
349 this->recycle_item_main_loop_(this->items_[read]);
352 this->items_.erase(this->items_.begin() + write, this->items_.end());
354 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
355 this->to_remove_clear_locked_();
358#ifndef ESPHOME_THREAD_SINGLE
359void Scheduler::compact_defer_queue_locked_() {
371 size_t remaining = this->defer_queue_.size() - this->defer_queue_front_;
372 for (
size_t i = 0; i < remaining; i++) {
373 this->defer_queue_[i] = this->defer_queue_[this->defer_queue_front_ + i];
377 this->defer_queue_.erase(this->defer_queue_.begin() + remaining, this->defer_queue_.end());
379void HOT Scheduler::process_defer_queue_slow_path_(
uint32_t &now) {
404 this->defer_count_clear_locked_();
405 size_t defer_queue_end = this->defer_queue_.size();
406 if (this->defer_queue_front_ >= defer_queue_end) {
407 this->lock_.unlock();
410 while (this->defer_queue_front_ < defer_queue_end) {
416 item = this->defer_queue_[this->defer_queue_front_];
417 this->defer_queue_[this->defer_queue_front_] =
nullptr;
418 this->defer_queue_front_++;
419 this->lock_.unlock();
423 if (!this->should_skip_item_(item)) {
424 now = this->execute_item_(item, now);
428 this->recycle_item_main_loop_(item);
431 this->cleanup_defer_queue_locked_();
432 this->lock_.unlock();
437#ifndef ESPHOME_THREAD_SINGLE
438 this->process_defer_queue_(now);
442 const auto now_64 = this->millis_64_from_(now);
443 this->process_to_add();
446 bool has_added_items =
false;
448#ifdef ESPHOME_DEBUG_SCHEDULER
449 static uint64_t last_print = 0;
451 if (now_64 - last_print > 2000) {
453 std::vector<SchedulerItem *> old_items;
454 ESP_LOGD(TAG,
"Items: count=%zu, pool=%zu, now=%" PRIu64, this->items_.size(), this->scheduler_item_pool_size_,
458 while (!this->items_.empty()) {
462 item = this->pop_raw_locked_();
465 SchedulerNameLog name_log;
466 bool is_cancelled = is_item_removed_(item);
467 ESP_LOGD(TAG,
" %s '%s/%s' interval=%" PRIu32
" next_execution in %" PRId64
"ms at %" PRIu64
"%s",
468 LOG_STR_ARG(item->get_type_str()), LOG_STR_ARG(item->get_source()),
469 name_log.format(item->get_name_type(), item->get_name(), item->get_name_hash_or_id()), item->interval,
470 (int64_t) (item->get_next_execution() - now_64), item->get_next_execution(),
471 is_cancelled ? LOG_STR_LITERAL(
" [CANCELLED]") : LOG_STR_LITERAL(
""));
473 old_items.push_back(item);
479 this->items_ = std::move(old_items);
481 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
492 if (this->to_remove_count_() >= MAX_LOGICALLY_DELETED_ITEMS) {
493 this->full_cleanup_removed_items_();
501 while (!this->items_.empty()) {
503 SchedulerItem *item = this->items_[0];
504 if (item->get_next_execution() > now_64) {
512#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
516 if (is_item_removed_locked_(item)) {
517 this->recycle_item_main_loop_(this->pop_raw_locked_());
518 this->to_remove_decrement_locked_();
524 if (is_item_removed_(item)) {
526 this->recycle_item_main_loop_(this->pop_raw_locked_());
527 this->to_remove_decrement_locked_();
533 if (this->is_item_failed_(item)) {
535 this->recycle_item_main_loop_(this->pop_raw_locked_());
539#ifdef ESPHOME_DEBUG_SCHEDULER
541 SchedulerNameLog name_log;
542 ESP_LOGV(TAG,
"Running %s '%s/%s' with interval=%" PRIu32
" next_execution=%" PRIu64
" (now=%" PRIu64
")",
543 LOG_STR_ARG(item->get_type_str()), LOG_STR_ARG(item->get_source()),
544 name_log.format(item->get_name_type(), item->get_name(), item->get_name_hash_or_id()), item->interval,
545 item->get_next_execution(), now_64);
552 now = this->execute_item_(item, now);
558 SchedulerItem *executed_item = this->pop_raw_locked_();
560 if (this->is_item_removed_locked_(executed_item)) {
562 this->to_remove_decrement_locked_();
563 this->recycle_item_main_loop_(executed_item);
564 has_added_items |= !this->to_add_.empty();
568 if (executed_item->type == SchedulerItem::INTERVAL) {
569 executed_item->set_next_execution(now_64 + executed_item->interval);
580 this->items_.push_back(executed_item);
581 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
584 this->recycle_item_main_loop_(executed_item);
587 has_added_items |= !this->to_add_.empty();
590 if (has_added_items) {
591 this->process_to_add();
594#ifdef ESPHOME_DEBUG_SCHEDULER
605 this->debug_verify_no_leak_();
612void HOT Scheduler::process_to_add_slow_path_() {
614 for (
auto *&it : this->to_add_) {
615 if (is_item_removed_locked_(it)) {
617 this->recycle_item_main_loop_(it);
622 this->items_.push_back(it);
623 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
625 this->to_add_.clear();
626 this->to_add_count_clear_locked_();
628bool HOT Scheduler::cleanup_slow_path_() {
638 while (!this->items_.empty()) {
639 SchedulerItem *item = this->items_[0];
640 if (!this->is_item_removed_locked_(item))
642 this->to_remove_decrement_locked_();
643 this->recycle_item_main_loop_(this->pop_raw_locked_());
645 return !this->items_.empty();
647Scheduler::SchedulerItem *HOT Scheduler::pop_raw_locked_() {
648 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
650 SchedulerItem *item = this->items_.back();
651 this->items_.pop_back();
662 const LogString *source;
663 if (item->get_name_type() == NameType::SELF_POINTER) {
665 source = item->source_name;
671 LoopBlockingGuard guard{
component, source, now};
683bool HOT Scheduler::cancel_item_(Component *
component, NameType name_type,
const char *static_name,
uint32_t hash_or_id,
684 SchedulerItem::Type
type) {
688 return this->cancel_item_locked_(
component, name_type, static_name, hash_or_id,
type);
697size_t Scheduler::mark_matching_items_removed_slow_locked_(std::vector<SchedulerItem *> &container,
698 Component *
component, NameType name_type,
699 const char *static_name,
uint32_t hash_or_id,
700 SchedulerItem::Type
type,
bool find_first) {
702 for (
auto *item : container) {
703 if (this->matches_item_locked_(item,
component, name_type, static_name, hash_or_id,
type)) {
704 this->set_item_removed_(item,
true);
713bool HOT Scheduler::cancel_item_locked_(Component *
component, NameType name_type,
const char *static_name,
714 uint32_t hash_or_id, SchedulerItem::Type
type,
bool find_first) {
716 if (name_type == NameType::STATIC_STRING && static_name ==
nullptr) {
720 size_t total_cancelled = 0;
722#ifndef ESPHOME_THREAD_SINGLE
724 if (
type == SchedulerItem::TIMEOUT) {
725 total_cancelled += this->mark_matching_items_removed_locked_(this->defer_queue_,
component, name_type, static_name,
726 hash_or_id,
type, find_first);
727 if (find_first && total_cancelled > 0)
738 size_t heap_cancelled = this->mark_matching_items_removed_locked_(this->items_,
component, name_type, static_name,
739 hash_or_id,
type, find_first);
740 total_cancelled += heap_cancelled;
741 this->to_remove_add_locked_(heap_cancelled);
742 if (find_first && total_cancelled > 0)
747 total_cancelled += this->mark_matching_items_removed_locked_(this->to_add_,
component, name_type, static_name,
748 hash_or_id,
type, find_first);
750 return total_cancelled > 0;
753bool HOT Scheduler::SchedulerItem::cmp(SchedulerItem *a, SchedulerItem *b) {
756 return (a->next_execution_high_ ==
b->next_execution_high_) ? (a->next_execution_low_ >
b->next_execution_low_)
757 : (a->next_execution_high_ >
b->next_execution_high_);
762void Scheduler::recycle_item_main_loop_(SchedulerItem *item) {
766 item->callback =
nullptr;
767 item->next_free = this->scheduler_item_pool_head_;
768 this->scheduler_item_pool_head_ = item;
769 this->scheduler_item_pool_size_++;
770#ifdef ESPHOME_DEBUG_SCHEDULER
771 ESP_LOGD(TAG,
"Recycled item to pool (pool size now: %zu)", this->scheduler_item_pool_size_);
783void __attribute__((noinline)) Scheduler::shrink_scheduler_vector_(std::vector<SchedulerItem *> *v) {
784 if (v->capacity() == v->size())
786 std::vector<SchedulerItem *> tmp;
787 tmp.reserve(v->size());
788 for (SchedulerItem *p : *v)
793void Scheduler::trim_freelist() {
795 SchedulerItem *item = this->scheduler_item_pool_head_;
797 while (item !=
nullptr) {
798 SchedulerItem *
next = item->next_free;
800#ifdef ESPHOME_DEBUG_SCHEDULER
801 this->debug_live_items_--;
806 this->scheduler_item_pool_head_ =
nullptr;
807 this->scheduler_item_pool_size_ = 0;
811 shrink_scheduler_vector_(&this->items_);
812 shrink_scheduler_vector_(&this->to_add_);
813#ifndef ESPHOME_THREAD_SINGLE
814 shrink_scheduler_vector_(&this->defer_queue_);
817#ifdef ESPHOME_DEBUG_SCHEDULER
818 ESP_LOGD(TAG,
"Freelist trimmed (%zu items freed)", freed);
824#ifdef ESPHOME_DEBUG_SCHEDULER
825void Scheduler::debug_log_timer_(
const SchedulerItem *item, NameType name_type,
const char *static_name,
828 if (name_type == NameType::STATIC_STRING && static_name !=
nullptr) {
829 validate_static_string(static_name);
833 SchedulerNameLog name_log;
834 const char *type_str = LOG_STR_ARG(item->get_type_str());
835 if (item->type == SchedulerItem::TIMEOUT) {
836 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
837 name_log.format(name_type, static_name, hash_or_id), type_str,
delay);
839 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
", offset=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
840 name_log.format(name_type, static_name, hash_or_id), type_str,
delay,
841 static_cast<uint32_t>(item->get_next_execution() - now));
848Scheduler::SchedulerItem *Scheduler::get_item_from_pool_locked_() {
849 if (this->scheduler_item_pool_head_ !=
nullptr) {
850 SchedulerItem *item = this->scheduler_item_pool_head_;
851 this->scheduler_item_pool_head_ = item->next_free;
852 this->scheduler_item_pool_size_--;
853#ifdef ESPHOME_DEBUG_SCHEDULER
854 ESP_LOGD(TAG,
"Reused item from pool (pool size now: %zu)", this->scheduler_item_pool_size_);
858#ifdef ESPHOME_DEBUG_SCHEDULER
859 ESP_LOGD(TAG,
"Allocated new item (pool empty)");
861 auto *item =
new SchedulerItem();
862#ifdef ESPHOME_DEBUG_SCHEDULER
863 this->debug_live_items_++;
868#ifdef ESPHOME_DEBUG_SCHEDULER
869bool Scheduler::debug_verify_no_leak_()
const {
872 size_t accounted = this->items_.size() + this->to_add_.size() + this->scheduler_item_pool_size_;
873#ifndef ESPHOME_THREAD_SINGLE
874 accounted += this->defer_queue_.size();
876 if (accounted != this->debug_live_items_) {
878 "SCHEDULER LEAK DETECTED: live=%" PRIu32
" but accounted=%" PRIu32
" (items=%" PRIu32
" to_add=%" PRIu32
880#ifndef ESPHOME_THREAD_SINGLE
884 static_cast<uint32_t>(this->debug_live_items_),
static_cast<uint32_t>(accounted),
885 static_cast<uint32_t>(this->items_.size()),
static_cast<uint32_t>(this->to_add_.size()),
886 static_cast<uint32_t>(this->scheduler_item_pool_size_)
887#ifndef ESPHOME_THREAD_SINGLE
889 static_cast<uint32_t>(this->defer_queue_.size())
void ESPHOME_ALWAYS_INLINE feed_wdt_with_time(uint32_t time)
Feed the task watchdog, hot entry.
const LogString * get_component_log_str() const ESPHOME_ALWAYS_INLINE
Get the integration where this component was declared as a LogString for logging.
Helper class that wraps a mutex with a RAII-style API.
Mutex implementation, with API based on the unavailable std::mutex.
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
const Component * component
ESPHOME_LOG_TAG(TAG, CRASH_LOG_TAG)
LockGuard SchedulerLockGuard
void wake_scheduler_threadsafe()
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
void HOT delay(uint32_t ms)
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint32_t SCHEDULER_DONT_RUN