Skip to content

Partial POST /json/cfg resets unrelated settings (linked remotes, FPS, auto-white mode, gamma, I2C, 2D setup, some usermod settings) #5883

Open

Description

@Tycorc

What happened?

After I sent a small POST /json/cfg that only changed the LED power cap, the WiZmote I had paired stopped working. GET /json/cfg showed "linked_remote": [] where it had shown my remote's MAC before, and the empty list survived a reboot.

Reading wled00/cfg.cpp (deserializeConfig), this seems to be what the code does when the posted document has no nw object: linked_remotes.clear() runs before the lookup of nw.linked_remote, and the list is only refilled when that key is present.

  JsonObject nw = doc["nw"];
#ifndef WLED_DISABLE_ESPNOW
  CJSON(enableESPNow, nw[F("espnow")]);
  linked_remotes.clear();
  JsonVariant lrem = nw[F("linked_remote")];
  if (!lrem.isNull()) {

The neighbouring lists in the same function (nw.ins, dns, hw.btn.ins, bus ins, timers) appear to be guarded by an isNull() check, so a partial POST leaves them alone. I may be missing a reason why the remote list is handled differently; if the JSON API is expected to always send the complete nw block, this is a documentation question rather than a bug, and I would be glad to know.

As far as I can tell from the history, the earlier single-remote code used getStringFromJson, which does not touch the variable when the key is absent, and the behaviour changed with the multi-remote support in #4654. I have not bisected that, it is from reading the diff.

To Reproduce Bug

  1. Pair a WiZmote via WiFi settings → Linked MACs, confirm GET /json/cfg shows the MAC under nw.linked_remote.
  2. curl -X POST -H 'Content-Type: application/json' -d '{"hw":{"led":{"maxpwr":4000}}}' http://<wled>/json/cfg
  3. GET /json/cfg → "linked_remote": [], remote no longer reacts, still empty after reboot.

Sending the same POST with "nw":{"espnow":true,"linked_remote":["<mac>"]} included keeps the remote, which is what I do now as a workaround.

Expected Behavior

I expected a /json/cfg write to leave settings it does not mention unchanged, as it does for the WiFi list and the buttons. If that expectation is right, moving the clear() inside the if (!lrem.isNull()) block, or guarding the block with if (!nw.isNull()), would be one possible fix. Happy to open a PR if a maintainer confirms the intended behaviour.

Install Method

Self-Compiled

What version of WLED?

16.0.0 (build 2605030) on the device; the same lines are present in the 16.0.1 tag and in main as of 2026-10-03, which I only checked by reading, not by flashing.

Which microcontroller/board are you seeing the problem on?

ESP32

Relevant log/trace output

GET  /json/cfg  -> "nw":{"espnow":true,"linked_remote":["4cebd6203de7"], ...}
POST /json/cfg  {"hw":{"led":{"maxpwr":4000}}}  -> {"success":true}
GET  /json/cfg  -> "nw":{"espnow":true,"linked_remote":[], ...}

Anything else?

Seen from home automation that writes single settings over the JSON API. The settings web form is not affected as far as I can see, since it submits the whole list every time.

Update 2026-10-04

Same function, 4 more settings reset on a partial POST, different cause: hw.led.rgbwm, hw.led.fps, light.gc.bri and light.gc.col fall back to a constant when the key is missing (cfg.cpp L183, L189, L531, L532 on main). After a POST with only hw.led.maxpwr: fps 30 back to 42, auto-white mode back to disabled, Brightness Gamma off, a disabled colour Gamma on again, all written to cfg.json. Confirmed on ESP8266 with 16.0.1 and main. Details in the comments, fix is in #5885 as a second commit.

Activity

  1. DedeHai commented on Oct 3, 2026

    @DedeHai
    Collaborator

    The cfg endpoint is tailored to the config htm pages, I dont think it is cosidered an API to be used as it can mess things up, as you discovered. I think KB even states not to use that endpint.

    Edit: I cant currently check code, so there may be a legit bug here

    Edit2: @Tycorc can you check how other vector lists differ from the remote wrt the code you posted above? I.e. clear and rebuild?

  2. willmmiles commented on Oct 3, 2026

    @willmmiles
    Member

    The cfg endpoint is tailored to the config htm pages, I dont think it is cosidered an API to be used as it can mess things up, as you discovered. I think KB even states not to use that endpint.

    We should probably keep tabs on this, given the intent to replace the settings UI. Native JSON cfg writing is the obvious alternative.

  3. blazoncek commented on Oct 4, 2026

    @blazoncek
    Contributor

    /json/cfg is a configuration endpoint for JSON capable configurators (like xLights, LedFX, etc). Configuration JSON submitted should work with partially filled config keys.

    This is a bug. Cause: cfg.cpp L:65

  4. Tycorc commented on Oct 4, 2026

    @Tycorc
    Author

    @DedeHai checked against main (1252853). linked_remotes is the only list in deserializeConfig whose clear runs outside the key's presence check. The others clear and rebuild only when their array is in the document:

    list guard clear
    strip.panel if (!matrix.isNull()) strip.panel.clear() inside the guard (cfg.cpp ~L195/199)
    buttons if (!hw_btn_ins.isNull()) buttons.clear() inside the guard (~L367/370)
    timers if (!timersArray.isNull()) clearTimers() inside the guard (~L705/706)
    busConfigs if (!ins.isNull()) cleared only in the else if (fromFS) branch (~L264/267), so a partial POST leaves the buses alone
    multiWiFi if (!nw_ins.isNull()) never cleared, resized and overwritten in place (~L87/89)
    linked_remotes if (!lrem.isNull()) linked_remotes.clear() before the guard (L65)

    Before #4654 the single remote was read with getStringFromJson(linked_remote, nw[F("linked_remote")], 13), which leaves the variable untouched when the key is absent, so the partial-POST case used to be safe. The vector port moved the reset in front of the lookup.

    Minimal fix is to move the clear inside the guard, matching the other lists:

      JsonVariant lrem = nw[F("linked_remote")];
      if (!lrem.isNull()) {
        linked_remotes.clear();
        if (lrem.is<JsonArray>()) {

    An explicit "linked_remote": [] still empties the list, so the settings page's unpair path is unchanged. I can open the PR against main if that shape is what you want.

  5. softhack007 commented on Oct 4, 2026

    @softhack007
    Member

    @Tycorc you are an AI agent? I've never seen humans who use tables to explain a simple fix.

    But it might be a correct fix, we can check.

  6. Tycorc commented on Oct 4, 2026

    @Tycorc
    Author
  7. softhack007 commented on Oct 4, 2026

    @softhack007
    Member

    I can open the PR against main if that shape is what you want.

    @Tycorc if your suggested change solves it for you, yes feel free to open a PR. We can continue our discussion when reviewing the PR.

    Please be sure to read though our contributor guidelines https://github.com/wled/WLED?tab=contributing-ov-file first, especially in case you want to use AI assistance for the PR.

  8. added a commit that references this issue on Oct 4, 2026
    6bdea2d
  9. Tycorc commented on Oct 4, 2026

    @Tycorc
    Author

    While testing #5885 i found 4 more Settings that get resetted on a partial /json/cfg post, same function, different cause. They fall back to a constant when the key is missing instead of the current value like CJSON does for the rest. cfg.cpp on main:

    L183: Bus::setGlobalAWMode(hw_led[F("rgbwm")] | AW_GLOBAL_DISABLED);
    L189: unsigned targetFPS = hw_led["fps"] | WLED_FPS;
    L531: float light_gc_bri = light["gc"]["bri"] | 1.0f;
    L532: float light_gc_col = light["gc"]["col"] | gammaCorrectVal;

    Result after a post with only hw.led.maxpwr: fps 30 back to 42, rgbwm back to disabled, Brightness Gamma off, and a disabled colour Gamma turns on again. All written to cfg.json. Confirmed on my 8266 with 16.0.1 and main. The constants came from the fresh install fixes #5225 and #5408, Brightness Gamma is resetted since 0.14 and #5225 fixed only the colour half.

    Fix is the same 4 lines with fallback = current value, fresh install still gets the defaults cause nothing wrote the variables at that point. Tested on the 8266, builds for esp32dev and nodemcuv2.

    Kinda the same bug i would assume. Will wait for advise how to proceed, seperate issue + Pull request or add it to #5885.

  10. Aircoookie commented on Oct 4, 2026

    @Aircoookie
    Member

    Will wait for advise how to proceed, seperate issue + Pull request or add it to #5885.

    Given that the proposed fixes aim to solve more instances of the same underlying issue, feel free to add it to #5885 :)

  11. changed the title [-]Partial POST /json/cfg without an nw block clears the linked ESP-NOW remotes — intended?[/-] [+]Partial POST /json/cfg resets settings it does not mention (linked remotes, FPS, auto-white mode, gamma)[/+] on Oct 4, 2026
  12. Tycorc commented on Oct 4, 2026

    @Tycorc
    Author
  13. blazoncek commented on Oct 5, 2026

    @blazoncek
    Contributor

    "hw":{"led":{"rgbwm",...}} is deprecated and should be removed (Bus::setGlobalAWMode() is legacy workaround to help upgrade from 0.13)

    Same principle (legacy compatibility) is applied to gamma. Not the best approach but having brightness gama != 1 is something not really desired.

  14. Tycorc commented on Oct 5, 2026

    @Tycorc
    Author

    @blazoncek thanks for the info, i tested an alternative for the gamma part: instead of key | current only touch the flag when the key is in the document, which is what 0.13 did (cfg.cpp L238 in v0.13.3: > 1.5 on, > 0.5 off, else untouched). 0.14 turned the else into = false, thats where the reset comes from.

      JsonVariant gc_bri = light["gc"]["bri"]; // 1.0 = off, absent = keep current
      JsonVariant gc_col = light["gc"]["col"];
      if (!gc_bri.isNull()) gammaCorrectBri = (gc_bri.as<float>() != 1.0f);
      if (!gc_col.isNull()) gammaCorrectCol = (gc_col.as<float>() != 1.0f);

    builds for esp32dev and nodemcuv2, verified on my 8266 as well, solves the issue too, incl. the corner coderabbit flagged on the PR (flag set while gc.val is 1.0). this fix or the one in pr both look fine to me, i dont know the codebase well enough to jugde what is to be prefered.

    Regarding rgbwm: i looked into this and i get why the global override should be removed moving forward, usually would always prefer to stay consistent, but removing eol stuff needs to start somewhere. for this PR i keep or drop the rgbwm line, just let me know.

  15. blazoncek commented on Oct 5, 2026

    @blazoncek
    Contributor

    @Tycorc just a hint: There's just one gamma table. You can't have different gamma for brightness and color.

  16. Tycorc commented on Oct 5, 2026

    @Tycorc
    Author

    @blazoncek oh well, made it more complicate in my head then it needed to be. only on/off...

  17. softhack007 commented on Oct 11, 2026

    @softhack007
    Member

    @coderabbitai please scan the source code for other cfg.json items that could be reset to default by a partial post to /json/cfg - for example I2C pins, SPI pins, timers, etc.

  18. coderabbitai commented on Oct 11, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    git rev-parse HEAD
    git status --short
    fd -i '^(cfg\.cpp|json\.cpp|usermod.*|.*contribut.*)$'
    ast-grep outline wled00/cfg.cpp --items all
    rg -n -C3 'deserializeConfig\s*\(|readFromConfig\s*\(' wled00
    gh pr view 5885 --repo wled/WLED --json title,state,headRefName,files

    Length of output: 8686


    🏁 Script executed:

    #!/bin/bash
    sed -n '1,400p' wled00/cfg.cpp | nl -ba
    sed -n '401,784p' wled00/cfg.cpp | nl -ba -v401
    sed -n '851,1284p' wled00/cfg.cpp | nl -ba -v851
    ast-grep outline wled00/wled_server.cpp --items all
    sed -n '410,475p' wled00/wled_server.cpp | nl -ba -v410
    rg -n -C2 'bool\s+readFromConfig\s*\(' usermods
    gh pr diff 5885 --repo wled/WLED

    Length of output: 85831


    🏁 Script executed:

    #!/bin/bash
    fd -i 'pin_manager|ntp|ethernet'
    rg -n -C4 'allocateMultiplePins\s*\(|setCountdown\s*\(|getJsonValue\s*\(' wled00 -g '*pin*' -g '*ntp*' -g 'fcn_declare.h'
    ast-grep run --lang cpp --pattern 'bool $NAME::readFromConfig($$$ARGS) { $$$BODY }' usermods --json=compact > /tmp/cfg-readers-qualified.json
    ast-grep run --lang cpp --pattern 'bool readFromConfig($$$ARGS) { $$$BODY }' usermods --json=compact > /tmp/cfg-readers-inline.json
    python - <<'PY'
    import json
    for filename in ['/tmp/cfg-readers-qualified.json','/tmp/cfg-readers-inline.json']:
        for match in json.load(open(filename)):
            print('\nREADER',match['file'],match['range']['start']['line']+1)
            lines=match['text'].splitlines()
            for i,line in enumerate(lines):
                if any(x in line for x in ['isNull(', 'getJsonValue(', ' | ', '.as<', '.clear(', ' = root', '= top[', '= umData[', '= 0;', '= false;', '= true;']):
                    print(f"{match['range']['start']['line']+i+1}: {line.strip()}")
    PY
    rg -n -C3 'getJsonValue\s*\(' wled00/fcn_declare.h

    Length of output: 7867


    🏁 Script executed:

    #!/bin/bash
    ast-grep outline wled00/pin_manager.cpp --items all
    sed -n '1,175p' wled00/pin_manager.cpp | nl -ba
    ast-grep outline wled00/ntp.cpp --match setCountdown
    sed -n '372,380p' wled00/ntp.cpp | nl -ba -v372
    ast-grep outline usermods --items all --match readFromConfig --type function,method
    python - <<'PY'
    from pathlib import Path
    import re
    for p in sorted(Path('usermods').rglob('*')):
        if p.suffix not in ('.h','.cpp'): continue
        s=p.read_text(errors='replace')
        for m in re.finditer(r'\bbool\s+(?:[\w:]+::)?readFromConfig\s*\([^;{}]*\)[^{;]*\{',s):
            start=m.end()-1; depth=1; end=start+1
            while end<len(s) and depth:
                depth+=(s[end]=='{')-(s[end]=='}'); end+=1
            text=s[m.start():end]; base=s[:m.start()].count('\n')+1
            print(f'\nREADER {p}:{base}')
            for i,line in enumerate(text.splitlines()):
                if any(x in line for x in ['isNull()', 'getJsonValue(', ' | ', '.clear(', '= root[', '= top[', '= umData[', '.as<']):
                    print(f'{base+i}: {line.strip()}')
    PY
    rg -n -C3 'Wire\.setPins\s*\(|HW_SPI|HW_I2C' wled00/pin_manager.cpp wled00/pin_manager.h

    Length of output: 59602


    🏁 Script executed:

    #!/bin/bash
    python - <<'PY'
    from pathlib import Path
    import re
    names={'Analog_Clock.cpp','BME68X_v2.cpp','LD2410_v2.cpp','boblight.cpp','deep_sleep.cpp','mpu6050_imu.cpp','usermod_gyro_surge.h','INA226_v2.cpp','usermod_rotary_brightness_color.cpp','BH1750_v2.cpp','BME280_v2.cpp','MAX17048_v2.cpp','usermod_v2_brightness_follow_sun.cpp'}
    for p in sorted(Path('usermods').rglob('*')):
        if p.name not in names: continue
        s=p.read_text(errors='replace')
        for m in re.finditer(r'\bbool\s+(?:[\w:]+::)?readFromConfig\s*\([^;{}]*\)[^{;]*\{',s):
            start=m.end()-1; depth=1; end=start+1
            while end<len(s) and depth:
                depth+=(s[end]=='{')-(s[end]=='}'); end+=1
            base=s[:m.start()].count('\n')+1
            print('\nFILE',p)
            for i,line in enumerate(s[m.start():end].splitlines()): print(f'{base+i}: {line}')
    PY
    rg -n -C2 '(UMOD_NAME|_name|_interrupt_pin|_x_acc_bias|_y_acc_bias|_z_acc_bias|_x_gyro_bias|_y_gyro_bias|_z_gyro_bias)\[\].*=' usermods/BME68X_v2 usermods/LD2410_v2 usermods/boblight usermods/deep_sleep usermods/mpu6050_imu usermods/BH1750_v2 usermods/BME280_v2 usermods/MAX17048_v2 usermods/usermod_v2_brightness_follow_sun
    fd -i 'platformio.*\.ini|.*esp32.*\.ini'
    rg -n -C2 'platform\s*=|platform_packages|framework-arduinoespressif32' -g '*.ini' .

    Length of output: 53272


    🤖 web_search executed:

    In Arduino-ESP32 TwoWire::setPins, does calling setPins after Wire.begin return false even if the SDA and SCL pins are unchanged? Check the implementation in Arduino-ESP32 2.0.17 and 3.x.

    Length of output: 1232


    🏁 Script executed:

    #!/bin/bash
    python - <<'PY'
    import urllib.request
    urls=[
    'https://raw.githubusercontent.com/espressif/arduino-esp32/3.3.8/libraries/Wire/src/Wire.cpp',
    'https://raw.githubusercontent.com/tasmota/arduino-esp32/3.3.8.260506/libraries/Wire/src/Wire.cpp',
    ]
    for url in urls:
        print('\nURL',url)
        try:
            text=urllib.request.urlopen(url,timeout=20).read().decode()
            lines=text.splitlines()
            for i,line in enumerate(lines):
                if 'bool TwoWire::setPins(' in line:
                    for j in range(i,min(i+38,len(lines))): print(f'{j+1}: {lines[j]}')
        except Exception as e:
            print(type(e).__name__,str(e))
    PY

    Length of output: 2181


    @softhack007 I found three additional core reset paths, plus several usermod reset paths.

    I scanned revision 5acf3371aee918046a10fb17fe857b707030121d and compared the changes in #5885. These findings come from source inspection, not device tests.

    Additional core reset paths

    1. I2C pins can become [-1, -1] on an unrelated POST

    wled00/cfg.cpp, Line 491–505

    CJSON preserves the current pin values when hw.if.i2c-pin is absent. However, the code then allocates the pins and initializes I2C without checking whether that key exists.

    On ESP32, this statement resets both stored pins if Wire.setPins() fails:

    if (!Wire.setPins(i2c_sda, i2c_scl)) { i2c_scl = i2c_sda = -1; }

    Upstream Arduino-ESP32 3.3.8 returns false after the bus has initialized, even when the requested pins are unchanged.

    Thus, with that behavior, an unrelated POST such as this can reset configured I2C pins:

    {"hw":{"led":{"maxpwr":850}}}

    The serializer writes the resulting -1 values to cfg.json. This does not necessarily stop the already-running bus immediately, but it loses the saved pin configuration.

    Recommended handling: initialize I2C at boot, or when an explicit pin change requires it. Do not call setPins() again for omitted or unchanged pins.

    The exact Tasmota fork source was unavailable at the URL checked. Its behavior still needs verification.

    2. Partial Wi-Fi entries reset static addresses

    wled00/cfg.cpp, Line 90–121

    If nw.ins is absent, existing Wi-Fi entries remain unchanged.

    If nw.ins contains an entry, the reader creates these temporary defaults:

    • ip: 0.0.0.0
    • gw: 0.0.0.0
    • sn: 255.255.255.0

    It then assigns those values to the existing entry, even when the address keys are absent. For example:

    {"nw":{"ins":[{"ssid":"new-ssid"}]}}

    This resets the first entry’s static address configuration.

    With WLED_ENABLE_WPA_ENTERPRISE, omitted enc_type, e_anon_ident, and e_ident also reset to PSK and empty identity strings.

    Recommended handling: initialize temporary values from the existing Wi-Fi entry. Use fresh defaults only for newly created entries.

    3. Partial matrix objects clear panels

    wled00/cfg.cpp, Line 194–218

    The guard checks matrix, not matrix.panels.

    Consequently, this request clears all existing panels:

    {"hw":{"led":{"matrix":{"mpc":2}}}}

    strip.panel.clear() runs before the reader checks whether panels exists. The reader also sets strip.isMatrix = true.

    Recommended handling: preserve panels when panels is absent. Keep an explicit "panels":[] as the clear operation.

    SPI pins and timers

    • SPI pins: I found no normal omitted-key reset. CJSON preserves the pins. PinManager explicitly permits repeated allocation by the same HW_SPI owner. However, every POST repeats allocation and SPI.begin(). Both SPI and I2C allocation counters increase on each successful call without a matching release. This is a separate lifecycle problem.
    • Timers: omitted timers.ins preserves the timer list. The countdown fields also preserve their values through CJSON.
    • Supplied timer arrays: timers.ins replaces the complete list. For example, [{"macro":5}] clears existing timers and creates a timer with default time, date range, and disabled state. This is array replacement, not an unrelated omitted-key reset. LED-output and button arrays also rebuild entries rather than merge their fields.

    Usermod reset paths

    If um is absent, no usermod reader runs. If um exists—even as {}—the manager calls every enabled usermod’s reader.

    The following readers reset settings even when their own object is absent:

    • usermods/Analog_Clock/Analog_Clock.cpp, Line 228–242: enable flags, ring positions, seconds effect, and blending.
    • usermods/BME68X_v2/BME68X_v2.cpp, Line 804–829: enabled state, I2C address, interval, publishing options, temperature settings, and sensor display options.
    • usermods/boblight/boblight.cpp, Line 336–340: edge counts and scan depth.
    • usermods/deep_sleep/deep_sleep.cpp, Line 273–286: wakeup pins, wake conditions, and sleep timing.
    • usermods/mpu6050_imu/mpu6050_imu.cpp, Line 388–395: enabled state, interrupt pin, and calibration offsets.
    • usermods/mpu6050_imu/usermod_gyro_surge.h, Line 157–158: max and sensitivity.
    • usermods/usermod_rotary_brightness_color/usermod_rotary_brightness_color.cpp, Line 172–175: fadeAmount and all three pins.

    These readers preserve an absent object, but reset omitted fields inside a supplied object:

    • BH1750_v2: enabled state, reading intervals, discovery, and offset — Line 158–162.
    • BME280_v2: I2C address, precision, intervals, units, and publishing options — Line 434–444.
    • MAX17048_v2: reading intervals and discovery — Line 250–252.
    • LD2410_v2: UART pins — Line 184–185.
    • usermod_v2_brightness_follow_sun: enabled state, update interval, brightness limits, and relaxation time — Line 101–105.
    • INA226_v2: CurrentOffset — Line 593–594.

    The common usermod cause is a constant fallback in getJsonValue(), or an explicit reset before reading JSON. Checking configComplete does not prevent those assignments.

    Priority: investigate I2C first because an unrelated POST can lose its saved pin configuration. The Wi-Fi, matrix, and usermod cases require the corresponding section in the request. None of these additional paths is changed by the current #5885 diff.

    You are interacting with an AI system.

  19. changed the title [-]Partial POST /json/cfg resets settings it does not mention (linked remotes, FPS, auto-white mode, gamma)[/-] [+]Partial POST /json/cfg resets settings it does not mention (linked remotes, FPS, auto-white mode, gamma, I2C, 2D setup, some usermod settings)[/+] on Oct 11, 2026
  20. changed the title [-]Partial POST /json/cfg resets settings it does not mention (linked remotes, FPS, auto-white mode, gamma, I2C, 2D setup, some usermod settings)[/-] [+]Partial POST /json/cfg resets unrelated settings (linked remotes, FPS, auto-white mode, gamma, I2C, 2D setup, some usermod settings)[/+] on Oct 11, 2026
  21. added
    AIPartly generated by an AI. Make sure that the contributor fully understands the code!
    on Oct 11, 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

    AIPartly generated by an AI. Make sure that the contributor fully understands the code!bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ 换网址