Skip to content

"Power button preset override" for on/off are retained after Factory Reset #5562

Open

Description

@Yersi88

What happened?

"Power button preset override for On:" setting is retained between Factory Resets.

To Reproduce Bug

  1. Change "Power button preset override for On:" to value other than default 0.
  2. Apply settings.
  3. Choose 'Factory Reset' in Update Settings Menu.
  4. Apply settings.
  5. "Power button preset override for On:" remains at value you set it to in step 1.

Expected Behavior

Setting resets to default value of 0 after factory reset.

Install Method

Binary from WLED.me

What version of WLED?

WLED version: 16.0.0 (2605030)

Which microcontroller/board are you seeing the problem on?

ESP32

Relevant log/trace output

Anything else?

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. added
    needs investigation
    on May 4, 2026
  2. DedeHai commented on May 4, 2026

    @DedeHai
    Collaborator

    both factory reset path's call
    WLED_FS.format(); doReboot = true;

    so either this is a bug in littleFS or it is async and gets halted by the reboot. I have no other explanation that would not wipe the file system flash.
    @willmmiles do you see any other reason?

  3. softhack007 commented on May 4, 2026

    @softhack007
    Member

    @DedeHai @willmmiles just a wild guess - could it be that writing to cfg.json is needed (asyncWebserver task is in serializeConfig()), then the filesystem is formated by the main task (cfg.json write still pending/preparing JSON), and then the pending write happens directly after formatting but before the reboot executes (next turn in main loop) ?

  4. DedeHai commented on May 4, 2026

    @DedeHai
    Collaborator

    @coderabbitai please trace the factory reset and confirm / disprove our theories.

  5. coderabbitai commented on May 4, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    # Find all occurrences of WLED_FS.format() and doReboot near factory reset
    rg -n "WLED_FS.format|doReboot|factoryReset|factory_reset" --type cpp -C5
    
    echo "=== serializeConfig ==="
    rg -n "serializeConfig" --type cpp -C3
    
    echo "=== handleSet or reboot triggers ==="
    rg -n "doReboot\s*=\s*true" --type cpp -C8
    

    Length of output: 37252


    🏁 Script executed:

    #!/bin/bash
    # Also check .h files
    rg -n "WLED_FS.format|doReboot|factoryReset|factory_reset" -C5
    rg -n "serializeConfig" -C3
    

    Length of output: 28818


    🏁 Script executed:

    #!/bin/bash
    # Get the main loop structure of wled.cpp
    cat wled00/wled.cpp | grep -n "void WLED::loop\|configNeedsWrite\|doReboot\|handleButton\|userLoop\|handleWs\|handleIR\|yield" | head -80
    

    Length of output: 652


    🏁 Script executed:

    #!/bin/bash
    # Get main loop context around the key lines
    sed -n '41,260p' wled00/wled.cpp
    

    Length of output: 7346


    @DedeHai Here's a detailed trace of both factory reset paths:


    Factory Reset Paths

    Path 1 — Web UI (wled00/set.cpp Lines 628–632 + 882)

    // In handleSet(), runs in async web server handler:
    if (request->hasArg(F("RS"))) {
        WLED_FS.format();                                       // (1) synchronous format
        serveMessage(request, 200, ...);                        // (2) send response
        doReboot = true;                                        // (3) set reboot flag
    }
    // ... at the very end of handleSet():
    configNeedsWrite = subPage != SUBPAGE_LEDS && !(subPage == SUBPAGE_SEC && doReboot);
    //  ↑ evaluates to FALSE when factory reset was triggered   // (4) guard clears write flag

    Path 2 — Button (wled00/button.cpp Lines 328–330)

    if (dur > WLED_LONG_FACTORY_RESET) {
        WLED_FS.format();   // (1) synchronous format
        doReboot = true;    // (2) set reboot flag
        // ⚠️ NO configNeedsWrite = false guard here!
    }

    Main Loop Order (wled00/wled.cpp)

    handleIO()         ← handleButton() lives here (EARLY in loop)
      ...
    doInitBusses block → configNeedsWrite = true  ← Line 225 (can set flag!)
      ...
    if (configNeedsWrite) serializeConfigToFS();  ← Line 232
      ...
    if (doReboot && ...) reset();                 ← Line 255
    

    Theory Analysis

    ❌ DedeHai's theory (format() is async / interrupted by reboot)

    Disproved. WLED_FS.format() is synchronous — it blocks until complete. doReboot = true is only set after format() returns, and reset() only fires from the main loop at Line 255. There is no way reboot can interrupt the format.

    ✅ softhack007's theory (config write after format, before reboot)

    Confirmed, but the mechanism is slightly different from the description — serializeConfigToFS() is called from the main loop (Line 232), not directly from the async server. The trigger is the configNeedsWrite flag.

    The critical race has two flavours:

    Flavour A — Button path (deterministic bug, no race needed)

    handleButton() runs inside handleIO() early in the loop, before Line 232. It calls format() + sets doReboot = true but never clears configNeedsWrite. Later in the same loop iteration:

    • If configNeedsWrite was already true from any prior operation → serializeConfigToFS() fires right after format ✅ reproduces
    • The doInitBusses block at Line 225 can also set configNeedsWrite = true in that very same iteration
    Same loop iteration:
      handleIO() → handleButton() → format() → doReboot=true
           ...
      doInitBusses block → configNeedsWrite = true   ← potential trigger
           ...
      configNeedsWrite? YES → serializeConfigToFS()  ← writes cfg.json to clean FS!
           ...
      doReboot? YES → reset()
    

    Flavour B — Web UI path on dual-core ESP32 (race condition)

    The web UI path has the configNeedsWrite = false guard at Line 882, which protects single-core (ESP8266) completely. But on ESP32 dual-core:

    • Core 0 (async handler): format() → doReboot = true → (eventually) configNeedsWrite = false
    • Core 1 (main loop): If it reads configNeedsWrite == true (set by a prior request) and executes Line 232 concurrently while Core 0 is anywhere between format() starting and Line 882 executing, it writes cfg.json to the filesystem being formatted.

    The existing comment at Line 632 (// may reboot immediately on dual-core system (race condition)) shows the devs were already aware of dual-core sensitivity in this function.


    Suggested Fix

    The cleanest fix covers both paths: clear configNeedsWrite before formatting, and do it in both places:

    wled00/set.cpp (Web path — move the guard earlier):

    if (request->hasArg(F("RS"))) {
        configNeedsWrite = false;   // ← add: prevent post-format write on dual-core
        doReboot = true;            // ← move doReboot before format so main loop can't run serializeConfig
        WLED_FS.format();
        serveMessage(...);
    }

    wled00/button.cpp (Button path — add missing guard):

    if (dur > WLED_LONG_FACTORY_RESET) {
        configNeedsWrite = false;   // ← add: prevent serializeConfigToFS in same loop iteration
        WLED_FS.format();
        doReboot = true;
    }

    Alternatively, the main loop check at Line 232 could be strengthened:

    if (configNeedsWrite && !doReboot) serializeConfigToFS();

    This single-line change would protect both paths and any future ones.

  6. softhack007 commented on May 4, 2026

    @softhack007
    Member

    lessons learned: global state is a nightmare 😓

    We could try the "fix covers both paths" from the rabbit - it does not make much sense to keep a config write pending after FS re-formating.

  7. DedeHai commented on May 4, 2026

    @DedeHai
    Collaborator

    @coderabbitai in the webUI path, is the configNeedsWrite always set when confirming the factory reset through the UI or do conditions apply? since this is the path the issue is about it would mean that the race condition is met every time - or it is pretty much an edge case hit by bad luck.

  8. coderabbitai commented on May 4, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    # Get the full handleSet function to understand the flow
    echo "=== Full handleSet function in set.cpp ==="
    grep -n "configNeedsWrite\|void handleSet\|void WLED_GLOBAL\|subPage\|SUBPAGE_SEC\|SUBPAGE_LEDS\|hasArg.*RS\|doReboot" wled00/set.cpp | head -80
    
    echo ""
    echo "=== Context around RS factory reset block ==="
    grep -n "hasArg.*RS\|RS.*hasArg" wled00/set.cpp -A 10 -B 5
    
    echo ""
    echo "=== The configNeedsWrite assignment at end of handleSet ==="
    tail -60 wled00/set.cpp
    
    echo ""
    echo "=== Where configNeedsWrite is set to true in set.cpp ==="
    grep -n "configNeedsWrite\s*=\s*true" wled00/set.cpp -B3 -A3
    
    echo ""
    echo "=== Where configNeedsWrite is set anywhere globally ==="
    grep -rn "configNeedsWrite\s*=" --include="*.cpp" --include="*.h" -B2 -A2
    

    Length of output: 5872


    @DedeHai — No, configNeedsWrite is not always true on the Web UI path. The race is a genuine edge case, not guaranteed. Here's the breakdown:

    Why it's NOT always triggered

    handleSettingsSet() does not set configNeedsWrite = true anywhere inside the function. The only assignment is at the very end (Line 882), which clears it when factory reset is detected:

    configNeedsWrite = subPage != SUBPAGE_LEDS && !(subPage == SUBPAGE_SEC && doReboot);
    // → evaluates to false when factory reset is triggered

    So the race only fires if configNeedsWrite was already true from a prior, still-pending operation when the factory reset request arrives. That's the two-condition requirement on dual-core ESP32:

    1. Something set configNeedsWrite = true before the factory reset request
    2. Core 1 (main loop) reads and acts on it during the window between WLED_FS.format() completing on Core 0 and Line 882 clearing the flag

    What can put configNeedsWrite into a pending-true state

    From the code, these are the only setters:

    Location Trigger
    wled.cpp:225 Bus re-initialization (doInitBusses block)
    wled_server.cpp:460 JSON API config save
    presets.cpp:242 Boot preset changed
    dmx_input.cpp:25,43 DMX personality / start address changed

    Most likely triggering scenario

    The most plausible path to hit this in the field is:

    • User changes LED configuration → bus re-init runs → configNeedsWrite = true (wled.cpp:225)
    • User then quickly navigates to the Security page and triggers factory reset
    • The pending write hasn't flushed yet, and Core 1 wins the race window

    Bottom line

    • Button path = deterministic bug (same loop iteration, no luck needed)
    • Web UI path on ESP32 = race condition, bad luck required — but the probability isn't negligible if the user made any config change in the same session before factory resetting

    The !doReboot guard in the main loop (if (configNeedsWrite && !doReboot) serializeConfigToFS()) would be the most defensive single-line fix covering both paths, since doReboot is set before Line 232 is reached in the button case, and on ESP32 the async handler sets it early enough for most timing scenarios.

  9. DedeHai commented on May 4, 2026

    @DedeHai
    Collaborator

    given that it is almost impossible to have configNeedsWrite set prior to doing a factory reset through the UI I would call the rabbits analysis either incomplete or wrong. The finding of playing it save in the main loop is still a good idea. If it is in fact the root cause for the issue raised this is an extreme edge case.

  10. softhack007 commented on May 4, 2026

    @softhack007
    Member

    Maybe the better solution is to "serialize" filesystem formatting so it only happens in the main loop. Similar to doReboot, we could add doReformat, and the main loop would take care of setting configNeedsWrite = false, then doing doCloseFile(); WLED_FS.format(); doReboot = true; in a single place. WebUI and other locations would only request doReformat = true, so the real re-formating happens later with a well-controlled sequence.

    Secondary bug: both doReboot and configNeedsWrite are missing the volatile attribute, so different tasks can have different "opinions" about the value.

    WLED/wled00/wled.h

    Lines 890 to 891 in e321514

    WLED_GLOBAL bool configNeedsWrite _INIT(false); // flag to initiate saving of config
    WLED_GLOBAL bool doReboot _INIT(false); // flag to initiate reboot from async handlers

    My experience with multitasking is "never assume <can't happen>" 😉 if there is a time window for races or a potential to get into an almost-impossible state, this will happen.

  11. DedeHai commented on May 4, 2026

    @DedeHai
    Collaborator

    good point. Lets fix it that way.
    I am not saying it can not happen, it definitely can. But it is very highly unlikely so having someone hit these exact conditions within a few millisecond window... manually. I have seen bugs that caused havoc in a sub micro-second window more than once - its not a question on IF but WHEN :) the fun of race conditions.

  12. softhack007 commented on May 4, 2026

    @softhack007
    Member

    But it is very highly unlikely

    I agree, otherwise we would have heard about this problem earlier - the mechanism is the same since 0.14.x, maybe upgrading the framework (and the FreeRTOS kernel) has made it more likely to happen.

  13. DedeHai commented on May 4, 2026

    @DedeHai
    Collaborator

    One thing I only learned last week: apparently at each boot, the config gets re-saved (after initbuses is called, at least the rabbit claimed so).

  14. self-assigned this
    on May 4, 2026
  15. blazoncek commented on May 8, 2026

    @blazoncek
    Contributor

    FYI OP issue lies in browser's local storage (which persists factory restore in the same way presets do).
    Clearing browser's local storage or assigning different IP/mDNS name will redirect browser to allocate new storage area.

    BTW stop relynig on rabbit's flawed analyses.

  16. DedeHai commented on May 9, 2026

    @DedeHai
    Collaborator

    Thanks for the pointer. I did not know the button override is not even part of the config but only exists in the UI.
    @softhack007 while the findings about that race condition stand, they have nothing to do with this issue, in my assumption that this being part of the config I derailed the analysis.
    Having the browser cache persist between firmware updates and factory resets is a bit of a weak spot. We could add a variable to the json info that tells the browser to clear the cache & localstorage, then clear that variable. That way at least the first browser to load the UI would be cleaned.

  17. blazoncek commented on May 9, 2026

    @blazoncek
    Contributor

    Browser's local storage is intended and deliberate functionality.

    Changing it will be a breaking change an will also make preset recovering from accidental factory reset (via button or otherwise) unavailable.

    However, theoretical race condition for saving config during reboot request will require ms timing (loop executes about 1500 times/s) which is unlikely (but not impossible). One-line solution from @coderabbitai is adequate if you want to prevent that.

    Intentional clearing of browser's local storage is implemented in settings already but perhaps not documented.

  18. softhack007 commented on May 9, 2026

    @softhack007
    Member

    @DedeHai I'm also surprised that "Power button preset override" is not stored on the device cfg.json but its a per-frontend (browser) setting like some "UI settings" 🤔 maybe we should move these into cfg.json, does not make much sense to me that the option is stored on browser level.

    Having the browser clear its cache & localstorage on a factory reset makes sense 👍, in addition to fixing the race condition we found earlier. I have a proper fix for the race condition in my head already :-)

  19. coderabbitai commented on May 9, 2026

    @coderabbitai
  20. softhack007 commented on May 9, 2026

    @softhack007
    Member

    this is the feature request where "power button preset override" was discussed

    Edit: the concern that "clear browser cache & localstorage" will also clear the stored presets.json (making presets recovery unavailable) is a good point, we should be careful to preserve the presets cached in localstorage as a backup.

    Edit2: Setting stored on the browser localstorage are listed here, I think we should clear them all (or most of them?) on a factory reset

    var l = {
    "comp":{
    "labels":"Show button labels",
    "colors":{
    "LABEL":"Color selection methods",
    "picker": "Color Wheel",
    "rgb": "RGB sliders",
    "quick": "Quick color selectors",
    "hex": "HEX color input"
    },
    "pcmbot": "Show bottom tab bar in PC mode",
    "pid": "Show preset IDs",
    "seglen": "Set segment length instead of stop LED",
    "segpwr": "Hide segment power &amp; brightness",
    "segexp" : "Always expand first segment",
    "css": "Enable custom CSS",
    "hdays": "Enable custom Holidays list",
    "fxdef": "Use effect default parameters",
    "on": "Power button preset override for On",
    "off": "Power button preset override for Off",
    "idsort": "Sort presets by ID"
    },
    "theme":{
    "alpha": {
    "bg":"Background opacity",
    "tab":"Button opacity"
    },
    "bg":{
    "url":"BG image URL",
    "rnd":"Random BG image",
    "rndGrayscale":"Grayscale",
    "rndBlur":"Blur"
    },
    "color":{
    "bg":"BG HEX color"
    }
    }
    };

    <hr><button type="button" onclick="cLS()">Clear local storage</button>

  21. changed the title [-]"Power button preset override for On:" retained after Factory Reset.[/-] [+]"Power button preset override" for on/off are retained after Factory Reset[/+] on May 9, 2026
  22. added
    confirmed
    and removed
    needs investigation
    on May 9, 2026
  23. softhack007 commented on May 9, 2026

    @softhack007
    Member

    @coderabbitai please remember there are two methods in WLED for persisting user settings.

    • browser/app local storage (example settings_ui.htm)
    • LittleFS filesystem (cfg.json, presets.json)
  24. coderabbitai commented on May 9, 2026

    @coderabbitai
    Contributor

    @softhack007, noted and recorded! This distinction is important — the factory reset fix must handle both layers independently:

    • WLED_FS.format() handles the LittleFS side (cfg.json, presets.json)
    • The JavaScript localStorage.clear() (injected via the reset confirmation page) handles the browser side

    And as you raised in the earlier comment, the cached presets in localStorage (wledP, wledPmt) arguably should not be cleared on factory reset, to allow preset recovery. The selective clearing approach (clearing UI/config keys like wledUiCfg, locIp, pcm but keeping preset backup keys) from settings_ui.htm lines 20–57 is the safer path.


    ✏️ Learnings added
    Learnt from: softhack007
    URL: https://github.com/wled/WLED/issues/5562
    
    Timestamp: 2026-05-09T13:44:14.652Z
    Learning: In the WLED codebase (C++/ESP32/ESP8266), user settings are persisted via two independent mechanisms:
    1. **Browser/app localStorage** — stores UI preferences and settings client-side (e.g., `wledUiCfg`, `locIp`, `pcm`, `wledP`, `wledPmt`, `wledPalx`). Managed by the frontend JavaScript in files like `wled00/data/settings_ui.htm`.
    2. **LittleFS filesystem** — stores device-side configuration (`cfg.json`) and presets (`presets.json`) on the ESP's flash. Managed by the firmware via `WLED_FS`.
    A factory reset (`WLED_FS.format()`) only clears the LittleFS side. Browser localStorage must be cleared separately via JavaScript injected into the reset confirmation page. Presets cached in localStorage (`wledP`, `wledPmt`) should ideally be preserved during factory reset to allow preset recovery.
    

    Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

  25. added this to the 16.1 milestone on May 10, 2026
  26. modified the milestones: 16.1, 17.0 on Jun 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugconfirmed

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions