Skip to content

Unified cross-platform Watchdog Timer API via FastLED.watchdog() singleton #2731

Closed

Description

@zackees

Motivation

AutoResearch currently bricks itself temporarily when FlexIO/RMT/PARLIO peripherals wedge — the only recovery is a physical button press to enter the bootloader. We already have a partial ESP32-only watchdog (src/platforms/esp/32/watchdog_esp32.h, called from examples/AutoResearch/AutoResearch.ino:315), and a previous attempt to enable WDOG3 on Teensy 4 caused a reset loop (see AutoResearch.ino:204-214). Time to do this properly across the whole supported MCU matrix, behind a single uniform API.

The goal is a god-object accessible watchdog singleton — FastLED.watchdog() — that:

  • Has a small, guaranteed-portable minimum API surface
  • Tiered capability flags for advanced features
  • Persists a crash counter + safe-mode flag across resets so the board can recover itself instead of looping into the same crash forever

Per-platform capability matrix (from cross-MCU research)

Family Max timeout Pre-reset IRQ Window mode Crash-cause reg Persist (no power loss) Persist (power cycle) Decoded crash report
ESP32 / S2 / S3 / C3 / C6 / H2 / P4 configurable (TWDT) shutdown handler no esp_reset_reason() RTC_NOINIT (8KB classic/S2/S3/C3, 4KB C6/H2, none on P4) → fall back to __NOINIT_ATTR NVS partition Core dump partition (opt-in)
Teensy 4.x (iMXRT1062) 0.5s–128s (WDT_T4<WDT3>) .trigger + callback yes (.window) SRC_SRSR OCRAM2 retained @ 0x2027FF80 EEPROM emul (4284B T4.1) Bundled CrashReport
Teensy 3.x (K20/K66/KL26) ms–days (LPO/bus clk) IRQRSTEN yes RCM_SRS0/1 custom .noinit SRAM section FlexNVM EEPROM (2KB) manual
RP2040 8.388 s none (HW) no VREG_AND_CHIP_RESET + watchdog_caused_reboot() watchdog_hw->scratch[0..3] (16B) — scratch[4..7] reserved by SDK flash (LittleFS) manual via fault handler
RP2350 16.777 s none (HW) no POWMAN.CHIP_RESET (POR/BOR/RUN/DBG/GLITCH) watchdog->scratch[0..3] POWMAN.SCRATCH[0..7] (VBAT-backed) manual
nRF52 (Adafruit BSP) ~36 h ~61 µs warn no POWER->RESETREAS GPREGRET/GPREGRET2 (2B, shared with bootloader) InternalFS (LittleFS) none
STM32 (IWDG / WWDG) ~32 s / ~50 ms WWDG EWI WWDG only RCC->CSR/RSR none reliable RTC BKPxR (20–32 × 32-bit, VBAT) manual via CFSR
SAMD21 / SAMD51 ~16 s Early Warning IRQ yes PM->RCAUSE / RSTC->RCAUSE none FlashStorage / SmartEEPROM (SAMD51) SAMD51 CFSR only
Apollo3 ~250 s programmable no RSTGEN->STAT none (RAM cleared) flash via am_hal_flash_* none
AVR (atmega/attiny) 8 s WDIE int-then-reset no MCUSR none safe across boot EEPROM (1KB / 512B) none
MGM240 (EFR32MG24) ~32 s WARN IRQ yes EMU->RSTCAUSE RETREG (4 × 32-bit) BURAM / NVM3 CFSR via M33 SAU

Constraints driving the design:

  • AVR's 8 s max bounds the minimum-portable timeout range
  • AVR's WDRF/WDE boot-loop hazard requires MCUSR=0; wdt_disable() very early in .init3
  • ESP32-P4 has no RTC slow memory — persist layer must fall back to __NOINIT_ATTR
  • RP scratch[4..7] are SDK/bootrom-reserved — never touch
  • K20/K66 WDOG_STCTRLH is one-shot writable for ~256 bus cycles after unlock — must configure from startup_early_hook(), not setup()
  • Teensy 4 must use WDT_T4<WDT3> (RTWDOG), never WDOG1/WDOG2 (bootloader chip interaction)
  • Preserve the existing ESP32 USB-CDC disconnect-on-reset behavior (watchdog_esp32.cpp.hpp:5-10) — fixes Windows phantom-COM-port bug

