ESPHome 2025.12.0-dev
Loading...
Searching...
No Matches
scheduler.cpp
Go to the documentation of this file.
1#include "scheduler.h"
2
3#include "application.h"
5#include "esphome/core/hal.h"
7#include "esphome/core/log.h"
8#include <algorithm>
9#include <cinttypes>
10#include <cstring>
11#include <limits>
12
13namespace esphome {
14
15static const char *const TAG = "scheduler";
16
17// Memory pool configuration constants
18// Pool size of 5 matches typical usage patterns (2-4 active timers)
19// - Minimal memory overhead (~250 bytes on ESP32)
20// - Sufficient for most configs with a couple sensors/components
21// - Still prevents heap fragmentation and allocation stalls
22// - Complex setups with many timers will just allocate beyond the pool
23// See https://github.com/esphome/backlog/issues/52
24static constexpr size_t MAX_POOL_SIZE = 5;
25
26// Maximum number of logically deleted (cancelled) items before forcing cleanup.
27// Set to 5 to match the pool size - when we have as many cancelled items as our
28// pool can hold, it's time to clean up and recycle them.
29static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
30// Half the 32-bit range - used to detect rollovers vs normal time progression
31static constexpr uint32_t HALF_MAX_UINT32 = std::numeric_limits<uint32_t>::max() / 2;
32// max delay to start an interval sequence
33static constexpr uint32_t MAX_INTERVAL_DELAY = 5000;
34
35// Uncomment to debug scheduler
36// #define ESPHOME_DEBUG_SCHEDULER
37
38#ifdef ESPHOME_DEBUG_SCHEDULER
39// Helper to validate that a pointer looks like it's in static memory
40static void validate_static_string(const char *name) {
41 if (name == nullptr)
42 return;
43
44 // This is a heuristic check - stack and heap pointers are typically
45 // much higher in memory than static data
46 uintptr_t addr = reinterpret_cast<uintptr_t>(name);
47
48 // Create a stack variable to compare against
49 int stack_var;
50 uintptr_t stack_addr = reinterpret_cast<uintptr_t>(&stack_var);
51
52 // If the string pointer is near our stack variable, it's likely on the stack
53 // Using 8KB range as ESP32 main task stack is typically 8192 bytes
54 if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
55 ESP_LOGW(TAG,
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);
59 }
60
61 // Also check if it might be on the heap by seeing if it's in a very different range
62 // This is platform-specific but generally heap is allocated far from static memory
63 static const char *static_str = "test";
64 uintptr_t static_addr = reinterpret_cast<uintptr_t>(static_str);
65
66 // If the address is very far from known static memory, it might be heap
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);
69 }
70}
71#endif /* ESPHOME_DEBUG_SCHEDULER */
72
73// A note on locking: the `lock_` lock protects the `items_` and `to_add_` containers. It must be taken when writing to
74// them (i.e. when adding/removing items, but not when changing items). As items are only deleted from the loop task,
75// iterating over them from the loop task is fine; but iterating from any other context requires the lock to be held to
76// avoid the main thread modifying the list while it is being accessed.
77
78// Common implementation for both timeout and interval
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,
81 bool skip_cancel) {
82 // Get the name as const char*
83 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
84
85 if (delay == SCHEDULER_DONT_RUN) {
86 // Still need to cancel existing timer if name is not empty
87 if (!skip_cancel) {
88 LockGuard guard{this->lock_};
89 this->cancel_item_locked_(component, name_cstr, type);
90 }
91 return;
92 }
93
94 // Get fresh timestamp BEFORE taking lock - millis_64_ may need to acquire lock itself
95 const uint64_t now = this->millis_64_(millis());
96
97 // Take lock early to protect scheduler_item_pool_ access
98 LockGuard guard{this->lock_};
99
100 // Create and populate the scheduler item
101 std::unique_ptr<SchedulerItem> item;
102 if (!this->scheduler_item_pool_.empty()) {
103 // Reuse from pool
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());
108#endif
109 } else {
110 // Allocate new if pool is empty
111 item = make_unique<SchedulerItem>();
112#ifdef ESPHOME_DEBUG_SCHEDULER
113 ESP_LOGD(TAG, "Allocated new item (pool empty)");
114#endif
115 }
116 item->component = component;
117 item->set_name(name_cstr, !is_static_string);
118 item->type = type;
119 item->callback = std::move(func);
120 // Reset remove flag - recycled items may have been cancelled (remove=true) in previous use
121 this->set_item_removed_(item.get(), false);
122 item->is_retry = is_retry;
123
124#ifndef ESPHOME_THREAD_SINGLE
125 // Special handling for defer() (delay = 0, type = TIMEOUT)
126 // Single-core platforms don't need thread-safe defer handling
127 if (delay == 0 && type == SchedulerItem::TIMEOUT) {
128 // Put in defer queue for guaranteed FIFO execution
129 if (!skip_cancel) {
130 this->cancel_item_locked_(component, name_cstr, type);
131 }
132 this->defer_queue_.push_back(std::move(item));
133 return;
134 }
135#endif /* not ESPHOME_THREAD_SINGLE */
136
137 // Type-specific setup
138 if (type == SchedulerItem::INTERVAL) {
139 item->interval = delay;
140 // first execution happens immediately after a random smallish offset
141 // Calculate random offset (0 to min(interval/2, 5s))
142 uint32_t offset = (uint32_t) (std::min(delay / 2, MAX_INTERVAL_DELAY) * random_float());
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,
145 offset);
146 } else {
147 item->interval = 0;
148 item->set_next_execution(now + delay);
149 }
150
151#ifdef ESPHOME_DEBUG_SCHEDULER
152 this->debug_log_timer_(item.get(), is_static_string, name_cstr, type, delay, now);
153#endif /* ESPHOME_DEBUG_SCHEDULER */
154
155 // For retries, check if there's a cancelled timeout first
156 if (is_retry && name_cstr != nullptr && type == SchedulerItem::TIMEOUT &&
157 (has_cancelled_timeout_in_container_(this->items_, component, name_cstr, /* match_retry= */ true) ||
158 has_cancelled_timeout_in_container_(this->to_add_, component, name_cstr, /* match_retry= */ true))) {
159 // Skip scheduling - the retry was cancelled
160#ifdef ESPHOME_DEBUG_SCHEDULER
161 ESP_LOGD(TAG, "Skipping retry '%s' - found cancelled item", name_cstr);
162#endif
163 return;
164 }
165
166 // If name is provided, do atomic cancel-and-add (unless skip_cancel is true)
167 // Cancel existing items
168 if (!skip_cancel) {
169 this->cancel_item_locked_(component, name_cstr, type);
170 }
171 // Add new item directly to to_add_
172 // since we have the lock held
173 this->to_add_.push_back(std::move(item));
174}
175
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));
178}
179
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));
183}
184bool HOT Scheduler::cancel_timeout(Component *component, const std::string &name) {
185 return this->cancel_item_(component, false, &name, SchedulerItem::TIMEOUT);
186}
187bool HOT Scheduler::cancel_timeout(Component *component, const char *name) {
188 return this->cancel_item_(component, true, name, SchedulerItem::TIMEOUT);
189}
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));
193}
194
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));
198}
199bool HOT Scheduler::cancel_interval(Component *component, const std::string &name) {
200 return this->cancel_item_(component, false, &name, SchedulerItem::INTERVAL);
201}
202bool HOT Scheduler::cancel_interval(Component *component, const char *name) {
203 return this->cancel_item_(component, true, name, SchedulerItem::INTERVAL);
204}
205
206struct RetryArgs {
207 std::function<RetryResult(uint8_t)> func;
208 uint8_t retry_countdown;
209 uint32_t current_interval;
210 Component *component;
211 std::string name; // Keep as std::string since retry uses it dynamically
212 float backoff_increase_factor;
213 Scheduler *scheduler;
214};
215
216void retry_handler(const std::shared_ptr<RetryArgs> &args) {
217 RetryResult const retry_result = args->func(--args->retry_countdown);
218 if (retry_result == RetryResult::DONE || args->retry_countdown <= 0)
219 return;
220 // second execution of `func` happens after `initial_wait_time`
221 args->scheduler->set_timer_common_(
222 args->component, Scheduler::SchedulerItem::TIMEOUT, false, &args->name, args->current_interval,
223 [args]() { retry_handler(args); }, /* is_retry= */ true);
224 // backoff_increase_factor applied to third & later executions
225 args->current_interval *= args->backoff_increase_factor;
226}
227
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);
232
233 if (name_cstr != nullptr)
234 this->cancel_retry(component, name_cstr);
235
236 if (initial_wait_time == SCHEDULER_DONT_RUN)
237 return;
238
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);
241
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;
245 }
246
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;
251 args->component = component;
252 args->name = name_cstr ? name_cstr : ""; // Convert to std::string for RetryArgs
253 args->backoff_increase_factor = backoff_increase_factor;
254 args->scheduler = this;
255
256 // First execution of `func` immediately - use set_timer_common_ with is_retry=true
257 this->set_timer_common_(
258 component, SchedulerItem::TIMEOUT, false, &args->name, 0, [args]() { retry_handler(args); },
259 /* is_retry= */ true);
260}
261
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);
267}
268
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);
273}
274bool HOT Scheduler::cancel_retry(Component *component, const std::string &name) {
275 return this->cancel_retry(component, name.c_str());
276}
277
278bool HOT Scheduler::cancel_retry(Component *component, const char *name) {
279 // Cancel timeouts that have is_retry flag set
280 LockGuard guard{this->lock_};
281 return this->cancel_item_locked_(component, name, SchedulerItem::TIMEOUT, /* match_retry= */ true);
282}
283
284optional<uint32_t> HOT Scheduler::next_schedule_in(uint32_t now) {
285 // IMPORTANT: This method should only be called from the main thread (loop task).
286 // It performs cleanup and accesses items_[0] without holding a lock, which is only
287 // safe when called from the main thread. Other threads must not call this method.
288
289 // If no items, return empty optional
290 if (this->cleanup_() == 0)
291 return {};
292
293 auto &item = this->items_[0];
294 // Convert the fresh timestamp from caller (usually Application::loop()) to 64-bit
295 const auto now_64 = this->millis_64_(now); // 'now' from parameter - fresh from caller
296 const uint64_t next_exec = item->get_next_execution();
297 if (next_exec < now_64)
298 return 0;
299 return next_exec - now_64;
300}
301
302void Scheduler::full_cleanup_removed_items_() {
303 // We hold the lock for the entire cleanup operation because:
304 // 1. We're rebuilding the entire items_ list, so we need exclusive access throughout
305 // 2. Other threads must see either the old state or the new state, not intermediate states
306 // 3. The operation is already expensive (O(n)), so lock overhead is negligible
307 // 4. No operations inside can block or take other locks, so no deadlock risk
308 LockGuard guard{this->lock_};
309
310 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
311
312 // Move all non-removed items to valid_items, recycle removed ones
313 for (auto &item : this->items_) {
314 if (!is_item_removed_(item.get())) {
315 valid_items.push_back(std::move(item));
316 } else {
317 // Recycle removed items
318 this->recycle_item_(std::move(item));
319 }
320 }
321
322 // Replace items_ with the filtered list
323 this->items_ = std::move(valid_items);
324 // Rebuild the heap structure since items are no longer in heap order
325 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
326 this->to_remove_ = 0;
327}
328
329void HOT Scheduler::call(uint32_t now) {
330#ifndef ESPHOME_THREAD_SINGLE
331 this->process_defer_queue_(now);
332#endif /* not ESPHOME_THREAD_SINGLE */
333
334 // Convert the fresh timestamp from main loop to 64-bit for scheduler operations
335 const auto now_64 = this->millis_64_(now); // 'now' from parameter - fresh from Application::loop()
336 this->process_to_add();
337
338 // Track if any items were added to to_add_ during this call (intervals or from callbacks)
339 bool has_added_items = false;
340
341#ifdef ESPHOME_DEBUG_SCHEDULER
342 static uint64_t last_print = 0;
343
344 if (now_64 - last_print > 2000) {
345 last_print = now_64;
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);
352#else /* not ESPHOME_THREAD_MULTI_ATOMICS */
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_);
355#endif /* else ESPHOME_THREAD_MULTI_ATOMICS */
356 // Cleanup before debug output
357 this->cleanup_();
358 while (!this->items_.empty()) {
359 std::unique_ptr<SchedulerItem> item;
360 {
361 LockGuard guard{this->lock_};
362 item = std::move(this->items_[0]);
363 this->pop_raw_();
364 }
365
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]" : "");
371
372 old_items.push_back(std::move(item));
373 }
374 ESP_LOGD(TAG, "\n");
375
376 {
377 LockGuard guard{this->lock_};
378 this->items_ = std::move(old_items);
379 // Rebuild heap after moving items back
380 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
381 }
382 }
383#endif /* ESPHOME_DEBUG_SCHEDULER */
384
385 // Cleanup removed items before processing
386 // First try to clean items from the top of the heap (fast path)
387 this->cleanup_();
388
389 // If we still have too many cancelled items, do a full cleanup
390 // This only happens if cancelled items are stuck in the middle/bottom of the heap
391 if (this->to_remove_ >= MAX_LOGICALLY_DELETED_ITEMS) {
392 this->full_cleanup_removed_items_();
393 }
394 while (!this->items_.empty()) {
395 // Don't copy-by value yet
396 auto &item = this->items_[0];
397 if (item->get_next_execution() > now_64) {
398 // Not reached timeout yet, done for this call
399 break;
400 }
401 // Don't run on failed components
402 if (item->component != nullptr && item->component->is_failed()) {
403 LockGuard guard{this->lock_};
404 this->pop_raw_();
405 continue;
406 }
407
408 // Check if item is marked for removal
409 // This handles two cases:
410 // 1. Item was marked for removal after cleanup_() but before we got here
411 // 2. Item is marked for removal but wasn't at the front of the heap during cleanup_()
412#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
413 // Multi-threaded platforms without atomics: must take lock to safely read remove flag
414 {
415 LockGuard guard{this->lock_};
416 if (is_item_removed_(item.get())) {
417 this->pop_raw_();
418 this->to_remove_--;
419 continue;
420 }
421 }
422#else
423 // Single-threaded or multi-threaded with atomics: can check without lock
424 if (is_item_removed_(item.get())) {
425 LockGuard guard{this->lock_};
426 this->pop_raw_();
427 this->to_remove_--;
428 continue;
429 }
430#endif
431
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);
437#endif /* ESPHOME_DEBUG_SCHEDULER */
438
439 // Warning: During callback(), a lot of stuff can happen, including:
440 // - timeouts/intervals get added, potentially invalidating vector pointers
441 // - timeouts/intervals get cancelled
442 now = this->execute_item_(item.get(), now);
443
444 LockGuard guard{this->lock_};
445
446 auto executed_item = std::move(this->items_[0]);
447 // Only pop after function call, this ensures we were reachable
448 // during the function call and know if we were cancelled.
449 this->pop_raw_();
450
451 if (executed_item->remove) {
452 // We were removed/cancelled in the function call, stop
453 this->to_remove_--;
454 continue;
455 }
456
457 if (executed_item->type == SchedulerItem::INTERVAL) {
458 executed_item->set_next_execution(now_64 + executed_item->interval);
459 // Add new item directly to to_add_
460 // since we have the lock held
461 this->to_add_.push_back(std::move(executed_item));
462 } else {
463 // Timeout completed - recycle it
464 this->recycle_item_(std::move(executed_item));
465 }
466
467 has_added_items |= !this->to_add_.empty();
468 }
469
470 if (has_added_items) {
471 this->process_to_add();
472 }
473}
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())) {
478 // Recycle cancelled items
479 this->recycle_item_(std::move(it));
480 continue;
481 }
482
483 this->items_.push_back(std::move(it));
484 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
485 }
486 this->to_add_.clear();
487}
488size_t HOT Scheduler::cleanup_() {
489 // Fast path: if nothing to remove, just return the current size
490 // Reading to_remove_ without lock is safe because:
491 // 1. We only call this from the main thread during call()
492 // 2. If it's 0, there's definitely nothing to cleanup
493 // 3. If it becomes non-zero after we check, cleanup will happen on the next loop iteration
494 // 4. Not all platforms support atomics, so we accept this race in favor of performance
495 // 5. The worst case is a one-loop-iteration delay in cleanup, which is harmless
496 if (this->to_remove_ == 0)
497 return this->items_.size();
498
499 // We must hold the lock for the entire cleanup operation because:
500 // 1. We're modifying items_ (via pop_raw_) which requires exclusive access
501 // 2. We're decrementing to_remove_ which is also modified by other threads
502 // (though all modifications are already under lock)
503 // 3. Other threads read items_ when searching for items to cancel in cancel_item_locked_()
504 // 4. We need a consistent view of items_ and to_remove_ throughout the operation
505 // Without the lock, we could access items_ while another thread is reading it,
506 // leading to race conditions
507 LockGuard guard{this->lock_};
508 while (!this->items_.empty()) {
509 auto &item = this->items_[0];
510 if (!item->remove)
511 break;
512 this->to_remove_--;
513 this->pop_raw_();
514 }
515 return this->items_.size();
516}
517void HOT Scheduler::pop_raw_() {
518 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
519
520 // Instead of destroying, recycle the item
521 this->recycle_item_(std::move(this->items_.back()));
522
523 this->items_.pop_back();
524}
525
526// Helper to execute a scheduler item
527uint32_t HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
528 App.set_current_component(item->component);
529 WarnIfComponentBlockingGuard guard{item->component, now};
530 item->callback();
531 return guard.finish();
532}
533
534// Common implementation for cancel operations
535bool HOT Scheduler::cancel_item_(Component *component, bool is_static_string, const void *name_ptr,
536 SchedulerItem::Type type) {
537 // Get the name as const char*
538 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
539
540 // obtain lock because this function iterates and can be called from non-loop task context
541 LockGuard guard{this->lock_};
542 return this->cancel_item_locked_(component, name_cstr, type);
543}
544
545// Helper to cancel items by name - must be called with lock held
546bool HOT Scheduler::cancel_item_locked_(Component *component, const char *name_cstr, SchedulerItem::Type type,
547 bool match_retry) {
548 // Early return if name is invalid - no items to cancel
549 if (name_cstr == nullptr) {
550 return false;
551 }
552
553 size_t total_cancelled = 0;
554
555 // Check all containers for matching items
556#ifndef ESPHOME_THREAD_SINGLE
557 // Mark items in defer queue as cancelled (they'll be skipped when processed)
558 if (type == SchedulerItem::TIMEOUT) {
559 total_cancelled += this->mark_matching_items_removed_(this->defer_queue_, component, name_cstr, type, match_retry);
560 }
561#endif /* not ESPHOME_THREAD_SINGLE */
562
563 // Cancel items in the main heap
564 // Special case: if the last item in the heap matches, we can remove it immediately
565 // (removing the last element doesn't break heap structure)
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();
571 total_cancelled++;
572 }
573 // For other items in heap, we can only mark for removal (can't remove from middle of heap)
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; // Track removals for heap items
577 }
578
579 // Cancel items in to_add_
580 total_cancelled += this->mark_matching_items_removed_(this->to_add_, component, name_cstr, type, match_retry);
581
582 return total_cancelled > 0;
583}
584
585uint64_t Scheduler::millis_64_(uint32_t now) {
586 // THREAD SAFETY NOTE:
587 // This function has three implementations, based on the precompiler flags
588 // - ESPHOME_THREAD_SINGLE - Runs on single-threaded platforms (ESP8266, RP2040, etc.)
589 // - ESPHOME_THREAD_MULTI_NO_ATOMICS - Runs on multi-threaded platforms without atomics (LibreTiny)
590 // - ESPHOME_THREAD_MULTI_ATOMICS - Runs on multi-threaded platforms with atomics (ESP32, HOST, etc.)
591 //
592 // Make sure all changes are synchronized if you edit this function.
593 //
594 // IMPORTANT: Always pass fresh millis() values to this function. The implementation
595 // handles out-of-order timestamps between threads, but minimizing time differences
596 // helps maintain accuracy.
597 //
598
599#ifdef ESPHOME_THREAD_SINGLE
600 // This is the single core implementation.
601 //
602 // Single-core platforms have no concurrency, so this is a simple implementation
603 // that just tracks 32-bit rollover (every 49.7 days) without any locking or atomics.
604
605 uint16_t major = this->millis_major_;
606 uint32_t last = this->last_millis_;
607
608 // Check for rollover
609 if (now < last && (last - now) > HALF_MAX_UINT32) {
610 this->millis_major_++;
611 major++;
612#ifdef ESPHOME_DEBUG_SCHEDULER
613 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
614#endif /* ESPHOME_DEBUG_SCHEDULER */
615 }
616
617 // Only update if time moved forward
618 if (now > last) {
619 this->last_millis_ = now;
620 }
621
622 // Combine major (high 32 bits) and now (low 32 bits) into 64-bit time
623 return now + (static_cast<uint64_t>(major) << 32);
624
625#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
626 // This is the multi core no atomics implementation.
627 //
628 // Without atomics, this implementation uses locks more aggressively:
629 // 1. Always locks when near the rollover boundary (within 10 seconds)
630 // 2. Always locks when detecting a large backwards jump
631 // 3. Updates without lock in normal forward progression (accepting minor races)
632 // This is less efficient but necessary without atomic operations.
633 uint16_t major = this->millis_major_;
634 uint32_t last = this->last_millis_;
635
636 // Define a safe window around the rollover point (10 seconds)
637 // This covers any reasonable scheduler delays or thread preemption
638 static const uint32_t ROLLOVER_WINDOW = 10000; // 10 seconds in milliseconds
639
640 // Check if we're near the rollover boundary (close to std::numeric_limits<uint32_t>::max() or just past 0)
641 bool near_rollover = (last > (std::numeric_limits<uint32_t>::max() - ROLLOVER_WINDOW)) || (now < ROLLOVER_WINDOW);
642
643 if (near_rollover || (now < last && (last - now) > HALF_MAX_UINT32)) {
644 // Near rollover or detected a rollover - need lock for safety
645 LockGuard guard{this->lock_};
646 // Re-read with lock held
647 last = this->last_millis_;
648
649 if (now < last && (last - now) > HALF_MAX_UINT32) {
650 // True rollover detected (happens every ~49.7 days)
651 this->millis_major_++;
652 major++;
653#ifdef ESPHOME_DEBUG_SCHEDULER
654 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
655#endif /* ESPHOME_DEBUG_SCHEDULER */
656 }
657 // Update last_millis_ while holding lock
658 this->last_millis_ = now;
659 } else if (now > last) {
660 // Normal case: Not near rollover and time moved forward
661 // Update without lock. While this may cause minor races (microseconds of
662 // backwards time movement), they're acceptable because:
663 // 1. The scheduler operates at millisecond resolution, not microsecond
664 // 2. We've already prevented the critical rollover race condition
665 // 3. Any backwards movement is orders of magnitude smaller than scheduler delays
666 this->last_millis_ = now;
667 }
668 // If now <= last and we're not near rollover, don't update
669 // This minimizes backwards time movement
670
671 // Combine major (high 32 bits) and now (low 32 bits) into 64-bit time
672 return now + (static_cast<uint64_t>(major) << 32);
673
674#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
675 // This is the multi core with atomics implementation.
676 //
677 // Uses atomic operations with acquire/release semantics to ensure coherent
678 // reads of millis_major_ and last_millis_ across cores. Features:
679 // 1. Epoch-coherency retry loop to handle concurrent updates
680 // 2. Lock only taken for actual rollover detection and update
681 // 3. Lock-free CAS updates for normal forward time progression
682 // 4. Memory ordering ensures cores see consistent time values
683
684 for (;;) {
685 uint16_t major = this->millis_major_.load(std::memory_order_acquire);
686
687 /*
688 * Acquire so that if we later decide **not** to take the lock we still
689 * observe a `millis_major_` value coherent with the loaded `last_millis_`.
690 * The acquire load ensures any later read of `millis_major_` sees its
691 * corresponding increment.
692 */
693 uint32_t last = this->last_millis_.load(std::memory_order_acquire);
694
695 // If we might be near a rollover (large backwards jump), take the lock for the entire operation
696 // This ensures rollover detection and last_millis_ update are atomic together
697 if (now < last && (last - now) > HALF_MAX_UINT32) {
698 // Potential rollover - need lock for atomic rollover detection + update
699 LockGuard guard{this->lock_};
700 // Re-read with lock held; mutex already provides ordering
701 last = this->last_millis_.load(std::memory_order_relaxed);
702
703 if (now < last && (last - now) > HALF_MAX_UINT32) {
704 // True rollover detected (happens every ~49.7 days)
705 this->millis_major_.fetch_add(1, std::memory_order_relaxed);
706 major++;
707#ifdef ESPHOME_DEBUG_SCHEDULER
708 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
709#endif /* ESPHOME_DEBUG_SCHEDULER */
710 }
711 /*
712 * Update last_millis_ while holding the lock to prevent races
713 * Publish the new low-word *after* bumping `millis_major_` (done above)
714 * so readers never see a mismatched pair.
715 */
716 this->last_millis_.store(now, std::memory_order_release);
717 } else {
718 // Normal case: Try lock-free update, but only allow forward movement within same epoch
719 // This prevents accidentally moving backwards across a rollover boundary
720 while (now > last && (now - last) < HALF_MAX_UINT32) {
721 if (this->last_millis_.compare_exchange_weak(last, now,
722 std::memory_order_release, // success
723 std::memory_order_relaxed)) { // failure
724 break;
725 }
726 // CAS failure means no data was published; relaxed is fine
727 // last is automatically updated by compare_exchange_weak if it fails
728 }
729 }
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);
733 }
734 // Unreachable - the loop always returns when major_end == major
735 __builtin_unreachable();
736
737#else
738#error \
739 "No platform threading model defined. One of ESPHOME_THREAD_SINGLE, ESPHOME_THREAD_MULTI_NO_ATOMICS, or ESPHOME_THREAD_MULTI_ATOMICS must be defined."
740#endif
741}
742
743bool HOT Scheduler::SchedulerItem::cmp(const std::unique_ptr<SchedulerItem> &a,
744 const std::unique_ptr<SchedulerItem> &b) {
745 // High bits are almost always equal (change only on 32-bit rollover ~49 days)
746 // Optimize for common case: check low bits first when high bits are equal
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_);
749}
750
751void Scheduler::recycle_item_(std::unique_ptr<SchedulerItem> item) {
752 if (!item)
753 return;
754
755 if (this->scheduler_item_pool_.size() < MAX_POOL_SIZE) {
756 // Clear callback to release captured resources
757 item->callback = nullptr;
758 // Clear dynamic name if any
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());
763#endif
764 } else {
765#ifdef ESPHOME_DEBUG_SCHEDULER
766 ESP_LOGD(TAG, "Pool full (size: %zu), deleting item", this->scheduler_item_pool_.size());
767#endif
768 }
769 // else: unique_ptr will delete the item when it goes out of scope
770}
771
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) {
775 // Validate static strings in debug mode
776 if (is_static_string && name_cstr != nullptr) {
777 validate_static_string(name_cstr);
778 }
779
780 // Debug logging
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);
785 } else {
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));
789 }
790}
791#endif /* ESPHOME_DEBUG_SCHEDULER */
792
793} // namespace esphome
void set_current_component(Component *component)
const Component * component
Definition component.cpp:37
uint16_t type
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:157
void retry_handler(const std::shared_ptr< RetryArgs > &args)
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:31
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:30
Application App
Global storage of Application pointer - only one Application can exist.