Skip to content

Normalized non-allocating reset/crash classification API for FastLED.watchdog() #2755

Closed

Description

@zackees

Motivation

The unified watchdog API (#2731, landed in #2738 + follow-ups) gives a portable ResetCause enum and WatchdogCrashReport struct, but anyone who wants a human-readable description of what just reset the chip still has to write code like this (taken from examples/AutoResearch/AutoResearch.ino lines 374-392):

const uint32_t srsr = SRC_SRSR;
Serial.print("[boot] SRC_SRSR = 0x");
Serial.println(srsr, HEX);
if (srsr & SRC_SRSR_WDOG3_RST_B)        Serial.println("[boot]   WDOG3_RST_B (RTWDOG fired)");
if (srsr & SRC_SRSR_WDOG_RST_B)         Serial.println("[boot]   WDOG_RST_B (WDOG1/2 fired)");
if (srsr & SRC_SRSR_IPP_RESET_B)        Serial.println("[boot]   POR (power-on reset)");
if (srsr & SRC_SRSR_LOCKUP_SYSRESETREQ) Serial.println("[boot]   LOCKUP_SYSRESETREQ (HardFault)");
if (srsr & SRC_SRSR_IPP_USER_RESET_B)   Serial.println("[boot]   IPP_USER_RESET_B (external pin)");
if (srsr & SRC_SRSR_JTAG_SW_RST)        Serial.println("[boot]   JTAG/SW reset");

That's eight lines of platform-specific bit-twiddling per sketch — not portable, not idiomatic, easy to get the bit positions wrong (which I did get wrong in this very file — the prior version had every shift off by 1–9 bits, see PR #2753 P0 fix).

There should be a normalized, allocation-free, no-destructor classification API that handles the cross-platform 90% case in one line, but also gives an escape hatch for the platform-specific bits when a sketch genuinely needs them.

Design

Three tiers, layered so each tier just composes the previous one. Zero heap allocation, zero non-trivial destructors anywhere on the hot path.

Tier 0 — normalized enum + zero-cost name

The existing fl::ResetCause enum gains a paired free function returning a static name through fl::string_view:

namespace fl {

enum class ResetCause : fl::u8 {
    UNKNOWN, POWER_ON, BROWNOUT, EXTERNAL_PIN,
    WATCHDOG, SOFTWARE, LOCKUP, DEBUGGER, PANIC,
};

// Returns a static-lifetime view of the enum name.
// String literal lives in FLASH on embedded platforms.
// Zero cost — compiles to a constant pointer + length.
constexpr fl::string_view resetCauseName(ResetCause c) noexcept;

} // namespace fl

Usage:

fl::string_view name = fl::resetCauseName(FastLED.watchdog().lastResetCause());
Serial.write(name.data(), name.size());   // "WATCHDOG"

Why fl::string_view: non-owning, no allocation, no destructor, already in the tree (src/fl/stl/string_view.h). Backed by a string literal in flash.

Tier 1 — ResetInfo with platform raw register + describe() to caller buffer

Adds a ResetInfo struct that bundles the normalized cause with a platform-specific subcause id and the raw register value, plus a describe() method that writes a human-readable summary to a caller-owned buffer.

namespace fl {

struct ResetInfo {
    ResetCause cause;          // Normalized cross-platform enum
    fl::u8     subcauseId;     // Platform-specific subcause id (0 = none)
    fl::u32    rawRegister;    // Raw value of the platform's reset-cause register
                               // (SRC_SRSR on Teensy 4, MCUSR on AVR, RESETREAS on nRF52, etc.)

    // Free, allocation-less name views
    fl::string_view causeName() const noexcept { return resetCauseName(cause); }
    fl::string_view subcauseName() const noexcept;   // "WDOG3", "WDOG1/2", or ""

    // Write a single-line human-readable description into out.
    // Format:  "<cause>"          if subcauseId == 0
    //          "<cause> (<sub>)"  if subcauseId != 0 and verbose==false
    //          "<cause> (<sub>) raw=0x<hex>"   if verbose==true
    //
    // Returns number of bytes written (not including a trailing NUL — but
    // a NUL is appended if there's room). Truncates safely if out is too
    // small. Never allocates.
    fl::size describe(fl::span<char> out, bool verbose = false) const noexcept;
};

class Watchdog {
public:
    // ... existing API ...
    ResetInfo lastResetInfo() const noexcept;
};

} // namespace fl

Usage:

ResetInfo info = FastLED.watchdog().lastResetInfo();
char buf[64];
fl::size n = info.describe(fl::span<char>(buf, sizeof(buf)), /*verbose=*/true);
Serial.write(buf, n);   // "WATCHDOG (WDOG3) raw=0x00000080"

The subcauseId lets a sketch distinguish "WDOG3 fired" from "WDOG1/2 fired" on Teensy 4 without leaking the actual SRC_SRSR_*_B macros into user code. The rawRegister field is the escape hatch for sketches that genuinely need the bit pattern.

Tier 2 — CrashReport with decoded fault frame

Already exists as WatchdogCrashReport. The proposal adds describe() and switches the fault_type raw const char* to fl::string_view:

namespace fl {

struct CrashReport {
    bool valid;

    // ARM Cortex-M fault frame (zero on platforms without it)
    fl::u32 pc;
    fl::u32 lr;
    fl::u32 psr;
    fl::u32 cfsr;          // Configurable Fault Status Register
    fl::u32 hfsr;          // HardFault Status Register
    fl::u32 fault_address; // BFAR or MMFAR

    // Platform-defined fault classification
    fl::string_view faultType() const noexcept;     // "HardFault" / "LoadProhibited" / ""

    // Source location (empty if not embedded by the platform's crash hook)
    fl::string_view sourceFile() const noexcept;
    fl::u32         sourceLine() const noexcept;

    // Multi-line human-readable description to caller's buffer.
    // Format:
    //   "<faultType> @ PC=0x<hex> LR=0x<hex>\n"
    //   "  CFSR=0x<hex> BFAR=0x<hex>\n"
    //   "  (file: <sourceFile>:<sourceLine>)\n"   <-- if available
    fl::size describe(fl::span<char> out) const noexcept;

    // Tier Max escape hatch — platform-specific extended struct.
    // Cast to fl::Mxrt1062CrashDetails* on Teensy 4, fl::Esp32CrashDetails*
    // on ESP32, etc. nullptr if no extended data on this platform.
    const void* platformDetails() const noexcept;
    fl::size    platformDetailsSize() const noexcept;
};

} // namespace fl

Usage:

auto report = FastLED.watchdog().crashReport();
if (report.valid) {
    char buf[256];
    fl::size n = report.describe(fl::span<char>(buf, sizeof(buf)));
    Serial.write(buf, n);
}

Tier 1.5 — FL_WATCHDOG_AUTOFEED() macro for zero-setup loop() integration

The shortest path to a working watchdog for a typical user: drop one macro at the top of loop() and never touch setup() for the WDT at all. Lazy-init on first call, RAII feed in the destructor.

void setup() {
    Serial.begin(115200);
    // No watchdog code here — the macro below does everything.
}

void loop() {
    FL_WATCHDOG_AUTOFEED();   // First line of loop()

    doWork();
    FastLED.show();
    // Destructor fires here at end of scope → calls feed() automatically.
}

The macro is variadic — pass nothing for the 15 000 ms default, or pass an explicit uint32_t timeout:

// Variadic macro — optional timeout argument with default 15000 ms.
// Calls the default ctor when no arg is passed, the explicit-timeout ctor
// when one is. Same macro name covers both common forms.
#define FL_WATCHDOG_AUTOFEED(...) \
    ::fl::ScopedWatchdog FL_CONCAT(_fl_wdt_, __LINE__) { __VA_ARGS__ }

Examples — same macro, optional argument:

void loop() {
    FL_WATCHDOG_AUTOFEED();      // 15 000 ms default (most common case)
    // …
}

void loop() {
    FL_WATCHDOG_AUTOFEED(5000);  // 5-second timeout for tighter loops
    // …
}

void loop() {
    FL_WATCHDOG_AUTOFEED(60000u);  // 60 s for sketches with long blocking flash writes
    // …
}

Where ScopedWatchdog does this:

namespace fl {

class ScopedWatchdog {
public:
    // Default-construct with the library default timeout (15 s).
    ScopedWatchdog() noexcept : ScopedWatchdog(15000u) {}

    explicit ScopedWatchdog(fl::u32 timeout_ms) noexcept {
        // Function-local static: zero-cost after the first invocation.
        // Single-threaded loop() is the canonical caller — no atomics needed.
        static bool sInitialized = false;
        if (!sInitialized) {
            sInitialized = true;
            firstInit(timeout_ms);
        }
        // Feed IMMEDIATELY on construction. Together with the destructor
        // feed below, this means a long synchronous block at the top of
        // loop() starts with a fresh deadline AND the entire iteration is
        // covered before the next `loop()` call lands. If the work between
        // construction and destruction exceeds the configured timeout the
        // WDT still bites — which is exactly the intent.
        Watchdog::instance().feed();
    }

    ~ScopedWatchdog() noexcept {
        // Feed again at end-of-scope so the *next* iteration of `loop()` has
        // a full timeout window before its own construction-side feed lands.
        Watchdog::instance().feed();
    }

    ScopedWatchdog(const ScopedWatchdog&) = delete;
    ScopedWatchdog& operator=(const ScopedWatchdog&) = delete;

private:
    static void firstInit(fl::u32 timeout_ms) noexcept {
        auto& wdt = Watchdog::instance();
        wdt.begin(timeout_ms);

        // If the previous boot died, print a diagnostic and pause for 3 s
        // so the developer can actually see it on the serial monitor before
        // the new loop iteration overwrites the screen.
        ResetInfo info = wdt.lastResetInfo();
        if (info.cause == ResetCause::WATCHDOG ||
            info.cause == ResetCause::PANIC    ||
            info.cause == ResetCause::LOCKUP) {

            char buf[128];
            fl::size n = info.describe(fl::span<char>(buf, sizeof(buf)), /*verbose=*/true);
            // Use the same print sink the rest of FastLED uses so this works
            // on stub/WASM too. fl::println(string_view) is unconditional.
            fl::print("[FastLED.watchdog] recovered from: ");
            fl::println(fl::string_view(buf, n));

            // Also print decoded crash report if Tier 2 platform has it.
            if (wdt.hasCrashReport()) {
                CrashReport rep = wdt.crashReport();
                char rbuf[256];
                fl::size rn = rep.describe(fl::span<char>(rbuf, sizeof(rbuf)));
                fl::print("[FastLED.watchdog] crash report:\n");
                fl::println(fl::string_view(rbuf, rn));
            }

            // 3-second pause so the developer can actually read the message.
            // Uses fl::delay() so this works on every platform including stub.
            fl::delay(3000);
        }

        // Always log a one-line "ready" so users know the macro fired.
        fl::println("[FastLED.watchdog] armed via FL_WATCHDOG_AUTOFEED()");
    }
};

} // namespace fl

Why a macro, not a plain class? Two reasons:

  1. The unique-name trick (FL_CONCAT(_fl_wdt_, __LINE__)) avoids accidental name collisions if the user nests blocks or has multiple guards.
  2. Future evolution: we can add __FILE__ / __LINE__ capture for breadcrumb-style debugging without breaking call sites.

Why static bool sInitialized and not a Singleton? Function-local statics on Cortex-M/AVR are zero-cost after the first call (just a branch on a guard byte). On Teensy 3.x there's a __cxa_guard_* ABI nuance, but Teensyduino provides weak implementations that are safe in single-threaded loop() — already used by fl::Singleton<T> elsewhere in the tree.

Why fl::delay(3000) and not delay()? fl::delay() works on the host stub (where Arduino delay() doesn't exist), works on WASM (where it cooperatively yields), and is the existing FastLED-portable name.

What if Serial.begin() hasn't run yet? The macro defers all output through fl::print / fl::println which are no-ops if no sink is attached. Users who care about seeing the recovery message will already have Serial.begin() in setup() before loop() runs (since loop() doesn't execute until setup() returns).

Tier Max — platform-specific escape hatch via void*

Per-platform header defines the extended struct cast type:

// src/platforms/arm/mxrt1062/watchdog_mxrt1062.h
namespace fl {
struct Mxrt1062CrashDetails {
    fl::u32 src_srsr;        // Raw SRC.SRSR
    fl::u32 src_gpr5;        // GPR5 sentinel (lockup vs SYSRESETREQ disambiguation)
    fl::u32 wdog3_cs;        // RTWDOG state at capture
    // ... whatever else this platform has ...
};
}

User opt-in:

#if defined(FL_IS_TEENSY_4X)
#include "platforms/arm/mxrt1062/watchdog_mxrt1062.h"

auto report = FastLED.watchdog().crashReport();
auto* details = static_cast<const fl::Mxrt1062CrashDetails*>(report.platformDetails());
if (details) {
    Serial.print("SRSR = 0x"); Serial.println(details->src_srsr, HEX);
}
#endif

Capability gating macro: FL_WATCHDOG_HAS_PLATFORM_DETAILS — defined per-platform if platformDetails() returns non-null.

Why fl::span<char> for the dynamic content and not fl::string

The user's framing of the requirement: "fl::string which doesn't allocate memory, nor destruct the memory". The closest existing type is fl::StrN<N> (inline buffer string), but for the embedded use case the right answer is the caller-owns-the-buffer pattern:

Approach Allocates? Destructor? Truncation-safe? Mixes-with-Serial.write? Good for:
fl::string (returned) Sometimes (heap if > inline) Non-trivial No (resizes) Yes General purpose, not embedded hot path
fl::StrN<N> (returned) No Trivial if N covers it Yes (truncates silently) Yes Bounded fixed-size content
fl::string_view (returned) No None N/A (read-only) Yes Fixed string literals (Tier 0 names)
fl::span<char> (taken) No None Yes (returns bytes written) Yes Dynamic content with caller-chosen capacity

The describe() method takes fl::span<char> for dynamic content because:

  • The caller controls capacity (stack buffer, retained-RAM buffer, network MTU, …)
  • The method returns the number of bytes written so the caller can Serial.write(buf, n)
  • Truncation is safe and explicit
  • Same shape as snprintf() so the pattern is instantly recognizable
  • Zero allocation, zero destructor

fl::string_view is the right return type for Tier 0 fixed names because they're literally addresses of string literals in flash.

Fluent integration

The struct describes are chainable from FastLED.watchdog():

char buf[128];
fl::size n = FastLED.watchdog().lastResetInfo().describe(buf);
Serial.write(buf, n);

Or for the most common one-liner case:

auto cause_name = FastLED.watchdog().lastResetCauseName();  // fl::string_view shortcut
Serial.println(cause_name);  // works via fl::println(string_view) overload

Per-platform implementation plan

Each platform's watchdog_*.impl.hpp extends its existing reset-cause translation to also populate subcauseId + rawRegister:

Platform Raw register Subcauses to expose
Teensy 4 SRC_SRSR WDOG3, WDOG1/2, LOCKUP_SYSRESETREQ (with SRC_GPR5 sentinel disambiguation), JTAG_SW, IPP_USER, IPP_RESET
Teensy 3 RCM_SRS0 / RCM_SRS1 WDOG, LVD, PIN, POR, LOCKUP, SW, MDM_AP
ESP32 esp_reset_reason() result TASK_WDT, INT_WDT, WDT, PANIC, BROWNOUT, DEEPSLEEP, USB, JTAG
RP2040/2350 VREG_AND_CHIP_RESET/POWMAN.CHIP_RESET WATCHDOG, RUN_PIN, POR, BOR (RP2350), DP_RESET_REQ (RP2350), GLITCH_DETECT (RP2350)
nRF52 POWER->RESETREAS DOG, RESETPIN, SREQ, LOCKUP, OFF, LPCOMP, DIF
STM32 RCC->CSR / RCC->RSR IWDG, WWDG, SFT, POR/BOR, PIN, LPWR, OBL
SAMD PM->RCAUSE / RSTC->RCAUSE POR, BOD12, BOD33, EXT, WDT, SYST, BACKUP (SAMD51)
Apollo3 RSTGEN->STAT EXTRSTAT, PORSTAT, BORSTAT, SWRSTAT, POIRSTAT, DBGRSTAT, WDRSTAT
AVR MCUSR WDRF, BORF, EXTRF, PORF
MGM240 EMU->RSTCAUSE POR, PIN, EM4, WDOG0, WDOG1, LOCKUP, SYSREQ, *BOD*
Host stub synthesized WATCHDOG, SOFTWARE
WASM/noop (none) ""

Each platform's describe() implementation runs a small switch on subcauseId to emit the short name; the helper format is shared.

Test plan

  • Host unit tests against the stub impl in tests/fl/wdt/:
    • describe() writes exactly the expected bytes for each cause
    • describe() truncates safely when buffer is too small
    • describe() writes a NUL terminator if there's room
    • causeName() returns the right fl::string_view per enum value
    • fl::span<char>(nullptr, 0) is safe (returns 0, no UB)
  • ESP32 hardware verification: trigger a watchdog reset, confirm info.describe() produces "WATCHDOG (TASK_WDT) raw=0x00000003" or similar
  • Teensy 4 hardware verification: trigger deliberateHang, confirm post-reset boot prints "WATCHDOG (WDOG3) raw=0x80" (this PR feat(watchdog): Teensy 4 bare-register WDOG3 impl, hardware-verified #2753 already proved the reset path works — just the description is bit-twiddly)

Migration

Existing API stays compatible:

  • lastResetCause() keeps returning ResetCause
  • lastResetWasWatchdog() keeps returning bool
  • WatchdogCrashReport becomes CrashReport typedef-aliased for source compatibility

New additions:

  • fl::resetCauseName(ResetCause) — Tier 0
  • fl::ResetInfo + Watchdog::lastResetInfo() — Tier 1
  • CrashReport::describe() and CrashReport::faultType() returns fl::string_view — Tier 2
  • CrashReport::platformDetails() — Tier Max escape hatch

AutoResearch.ino's eight-line bit-twiddle becomes one line:

char buf[64];
Serial.write(buf, FastLED.watchdog().lastResetInfo().describe(buf, /*verbose=*/true));

References

Activity

  1. zackees commented on Jun 5, 2026

    @zackees
    MemberAuthor

    Verified the API landed: fl::resetCauseName(ResetCause) is in src/fl/wdt/watchdog.h (and used as the causeName() accessor on the crash report struct), shipped in #2756 ("feat(watchdog): non-allocating reset/crash classification API + ScopedWatchdog"). Closing as resolved. Please reopen with a specific gap if any tier of the proposed design is still missing.

  2. moved this from Triage to Done in FastLED Trackeron Jun 5, 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