Proposed API

Access point (god-object)

fl::Watchdog& dog = FastLED.watchdog();   // singleton, same shape as FastLED.channelEvents()

Usage example — the 95% case

This is the pattern every AutoResearch sketch (and every production FastLED sketch that wants crash recovery) should follow. feed() is the canonical name for the refresh call — same word used by Watchdog_t4::feed(), Arduino wdt_reset()'s docs, mbed's Watchdog::kick() family of synonyms — and goes naturally with "watchdog." It is NOT ping(), tick(), heartbeat(), or keepalive(). Read it as: "feed the dog so it doesn't bite."

#include <FastLED.h>

#define NUM_LEDS 100
CRGB leds[NUM_LEDS];

void setup() {
    Serial.begin(115200);

    // 1. Set up the watchdog FIRST, before any peripheral that might wedge.
    //    15-second timeout matches the existing AutoResearch budget. Use a
    //    smaller value (1-2 s) for production sketches with a fixed frame rate.
    FastLED.watchdog().begin(15000);

    // 2. If the previous boot crashed enough times in a row, the board is
    //    probably stuck on broken firmware. Don't initialize the LED peripheral
    //    — leave USB alive so the host can upload a fix.
    if (FastLED.watchdog().isInSafeMode()) {
        Serial.println("[SAFE MODE] previous boots crashed — LED peripheral disabled");
        // Hang here forever WITHOUT feeding the watchdog. The board stays
        // responsive to USB / serial so a new firmware upload can rescue it.
        while (true) {
            delay(100);
            // Intentionally do NOT call FastLED.watchdog().feed() here.
        }
    }

    // 3. Normal boot. Optionally inspect what killed the previous run.
    if (FastLED.watchdog().lastResetWasWatchdog()) {
        Serial.println("[recovery] previous boot was killed by watchdog");
    }

    FastLED.addLeds<WS2812B, 3, GRB>(leds, NUM_LEDS);
}

void loop() {
    // 4. Run the dangerous work — anything that could wedge the LED peripheral,
    //    DMA, FlexIO, RMT, etc.
    fill_rainbow(leds, NUM_LEDS, millis() / 16);
    FastLED.show();

    // 5. Feed the watchdog AFTER the dangerous work succeeded.
    //    If show() never returns (peripheral hang), we never reach this line,
    //    the watchdog fires, and the board reboots into safe-mode recovery.
    FastLED.watchdog().feed();

    // 6. Tell the watchdog this frame was clean. This resets the
    //    consecutive-crash counter to zero so a transient hang doesn't
    //    eventually push the board into safe mode.
    FastLED.watchdog().markCleanShutdown();
}

Critical: where you call feed() matters. Feed after the work that might hang, not before. Feeding before show() defeats the watchdog — a wedged DMA transfer would still feed itself by virtue of the feed call having happened first. The placement above is the right pattern.

Don't feed from an ISR or a timer callback. That decouples the feed from the actual liveness of loop() and turns the watchdog into a useless heartbeat. If you need per-subtask liveness (rare), see the Tier 3 multi-core / multi-task section.

Tier 0 — minimum, every supported platform (incl. AVR)

namespace fl {

enum class ResetCause : uint8_t {
    UNKNOWN = 0,
    POWER_ON,
    BROWNOUT,
    EXTERNAL_PIN,
    WATCHDOG,       // hardware WDT bit
    SOFTWARE,       // SYSRESETREQ / NVIC_SystemReset
    LOCKUP,         // CPU lockup (where distinguishable)
    DEBUGGER,
    PANIC,          // ESP panic, ARM HardFault decoded by us
};

class Watchdog {
public:
    // --- Lifecycle ---
    void begin(uint32_t timeout_ms);    // arm watchdog; AVR clamps to <=8000
    void feed();                         // refresh / kick
    void disable();                      // best-effort; no-op on nRF52, arduino-pico

