ESPHome 2025.8.0
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
17static const uint32_t MAX_LOGICALLY_DELETED_ITEMS = 10;
18// Half the 32-bit range - used to detect rollovers vs normal time progression
19static constexpr uint32_t HALF_MAX_UINT32 = std::numeric_limits<uint32_t>::max() / 2;
20// max delay to start an interval sequence
21static constexpr uint32_t MAX_INTERVAL_DELAY = 5000;
22
23// Uncomment to debug scheduler
24// #define ESPHOME_DEBUG_SCHEDULER
25
26#ifdef ESPHOME_DEBUG_SCHEDULER
27// Helper to validate that a pointer looks like it's in static memory
28static void validate_static_string(const char *name) {
29 if (name == nullptr)
30 return;
31
32 // This is a heuristic check - stack and heap pointers are typically
33 // much higher in memory than static data
34 uintptr_t addr = reinterpret_cast<uintptr_t>(name);
35
36 // Create a stack variable to compare against
37 int stack_var;
38 uintptr_t stack_addr = reinterpret_cast<uintptr_t>(&stack_var);
39
40 // If the string pointer is near our stack variable, it's likely on the stack
41 // Using 8KB range as ESP32 main task stack is typically 8192 bytes
42 if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
43 ESP_LOGW(TAG,
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);
47 }
48
49 // Also check if it might be on the heap by seeing if it's in a very different range
50 // This is platform-specific but generally heap is allocated far from static memory
51 static const char *static_str = "test";
52 uintptr_t static_addr = reinterpret_cast<uintptr_t>(static_str);
53
54 // If the address is very far from known static memory, it might be heap
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);
57 }
58}
59#endif /* ESPHOME_DEBUG_SCHEDULER */
60
61// A note on locking: the `lock_` lock protects the `items_` and `to_add_` containers. It must be taken when writing to
62// them (i.e. when adding/removing items, but not when changing items). As items are only deleted from the loop task,
63// iterating over them from the loop task is fine; but iterating from any other context requires the lock to be held to
64// avoid the main thread modifying the list while it is being accessed.
65
66// Common implementation for both timeout and interval
67void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type type, bool is_static_string,
68 const void *name_ptr, uint32_t delay, std::function<void()> func, bool is_retry) {
69 // Get the name as const char*
70 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
71
72 if (delay == SCHEDULER_DONT_RUN) {
73 // Still need to cancel existing timer if name is not empty
74 LockGuard guard{this->lock_};
75 this->cancel_item_locked_(component, name_cstr, type);
76 return;
77 }
78
79 // Create and populate the scheduler item
80 auto item = make_unique<SchedulerItem>();
81 item->component = component;
82 item->set_name(name_cstr, !is_static_string);
83 item->type = type;
84 item->callback = std::move(func);
85 // Initialize remove to false (though it should already be from constructor)
86 // Not using mark_item_removed_ helper since we're setting to false, not true
87#ifdef ESPHOME_THREAD_MULTI_ATOMICS
88 item->remove.store(false, std::memory_order_relaxed);
89#else
90 item->remove = false;
91#endif
92 item->is_retry = is_retry;
93
94#ifndef ESPHOME_THREAD_SINGLE
95 // Special handling for defer() (delay = 0, type = TIMEOUT)
96 // Single-core platforms don't need thread-safe defer handling
97 if (delay == 0 && type == SchedulerItem::TIMEOUT) {
98 // Put in defer queue for guaranteed FIFO execution
99 LockGuard guard{this->lock_};
100 this->cancel_item_locked_(component, name_cstr, type);
101 this->defer_queue_.push_back(std::move(item));
102 return;
103 }
104#endif /* not ESPHOME_THREAD_SINGLE */
105
106 // Get fresh timestamp for new timer/interval - ensures accurate scheduling
107 const auto now = this->millis_64_(millis()); // Fresh millis() call
108
109 // Type-specific setup
110 if (type == SchedulerItem::INTERVAL) {
111 item->interval = delay;
112 // first execution happens immediately after a random smallish offset
113 // Calculate random offset (0 to min(interval/2, 5s))
114 uint32_t offset = (uint32_t) (std::min(delay / 2, MAX_INTERVAL_DELAY) * random_float());
115 item->next_execution_ = now + offset;
116 ESP_LOGV(TAG, "Scheduler interval for %s is %" PRIu32 "ms, offset %" PRIu32 "ms", name_cstr ? name_cstr : "", delay,
117 offset);
118 } else {
119 item->interval = 0;
120 item->next_execution_ = now + delay;
121 }
122
123#ifdef ESPHOME_DEBUG_SCHEDULER
124 // Validate static strings in debug mode
125 if (is_static_string && name_cstr != nullptr) {
126 validate_static_string(name_cstr);
127 }
128
129 // Debug logging
130 const char *type_str = (type == SchedulerItem::TIMEOUT) ? "timeout" : "interval";
131 if (type == SchedulerItem::TIMEOUT) {
132 ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ")", type_str, item->get_source(),
133 name_cstr ? name_cstr : "(null)", type_str, delay);
134 } else {
135 ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ", offset=%" PRIu32 ")", type_str, item->get_source(),
136 name_cstr ? name_cstr : "(null)", type_str, delay, static_cast<uint32_t>(item->next_execution_ - now));
137 }
138#endif /* ESPHOME_DEBUG_SCHEDULER */
139
140 LockGuard guard{this->lock_};
141
142 // For retries, check if there's a cancelled timeout first
143 if (is_retry && name_cstr != nullptr && type == SchedulerItem::TIMEOUT &&
144 (has_cancelled_timeout_in_container_(this->items_, component, name_cstr, /* match_retry= */ true) ||
145 has_cancelled_timeout_in_container_(this->to_add_, component, name_cstr, /* match_retry= */ true))) {
146 // Skip scheduling - the retry was cancelled
147#ifdef ESPHOME_DEBUG_SCHEDULER
148 ESP_LOGD(TAG, "Skipping retry '%s' - found cancelled item", name_cstr);
149#endif
150 return;
151 }
152
153 // If name is provided, do atomic cancel-and-add
154 // Cancel existing items
155 this->cancel_item_locked_(component, name_cstr, type);
156 // Add new item directly to to_add_
157 // since we have the lock held
158 this->to_add_.push_back(std::move(item));
159}
160
161void HOT Scheduler::set_timeout(Component *component, const char *name, uint32_t timeout, std::function<void()> func) {
162 this->set_timer_common_(component, SchedulerItem::TIMEOUT, true, name, timeout, std::move(func));
163}
164
165void HOT Scheduler::set_timeout(Component *component, const std::string &name, uint32_t timeout,
166 std::function<void()> func) {
167 this->set_timer_common_(component, SchedulerItem::TIMEOUT, false, &name, timeout, std::move(func));
168}
169bool HOT Scheduler::cancel_timeout(Component *component, const std::string &name) {
170 return this->cancel_item_(component, false, &name, SchedulerItem::TIMEOUT);
171}
172bool HOT Scheduler::cancel_timeout(Component *component, const char *name) {
173 return this->cancel_item_(component, true, name, SchedulerItem::TIMEOUT);
174}
175void HOT Scheduler::set_interval(Component *component, const std::string &name, uint32_t interval,
176 std::function<void()> func) {
177 this->set_timer_common_(component, SchedulerItem::INTERVAL, false, &name, interval, std::move(func));
178}
179
180void HOT Scheduler::set_interval(Component *component, const char *name, uint32_t interval,
181 std::function<void()> func) {
182 this->set_timer_common_(component, SchedulerItem::INTERVAL, true, name, interval, std::move(func));
183}
184bool HOT Scheduler::cancel_interval(Component *component, const std::string &name) {
185 return this->cancel_item_(component, false, &name, SchedulerItem::INTERVAL);
186}
187bool HOT Scheduler::cancel_interval(Component *component, const char *name) {
188 return this->cancel_item_(component, true, name, SchedulerItem::INTERVAL);
189}
190
191struct RetryArgs {
192 std::function<RetryResult(uint8_t)> func;
193 uint8_t retry_countdown;
194 uint32_t current_interval;
195 Component *component;
196 std::string name; // Keep as std::string since retry uses it dynamically
197 float backoff_increase_factor;
198 Scheduler *scheduler;
199};
200
201void retry_handler(const std::shared_ptr<RetryArgs> &args) {
202 RetryResult const retry_result = args->func(--args->retry_countdown);
203 if (retry_result == RetryResult::DONE || args->retry_countdown <= 0)
204 return;
205 // second execution of `func` happens after `initial_wait_time`
206 args->scheduler->set_timer_common_(
207 args->component, Scheduler::SchedulerItem::TIMEOUT, false, &args->name, args->current_interval,
208 [args]() { retry_handler(args); }, /* is_retry= */ true);
209 // backoff_increase_factor applied to third & later executions
210 args->current_interval *= args->backoff_increase_factor;
211}
212
213void HOT Scheduler::set_retry_common_(Component *component, bool is_static_string, const void *name_ptr,
214 uint32_t initial_wait_time, uint8_t max_attempts,
215 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor) {
216 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
217
218 if (name_cstr != nullptr)
219 this->cancel_retry(component, name_cstr);
220
221 if (initial_wait_time == SCHEDULER_DONT_RUN)
222 return;
223
224 ESP_LOGVV(TAG, "set_retry(name='%s', initial_wait_time=%" PRIu32 ", max_attempts=%u, backoff_factor=%0.1f)",
225 name_cstr ? name_cstr : "", initial_wait_time, max_attempts, backoff_increase_factor);
226
227 if (backoff_increase_factor < 0.0001) {
228 ESP_LOGE(TAG, "backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor, name_cstr ? name_cstr : "");
229 backoff_increase_factor = 1;
230 }
231
232 auto args = std::make_shared<RetryArgs>();
233 args->func = std::move(func);
234 args->retry_countdown = max_attempts;
235 args->current_interval = initial_wait_time;
236 args->component = component;
237 args->name = name_cstr ? name_cstr : ""; // Convert to std::string for RetryArgs
238 args->backoff_increase_factor = backoff_increase_factor;
239 args->scheduler = this;
240
241 // First execution of `func` immediately - use set_timer_common_ with is_retry=true
242 this->set_timer_common_(
243 component, SchedulerItem::TIMEOUT, false, &args->name, 0, [args]() { retry_handler(args); },
244 /* is_retry= */ true);
245}
246
247void HOT Scheduler::set_retry(Component *component, const std::string &name, uint32_t initial_wait_time,
248 uint8_t max_attempts, std::function<RetryResult(uint8_t)> func,
249 float backoff_increase_factor) {
250 this->set_retry_common_(component, false, &name, initial_wait_time, max_attempts, std::move(func),
251 backoff_increase_factor);
252}
253
254void HOT Scheduler::set_retry(Component *component, const char *name, uint32_t initial_wait_time, uint8_t max_attempts,
255 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor) {
256 this->set_retry_common_(component, true, name, initial_wait_time, max_attempts, std::move(func),
257 backoff_increase_factor);
258}
259bool HOT Scheduler::cancel_retry(Component *component, const std::string &name) {
260 return this->cancel_retry(component, name.c_str());
261}
262
263bool HOT Scheduler::cancel_retry(Component *component, const char *name) {
264 // Cancel timeouts that have is_retry flag set
265 LockGuard guard{this->lock_};
266 return this->cancel_item_locked_(component, name, SchedulerItem::TIMEOUT, /* match_retry= */ true);
267}
268
269optional<uint32_t> HOT Scheduler::next_schedule_in(uint32_t now) {
270 // IMPORTANT: This method should only be called from the main thread (loop task).
271 // It performs cleanup and accesses items_[0] without holding a lock, which is only
272 // safe when called from the main thread. Other threads must not call this method.
273
274 // If no items, return empty optional
275 if (this->cleanup_() == 0)
276 return {};
277
278 auto &item = this->items_[0];
279 // Convert the fresh timestamp from caller (usually Application::loop()) to 64-bit
280 const auto now_64 = this->millis_64_(now); // 'now' from parameter - fresh from caller
281 if (item->next_execution_ < now_64)
282 return 0;
283 return item->next_execution_ - now_64;
284}
285void HOT Scheduler::call(uint32_t now) {
286#ifndef ESPHOME_THREAD_SINGLE
287 // Process defer queue first to guarantee FIFO execution order for deferred items.
288 // Previously, defer() used the heap which gave undefined order for equal timestamps,
289 // causing race conditions on multi-core systems (ESP32, BK7200).
290 // With the defer queue:
291 // - Deferred items (delay=0) go directly to defer_queue_ in set_timer_common_
292 // - Items execute in exact order they were deferred (FIFO guarantee)
293 // - No deferred items exist in to_add_, so processing order doesn't affect correctness
294 // Single-core platforms don't use this queue and fall back to the heap-based approach.
295 //
296 // Note: Items cancelled via cancel_item_locked_() are marked with remove=true but still
297 // processed here. They are removed from the queue normally via pop_front() but skipped
298 // during execution by should_skip_item_(). This is intentional - no memory leak occurs.
299 while (!this->defer_queue_.empty()) {
300 // The outer check is done without a lock for performance. If the queue
301 // appears non-empty, we lock and process an item. We don't need to check
302 // empty() again inside the lock because only this thread can remove items.
303 std::unique_ptr<SchedulerItem> item;
304 {
305 LockGuard lock(this->lock_);
306 item = std::move(this->defer_queue_.front());
307 this->defer_queue_.pop_front();
308 }
309
310 // Execute callback without holding lock to prevent deadlocks
311 // if the callback tries to call defer() again
312 if (!this->should_skip_item_(item.get())) {
313 this->execute_item_(item.get(), now);
314 }
315 }
316#endif /* not ESPHOME_THREAD_SINGLE */
317
318 // Convert the fresh timestamp from main loop to 64-bit for scheduler operations
319 const auto now_64 = this->millis_64_(now); // 'now' from parameter - fresh from Application::loop()
320 this->process_to_add();
321
322#ifdef ESPHOME_DEBUG_SCHEDULER
323 static uint64_t last_print = 0;
324
325 if (now_64 - last_print > 2000) {
326 last_print = now_64;
327 std::vector<std::unique_ptr<SchedulerItem>> old_items;
328#ifdef ESPHOME_THREAD_MULTI_ATOMICS
329 const auto last_dbg = this->last_millis_.load(std::memory_order_relaxed);
330 const auto major_dbg = this->millis_major_.load(std::memory_order_relaxed);
331 ESP_LOGD(TAG, "Items: count=%zu, now=%" PRIu64 " (%" PRIu16 ", %" PRIu32 ")", this->items_.size(), now_64,
332 major_dbg, last_dbg);
333#else /* not ESPHOME_THREAD_MULTI_ATOMICS */
334 ESP_LOGD(TAG, "Items: count=%zu, now=%" PRIu64 " (%" PRIu16 ", %" PRIu32 ")", this->items_.size(), now_64,
335 this->millis_major_, this->last_millis_);
336#endif /* else ESPHOME_THREAD_MULTI_ATOMICS */
337 // Cleanup before debug output
338 this->cleanup_();
339 while (!this->items_.empty()) {
340 std::unique_ptr<SchedulerItem> item;
341 {
342 LockGuard guard{this->lock_};
343 item = std::move(this->items_[0]);
344 this->pop_raw_();
345 }
346
347 const char *name = item->get_name();
348 ESP_LOGD(TAG, " %s '%s/%s' interval=%" PRIu32 " next_execution in %" PRIu64 "ms at %" PRIu64,
349 item->get_type_str(), item->get_source(), name ? name : "(null)", item->interval,
350 item->next_execution_ - now_64, item->next_execution_);
351
352 old_items.push_back(std::move(item));
353 }
354 ESP_LOGD(TAG, "\n");
355
356 {
357 LockGuard guard{this->lock_};
358 this->items_ = std::move(old_items);
359 // Rebuild heap after moving items back
360 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
361 }
362 }
363#endif /* ESPHOME_DEBUG_SCHEDULER */
364
365 // If we have too many items to remove
366 if (this->to_remove_ > MAX_LOGICALLY_DELETED_ITEMS) {
367 // We hold the lock for the entire cleanup operation because:
368 // 1. We're rebuilding the entire items_ list, so we need exclusive access throughout
369 // 2. Other threads must see either the old state or the new state, not intermediate states
370 // 3. The operation is already expensive (O(n)), so lock overhead is negligible
371 // 4. No operations inside can block or take other locks, so no deadlock risk
372 LockGuard guard{this->lock_};
373
374 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
375
376 // Move all non-removed items to valid_items
377 for (auto &item : this->items_) {
378 if (!item->remove) {
379 valid_items.push_back(std::move(item));
380 }
381 }
382
383 // Replace items_ with the filtered list
384 this->items_ = std::move(valid_items);
385 // Rebuild the heap structure since items are no longer in heap order
386 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
387 this->to_remove_ = 0;
388 }
389
390 // Cleanup removed items before processing
391 this->cleanup_();
392 while (!this->items_.empty()) {
393 // use scoping to indicate visibility of `item` variable
394 {
395 // Don't copy-by value yet
396 auto &item = this->items_[0];
397 if (item->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(), item->get_source(), item_name ? item_name : "(null)", item->interval,
436 item->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 this->execute_item_(item.get(), now);
443 }
444
445 {
446 LockGuard guard{this->lock_};
447
448 // new scope, item from before might have been moved in the vector
449 auto item = std::move(this->items_[0]);
450 // Only pop after function call, this ensures we were reachable
451 // during the function call and know if we were cancelled.
452 this->pop_raw_();
453
454 if (item->remove) {
455 // We were removed/cancelled in the function call, stop
456 this->to_remove_--;
457 continue;
458 }
459
460 if (item->type == SchedulerItem::INTERVAL) {
461 item->next_execution_ = now_64 + item->interval;
462 // Add new item directly to to_add_
463 // since we have the lock held
464 this->to_add_.push_back(std::move(item));
465 }
466 }
467 }
468
469 this->process_to_add();
470}
471void HOT Scheduler::process_to_add() {
472 LockGuard guard{this->lock_};
473 for (auto &it : this->to_add_) {
474 if (it->remove) {
475 continue;
476 }
477
478 this->items_.push_back(std::move(it));
479 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
480 }
481 this->to_add_.clear();
482}
483size_t HOT Scheduler::cleanup_() {
484 // Fast path: if nothing to remove, just return the current size
485 // Reading to_remove_ without lock is safe because:
486 // 1. We only call this from the main thread during call()
487 // 2. If it's 0, there's definitely nothing to cleanup
488 // 3. If it becomes non-zero after we check, cleanup will happen on the next loop iteration
489 // 4. Not all platforms support atomics, so we accept this race in favor of performance
490 // 5. The worst case is a one-loop-iteration delay in cleanup, which is harmless
491 if (this->to_remove_ == 0)
492 return this->items_.size();
493
494 // We must hold the lock for the entire cleanup operation because:
495 // 1. We're modifying items_ (via pop_raw_) which requires exclusive access
496 // 2. We're decrementing to_remove_ which is also modified by other threads
497 // (though all modifications are already under lock)
498 // 3. Other threads read items_ when searching for items to cancel in cancel_item_locked_()
499 // 4. We need a consistent view of items_ and to_remove_ throughout the operation
500 // Without the lock, we could access items_ while another thread is reading it,
501 // leading to race conditions
502 LockGuard guard{this->lock_};
503 while (!this->items_.empty()) {
504 auto &item = this->items_[0];
505 if (!item->remove)
506 break;
507 this->to_remove_--;
508 this->pop_raw_();
509 }
510 return this->items_.size();
511}
512void HOT Scheduler::pop_raw_() {
513 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
514 this->items_.pop_back();
515}
516
517// Helper to execute a scheduler item
518void HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
519 App.set_current_component(item->component);
520 WarnIfComponentBlockingGuard guard{item->component, now};
521 item->callback();
522 guard.finish();
523}
524
525// Common implementation for cancel operations
526bool HOT Scheduler::cancel_item_(Component *component, bool is_static_string, const void *name_ptr,
527 SchedulerItem::Type type) {
528 // Get the name as const char*
529 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
530
531 // obtain lock because this function iterates and can be called from non-loop task context
532 LockGuard guard{this->lock_};
533 return this->cancel_item_locked_(component, name_cstr, type);
534}
535
536// Helper to cancel items by name - must be called with lock held
537bool HOT Scheduler::cancel_item_locked_(Component *component, const char *name_cstr, SchedulerItem::Type type,
538 bool match_retry) {
539 // Early return if name is invalid - no items to cancel
540 if (name_cstr == nullptr) {
541 return false;
542 }
543
544 size_t total_cancelled = 0;
545
546 // Check all containers for matching items
547#ifndef ESPHOME_THREAD_SINGLE
548 // Only check defer queue for timeouts (intervals never go there)
549 if (type == SchedulerItem::TIMEOUT) {
550 for (auto &item : this->defer_queue_) {
551 if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
552 this->mark_item_removed_(item.get());
553 total_cancelled++;
554 }
555 }
556 }
557#endif /* not ESPHOME_THREAD_SINGLE */
558
559 // Cancel items in the main heap
560 for (auto &item : this->items_) {
561 if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
562 this->mark_item_removed_(item.get());
563 total_cancelled++;
564 this->to_remove_++; // Track removals for heap items
565 }
566 }
567
568 // Cancel items in to_add_
569 for (auto &item : this->to_add_) {
570 if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
571 this->mark_item_removed_(item.get());
572 total_cancelled++;
573 // Don't track removals for to_add_ items
574 }
575 }
576
577 return total_cancelled > 0;
578}
579
580uint64_t Scheduler::millis_64_(uint32_t now) {
581 // THREAD SAFETY NOTE:
582 // This function has three implementations, based on the precompiler flags
583 // - ESPHOME_THREAD_SINGLE - Runs on single-threaded platforms (ESP8266, RP2040, etc.)
584 // - ESPHOME_THREAD_MULTI_NO_ATOMICS - Runs on multi-threaded platforms without atomics (LibreTiny)
585 // - ESPHOME_THREAD_MULTI_ATOMICS - Runs on multi-threaded platforms with atomics (ESP32, HOST, etc.)
586 //
587 // Make sure all changes are synchronized if you edit this function.
588 //
589 // IMPORTANT: Always pass fresh millis() values to this function. The implementation
590 // handles out-of-order timestamps between threads, but minimizing time differences
591 // helps maintain accuracy.
592 //
593
594#ifdef ESPHOME_THREAD_SINGLE
595 // This is the single core implementation.
596 //
597 // Single-core platforms have no concurrency, so this is a simple implementation
598 // that just tracks 32-bit rollover (every 49.7 days) without any locking or atomics.
599
600 uint16_t major = this->millis_major_;
601 uint32_t last = this->last_millis_;
602
603 // Check for rollover
604 if (now < last && (last - now) > HALF_MAX_UINT32) {
605 this->millis_major_++;
606 major++;
607#ifdef ESPHOME_DEBUG_SCHEDULER
608 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
609#endif /* ESPHOME_DEBUG_SCHEDULER */
610 }
611
612 // Only update if time moved forward
613 if (now > last) {
614 this->last_millis_ = now;
615 }
616
617 // Combine major (high 32 bits) and now (low 32 bits) into 64-bit time
618 return now + (static_cast<uint64_t>(major) << 32);
619
620#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
621 // This is the multi core no atomics implementation.
622 //
623 // Without atomics, this implementation uses locks more aggressively:
624 // 1. Always locks when near the rollover boundary (within 10 seconds)
625 // 2. Always locks when detecting a large backwards jump
626 // 3. Updates without lock in normal forward progression (accepting minor races)
627 // This is less efficient but necessary without atomic operations.
628 uint16_t major = this->millis_major_;
629 uint32_t last = this->last_millis_;
630
631 // Define a safe window around the rollover point (10 seconds)
632 // This covers any reasonable scheduler delays or thread preemption
633 static const uint32_t ROLLOVER_WINDOW = 10000; // 10 seconds in milliseconds
634
635 // Check if we're near the rollover boundary (close to std::numeric_limits<uint32_t>::max() or just past 0)
636 bool near_rollover = (last > (std::numeric_limits<uint32_t>::max() - ROLLOVER_WINDOW)) || (now < ROLLOVER_WINDOW);
637
638 if (near_rollover || (now < last && (last - now) > HALF_MAX_UINT32)) {
639 // Near rollover or detected a rollover - need lock for safety
640 LockGuard guard{this->lock_};
641 // Re-read with lock held
642 last = this->last_millis_;
643
644 if (now < last && (last - now) > HALF_MAX_UINT32) {
645 // True rollover detected (happens every ~49.7 days)
646 this->millis_major_++;
647 major++;
648#ifdef ESPHOME_DEBUG_SCHEDULER
649 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
650#endif /* ESPHOME_DEBUG_SCHEDULER */
651 }
652 // Update last_millis_ while holding lock
653 this->last_millis_ = now;
654 } else if (now > last) {
655 // Normal case: Not near rollover and time moved forward
656 // Update without lock. While this may cause minor races (microseconds of
657 // backwards time movement), they're acceptable because:
658 // 1. The scheduler operates at millisecond resolution, not microsecond
659 // 2. We've already prevented the critical rollover race condition
660 // 3. Any backwards movement is orders of magnitude smaller than scheduler delays
661 this->last_millis_ = now;
662 }
663 // If now <= last and we're not near rollover, don't update
664 // This minimizes backwards time movement
665
666 // Combine major (high 32 bits) and now (low 32 bits) into 64-bit time
667 return now + (static_cast<uint64_t>(major) << 32);
668
669#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
670 // This is the multi core with atomics implementation.
671 //
672 // Uses atomic operations with acquire/release semantics to ensure coherent
673 // reads of millis_major_ and last_millis_ across cores. Features:
674 // 1. Epoch-coherency retry loop to handle concurrent updates
675 // 2. Lock only taken for actual rollover detection and update
676 // 3. Lock-free CAS updates for normal forward time progression
677 // 4. Memory ordering ensures cores see consistent time values
678
679 for (;;) {
680 uint16_t major = this->millis_major_.load(std::memory_order_acquire);
681
682 /*
683 * Acquire so that if we later decide **not** to take the lock we still
684 * observe a `millis_major_` value coherent with the loaded `last_millis_`.
685 * The acquire load ensures any later read of `millis_major_` sees its
686 * corresponding increment.
687 */
688 uint32_t last = this->last_millis_.load(std::memory_order_acquire);
689
690 // If we might be near a rollover (large backwards jump), take the lock for the entire operation
691 // This ensures rollover detection and last_millis_ update are atomic together
692 if (now < last && (last - now) > HALF_MAX_UINT32) {
693 // Potential rollover - need lock for atomic rollover detection + update
694 LockGuard guard{this->lock_};
695 // Re-read with lock held; mutex already provides ordering
696 last = this->last_millis_.load(std::memory_order_relaxed);
697
698 if (now < last && (last - now) > HALF_MAX_UINT32) {
699 // True rollover detected (happens every ~49.7 days)
700 this->millis_major_.fetch_add(1, std::memory_order_relaxed);
701 major++;
702#ifdef ESPHOME_DEBUG_SCHEDULER
703 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
704#endif /* ESPHOME_DEBUG_SCHEDULER */
705 }
706 /*
707 * Update last_millis_ while holding the lock to prevent races
708 * Publish the new low-word *after* bumping `millis_major_` (done above)
709 * so readers never see a mismatched pair.
710 */
711 this->last_millis_.store(now, std::memory_order_release);
712 } else {
713 // Normal case: Try lock-free update, but only allow forward movement within same epoch
714 // This prevents accidentally moving backwards across a rollover boundary
715 while (now > last && (now - last) < HALF_MAX_UINT32) {
716 if (this->last_millis_.compare_exchange_weak(last, now,
717 std::memory_order_release, // success
718 std::memory_order_relaxed)) { // failure
719 break;
720 }
721 // CAS failure means no data was published; relaxed is fine
722 // last is automatically updated by compare_exchange_weak if it fails
723 }
724 }
725 uint16_t major_end = this->millis_major_.load(std::memory_order_relaxed);
726 if (major_end == major)
727 return now + (static_cast<uint64_t>(major) << 32);
728 }
729 // Unreachable - the loop always returns when major_end == major
730 __builtin_unreachable();
731
732#else
733#error \
734 "No platform threading model defined. One of ESPHOME_THREAD_SINGLE, ESPHOME_THREAD_MULTI_NO_ATOMICS, or ESPHOME_THREAD_MULTI_ATOMICS must be defined."
735#endif
736}
737
738bool HOT Scheduler::SchedulerItem::cmp(const std::unique_ptr<SchedulerItem> &a,
739 const std::unique_ptr<SchedulerItem> &b) {
740 return a->next_execution_ > b->next_execution_;
741}
742
743} // namespace esphome
void set_current_component(Component *component)
uint8_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:143
void retry_handler(const std::shared_ptr< RetryArgs > &args)
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.