Skip to content

Stop mDNS before Wi-Fi teardown in initConnection() (#5945) - #5965

Merged
softhack007 merged 6 commits into
wled:mainfrom
sionnn9:fix/mdns-stop-before-wifi-teardown
Dec 2, 2026
Merged

softhack007 merged 6 commits into
wled:mainfrom
sionnn9:fix/mdns-stop-before-wifi-teardown

Conversation

@sionnn9

@sionnn9 sionnn9 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What it does

The issue was that when an ESP32-C5 switches the Wi-Fi band and reconnects, the board could crash, and a reboot fixes it. So what we did is stop mDNS before the Wi-Fi interface is destroyed. It is started again once the board has reconnected.

Additional references and context

How it works

We updated initConnection() in wled00/wled.cpp. Before WiFi.disconnect(true) it calls MDNS.end(), only if interfacesInited && strlen(cmDNS) > 0, meaning mDNS is actually running. It is inside #ifdef ARDUINO_ARCH_ESP32, so ESP8266 is unchanged. No restart code was added, because initInterfaces() already calls MDNS.end() and MDNS.begin() once the board is connected.

AI assistance: yes

  • What the AI drafted: we used AI to understand the code and the architecture and how it works to understand the error we reffered a comment onthe issue which gave us a breif understanding of where the issue was.
  • What I verified/tested myself: we reproduced the crash in an emulator simulating the ESP32-C5 board (details in the README linked above).
  • Untested / unsure about: we did not test on a real ESP32-C5, and we did not build locally.

Testing and Validation

Emulator: first we tested the unchanged code to recreate the error. It panicked on cycle 2 of 10 (backtrace: join_group in mDNS). With the change, there were no errors in three runs of 10 cycles. The emulator has one band, so there was no real 5 GHz connection. A temporary test harness triggered the band change and is not part of this PR.

  • Tested on actual hardware:
    • No, not tested on a real ESP32-C5.
  • Open ends, known limitations, breaking changes:
    • Not built locally because of a PlatformIO setup problem on my machine, so I'm relying on CI. One crash reproduction only, so no crash rate.
  • Anything you couldn't quite solve?
    • A real 2.4 GHz to 5 GHz test on hardware. It would be great if a maintainer with a C5 and a dual-band router could try it.

Checklist

  • I have personally reviewed all changes (incl. source code) before opening this PR.
  • I'm ready to explain my proposed source code changes in detail (without an AI agent answering for me).
  • I agree to follow this project's Code of Conduct

Summary by CodeRabbit

  • Bug Fixes
    • Improved local network service discovery during Wi-Fi reconnections by stopping mDNS before the network interface resets and restarting it after reconnection.
    • Improved cleanup of over-the-air update services when Wi-Fi disconnects.

@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

  • Source mode: Auto
  • Repository: wled/WLED
  • Branch: main
  • File: .coderabbit.yaml
  • Commit: c1f6bfb
  • Layers: Repository YAML (base), Repository UI (inherited), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 425b6837-b12f-4917-9bac-088d3e3d5d84
Commits

Reviewing files that changed from the base of the PR and between 59638de and c70cbe8.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

Walkthrough

On ESP32, WLED::initConnection() now stops mDNS and, when AOTA is enabled, ArduinoOTA before disconnecting Wi-Fi and switching the interface to WIFI_MODE_NULL. The code logs this shutdown. initInterfaces restarts mDNS after reconnecting.

Changes

mDNS and Wi-Fi reconnection

Layer / File(s) Summary
Stop network services before Wi-Fi teardown
wled00/wled.cpp
On ESP32, WLED::initConnection() logs the shutdown and stops mDNS and, when enabled, ArduinoOTA before Wi-Fi teardown.

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix

Possibly related issues

Possibly related PRs

  • wled/WLED#5719 — The HomeWizard usermod uses mDNS for meter discovery, which may be affected while mDNS is stopped during Wi-Fi teardown.

Suggested labels: bug, AI

Suggested reviewers: dedehai

Merge Risk: Minimal · previous review f3191

ESP32 network services are stopped before Wi-Fi teardown. No actionable merge-blocking risk was established.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly describes the main change: stopping mDNS before Wi-Fi teardown in initConnection(). It does not mention the secondary ArduinoOTA teardown, which is not required in the title.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 1 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@softhack007

Copy link
Copy Markdown
Member

thanks, the change looks reasonable. Needs testing on a real -C5 (and on -S3 for regression tests) before merging.

@softhack007

Copy link
Copy Markdown
Member

@coderabbitai are there other protocol handlers that should be stopped before Wi-Fi teardown, for example asyncWebserver?

@coderabbitai

coderabbitai Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
echo '=== Connection lifecycle outline ==='
ast-grep outline wled00/wled.cpp --items all --match 'initConnection|initInterfaces|handleConnection|WLED' --view expanded
echo '=== Connection and service lifecycle references ==='
rg -n -C 3 'initConnection\s*\(|initInterfaces\s*\(|interfacesInited|WiFi\.disconnect\s*\(|WIFI_MODE_NULL|MDNS\.(begin|end)|ArduinoOTA\.(begin|end)' wled00
echo '=== Web server and protocol references ==='
rg -n -C 2 'AsyncWebServer|server\.(begin|end|reset)|ws\.(begin|end|closeAll)|udp\.(begin|stop)|\.stop\(\)|mqtt\.(connect|disconnect)' wled00 -g '*.{cpp,h}'
echo '=== Network library version declarations ==='
rg -n -i -C 2 'ESPAsyncWebServer|AsyncTCP|ESPAsyncUDP|PubSubClient|AsyncMqttClient|arduino-esp32|platformio' -g '*.{ini,json,yml,yaml}' . | head -n 260

Length of output: 66439


Script executed:

#!/bin/bash
echo '=== AP and Wi-Fi teardown ==='
cat -n wled00/wled.cpp | sed -n '708,810p'
echo '=== Service initialization and reconnect handling ==='
cat -n wled00/wled.cpp | sed -n '921,1115p'
echo '=== Network event handling ==='
ast-grep outline wled00/network.cpp --items all --match 'event|Event' --view expanded
cat -n wled00/network.cpp | sed -n '440,535p'
echo '=== Network service declarations ==='
rg -n -C 2 '\b(notifierUdp|udpConnected|ntpUdp|e131|ddp|dnsServer|mqtt|espalexa|ws)\b' wled00/wled.h | head -n 220
echo '=== Service lifecycle calls ==='
rg -n -C 3 '\b(notifierUdp|ntpUdp|e131|ddp|dnsServer|espalexa|mqtt|ws)\.(begin|end|stop|connect|disconnect|closeAll|cleanupClients|listen|listenMulticast)\s*\(' wled00 -g '*.{cpp,h}'
echo '=== E1.31 and DDP implementation locations ==='
rg -n -C 2 'class (ESPAsyncE131|ESPAsyncDDP|.*E131|.*DDP)|bool (ESPAsyncE131|ESPAsyncDDP)::begin|void (ESPAsyncE131|ESPAsyncDDP)::' wled00 -g '*.{cpp,h}'
echo '=== Relevant ESP32 platform configuration ==='
cat -n platformio.ini | sed -n '145,155p;260,268p;315,355p;425,455p'

Length of output: 34368


Script executed:

#!/bin/bash
set -u
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
echo '=== Pinned ESPAsyncWebServer source ==='
url='https://raw.githubusercontent.com/Aircoookie/ESPAsyncWebServer/ac44e32abf2a69ae650412fb6bc193c59ccac38a/src/WebServer.cpp'
if curl -fsSL --max-time 20 "$url" -o "$tmp/WebServer.cpp"; then
  rg -n -C 5 'AsyncWebServer::(begin|end|reset)' "$tmp/WebServer.cpp"
else
  echo 'Pinned ESPAsyncWebServer source unavailable'
fi
echo '=== AsyncTCP 3.4.10 source ==='
url='https://raw.githubusercontent.com/ESP32Async/AsyncTCP/v3.4.10/src/AsyncTCP.cpp'
if curl -fsSL --max-time 20 "$url" -o "$tmp/AsyncTCP.cpp"; then
  rg -n -C 12 'AsyncServer::(begin|end)|tcp_bind\(|tcp_listen|IP_ADDR_ANY' "$tmp/AsyncTCP.cpp" | head -n 240
else
  echo 'AsyncTCP 3.4.10 source unavailable at tag v3.4.10'
fi

Length of output: 5801


Script executed:

#!/bin/bash
echo '=== E1.31 implementation outline ==='
ast-grep outline wled00/src/dependencies/e131/ESPAsyncE131.cpp --items all --view expanded
ast-grep outline wled00/src/dependencies/e131/ESPAsyncE131.h --items all --match 'ESPAsyncE131' --view expanded
echo '=== E1.31 setup and teardown ==='
cat -n wled00/src/dependencies/e131/ESPAsyncE131.cpp | sed -n '1,100p'
cat -n wled00/src/dependencies/e131/ESPAsyncE131.h | sed -n '218,248p'
echo '=== Alexa initialization ==='
ast-grep outline wled00/alexa.cpp --items all --view expanded
cat -n wled00/alexa.cpp | sed -n '1,60p'
ast-grep outline wled00/src/dependencies/espalexa/Espalexa.h --items all --match 'begin|end|stop|Espalexa' --view expanded
rg -n -C 4 'udp\.(begin|stop|beginMulticast)|joinMulticast|listenMulticast|void end\(|bool begin\(' wled00/src/dependencies/espalexa/Espalexa.h
echo '=== MQTT connection handling ==='
rg -n -C 3 'mqtt->(connect|disconnect)|initMqtt\s*\(|WLEDNetwork\.isConnected\s*\(' wled00/mqtt.cpp wled00/wled.cpp | head -n 180

Length of output: 13467


Script executed:

#!/bin/bash
set -u
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
base='https://raw.githubusercontent.com/Aircoookie/ESPAsyncWebServer/ac44e32abf2a69ae650412fb6bc193c59ccac38a/src'
for file in WebServer.cpp ESPAsyncWebServer.h; do
  if curl -fsSL --max-time 20 "$base/$file" -o "$tmp/$file"; then
    echo "=== Pinned web server: $file ==="
    rg -n -C 5 'AsyncWebServer::AsyncWebServer|AsyncWebServer\s*\(' "$tmp/$file" | head -n 100
  else
    echo "$file unavailable"
  fi
done
url='https://raw.githubusercontent.com/ESP32Async/AsyncTCP/v3.4.10/src/AsyncTCP.cpp'
if curl -fsSL --max-time 20 "$url" -o "$tmp/AsyncTCP.cpp"; then
  echo '=== AsyncTCP 3.4.10 server constructors ==='
  rg -n -C 7 'AsyncServer::AsyncServer' "$tmp/AsyncTCP.cpp"
fi

Length of output: 3977


@softhack007 I do not see evidence that AsyncWebServer must be stopped before Wi-Fi teardown. The pinned server binds its listener to IPADDR_ANY, and AsyncTCP 3.4.10 leaves an existing listener in place on a repeated begin() (server constructor, AsyncTCP). That does not prove active HTTP or WebSocket clients survive teardown safely.

The best candidate for further investigation is E1.31 multicast. ESPAsyncE131::initMulticast() joins groups using the local interface address, and the wrapper has no public stop method (wled00/src/dependencies/e131/ESPAsyncE131.cpp Line 69; ESPAsyncE131.h Line 242). I cannot confirm that it needs explicit teardown or causes the reported crash.

Other services worth checking are the UDP receivers, MQTT, and the captive-portal DNS server. initConnection() does not explicitly stop them. A global shutdown also needs care because the web server and UDP receivers are shared by AP and station initialization.

Before merging, I recommend the requested real ESP32-C5 and ESP32-S3 tests. Exercise repeated reconnects with active HTTP/WebSocket traffic and E1.31 multicast, then verify service recovery, including AP fallback. I have not run those tests.


Learnings used

Learnt from: softhack007
Repo: wled/WLED PR: 0
File: :0-0
Timestamp: 2026-10-03T14:59:43.661Z
Learning: In wled/WLED, softhack007 prefers contributors to answer maintainer questions directly with short explanations in their own words, even if the explanations are technically imprecise or the English is imperfect. Contributors should state uncertainty and actual test results rather than relay unverified AI-generated technical answers. AI may assist with translation or wording, but should not manufacture explanations that shift fact-checking and AI-session supervision onto maintainers.

You are interacting with an AI system.

@sionnn9

sionnn9 commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

thanks, the change looks reasonable. Needs testing on a real -C5 (and on -S3 for regression tests) before merging.

Hello and thank you for taking a look at it, currently i do not have an ESP32-C5 or an s3 to test it on which is why i went for an emulator testing .so i was wondering if someone with an actual board could possibly test it ?ill update the pr according to the result.

@softhack007 softhack007 added Awaiting testing AI Partly generated by an AI. Make sure that the contributor fully understands the code! labels Nov 11, 2026
@softhack007 softhack007 added this to the 17.0 milestone Nov 25, 2026
@Tycorc

Tycorc commented Nov 25, 2026 •

Copy link
Copy Markdown

Tested this on an ESP32-S3 (N16R8, esp32s3dev_16MB_opi) and a classic ESP32 (D0WD-V3, esp32dev). No C5. On main I get the #5945 crash on both, so it is not C5 only.

Stock main (eaf9cb4) against main with this PR merged in (feb8292). The reconnect is forced with a /settings/wifi save that only changes the BSSID.

main main + this PR
ESP32-S3: 10 resets, each followed by one forced reconnect 3 crashes, all mDNS 0 crashes
ESP32: 20 boots 0 crashes 0 crashes
ESP32: forced reconnects 6 crashes in 39: 5 mDNS, 1 UDP 3 crashes in 40: 0 mDNS, 3 UDP
  • The mDNS crash is the one from random crashes (ESP32-C5) when changing from 2.4Ghz to 5Ghz Wi-Fi (same network name) #5945 (esp_netif_is_netif_up <- join_group <- pcb_if_init_lwip, tcpip thread). With this PR it did not happen any more, on either board.
  • No regression seen on the S3 or the ESP32: the board came back on the network after every reconnect, same IP, and the only config change was the BSSID.
  • There is a second crash that this PR does not touch, on the classic ESP32 with both images: handleNotifications() -> notifier2Udp.parsePacket() -> lwip_recvfrom -> pbuf_free, InstrFetchProhibited at PC 0 in the loop task. So the UDP notifier sockets look like one more thing to stop before the teardown . 3 against 1 is too few to say this PR makes it more frequent. I did not see it on the S3.
  • Every crash came 0.3-0.4 s after the save. On the ESP32 only on the first forced reconnect after a boot.

Not tested: whether mDNS still answers after the reconnect, and ArduinoOTA.end() (not compiled in the default builds).

I can post the decoded backtraces if that helps. The test runs were AI-assisted.

@sionnn9

sionnn9 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Tycorc, this is really helpful.

Summary: the #5945 mDNS crash is gone on both the S3 and the classic ESP32 with this PR.

ESP32-S3: 3 mDNS crashes on main → 0 with this PR (10 resets, each followed by a forced reconnect).
Classic ESP32: 5 mDNS crashes on main → 0 with this PR (about 40 forced reconnects each).
No regressions seen. The boards came back on the network after every reconnect, with the same IP.

The classic ESP32 also showed a separate UDP crash (notifier2Udp.parsePacket() → pbuf_free). This PR doesn't touch it, and it appears on both images (1 in 39 on main, 3 in 40 with the PR). That sample is too small to say whether the PR changes how often it happens. I'll open a follow-up issue for it, and the decoded backtraces would be very welcome there.

@softhack007, the S3 regression check you asked for is done.

Still untested:

A physical C5
mDNS answering after the reconnect
ArduinoOTA.end() (not in default builds)

Let me know if anything else is needed for this PR

@softhack007

softhack007 commented Nov 26, 2026 •

Copy link
Copy Markdown
Member
  • There is a second crash that this PR does not touch, on the classic ESP32 with both images: handleNotifications() -> notifier2Udp.parsePacket() -> lwip_recvfrom -> pbuf_free, InstrFetchProhibited at PC 0 in the loop task. So the UDP notifier sockets look like one more thing to stop before the teardown . 3 against 1 is too few to say this PR makes it more frequent. I did not see it on the S3.

@coderabbitai can we address these crashes in a similar way, for example by adding udpConnected=false; notifier2Udp.stop(); (and .stop() for all other global WiFiUDP instances) directly after the wifi stack tear-down?

@coderabbitai

coderabbitai Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
echo '=== Lifecycle outlines ==='
ast-grep outline wled00/wled.cpp --items all --match 'initConnection|initInterfaces|handleConnection|initAP' --view expanded
ast-grep outline wled00/udp.cpp --items all --match 'handleNotifications|notify' --view expanded
echo '=== Wi-Fi teardown and service initialization ==='
cat -n wled00/wled.cpp | sed -n '690,820p;900,1120p'
echo '=== WiFiUDP declarations and use ==='
rg -n -C 3 '\b(WiFiUDP|NetworkUDP|notifier2?Udp|udpConnected|ntpUdp)\b' wled00 -g '*.{h,cpp}'
echo '=== UDP socket operations in all source files ==='
rg -n -C 2 '\.(beginMulticast|beginPacket|beginPacketMulticast|parsePacket|stop)\s*\(' wled00 -g '*.{h,cpp}' | head -n 500
echo '=== Platform versions ==='
rg -n -i -C 2 'platform.*(tasmota|pioarduino|espressif)|framework-arduinoespressif32|arduino-esp32' platformio.ini

Length of output: 46832


Script executed:

#!/bin/bash
echo '=== UDP handling and node broadcast ==='
cat -n wled00/udp.cpp | sed -n '470,530p;680,745p'
echo '=== NTP lifecycle ==='
ast-grep outline wled00/ntp.cpp --items all --view expanded
cat -n wled00/ntp.cpp | sed -n '135,240p;285,325p'
rg -n -C 3 '\bntpConnected\b|sendSysInfoUDP\s*\(|handleNotifications\s*\(|handleNetworkTime\s*\(' wled00 -g '*.{h,cpp}'
echo '=== Main loop and connection flow ==='
ast-grep outline wled00/wled.cpp --items all --match 'loop|initConnection|handleConnection' --view expanded
rg -n -C 4 '\b(handleConnection|handleNotifications|handleTime|sendSysInfoUDP)\s*\(' wled00/wled.cpp wled00/*.cpp
cat -n wled00/wled.cpp | sed -n '810,900p'
echo '=== WiFiUDP use in usermods ==='
rg -n -C 2 '\bWiFiUDP\b' . -g '*.{h,cpp}' | head -n 200
echo '=== Configured core and environments ==='
cat -n platformio.ini | sed -n '290,330p;745,785p'
echo '=== Arduino ESP32 3.3.8 reference NetworkUDP implementation ==='
tmp=$(mktemp)
if curl -fsSL --max-time 20 'https://raw.githubusercontent.com/espressif/arduino-esp32/3.3.8/libraries/Network/src/NetworkUdp.cpp' -o "$tmp"; then
  rg -n -C 8 'NetworkUDP::(stop|begin|parsePacket)|rx_buffer|close\(' "$tmp" | head -n 220
else
  echo 'Reference source unavailable'
fi
rm -f "$tmp"

Length of output: 41523


@softhack007 Yes, this is worth testing. I would stop the sockets before WiFi.disconnect(true), rather than after it, so they are closed before Wi-Fi teardown starts.

For an ESP32 experiment, immediately before WiFi.disconnect(true) in wled00/wled.cpp Line 784:

#ifdef ARDUINO_ARCH_ESP32
udpConnected = false;
udp2Connected = false;
udpRgbConnected = false;
ntpConnected = false;

notifierUdp.stop();
notifier2Udp.stop();
rgbUdp.stop();
ntpUdp.stop();
#endif

All four flags matter. handleNotifications() checks udpConnected and udp2Connected, but sendSysInfoUDP() checks udp2Connected independently.

This is not yet a confirmed fix. The backtrace identifies where the crash occurs, not why the buffer becomes invalid. Closing a socket could also encounter the underlying problem.

The restart paths need care:

  • initAP() and initInterfaces() both start the shared receivers, but use different port conditions. Test AP fallback and station reconnect, including the supplemental and RGB ports.
  • initInterfaces() starts NTP again when enabled. Test NTP recovery too.
  • The flags are not synchronization. For example, the settings handler can call ntpUdp.begin(). Concurrent socket use and reinitialization need investigation before treating the snippet as safe.

I would repeat Tycorc’s forced-reconnect test with active UDP traffic and compare crash counts against the current PR. Check node broadcasts, UDP sync, RGB input and NTP after reconnect. The requested physical C5 test is still needed before merging; the S3 test should also be repeated for this additional change. mDNS response after reconnect and the enabled ArduinoOTA path remain untested. I have not run hardware tests.


Learnings used

Learnt from: softhack007
Repo: wled/WLED PR: 0
File: :0-0
Timestamp: 2026-10-03T14:59:43.661Z
Learning: In wled/WLED, softhack007 prefers contributors to answer maintainer questions directly with short explanations in their own words, even if the explanations are technically imprecise or the English is imperfect. Contributors should state uncertainty and actual test results rather than relay unverified AI-generated technical answers. AI may assist with translation or wording, but should not manufacture explanations that shift fact-checking and AI-session supervision onto maintainers.
Learnt from: softhack007
Repo: wled/WLED PR: 0
File: :0-0
Timestamp: 2026-10-03T14:59:43.661Z
Learning: In wled/WLED, CodeRabbit review findings are advisory, not mandatory changes. Contributors are responsible for deciding whether each finding warrants a PR update. softhack007 explicitly accepts contributors not addressing every CodeRabbit comment. Do not treat complete compliance with CodeRabbit findings as a requirement for contribution acceptance.
Learnt from: softhack007
Repo: wled/WLED PR: 5436
File: wled00/wled.cpp:791-798
Timestamp: 2026-03-22T00:14:29.430Z
Learning: In arduino-esp32 v2.x (and consistent with v1.0.6), calling WiFi.mode(WIFI_MODE_NULL) on ESP32 physically shuts down BOTH the STA and AP interfaces at the hardware/driver level. WIFI_MODE_NULL=0 clears all mode bits (WIFI_MODE_STA=bit0, WIFI_MODE_AP=bit1). Therefore, setting apActive=false immediately after WiFi.mode(WIFI_MODE_NULL) in WLED's initConnection() is correct and accurately reflects the actual hardware state. The official arduino-esp32 docs confirm: "To change the hostname, reset WiFi with WiFi.mode(WIFI_MODE_NULL), then proceed with WiFi.setHostname(...) and restart WiFi from scratch." AP behavior policy (AP_BEHAVIOR_NO_CONN, AP_BEHAVIOR_TEMPORARY, AP_BEHAVIOR_ALWAYS) is preserved in apBehavior (not apActive), so handleConnection() will correctly re-initiate AP on the next cycle if the policy requires it.

You are interacting with an AI system.

@softhack007

Copy link
Copy Markdown
Member

The flags are not synchronization. For example, the settings handler can call ntpUdp.begin().

@coderabbitai that might be another (long-existing) bug, please investigate.

@coderabbitai

coderabbitai Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
echo '=== Source outlines ==='
for f in wled00/set.cpp wled00/wled.cpp wled00/ntp.cpp wled00/wled.h; do
  echo "=== $f ==="
  ast-grep outline "$f" --items all --match 'Settings|settings|Connection|Interfaces|NetworkTime|ntp|loop' --view expanded
done
echo '=== NTP socket and state references ==='
rg -n -C 4 '\b(ntpUdp|ntpConnected|ntpEnabled|ntpServerName|ntpLocalPort)\b' wled00 -g '*.{h,cpp}'
echo '=== Settings callback registration and call sites ==='
rg -n -C 4 '\b(handleSettingsSet|handleSettings|settingsSet|serveSettings|initConnection|handleConnection|handleTime|handleNetworkTime)\s*\(' wled00 -g '*.{h,cpp}'
echo '=== Synchronization and task references ==='
rg -n -C 2 'AsyncWebServerRequest|xTaskCreate|xSemaphore|portENTER_CRITICAL|std::mutex|ntp.*(Mutex|mutex|Lock|lock)' wled00 -g '*.{h,cpp}' | head -n 300
echo '=== Platform and core references ==='
rg -n -C 3 -i 'pioarduino|espressif32|arduino-esp32|framework-arduinoespressif32|async(tcp|webserver)' platformio.ini | head -n 250

Length of output: 52435


Script executed:

#!/bin/bash
set -u
echo '=== Request handler outline and settings dispatch ==='
ast-grep outline wled00/wled_server.cpp --items all --match 'initServer|serveSettings' --view expanded
cat -n wled00/wled_server.cpp | sed -n '410,416p;746,803p'
cat -n wled00/set.cpp | sed -n '590,610p'
echo '=== Loop, reconnect, interface startup ==='
cat -n wled00/wled.cpp | sed -n '55,96p;758,809p;920,975p;975,1069p'
echo '=== Full NTP flow ==='
ast-grep outline wled00/ntp.cpp --items all --view expanded
cat -n wled00/ntp.cpp | sed -n '178,255p;256,326p'
echo '=== WLED_CONNECTED definition ==='
rg -n -C 3 '#\s*define\s+WLED_CONNECTED|WLED_CONNECTED\s*=' wled00 -g '*.{h,cpp}'
echo '=== Earlier WLED release NTP paths ==='
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
for f in set.cpp wled.cpp ntp.cpp; do
  if curl -fsSL --max-time 20 "https://raw.githubusercontent.com/wled/WLED/v0.15.0/wled00/$f" -o "$tmp/$f"; then
    echo "--- v0.15.0 $f ---"
    rg -n -C 3 'ntpUdp\.(begin|parsePacket|beginPacket|read)|ntpConnected|handleSettingsSet|handleNetworkTime' "$tmp/$f"
  else
    echo "v0.15.0 $f unavailable"
  fi
done
echo '=== Available git history ==='
git log -1 --format='%h %as %s' -- wled00/set.cpp
echo '=== AsyncTCP 3.4.10 task and callback dispatch ==='
if curl -fsSL --max-time 20 'https://raw.githubusercontent.com/ESP32Async/AsyncTCP/v3.4.10/src/AsyncTCP.cpp' -o "$tmp/AsyncTCP.cpp"; then
  rg -n -C 5 '_async_service_task|_async_service_task_handle|_handle_async_event|_recv\(|_recv_cb|_recv_cb\(|_on_data|_start_async_task|xTaskCreate' "$tmp/AsyncTCP.cpp" | head -n 260
else echo 'AsyncTCP source unavailable'; fi
echo '=== Async web server pinned callback chain ==='
for f in WebRequest.cpp WebHandlers.cpp WebServer.cpp; do
  if curl -fsSL --max-time 20 "https://raw.githubusercontent.com/Aircoookie/ESPAsyncWebServer/ac44e32abf2a69ae650412fb6bc193c59ccac38a/src/$f" -o "$tmp/$f"; then
    echo "--- $f ---"
    rg -n -C 4 '_onData|_on_data|_handleRequest|handleRequest|_onRequest|onData\(' "$tmp/$f" | head -n 110
  else echo "$f unavailable"; fi
done
echo '=== Representative ESP32 NetworkUDP source: upstream 3.3.8 ==='
if curl -fsSL --max-time 20 'https://raw.githubusercontent.com/espressif/arduino-esp32/3.3.8/libraries/Network/src/NetworkUdp.cpp' -o "$tmp/NetworkUdp.cpp"; then
  rg -n -C 8 'NetworkUDP::(begin|stop|parsePacket|read|clear)|rx_buffer|udp_server|tx_buffer' "$tmp/NetworkUdp.cpp" | head -n 300
else echo 'NetworkUDP source unavailable'; fi

Length of output: 48585


Script executed:

#!/bin/bash
set -u
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
echo '=== Request queue call sites in pinned web server ==='
base='https://raw.githubusercontent.com/Aircoookie/ESPAsyncWebServer/ac44e32abf2a69ae650412fb6bc193c59ccac38a/src'
for f in WebServer.cpp WebRequest.cpp WebHandlers.cpp ESPAsyncWebServer.h; do
  curl -fsSL --max-time 20 "$base/$f" -o "$tmp/$f" || echo "Unable to retrieve $f"
done
rg -n -C 5 'processQueue\s*\(|_requestReady\s*\(|_handleRequest\s*\(|_onRequest\s*\(' "$tmp" | head -n 220
echo '=== Network state after Wi-Fi connection ==='
cat -n wled00/wled.cpp | sed -n '1060,1115p'
echo '=== AsyncDNS query implementation ==='
ast-grep outline wled00/asyncDNS.h --items all --view expanded
cat -n wled00/asyncDNS.h | sed -n '1,150p'
echo '=== NTP settings and flags across source ==='
rg -n -C 2 '\bntpConnected\s*=|\bntpEnabled\s*=|\bntpLastSyncTime\s*=|\bntpServerName\b' wled00 -g '*.{cpp,h}'
echo '=== Platform release package metadata ==='
for url in \
  'https://raw.githubusercontent.com/tasmota/platform-espressif32/2026.05.50/platform.json' \
  'https://raw.githubusercontent.com/tasmota/arduino-esp32/3.3.8.260506/libraries/Network/src/NetworkUdp.cpp' \
  'https://raw.githubusercontent.com/tasmota/arduino-esp32/3.3.8/libraries/Network/src/NetworkUdp.cpp'; do
  echo "--- $url ---"
  if curl -fsSL --max-time 20 "$url" -o "$tmp/source"; then
    rg -n -C 4 '"framework-arduinoespressif32"|NetworkUDP::(begin|stop|write)|tx_buffer|udp_server' "$tmp/source" | head -n 100
  else echo 'Unavailable'; fi
done
echo '=== AsyncTCP task and callback windows ==='
if curl -fsSL --max-time 20 'https://raw.githubusercontent.com/ESP32Async/AsyncTCP/v3.4.10/src/AsyncTCP.cpp' -o "$tmp/AsyncTCP.cpp"; then
  cat -n "$tmp/AsyncTCP.cpp" | sed -n '280,340p;454,480p;1050,1072p'
fi

Length of output: 25674


Script executed:

#!/bin/bash
set -u
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
url='https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506/libraries/Network/src/NetworkUdp.cpp'
echo "=== Configured Tasmota core: $url ==="
if curl -fsSL --max-time 25 "$url" -o "$tmp/NetworkUdp.cpp"; then
  cat -n "$tmp/NetworkUdp.cpp" | sed -n '25,98p;140,188p;195,232p;270,288p;292,320p'
else
  echo 'Configured core source unavailable; upstream 3.3.8 is only a reference.'
fi
echo '=== NetworkUDP type aliases ==='
rg -n -C 3 '#include\s*[<"].*(WiFiUdp|NetworkUdp)|\bWiFiUDP\b' wled00/wled.h wled00/wled.cpp | head -n 90
echo '=== WLED v0.15.0 time-settings and loop windows ==='
for f in set.cpp wled.cpp; do
  if curl -fsSL --max-time 20 "https://raw.githubusercontent.com/wled/WLED/v0.15.0/wled00/$f" -o "$tmp/$f"; then
    rg -n -C 3 'ntpUdp\.begin\(|void WLED::loop\(|handleTime\(\)|handleConnection\(\)' "$tmp/$f"
  fi
done

Length of output: 9828


Script executed:

#!/bin/bash
set -u
base='https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506'
echo '=== Exact configured WiFiUDP header ==='
curl -fsSL --max-time 20 "$base/libraries/WiFi/src/WiFiUdp.h" | cat -n
echo '=== Exact configured NetworkUDP declarations ==='
curl -fsSL --max-time 20 "$base/libraries/Network/src/NetworkUdp.h" | cat -n | sed -n '1,130p'

Length of output: 4134


@softhack007 Yes. I found a potential pre-existing NTP race on ESP32.

The time-settings POST handler can call ntpUdp.begin() on the AsyncTCP task when ntpConnected is false (wled00/set.cpp Line 603). After a connection, the loop task can also call ntpUdp.begin() in initInterfaces() (wled00/wled.cpp Line 966). Both paths exist in WLED v0.15.0.

For example, if NTP was disabled and ntpConnected is false, a time-settings POST can enable NTP just as the station connects. Both tasks can then enter begin() before either updates ntpConnected. The flag does not serialize those calls.

In the configured Tasmota ESP32 core, NetworkUDP::begin() calls stop(), which frees buffers and closes the socket. Concurrent calls can therefore interfere with the same object. The settings handler also writes ntpServerName while the loop can read it without synchronization.

A correction to my earlier reply: handleNetworkTime() and initConnection() run sequentially in WLED::loop(). The overlap is between the settings handler and the loop task. The proposed ntpUdp.stop() snippet would also need synchronization with the settings handler.

I have not reproduced this race or established that it caused the reported notifier2Udp crash. I suggest moving NTP socket operations to the loop task and handing settings updates to it through a synchronized queue or equivalent mechanism. A test build could instrument both begin() paths and force their overlap, then check NTP recovery. The requested physical C5 test remains outstanding.


Learnings used

Learnt from: softhack007
Repo: wled/WLED PR: 5048
File: wled00/cfg.cpp:673-673
Timestamp: 2026-03-27T21:17:51.985Z
Learning: In WLED PR #5048, the NTP/UDP crash on ESP32-C5 (pioarduino IDF 5.5.x): CONFIG_LWIP_TCPIP_CORE_LOCKING defaults to n (disabled) in arduino-esp32/pioarduino, while CONFIG_LWIP_CHECK_THREAD_SAFETY=y is what actually causes the "Required to lock TCPIP core functionality!" assertion. LOCK_TCPIP_CORE() / UNLOCK_TCPIP_CORE() macros are only functional when CONFIG_LWIP_TCPIP_CORE_LOCKING=y; using them without enabling that config has no effect. The correct fix without sdkconfig changes is to use tcpip_callback() to schedule ntpUdp.begin() (and other raw lwIP API calls) on the TCPIP thread, which works regardless of the locking mode setting. The tasmota core (IDF 5.3.x, used for C6) likely has CONFIG_LWIP_CHECK_THREAD_SAFETY=n, which is why the same violation does not crash on C6.
Learnt from: softhack007
Repo: wled/WLED PR: 5048
File: wled00/cfg.cpp:673-673
Timestamp: 2026-03-28T00:51:30.926Z
Learning: In WLED PR #5048, the NTP-related crash on ESP32-C5 (pioarduino IDF 5.5.x with CONFIG_LWIP_CHECK_THREAD_SAFETY=y) is definitively NOT caused by ntpUdp.begin(). The crash dump shows the real call chain: WLED::loop() → handleTime() → handleNetworkTime() (ntp.cpp:212) → AsyncDNS::query() (asyncDNS.h:45) → dns_gethostbyname_addrtype() → dns_alloc_pcb() → dns_alloc_random_port() → udp_new_ip_type() ← ASSERT. The fix must be in AsyncDNS::query() (asyncDNS.h:45): the call to dns_gethostbyname_addrtype() must be dispatched to the TCPIP thread via tcpip_callback_with_block() on IDF V5+. The ntpUdp.begin() call sites (wled.cpp:926 and set.cpp:562) are NOT the crash location for this particular bug.
Learnt from: softhack007
Repo: wled/WLED PR: 0
File: :0-0
Timestamp: 2026-10-03T14:59:43.661Z
Learning: In wled/WLED, softhack007 prefers contributors to answer maintainer questions directly with short explanations in their own words, even if the explanations are technically imprecise or the English is imperfect. Contributors should state uncertainty and actual test results rather than relay unverified AI-generated technical answers. AI may assist with translation or wording, but should not manufacture explanations that shift fact-checking and AI-session supervision onto maintainers.

You are interacting with an AI system.

@DedeHai

DedeHai commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

@softhack007 I had minimax analyze this as well. I am not familiar enough with the network code to judge it, but here is the full analysis.

wled-mdns-crash-analysis.md

edit: this is the (probably a bit overboarding) patch it suggested, not sure if it builds on top of this PR or main as I did not check any of it. Could contain useful fixes or just a bunch of AI overly-cautios guards.

wled-mdns-crash-fix.patch

@softhack007

Copy link
Copy Markdown
Member
udpConnected = false;
notifierUdp.stop()

@coderabbitai I'm still not sure if an explicit stop is necessary before wifi teardown and reconnecting to another router. Please review the related arduino-esp32, esp-idf and lwip framework code for a clearer answer.

@coderabbitai

coderabbitai Bot commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -u
echo '=== Configuration: versions and envs ==='
rg -n -C 3 -i 'platform-espressif32|framework-arduinoespressif32|pioarduino|platform_packages|esp32c5|esp32s3|esp32dev' platformio.ini | head -n 300
echo '=== WLED lifecycle outline ==='
ast-grep outline wled00/wled.cpp --items all --match 'initConnection|initInterfaces|initAP|handleConnection|loop' --view expanded
ast-grep outline wled00/udp.cpp --items all --match 'handleNotifications|notify' --view expanded
echo '=== WLED lifecycle source ==='
cat -n wled00/wled.cpp | sed -n '60,105p;700,815p;920,1075p'
cat -n wled00/udp.cpp | sed -n '475,530p;680,735p'
echo '=== Other notifier use ==='
rg -n -C 3 '\b(notifierUdp|notifier2Udp|udpConnected|udp2Connected)\b' wled00 -g '*.{cpp,h}' | head -n 260
echo '=== Exact platform metadata ==='
for url in \
'https://raw.githubusercontent.com/tasmota/platform-espressif32/2026.05.50/platform.json' \
'https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506/package/package_esp32_index.template.json'; do
 echo "--- $url"; curl -fsSL --max-time 25 "$url" | head -n 90 || echo UNAVAILABLE
done
echo '=== Tasmota Arduino sources ==='
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
base='https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506'
for rel in libraries/Network/src/NetworkUdp.cpp libraries/WiFi/src/STA.cpp libraries/WiFi/src/WiFiGeneric.cpp libraries/Network/src/NetworkInterface.cpp; do
 file="$tmp/$(basename "$rel")"
 if curl -fsSL --max-time 25 "$base/$rel" -o "$file"; then
   echo "--- $rel ---"; rg -n -C 4 'NetworkUDP::(begin|stop|parsePacket|beginPacket)|STAClass::(disconnect|begin)|WiFiGenericClass::mode|ARDUINO_EVENT_WIFI_STA_DISCONNECTED|onSta(Stop|Disconnected)|esp_wifi_(disconnect|stop)|netif' "$file" | head -n 230
 else echo "$rel UNAVAILABLE"; fi
done

Length of output: 70042


Script executed:

#!/bin/bash
set -u
echo '=== Configuration: versions and environments ==='
rg -n -C 3 -i 'platform-espressif32|framework-arduinoespressif32|pioarduino|platform_packages|esp32c5|esp32s3|esp32dev' platformio.ini | head -n 300
echo '=== WLED lifecycle outline ==='
ast-grep outline wled00/wled.cpp --items all --match 'initConnection|initInterfaces|initAP|handleConnection|loop' --view expanded
ast-grep outline wled00/udp.cpp --items all --match 'handleNotifications|notify' --view expanded
echo '=== WLED lifecycle source ==='
cat -n wled00/wled.cpp | sed -n '60,105p;700,815p;920,1075p'
cat -n wled00/udp.cpp | sed -n '475,530p;680,735p'
echo '=== Other notifier use ==='
rg -n -C 3 '\b(notifierUdp|notifier2Udp|udpConnected|udp2Connected)\b' wled00 -g '*.{cpp,h}' | head -n 260
echo '=== Exact platform metadata ==='
for url in \
'https://raw.githubusercontent.com/tasmota/platform-espressif32/2026.05.50/platform.json' \
'https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506/package/package_esp32_index.template.json'; do
 echo "--- $url"; curl -fsSL --max-time 25 "$url" | head -n 90 || echo UNAVAILABLE
done
echo '=== Tasmota Arduino sources ==='
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
base='https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506'
for rel in libraries/Network/src/NetworkUdp.cpp libraries/WiFi/src/STA.cpp libraries/WiFi/src/WiFiGeneric.cpp libraries/Network/src/NetworkInterface.cpp; do
 file="$tmp/$(basename "$rel")"
 if curl -fsSL --max-time 25 "$base/$rel" -o "$file"; then
   echo "--- $rel ---"; rg -n -C 4 'NetworkUDP::(begin|stop|parsePacket|beginPacket)|STAClass::(disconnect|begin)|WiFiGenericClass::mode|ARDUINO_EVENT_WIFI_STA_DISCONNECTED|onSta(Stop|Disconnected)|esp_wifi_(disconnect|stop)|netif' "$file" | head -n 230
 else echo "$rel UNAVAILABLE"; fi
done

Length of output: 70084


Script executed:

#!/bin/bash
set -u
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
a='https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506'
for rel in libraries/Network/src/NetworkUdp.cpp libraries/WiFi/src/WiFiSTA.cpp libraries/WiFi/src/WiFiGeneric.cpp libraries/Network/src/NetworkUdp.h; do
 file="$tmp/$(basename "$rel")"
 echo "=== $rel ==="
 if curl -fsSL --max-time 25 "$a/$rel" -o "$file"; then
 case "$rel" in
 *NetworkUdp.cpp) cat -n "$file" | sed -n '15,99p;145,187p;297,346p';;
 *WiFiSTA.cpp) rg -n -C 8 'WiFiSTAClass::disconnect\(' "$file";;
 *WiFiGeneric.cpp) cat -n "$file" | sed -n '319,380p;602,680p';;
 *NetworkUdp.h) rg -n -C 3 'NetworkUDP|WiFiUDP' "$file" | head -n 80;;
 esac
 else echo 'UNAVAILABLE'; fi
done
echo '=== ESP-IDF exact submodule reference ==='
curl -fsSL --max-time 25 'https://api.github.com/repos/tasmota/esp-idf/contents/components/lwip/lwip?ref=v5.5.4.260407' | head -c 4000 || echo UNAVAILABLE
echo; echo '=== ESP-IDF WiFi guide source ==='
for rel in docs/en/api-guides/wifi.rst components/esp_wifi/src/wifi_default.c components/esp_netif/lwip/esp_netif_lwip.c; do
 echo "--- $rel"
 file="$tmp/$(basename "$rel")"
 if curl -fsSL --max-time 25 "https://raw.githubusercontent.com/tasmota/esp-idf/v5.5.4.260407/$rel" -o "$file"; then
  rg -n -i -C 5 'disconnect|socket|netif_remove|netif_set_down|esp_netif_action_(stop|disconnected)' "$file" | head -n 200
 else echo UNAVAILABLE; fi
done

Length of output: 38190


web_search executed:

In ESP-IDF 5.5.4 and its bundled lwIP, what do the official Wi-Fi event documentation and source say happens to TCP and UDP sockets on WIFI_EVENT_STA_DISCONNECTED, especially UDP sockets bound to INADDR_ANY? Are they closed, invalidated, or reusable across reconnect? Find exact versioned documentation or source, and whether it distinguishes UDP from TCP.

Length of output: 18458


Script executed:

#!/bin/bash
set -u
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
base='https://raw.githubusercontent.com/espressif/esp-lwip/fd432e4ee2cfb7f7f1c7eb7227e0173412e7b84e'
for rel in src/core/netif.c src/core/ipv4/ip4.c src/core/udp.c src/core/tcp.c src/api/api_msg.c src/api/sockets.c src/core/pbuf.c; do
 file="$tmp/$(basename "$rel")"
 echo "=== esp-lwip $rel ==="
 if curl -fsSL --max-time 25 "$base/$rel" -o "$file"; then
   rg -n -C 5 'netif_remove\(|netif_set_down\(|netif_set_addr\(|netif_set_ipaddr\(|netif_do_ip_addr_changed|ip_addr_changed|udp_netif|tcp_netif|netconn_remove|lwip_recvfrom|lwip_recv_udp_raw|netbuf_delete|pbuf_free\(|udp_remove\(|IP_IS_ANY|ip_addr_isany' "$file" | head -n 230
 else echo UNAVAILABLE; fi
done
echo '=== ESP-IDF exact disconnect and stop paths ==='
base='https://raw.githubusercontent.com/tasmota/esp-idf/v5.5.4.260407'
for rel in components/esp_netif/esp_netif_handlers.c components/esp_netif/lwip/esp_netif_lwip.c components/esp_wifi/src/wifi_default.c; do
 file="$tmp/$(basename "$rel")"
 echo "--- $rel"
 if curl -fsSL --max-time 25 "$base/$rel" -o "$file"; then
  rg -n -C 6 'esp_netif_action_disconnected|esp_netif_action_stop|esp_netif_down|esp_netif_stop|esp_netif_lwip_remove|netif_set_addr\(|netif_set_down\(' "$file" | head -n 190
 else echo UNAVAILABLE; fi
done

Length of output: 49165


Script executed:

#!/bin/bash
set -u
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
lwip='https://raw.githubusercontent.com/espressif/esp-lwip/fd432e4ee2cfb7f7f1c7eb7227e0173412e7b84e'
for rel in src/core/udp.c src/core/netif.c src/core/pbuf.c src/api/api_msg.c src/api/netbuf.c src/include/lwip/ip_addr.h; do
 file="$tmp/$(basename "$rel")"
 if curl -fsSL --max-time 25 "$lwip/$rel" -o "$file"; then
  echo "=== $rel ==="
  case "$rel" in
  src/core/udp.c) cat -n "$file" | sed -n '1290,1320p';;
  src/core/netif.c) cat -n "$file" | sed -n '466,518p;772,813p;956,990p';;
  src/core/pbuf.c) cat -n "$file" | sed -n '725,810p';;
  src/api/api_msg.c) cat -n "$file" | sed -n '220,295p;855,905p;1195,1245p';;
  src/api/netbuf.c) rg -n -A20 'netbuf_delete\(' "$file" | head -n 30;;
  src/include/lwip/ip_addr.h) rg -n -C 2 '#define ip_addr_isany' "$file";;
  esac
 else echo "$rel UNAVAILABLE"; fi
done
echo '=== NetworkUDP default IPAddress ==='
a='https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506'
for rel in cores/esp32/IPAddress.cpp libraries/WiFi/src/STA.cpp; do
 file="$tmp/$(basename "$rel")"
 if curl -fsSL --max-time 25 "$a/$rel" -o "$file"; then echo "=== $rel"; rg -n -C 5 'IPAddress::IPAddress\(\)|bool STAClass::end|bool STAClass::disconnect' "$file"; else echo UNAVAILABLE; fi
done
echo '=== WLED Art-Net reply call chain ==='
ast-grep outline wled00/e131.cpp --items all --match 'handleE131Packet|handleArtNet|sendArt|ArtPoll|PollReply' --view expanded
rg -n -C 4 'handleE131Packet\(|sendArt|ArtPollReply|sendSysInfoUDP\(' wled00 -g '*.{h,cpp}' | head -n 220
echo '=== async receiver dispatch ==='
ast-grep outline wled00/src/dependencies/e131/ESPAsyncE131.cpp --items all --view expanded
cat -n wled00/src/dependencies/e131/ESPAsyncE131.cpp | sed -n '1,100p'

Length of output: 34557


@softhack007 I cannot establish that notifierUdp.stop() is required before Wi-Fi teardown. My earlier recommendation was too strong. Closing it before teardown is an experiment, not a confirmed fix.

The source gives a more specific picture:

  • ESP-IDF: The Wi-Fi guide recommends closing and recreating sockets after a disconnect, if necessary. It does not require closing them before teardown.
  • Arduino: begin(port) binds to the wildcard IPv4 address and calls stop() first. WLED already calls begin() again in initInterfaces() after reconnection (wled00/wled.cpp Line 958). That closes and recreates the notifier sockets at that point, not at teardown.
  • lwIP: The configured UDP address-change handler does not close UDP sockets when the interface address is removed. The wildcard binding supports the possibility of reuse, but does not guarantee correct operation across this teardown. The ESP-IDF guide gives broader conservative advice for sockets.

There is still an important interval before initInterfaces(): WLED leaves udpConnected and udp2Connected set, so handleNotifications() can continue to call parsePacket() on the old sockets. Setting the flags false would prevent those calls; it would not close the sockets or synchronize other users.

The crash remains unexplained. A receive releases an lwIP packet buffer, and closing a socket also drains queued buffers. Therefore, moving stop() earlier might change the timing without fixing the underlying fault. It also needs synchronization with concurrent socket users.

I suggest comparing the current PR, flags-only, and a synchronized stop-before-teardown build under the same repeated reconnect and UDP traffic test. Check UDP recovery after a changed IP and during AP fallback. The decoded backtraces would help identify the failing buffer-release path. I have not run these tests. The requested physical C5 test remains outstanding; any added change should also be regression-tested on the S3.


Learnings used

Learnt from: softhack007
Repo: wled/WLED PR: 5436
File: wled00/wled.cpp:791-798
Timestamp: 2026-03-22T00:14:29.430Z
Learning: In arduino-esp32 v2.x (and consistent with v1.0.6), calling WiFi.mode(WIFI_MODE_NULL) on ESP32 physically shuts down BOTH the STA and AP interfaces at the hardware/driver level. WIFI_MODE_NULL=0 clears all mode bits (WIFI_MODE_STA=bit0, WIFI_MODE_AP=bit1). Therefore, setting apActive=false immediately after WiFi.mode(WIFI_MODE_NULL) in WLED's initConnection() is correct and accurately reflects the actual hardware state. The official arduino-esp32 docs confirm: "To change the hostname, reset WiFi with WiFi.mode(WIFI_MODE_NULL), then proceed with WiFi.setHostname(...) and restart WiFi from scratch." AP behavior policy (AP_BEHAVIOR_NO_CONN, AP_BEHAVIOR_TEMPORARY, AP_BEHAVIOR_ALWAYS) is preserved in apBehavior (not apActive), so handleConnection() will correctly re-initiate AP on the next cycle if the policy requires it.
Learnt from: softhack007
Repo: wled/WLED PR: 0
File: :0-0
Timestamp: 2026-10-03T14:59:43.661Z
Learning: In wled/WLED, softhack007 prefers contributors to answer maintainer questions directly with short explanations in their own words, even if the explanations are technically imprecise or the English is imperfect. Contributors should state uncertainty and actual test results rather than relay unverified AI-generated technical answers. AI may assist with translation or wording, but should not manufacture explanations that shift fact-checking and AI-session supervision onto maintainers.

You are interacting with an AI system.

@DedeHai

DedeHai commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

@softhack007 a user report on discord was: works on ESP32, S3 was still crashing. Although it was not a fresh install on that device so could be some other legacy / config issue there.

@softhack007
softhack007 marked this pull request as draft December 2, 2026 12:48
@softhack007

softhack007 commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

I think we should also stop all WiFiUDP receivers before the teardown, at least flag them as "unconnected" (and wait a few 100ms) so that all handlers stop processing - I'll do a quick test this week, then update this PR if needed.

Edit: restarting all UDP handlers might also solve the AP mode problem reported in #5709, in case that one is not related to using the wrong broadcast address.

@coderabbitai please double-check if this will work.

Edit2:
this one could also be related to the remining crash on S3:

The time-settings POST handler can call ntpUdp.begin() on the AsyncTCP task when ntpConnected is false (wled00/set.cpp Line 603).

@coderabbitai

coderabbitai Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
echo '=== Lifecycle outlines ==='
ast-grep outline wled00/wled.cpp --items all --match 'loop|initConnection|handleConnection|initAP|initInterfaces' --view expanded
ast-grep outline wled00/udp.cpp --items all --match 'notify|handleNotifications|sendSysInfoUDP' --view expanded
ast-grep outline wled00/ntp.cpp --items all --match 'handleNetworkTime|sendNTP' --view expanded
ast-grep outline wled00/src/dependencies/network/Network.cpp --items all --match 'gatewayIP|subnetMask|isConnected' --view expanded
echo '=== WiFiUDP instances and flags ==='
rg -n -C 3 '\b(WiFiUDP|NetworkUDP|notifierUdp|notifier2Udp|rgbUdp|ntpUdp|udpConnected|udp2Connected|udpRgbConnected|ntpConnected)\b' wled00 -g '*.{h,cpp}' 
echo '=== Connection lifecycle ==='
cat -n wled00/wled.cpp | sed -n '55,105p;680,815p;900,1075p'
echo '=== UDP receive and transmit ==='
cat -n wled00/udp.cpp | sed -n '1,115p;470,550p;680,750p'
echo '=== NTP and settings ==='
cat -n wled00/ntp.cpp | sed -n '175,255p;280,330p'
cat -n wled00/set.cpp | sed -n '580,615p'
echo '=== Network address selection ==='
rg -n -C 6 'Network::(subnetMask|gatewayIP|localIP|isConnected)|softAPBroadcastIP|broadcastIp' wled00/src/dependencies/network/Network.cpp wled00/udp.cpp
echo '=== Issue #5709 ==='
gh issue view 5709 --repo wled/WLED --json title,body,state,url 2>&1

Length of output: 55819


Script executed:

#!/bin/bash
echo '=== Lifecycle outlines ==='
ast-grep outline wled00/wled.cpp --items all --match 'loop|initConnection|handleConnection|initAP|initInterfaces' --view expanded
ast-grep outline wled00/udp.cpp --items all --match 'notify|handleNotifications|sendSysInfoUDP' --view expanded
ast-grep outline wled00/ntp.cpp --items all --match 'handleNetworkTime|sendNTP' --view expanded
ast-grep outline wled00/src/dependencies/network/Network.cpp --items all --match 'gatewayIP|subnetMask|isConnected' --view expanded
echo '=== WiFiUDP instances and flags ==='
rg -n -C 3 '\b(WiFiUDP|NetworkUDP|notifierUdp|notifier2Udp|rgbUdp|ntpUdp|udpConnected|udp2Connected|udpRgbConnected|ntpConnected)\b' wled00 -g '*.{h,cpp}'
echo '=== Connection lifecycle ==='
cat -n wled00/wled.cpp | sed -n '55,105p;680,815p;900,1075p'
echo '=== UDP receive and transmit ==='
cat -n wled00/udp.cpp | sed -n '1,115p;470,550p;680,750p'
echo '=== NTP and settings ==='
cat -n wled00/ntp.cpp | sed -n '175,255p;280,330p'
cat -n wled00/set.cpp | sed -n '580,615p'
echo '=== Network address selection ==='
rg -n -C 6 'Network::(subnetMask|gatewayIP|localIP|isConnected)|softAPBroadcastIP|broadcastIp' wled00/src/dependencies/network/Network.cpp wled00/udp.cpp
echo '=== Issue #5709 ==='
gh issue view 5709 --repo wled/WLED --json title,body,state,url 2>&1

Length of output: 55818


Script executed:

#!/bin/bash
echo '=== Network address implementations ==='
cat -n wled00/src/dependencies/network/Network.cpp | sed -n '1,100p'
echo '=== Art-Net callback and notifier use ==='
ast-grep outline wled00/e131.cpp --items all --match 'handleE131Packet|sendArtPollReply|send.*Reply' --view expanded
rg -n -C 5 'handleE131Packet\(|sendArtPollReply\(|notifierUdp\.beginPacket' wled00/e131.cpp wled00/src/dependencies/e131/ESPAsyncE131.cpp
echo '=== Async receive dispatch ==='
ast-grep outline wled00/src/dependencies/e131/ESPAsyncE131.cpp --items all --view expanded
cat -n wled00/src/dependencies/e131/ESPAsyncE131.cpp | sed -n '1,110p'
echo '=== Alexa receiver setup and loop ==='
ast-grep outline wled00/alexa.cpp --items all --view expanded
cat -n wled00/alexa.cpp | sed -n '1,80p'
rg -n -C 4 'espalexa\.loop\(|alexaLoop\(' wled00 -g '*.{cpp,h}'
echo '=== Initialization after connection ==='
cat -n wled00/wled.cpp | sed -n '1060,1120p'
echo '=== Local address and connection macro ==='
rg -n -C 4 '#\s*define\s+WLED_CONNECTED|WLEDNetworkClass::localIP\(' wled00 -g '*.{cpp,h}'

Length of output: 17067


Script executed:

#!/bin/bash
echo '=== Art-Net reply call chain ==='
rg -n -C 5 'sendArtnetPollReply\s*\(|handleArtPoll\s*\(|_callback\s*\(' wled00/e131.cpp wled00/src/dependencies/e131/ESPAsyncE131.cpp
echo '=== WiFiUDP in usermods ==='
rg -n -C 2 '\bWiFiUDP\b' usermods -g '*.{h,cpp}' | head -n 140
echo '=== IPAddress and INADDR_NONE references in configured framework ==='
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
for rel in cores/esp32/IPAddress.cpp cores/esp32/IPAddress.h; do
  if curl -fsSL --max-time 20 "https://raw.githubusercontent.com/tasmota/arduino-esp32/v3.3.8.260506/$rel" -o "$tmp/$(basename "$rel")"; then
    rg -n -C 4 'IPAddress::IPAddress\(uint32_t|IPAddress\(uint32_t|operator uint32_t' "$tmp/$(basename "$rel")"
  fi
done
if curl -fsSL --max-time 20 'https://raw.githubusercontent.com/espressif/esp-lwip/fd432e4ee2cfb7f7f1c7eb7227e0173412e7b84e/src/include/lwip/inet.h' -o "$tmp/inet.h"; then
  rg -n -C 2 'INADDR_NONE|INADDR_BROADCAST' "$tmp/inet.h"
fi

Length of output: 6544


@softhack007 This is worth testing, but I cannot confirm that flags and a delay will stop all UDP processing or fix the crash.

  • In WLED::loop(), handleConnection() and handleNotifications() run sequentially (wled00/wled.cpp Line 86 and Line 91). Clearing udpConnected before teardown prevents the later notification receive calls. It does not close the sockets or drain queued packets.
  • A delay can change timing, but it does not guarantee that other tasks have stopped. The time-settings handler can call ntpUdp.begin() after ntpConnected is cleared (wled00/set.cpp Line 603). Async Art-Net processing can also use notifierUdp outside handleNotifications() (wled00/e131.cpp Line 584). Safe stop() calls need coordination with concurrent users.
  • initAP() and initInterfaces() restart the notifier receivers, but use different port conditions. They do not cover every receiver: Espalexa has its own WiFiUDP, and E1.31/DDP use separate async receivers. Closing a socket can also release queued buffers, so the crash might move to stop() or the next begin().

For #5709, restarting the socket does not change the address that notify() calculates. In the current code, with neither STA nor Ethernet IP, the gateway fallback is INADDR_NONE, so the expression produces the limited broadcast 255.255.255.255, not the AP subnet’s directed broadcast. With WLED’s configured AP address and mask, that directed broadcast is 4.3.2.255 (wled00/wled.cpp Line 729). I checked the supplied Learning about #5709; its numerical example does not match this code. A packet capture is needed to determine whether the limited broadcast reaches the AP client and whether this explains the reported failure.

I suggest comparing the current PR, a flags-only build, and a synchronized stop-and-restart build under repeated reconnects with UDP traffic. Check for crashes during both receive and socket close, then check UDP sync, RGB input, NTP, and AP fallback. Repeat the S3 regression test for any added change. The requested physical C5 test remains needed before merging; mDNS response after reconnect and enabled ArduinoOTA also remain untested. I have not run hardware tests.


Learnings used

Learnt from: softhack007
Repo: wled/WLED PR: 5436
File: wled00/wled.cpp:791-798
Timestamp: 2026-03-22T00:14:29.430Z
Learning: In arduino-esp32 v2.x (and consistent with v1.0.6), calling WiFi.mode(WIFI_MODE_NULL) on ESP32 physically shuts down BOTH the STA and AP interfaces at the hardware/driver level. WIFI_MODE_NULL=0 clears all mode bits (WIFI_MODE_STA=bit0, WIFI_MODE_AP=bit1). Therefore, setting apActive=false immediately after WiFi.mode(WIFI_MODE_NULL) in WLED's initConnection() is correct and accurately reflects the actual hardware state. The official arduino-esp32 docs confirm: "To change the hostname, reset WiFi with WiFi.mode(WIFI_MODE_NULL), then proceed with WiFi.setHostname(...) and restart WiFi from scratch." AP behavior policy (AP_BEHAVIOR_NO_CONN, AP_BEHAVIOR_TEMPORARY, AP_BEHAVIOR_ALWAYS) is preserved in apBehavior (not apActive), so handleConnection() will correctly re-initiate AP on the next cycle if the policy requires it.
Learnt from: DedeHai
Repo: wled/WLED PR: 0
File: :0-0
Timestamp: 2026-07-09T07:37:36.713Z
Learning: In wled/WLED, `wled00/udp.cpp`'s `notify()` computes the UDP sync broadcast address via `IPAddress broadcastIp = ~uint32_t(Network.subnetMask()) | uint32_t(Network.gatewayIP());`, and `Network.subnetMask()`/`Network.gatewayIP()` in `wled00/src/dependencies/network/Network.cpp` only consider the ETH/STA (`WiFi.localIP()`) interface, with no AP-only branch. When a device runs AP-only (softAP, not connected as a station to any router), this falls back to a hardcoded `255.255.255.0` subnet mask and `INADDR_NONE` gateway, yielding an incorrect broadcast address (e.g. `0.0.0.255` instead of `192.168.4.255`), which breaks UDP sync between two AP/STA-linked ESP32s (reported in issue #5709). WLED 16.0.0 migrated all ESP32 targets from arduino-esp32 1.0.6.4 (ESP-IDF 3.3.x) to arduino-esp32 2.0.18 (ESP-IDF 4.4.8, Tasmota platform), which likely exposed this pre-existing latent bug since the older WiFi/lwIP stack seems to have tolerated the incorrectly-derived broadcast address. A correct fix should use `WiFi.softAPBroadcastIP()` when the STA interface has no IP but `apActive` is true.
Learnt from: softhack007
Repo: wled/WLED PR: 0
File: :0-0
Timestamp: 2026-10-03T14:59:43.661Z
Learning: In wled/WLED, softhack007 prefers contributors to answer maintainer questions directly with short explanations in their own words, even if the explanations are technically imprecise or the English is imperfect. Contributors should state uncertainty and actual test results rather than relay unverified AI-generated technical answers. AI may assist with translation or wording, but should not manufacture explanations that shift fact-checking and AI-session supervision onto maintainers.

You are interacting with an AI system.

@DedeHai

DedeHai commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

@softhack007 update from said user: it works on S3 as well. IMHO we should get this merged and refine later.

@softhack007

Copy link
Copy Markdown
Member

@DedeHai thanks, then let's merge 👍

@softhack007
softhack007 marked this pull request as ready for review December 2, 2026 17:58
@softhack007
softhack007 merged commit c7cd3ee into wled:main Dec 2, 2026
31 checks passed
softhack007 pushed a commit that referenced this pull request Dec 2, 2026
* Stop mDNS and ArduinoOTA before Wi-Fi teardown to prevent crashes
@sionnn9

sionnn9 commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @softhack007 for the review and for merging, and thanks @Tycorc and @DedeHai for the testing and the Discord confirmation.

I'd be happy to help with other issues too. I work mostly in TypeScript, React and Node. I don't have ESP32 boards, so I'm best on software-only tasks (code review, small fixes, docs, or testing in an emulator). If there are any open issues that fit that, I'd appreciate a pointer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI Partly generated by an AI. Make sure that the contributor fully understands the code! Awaiting testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants