| 73 | // Public API functions |
| 74 | |
| 75 | void run(fl::u32 microseconds, ExecFlags flags) { |
| 76 | // Re-entrancy guard: detect if run is called from within run |
| 77 | bool& running = SingletonThreadLocal<bool>::instance(); |
| 78 | if (running) { |
| 79 | FL_WARN_ONCE("task::run re-entrancy detected, skipping nested call"); |
| 80 | return; |
| 81 | } |
| 82 | running = true; |
| 83 | auto guard = fl::make_scope_exit([&running]() { running = false; }); |
| 84 | |
| 85 | const bool do_tasks = flags & ExecFlags::TASKS; |
| 86 | const bool do_coroutines = flags & ExecFlags::COROUTINES; |
| 87 | const bool do_system = flags & ExecFlags::SYSTEM; |
| 88 | |
| 89 | // Calculate start time with rollover protection |
| 90 | fl::u32 begin_time = fl::micros(); |
| 91 | |
| 92 | // Lambda to get elapsed time (rollover-safe) |
| 93 | auto elapsed = [begin_time]() { |
| 94 | return fl::micros() - begin_time; |
| 95 | }; |
| 96 | |
| 97 | // Lambda to get remaining time until deadline expires |
| 98 | auto remaining = [elapsed, microseconds]() -> fl::u32 { |
| 99 | fl::u32 e = elapsed(); |
| 100 | if (e >= microseconds) { |
| 101 | return 0; |
| 102 | } |
| 103 | return microseconds - e; |
| 104 | }; |
| 105 | |
| 106 | // Lambda to check if deadline has expired |
| 107 | auto expired = [remaining]() { |
| 108 | return remaining() == 0; |
| 109 | }; |
| 110 | |
| 111 | do { |
| 112 | // TASKS: Scheduler (fl::task timers) + Executor (fetch, HTTP server, audio) |
| 113 | if (do_tasks) { |
| 114 | Scheduler::instance().update(); |
| 115 | Executor::instance().update_all(); |
| 116 | } |
| 117 | |
| 118 | // SYSTEM: OS-level yield. |
| 119 | // |
| 120 | // When the caller provided a non-zero microseconds budget we treat |
| 121 | // this as an explicit spin-wait on hardware (typical DMA / driver |
| 122 | // wait loops). In that case we MUST use a deep yield (>= 1 FreeRTOS |
| 123 | // tick on ESP32) so that lower-priority network tasks — WiFi, |
| 124 | // Ethernet lwIP, etc. — actually get CPU time. Previously this |
| 125 | // path was gated on an active WiFi mode check, which missed |
| 126 | // Ethernet-only deployments and also the pre-connection window |
| 127 | // where `esp_wifi_get_mode` still returns WIFI_MODE_NULL. That |
| 128 | // regression manifested as the ESP32-S3 I2S-vs-websockets |
| 129 | // starvation reported in https://github.com/FastLED/FastLED/issues/2254 |
| 130 | // (Issue 1). |
| 131 | // |
| 132 | // When microseconds == 0 the caller wants the cheapest possible |