    // --- Reset cause (call once early in setup() — read clears on some platforms) ---
    ResetCause lastResetCause() const;
    bool       lastResetWasWatchdog() const;        // convenience

    // --- Tiny persistent storage (counter + safe-mode flag) ---
    // Always available. Backed by best per-platform mechanism that survives WDT reset.
    // Size guaranteed: at least 8 bytes. AVR uses EEPROM with internal write-coalescing.
    static constexpr size_t kPersistBytes = FL_WATCHDOG_PERSIST_BYTES;  // >= 8
    uint8_t  persistRead(size_t idx) const;
    void     persistWrite(size_t idx, uint8_t v);

    // --- Crash counter / safe mode (built on persistRead/Write) ---
    uint16_t consecutiveCrashCount() const;          // increments on WDT/PANIC, cleared on clean shutdown
    void     markCleanShutdown();                    // call when loop() is healthy
    bool     isInSafeMode() const;                   // counter >= safeModeThreshold()
    uint16_t safeModeThreshold() const;              // default 2; configurable

    // --- Forced reboot ---
    FL_NORETURN void reboot();                       // immediate (uses FL_NORETURN from src/fl/stl/compiler_control.h:543)
};

} // namespace fl

Tier 1 — most platforms (ESP, Teensy 4, RP, nRF, STM, SAMD, MGM240)

using WatchdogTimeoutCallback = void(*)(void* user_data);

class Watchdog {
public:
    // Pre-reset hook. Fires from ISR/shutdown handler ~ms before the bite.
    // On platforms with no HW pre-warning, the callback fires from the panic/fault handler.
    // RP2040/RP2350: NOT supported (returns false).
    //
    // Primary (default) signature is the C function pointer — no allocation, ISR-safe on
    // every platform, callable from the panic handler before the heap is trustworthy.
    bool onTimeout(WatchdogTimeoutCallback cb, void* user_data = nullptr);

    // Convenience overload for callers that want lambda capture / fl::function semantics.
    // NOT the default path: fl::function may allocate on construction, and the underlying
    // storage must outlive the callback. Use the C-pointer overload above for any callback
    // that needs to fire from an ISR or from the panic handler. This overload is intended
    // for sketches that capture sketch-local state in a callback registered once from
    // setup() and never re-registered. The implementation dispatches into fl::function from
    // a small ISR trampoline; on platforms where allocation in the callback path is unsafe
    // (AVR, some no-heap STM32 builds), this overload returns false and the C-pointer
    // overload remains the only option.
    bool onTimeout(fl::function<void()> cb);

    // Pause watchdog counting while a debugger is attached. true if applied.
    bool setPauseOnDebug(bool pause);

    // Larger crash log written to flash (NVS / EEPROM / SmartEEPROM / LittleFS).
    // Bounded at 256 bytes for portability. Empty span on platforms without flash backing.
    bool   writeCrashLog(fl::span<const uint8_t> payload);
    size_t readCrashLog(fl::span<uint8_t> out) const;

    // Reboot into bootloader / DFU mode where supported.
    // RP: reset_usb_boot()  Teensy 4: software bootloader entry  nRF: GPREGRET sentinel
    // ESP32: download mode via GPIO0  AVR/SAMD/STM32: no-op + false
    bool rebootIntoBootloader();
};

Tier 2 — advanced platforms (Teensy 4, STM32 WWDG, SAMD, MGM240, ESP32 core dump)

class Watchdog {
public:
    // Window mode: feeds before window_min_ms also trigger reset.
    bool setWindow(uint32_t window_min_ms, uint32_t window_max_ms);

    struct CrashReport {
        bool      valid;
        uint32_t  pc, lr, psr;
        uint32_t  fault_status;   // CFSR on ARM, exccause on Xtensa
        uint32_t  fault_address;
        const char* fault_type;   // "HardFault", "LoadProhibited", etc.
    };
    // Teensy 4: bundled CrashReport. ESP32: core dump partition. Others: best effort.
    bool        hasCrashReport() const;
    CrashReport readCrashReport() const;
    void        clearCrashReport();
};

Capability macros (compile-time)

#define FL_WATCHDOG_HAS_HARDWARE          // 1 wherever a real or emulated WDT runs (incl. WASM + stub); 0 only on bare ports with no timer infra
#define FL_WATCHDOG_PERSIST_BYTES         // >= 8 always, larger on capable platforms
#define FL_WATCHDOG_HAS_PRE_TIMEOUT_IRQ   // ESP/Teensy/nRF/STM/SAMD/MGM/Apollo3
#define FL_WATCHDOG_HAS_WINDOW_MODE       // Teensy 4 / STM32 WWDG / SAMD / MGM240
#define FL_WATCHDOG_HAS_CRASH_REPORT      // Teensy 4 / ESP32 / SAMD51 / MGM240
#define FL_WATCHDOG_HAS_BOOTLOADER_REBOOT // RP / Teensy 4 / nRF / ESP32
#define FL_WATCHDOG_MAX_TIMEOUT_MS        // 8000 on AVR, larger on everything else

Implementation layout

Follows the existing FastLED conventions:

  • Public header in src/fl/
  • Single dispatcher as *.impl.cpp.hpp in src/platforms/ — same pattern as src/platforms/coroutine.impl.cpp.hpp and src/platforms/channel_drivers.impl.cpp.hpp. Detects the platform via is_*.h headers and #includes the right per-platform impl.
  • Per-platform impls as *.impl.hpp next to existing platform code (matching coroutine_runtime_wasm.impl.hpp, coroutine_esp32.impl.hpp, etc.).
  • No-op fallback in src/platforms/shared/ with _noop.hpp suffix — same pattern as pin_noop.hpp, memory_noop.hpp, simd_noop.hpp.
src/fl/wdt/
  watchdog.h                       # public API (fl::Watchdog, ResetCause); exposed via FastLED.watchdog()
  reset_cause.h                    # ResetCause enum + helpers

src/platforms/
  watchdog.impl.cpp.hpp            # SINGLE dispatcher — selects platform impl via is_*.h macros

src/platforms/shared/
  watchdog_noop.hpp                # Truly unsupported boards only — all methods no-op (matches memory_noop.hpp style).
                                   # NOT used for WASM or stub — those get real emulated implementations below.

src/platforms/wasm/
  watchdog_wasm.impl.hpp           # Emulated WDT via the existing FastLED WASM ISR infrastructure
                                   # (same path used by coroutine_runtime_wasm.impl.hpp). Timer-driven
                                   # callback proxied through emscripten_set_timeout / JS-side setTimeout
                                   # into a wasm-side handler. "Reset" = call onTimeout cb + emscripten_force_exit
                                   # or a JS-controlled reboot of the sketch loop. Persist storage backed by
                                   # localStorage / IDBFS. Full Tier 0 + Tier 1 onTimeout callback supported.

src/platforms/stub/
  watchdog_stub.impl.hpp           # Emulated WDT for the host build. Uses std::chrono + a watchdog thread
                                   # OR the existing emulated ISR infrastructure in src/platforms/isr.h
                                   # (cf. isr_null.hpp and the tests that already exercise emulated handlers).
                                   # "Reset" = call onTimeout cb then std::abort() (or longjmp back into setup()
                                   # under FASTLED_STUB_REBOOT_VIA_LONGJMP). Persist storage backed by a tmp
                                   # file in the test working directory so unit tests can verify the
                                   # crash-counter / safe-mode behavior end-to-end on host CI. Full Tier 0 +
                                   # Tier 1 onTimeout callback supported.

src/platforms/esp/32/
  watchdog_esp32.h                 # EXISTING public header — refactor to implement fl::Watchdog
  watchdog_esp32.impl.hpp          # NEW: routes to idf4/idf5 sub-impls
  watchdog_esp32_idf4.impl.hpp     # RENAMED from watchdog_esp32_idf4.hpp — keep weak-symbol override
  watchdog_esp32_idf5.impl.hpp     # RENAMED from watchdog_esp32_idf5.hpp — keep esp_register_shutdown_handler

src/platforms/arm/mxrt1062/
  watchdog_mxrt1062.impl.hpp       # WDT_T4<WDT3> wrapper + CrashReport bridge

src/platforms/arm/k20/
  watchdog_k20.impl.hpp            # direct WDOG regs + startup_early_hook() override

src/platforms/arm/rp/
  watchdog_rp.impl.hpp             # routes to rp2040/rp2350 sub-impls via is_rp2040.h / is_rp2350.h
  watchdog_rp2040.impl.hpp         # hardware/watchdog.h + scratch[0..3]
  watchdog_rp2350.impl.hpp         # adds POWMAN.SCRATCH + richer reset cause

src/platforms/arm/nrf52/
  watchdog_nrf52.impl.hpp          # NRF_WDT + GPREGRET (mind Adafruit bootloader values)

src/platforms/arm/stm32/
  watchdog_stm32.impl.hpp          # IWDG + RTC BKP, WWDG optional

src/platforms/arm/d21/
  watchdog_samd21.impl.hpp         # WDT peripheral + FlashStorage
src/platforms/arm/d51/
  watchdog_samd51.impl.hpp         # WDT peripheral + SmartEEPROM

src/platforms/avr/
  watchdog_avr.impl.hpp            # avr/wdt.h + EEPROM, with .init3 MCUSR=0/wdt_disable()

src/platforms/arm/mgm240/
  watchdog_mgm240.impl.hpp         # em_wdog.h + BURAM/RETREG

src/platforms/apollo3/
  watchdog_apollo3.impl.hpp        # am_hal_wdt_* + flash for persistence

src/FastLED.h
  + fl::Watchdog& CFastLED::watchdog();   # singleton accessor

Naming conventions used (matches existing tree):

  • The unsupported-platform fallback is the no-op impl (not "null") — file is watchdog_noop.hpp, mirroring pin_noop.hpp / memory_noop.hpp / simd_noop.hpp in src/platforms/shared/. WASM and stub do NOT fall into the no-op bucket — both ship real emulated implementations (see below).
  • The dispatcher uses the .impl.cpp.hpp suffix (single file, #included once by the platform aggregator), mirroring src/platforms/coroutine.impl.cpp.hpp.
  • Per-platform implementations use the .impl.hpp suffix, mirroring coroutine_runtime_wasm.impl.hpp, coroutine_esp32.impl.hpp, etc.

Why WASM and stub get real implementations, not no-op:
Both platforms already carry emulated ISR / timer / coroutine infrastructure that the rest of FastLED reuses (src/platforms/isr.h, src/platforms/wasm/coroutine_runtime_wasm.impl.hpp, src/platforms/stub/ thread/mutex/semaphore shims). That infrastructure is enough to host a working WDT: the timer fires on a deadline, the callback runs, and "reset" maps to std::abort() / emscripten_force_exit / a longjmp back to setup(). This unlocks the most important thing this whole API enables — host-side unit tests of the crash-counter + safe-mode logic without flashing a board. Tier 0 + the onTimeout part of Tier 1 are fully supported on both. The _noop.hpp fallback is reserved for genuinely unsupported boards that have no timer infrastructure available to us.

Migration path

  1. Phase 1 — land fl::Watchdog interface + watchdog_noop.hpp + the stub/WASM emulated impls; refactor existing src/platforms/esp/32/watchdog_esp32.h to implement it (zero behavior change for ESP32, just structure). The stub impl unblocks host-CI tests of the crash counter / safe-mode logic for everything that follows.
  2. Phase 2 — Teensy 4 (WDT_T4<WDT3> + CrashReport bridge). Fixes the AutoResearch bricking documented at AutoResearch.ino:204-214. Removes the TODO.
  3. Phase 3 — RP2040/RP2350 (high value for Pico AutoResearch).
  4. Phase 4 — nRF52, STM32, SAMD21/51 (broad coverage).
  5. Phase 5 — AVR, Apollo3, MGM240, Teensy 3.x (long tail, AVR mainly for MCUSR=0 boot-loop fix).

Test plan

  • Host unit tests via the stub emulated impl — tests/fl/watchdog.cpp exercises the full Tier 0 + Tier 1 surface (begin/feed/disable, reset cause, persist read/write, consecutive crash counter, safe mode, onTimeout for both the C-pointer and fl::function overloads, bootloader-reboot returning false on unsupported features). The stub impl uses a real thread-backed deadline timer, so timeouts and feed races are reproducible on host CI.
  • Browser smoke tests via the WASM emulated impl — the WASM build is exercised by the existing WASM test harness; verifies the JS-side timeout callback path and localStorage-backed persist storage.
  • Integration test pattern in examples/AutoResearch/AutoResearch.ino:
    • Replace lines 204-214 + 314-316 with FastLED.watchdog().begin(15000) and if (FastLED.watchdog().isInSafeMode()) { /* skip LED init, USB only */ }.
    • Add an RPC command deliberateHang() that returns success then while(true){} — must see watchdog reset → boot count increment → safe mode after threshold.
    • Verify FastLED.watchdog().rebootIntoBootloader() triggers UF2 on RP and Teensy Loader on T4.
  • Hardware validation per platform via bash autoresearch <board>.

Risks / open questions

  • Memory cost on AVR — fl::Watchdog class size must be near-zero; consider a static-method-only implementation gated behind FL_WATCHDOG_HAS_HARDWARE.
  • Reset-cause register clears on read on some STM32 / SAMD variants — Watchdog::begin() must read and cache once, then return cached value forever.
  • K20 one-shot unlock window requires intercepting startup_early_hook() — this conflicts with sketches that already override it. Document a FASTLED_WDT_TAKE_STARTUP_HOOK opt-in macro.
  • Multi-core (ESP32, ESP32-S3/P4, RP) — Tier 0 monitors core that calls feed(). Per-core watching is Tier 3 and out of scope here.
  • Adafruit nRF52 bootloader values for GPREGRET (0x57, 0xA8, 0x4e, 0x90, 0xB0) must be avoided when writing the safe-mode flag.

Naming note

The public accessor is FastLED.watchdog() rather than FastLED.wdt() — wdt is acronym jargon, watchdog is the same word every embedded API uses (mbed::Watchdog, Watchdog_t4, hardware/watchdog.h). The same vocabulary applies to the capability macros: FL_WATCHDOG_*, not FL_WDT_*. The macro identifier and the public API name share one vocabulary so readers don't have to learn two names for the same thing. This is now codified in agents/docs/cpp-standards.md as the Type 3 component capability flag convention — spell out the component name, no acronym aliases.

References

Activity

  1. changed the title [-]Unified cross-platform Watchdog Timer API via FastLED.wdt() singleton[/-] [+]Unified cross-platform Watchdog Timer API via FastLED.watchdog() singleton[/+] on Jun 4, 2026
  2. zackees commented on Jun 4, 2026

    @zackees
    MemberAuthor

    Phase 1 PR opened: #2738

    Lands the unified API surface + host-testable stub impl + ESP32 refactor of the existing fl::watchdog_setup(). Every platform compiles and routes through the dispatcher — supported platforms get their impl, the rest fall through to the codified _noop.hpp fallback (#2732).

    What's in #2738:

    • ✅ Public header fl/wdt/watchdog.h — Tier 0 + Tier 1 + Tier 2 API surface
    • ✅ FastLED.watchdog() god-object accessor
    • ✅ Dispatcher platforms/watchdog.impl.cpp.hpp
    • ✅ No-op fallback platforms/shared/watchdog_noop.hpp
    • ✅ Stub host impl with thread-backed deadline timer — 15/15 host tests pass
    • ✅ ESP32 wraps the existing fl::watchdog_setup() (preserves Windows phantom-COM-port fix)
    • ✅ FL_WATCHDOG_* capability macros per Type 3 convention from docs(conventions): codify noop fallback and FL_<COMPONENT>_HAS_* macro patterns #2732
    • ✅ FL_NORETURN instead of [[noreturn]] per src/fl/stl/compiler_control.h:543

    Tracked for Phase 2+ follow-ups (separate PRs):

    • Teensy 4 (WDT_T4<WDT3> + CrashReport bridge) — highest priority, fixes the AutoResearch bricking documented in AutoResearch.ino:204-214
    • Teensy 3.x (K20/K66/KL26 register code with startup_early_hook intercept)
    • RP2040 + RP2350 (hardware/watchdog.h + scratch[0..3], plus POWMAN.SCRATCH on RP2350)
    • nRF52 (Adafruit BSP — NRF_WDT + GPREGRET, mind bootloader values)
    • STM32 (IWDG + RTC BKPxR, optional WWDG)
    • SAMD21 (FlashStorage) / SAMD51 (SmartEEPROM)
    • AVR (avr/wdt.h + EEPROM + .init3 MCUSR=0 boot-loop fix)
    • Apollo3 (am_hal_wdt_*)
    • MGM240 (em_wdog.h + BURAM / NVM3)
    • WASM emscripten-emulated impl (currently routes to noop)

    Conventions PR #2732 has already merged — the noop / .impl.cpp.hpp / FL_<COMPONENT>_HAS_* patterns are now codified in agents/docs/cpp-standards.md.

  3. zackees commented on Jun 4, 2026

    @zackees
    MemberAuthor

    Phase 1 merged in #2738 (commit c2faf92e) — closing this issue as the API design + dispatcher + universally-compiling infrastructure is now in master.

    What landed:

    • fl::Watchdog Tier 0 + Tier 1 + Tier 2 API surface (src/fl/wdt/watchdog.h)
    • FastLED.watchdog() god-object accessor
    • Dispatcher (src/platforms/watchdog.impl.cpp.hpp) routing to platform fragments
    • _noop.hpp fallback (src/platforms/shared/watchdog_noop.hpp) — every platform without an explicit impl compiles unconditionally
    • Stub host implementation with thread-backed deadline timer (src/platforms/stub/watchdog_stub.impl.hpp) — 15/15 unit tests
    • ESP32 implementation wrapping the existing fl::watchdog_setup() (src/platforms/esp/32/watchdog_esp32.impl.hpp); disable() now does real TWDT teardown via a new fl::watchdog_disable() entry with esp_task_wdt_deinit() failure propagated through to the caller (no more lying about being disabled)
    • FL_WATCHDOG_* capability macros per the Type 3 convention codified in docs(conventions): codify noop fallback and FL_<COMPONENT>_HAS_* macro patterns #2732
    • FL_NORETURN (from src/fl/stl/compiler_control.h:543) used throughout

    The unified API surface is callable on every supported MCU today — the no-op fallback lets sketches compile and run unconditionally. Per-platform hardware implementations are tracked in #2744 (Teensy 4 / 3, RP2040 / 2350, nRF52, STM32, SAMD21 / 51, AVR, Apollo3, MGM240, WASM emulated), each as an independent follow-up PR.

    Thanks to CodeRabbit for the four rounds of review feedback that caught:

    • Watchdog::instance() function-local static needing to move out of the public header (Teensy 3.x __cxa_guard ABI conflict)
    • ESP32 crash counter needing to live in the persist tail so the Phase 2 RTC_NOINIT_ATTR move is automatic
    • onTimeout() silently shortening the active timeout when registered after begin()
    • setWindow() advertising window mode on the stub before any backend honored it
    • Worker-thread data races on reset_was_watchdog / fired / crash_count
    • Distinguishing software reboot from watchdog crash in the stub's ResetCause
    • Real esp_task_wdt_deinit() teardown + return propagation through Watchdog::disable()

    Resolved at: c2faf92e0e88cefc984a2bbd49766486407386a4

  4. moved this from Triage to Done in FastLED Trackeron Jun 4, 2026
  5. zackees commented on Jun 4, 2026

    @zackees
    MemberAuthor

    Reopening — Phase 1 (#2738) landed only stub/ESP32; the per-platform hardware impls for ALL remaining platforms (Teensy 4/3, RP, nRF52, STM32, SAMD, Apollo3, MGM240, AVR) are now in PR #2745 as one squashed PR per the original design intent. Will close again when #2745 merges.

  6. reopened this on Jun 4, 2026
  7. moved this from Done to Triage in FastLED Trackeron Jun 4, 2026
  8. zackees commented on Jun 4, 2026

    @zackees
    MemberAuthor

    ALL platforms merged via one squashed PR — #2745 at `ca09808b`.

    Closing as fully resolved. The complete set of per-platform hardware implementations is now in master:

    Platform Backend Merged in
    Host / stub thread-backed deadline timer #2738
    ESP32 family wraps existing `fl::watchdog_setup()` + real `esp_task_wdt_deinit()` teardown #2738
    AVR `avr/wdt.h` + critical `.init3` MCUSR=0 + `wdt_disable()` boot-loop fix with `sAvrCapturedMcusr` in `.noinit` #2745
    Teensy 4.x (iMXRT1062) `WDT_T4` (RTWDOG) — fixes the AutoResearch bricking from `AutoResearch.ino:204-214` #2745
    Teensy 3.x / LC (K20/K66/KL26) direct `WDOG` register unlock + LPO-clocked timeout #2745
    RP2040 / RP2350 Pico SDK `hardware/watchdog.h` + `reset_usb_boot()` bootloader entry #2745
    nRF52 (Adafruit BSP) `NRF_WDT` registers + `POWER->RESETREAS` write-1-to-clear; preserves Adafruit bootloader GPREGRET sentinels #2745
    STM32 `IWatchdog` library + `RCC->CSR`/`RSR` per-family cause distinguishing with RMVF clear #2745
    SAMD21 / SAMD51 `Adafruit_SleepyDog` library #2745
    Apollo3 `am_hal_wdt_*` + `RSTGEN->STAT` reading with CLRSTAT #2745
    MGM240 (EFR32MG24) `em_wdog.h` Gecko SDK with corrected `WDOG_PeriodSel_TypeDef` mapping #2745
    WASM routes to noop (Phase 3 emscripten timer follow-up) #2738
    Any other / missing library `_noop.hpp` fallback via `FL_HAS_INCLUDE` guards #2745

    The unified `fl::Watchdog` API at `FastLED.watchdog()` works on every supported MCU today.

    Critical fixes caught in review

    • AVR: removed wrongly-applied `attribute((naked))` from the `.init3` constructor (toolchain UB with C statements); moved `sAvrCapturedMcusr` to `.noinit` section (was being clobbered by `.init4`).
    • MGM240: corrected `WDOG_PeriodSel_TypeDef` enum names — the originally-written `wdogPeriod_16/32/...` identifiers don't exist in the Gecko SDK and would have failed to compile on real hardware.
    • Teensy 4.1 CI failure caught the assumption that `Watchdog_t4.h` is auto-installed; fixed via `FL_HAS_INCLUDE` guards on every library-dependent platform so missing optional libraries fall through to noop instead of breaking the build.
    • ESP32: real `esp_task_wdt_deinit()` teardown via `fl::watchdog_disable()` with return-value propagation through `Watchdog::disable()` so callers aren't misled when teardown fails.
    • STM32: proper `RCC->CSR`/`RSR` cause distinguishing instead of every-non-IWDG-is-power-on.

    Phase 3 follow-ups (not closing this issue for)

    The Tier-0 API surface and capability macros are stable across the transition; Phase 3 is purely backing-storage migration without user-visible API change:

    • Persistent crash counter / safe-mode flag backing per platform:
      • ESP32: `RTC_NOINIT_ATTR` (or `__NOINIT_ATTR` on P4)
      • Teensy 4: OCRAM2 retained region above `CrashReport`
      • RP2040/2350: persist `crash_count` in `watchdog_hw->scratch[3]`; RP2350 `POWMAN.SCRATCH` for power-cycle survival
      • nRF52: InternalFS (mind Adafruit bootloader GPREGRET sentinels)
      • AVR: EEPROM with wear awareness
      • SAMD51: SmartEEPROM; SAMD21: FlashStorage
      • Apollo3: flash via `am_hal_flash_*`
      • MGM240: BURAM / RETREG / NVM3
      • STM32: RTC backup registers
    • WASM emscripten emulated impl (timer + `localStorage`-backed persist)
    • `onTimeout(fl::function<void()>)` overload for the platforms where `fl::function` is allocator-safe
    • Crash log to flash (`writeCrashLog`/`readCrashLog`) backing per platform
    • Window mode + decoded `CrashReport` struct for the platforms that support them

    Resolved at: `ca09808b5fba182524a10fd2d64dfe5842f53947`

  9. moved this from Triage to Done in FastLED Trackeron Jun 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions