Repository navigation
Refactor: Replace RemoteDebug with custom Logger and Telnet server - #824
Conversation
This commit removes the external RemoteDebug dependency and replaces it with a lightweight, project-tailored logging and console management infrastructure. Key changes: - Created ConsoleManager and ConsoleSession for multiplexing Serial and Telnet I/O with support for ANSI colors and line-ending policies. - Implemented a custom Logger that hooks into the ESP-IDF esp_log vprintf system, ensuring all system and library logs are captured and routed to all active console sessions. - Added a robust, BSD-socket based Telnet server (RFC 854) with protocol negotiation (WILL ECHO, WILL SGA) and state-machine based IAC/CRLF filtering. - Rewrote DebugCLI to use the new console system, featuring a zero-allocation tokenizer and improved tab completion. - Updated main.cpp and TaskManager to integrate the new services. - Removed RemoteDebug from platformio.ini. This change reduces binary size, improves memory efficiency, and provides a more reliable and extensible debugging interface.
This fixes the build error where F_GETFL, F_SETFL, and O_NONBLOCK were undefined in include/globals.h after the removal of RemoteDebug.h, which previously provided these headers.
…nding The variadic Logger template was attempting to bind a reference to packed struct fields in src/network.cpp (esp-now), which is an error. By passing by value in the default Unwrap case, we avoid this issue while still correctly specializing for String and std::string types.
The use of Args&&... in the variadic template was still attempting to bind references to packed struct fields before they reached Unwrap. By changing the template to take Args... (by value), we ensure all arguments are copied before binding, satisfying the compiler's restrictions on packed members.
8c6b82d to
6359906
Compare
There's a lot here. Honest! Machine-Generated part: “Waar gehakt wordt, vallen spaanders.” (Where wood is chopped, chips fall.) -- Part Deux This PR represents a comprehensive stabilization pass across the networking and logging infrastructure. What began as a targeted fix for WiFi connection issues evolved into a broader cleanup of HAL errors, performance bottlenecks, and thread-safety refinements. Summary of Changes 1. WiFi Connection Stabilization Reverted WPA3/SAE workarounds: Reverted experimental manual wifi_config_t manipulation. Returning to standard WiFi.begin() proved more robust for reliable WPA2/WPA3 handshakes across different AP configurations. Improved Retry Logic: Softened noisy "Waiting for WiFi" logs and ensured the connection loop handles WL_CONNECT_FAILED more gracefully without tight-looping. 2. Hardware Safety & HAL Cleanup Pin Access Guards: Added pin >= 0 guards to pinMode() calls for IR_REMOTE_PIN and INPUT_PIN. This eliminates constant "Invalid pin selected" HAL errors triggered when these pins were unassigned (-1) in the environment. Audio Task Efficiency: Updated AudioSamplerTaskEntry to yield the CPU (1s delay) when no local microphone is configured and no remote audio is active. This significantly reduces board heat and power consumption for idle audio builds. 3. Console & CLI Enhancements Log Color Toggling: Implemented color on / color off in the CLI to control ANSI escape sequences in the debug log, replicating legacy RemoteDebug functionality. Thread-Safe Broadcasting: Refined the ConsoleManager mutex strategy to ensure interleaved logs and CLI prompts don't scramble serial output. VURatio Fixes: Initialized VURatio to 0.0f (preventing "fake" active audio on boot) and resolved header visibility for MAC address utilities in main.cpp . 4. Code Quality & IWYU Include Consolidation: Tiered and consolidated includes in main.cpp and network.cpp to reduce compilation friction and remove redundant Arduino v3 compatibility blocks. Socket Logic Audit: Cleaned up return-value checks and non-blocking flags across the Telnet and Socket server implementations. Files changed: 34 Insertions/Deletions: +520 / -335 This "Enchilada" pass leaves the foundational networking and logging paths significantly more stable for both the tinyled-demo and production Mesmerizer hardware. Human-generated part: I sat out two days ago with this PR for the goal to be something like "type git pull; git push; observe glorious green checkmarks, profit!!" Clearly, that's not how it worked out. If this looks like a continuation of "IWYU staging", I don't disagree. Imagine the network guy making a service call, whining about all the screws found on the floor from the previous guy...and hoping you wouldn't notice that the previous guy is also the current guy. That's me. As a good example, I realized that when I changed some header dependencies, we had cases where we were alphabetic, but interleaved <systtem> and "local" includes in the same block. In some fantasy world, I've have "fixed" those in a separate PR, but it was invariably in files we were touching here anyway. There's no reason to make more work for all of us in the name of textbook purity. As a bonus, I also tightened the rules in the tools that detect such things for the future. console.h, debug_cli.cpp: In the original RemoteDebug, there was a way to turn off color sequences. I meant to emulate that flags. I implemented most of the infra, I just didn't wire up the switches to the CLI. Now humans can get pretty red colors for debugE but readers of logs or netcat don't have to filter out ANSI escape codes. deviceconfig.h: I actually had a device nearly desolder itself because it crashed with all the LEDs set to 0xfffff at max brightness. Debugging software shouldn't depend on your nose noticing the smell of rosin and PLA. PatternQr, Weather, Stocks, others: Don't depend on network.h just to know if you have WiFi or not. Provide helpers for that. nd_network.h: lighten up a little on "network.h means networking" dogma. There are some things that just make sense to have always available and let the callers sort it out. You shouldn't have to pull in ALL the netowking headers just to know if you're connected or not. soundanalyzer.h: don't provide bogus defaults if there's no audio. audio.cpp: Don't anger pinmanager if you're on hardware without audio INPUT_PINs or REMOTE Throughout : try to use debugE for Error conditions. various: make more correct use of non-blocking sockets, per the BSD definitions of 40 years ago. console.cpp: fix issues when system is under stress and both console and logging systems are hammering on the same output sinks. Be more honest gthat levelStr isn't a Str, but is just a plain ole char, optimizing accordingly. Fix a mess that I made about making multiple calls to WriteFoo() without a lock being held, resulting in messy splatter under load because buffers would be inappropriately interleaved and/or dropped. debug_cli.cpp: make 'log' command work betterer. Add 'color' command that is a desert topping AND a floor wax, err, both toggles the colorizing of error/warning text int he console AND changes the system default global palette. It felt slightly bad to mix two unrelated uses of "color", but it felt worse NOT to. Add ? as alias for 'help'. ledviewer.cpp: better use of non-blocking sockets, errors. main.cpp: Defer to values.cpp, better logging of errors, Centralize ModeSTA & GetMacAddressPrettyhandling, ** Lipe's Hard Lesson #1: don't hold onto an invalid string pointer to try to print it after it's been freed. In that way lies only punishment and insanity. ** Lipe's Hard Lesson #2: if your compile-time creds differ from your saved creds, prefer them. (Such as when your board moves from a temporary apartment back into your home with WiFi compiled-in...) network.cpp: try to protect some other other files from having to pull in huge amounts of network just ot get a true/false value that's essentially a session const or print a MAC or other trivially dumb things. Make WLtoString actually return strings. RemoteLoop holding onto a dangling pointer was gnarly to find! Less agressively to reconnnect to your DHCP server to get a grant. Less likely to be blocked as an attacker by your Ubiquiti. Better separation of warnings vw. Make SetSocketBlockingEnabled more readable. screen.cpp: better use of encapsulation to hide warts.A socketserver.cpp: more correct use of non-blcoking sockets. Improve logging to say the same telnetserver.cpp: fixed nonblocking sockets. tools/audit_include_rules.py - actually correctly flag rules about alphabetic ordering within blocks.
6359906 to
f962da4
Compare
|
@robertlipe I'm just noting for the record that I'm going to wait until you declare this PR stable, as it seems to be in flux at the moment, and I don't want to make bad guesses about when that ends. |
…and whitespace cleanup
|
Busted. Thanx for your patience. I fell asleep waiting for a passing CI pass, but I already had more changes in the oven. So there was another cycle. Now we've arrived. I'm done with this one unless you tell me otherwise. In the final minutes, I set the default serial coloring to ON and turned teelnet coloring OFF. AI's can munch ANSI codes these days, but it's just too handy to 'nc ADDR 23 | machine-process-output' and not have to filter out ^]XX;. This was a brutal merge conflict. I'll disclaim (I, in fact, did so in the commit log for f962da4) that some of this looks logically like it should have been part of a few other recent PRs. Somewhere I made the comparison that I was the next repairman under the hood and noticed a few dangling wires - some of which were needed here - or parts left on the floor that should have been hooked back up. I mean, I wasn't going to submit yet another PR (more merge conflicts! Yay!) to really, really finish the ordering work just because I crashed into new obscure build errors because we had ordering issues. Having to bring in nd_network.h just because I needed IsConnected was a motivational fork in the eye. The original version of this has been running in a permanent C6 (single core RISC-V, WiFi 6) display of two units in my home for over a week. RemoteDebug had a few options that I just didn't care to implement. Many of the ones it claimed to implement just plain didn't work, so I didn't feel terribly bad about that. Notably, it did have an output filter. This one does not. If you're using the serial system, Fun development story: I do a lot of my development on the S3 Matrix. I encountered a board crash while all the LEDS were full brightness. The board would crash at boot - that's the fix for the dangling pointer in COnnectToWiFi(); arguably another PR - and would re-enter the crash. I learned that the warning is understated. Even on USB power from a laptop (15W, not full-on PD) I learned the LEDS can, in fact, desolder themselves. A little attention on the hotplate and a few tweezer nudges got them all reseated, and my board was fine. This is why -DBRIGHTNESS_MAX=8 is now part of that build... Some day I hope to get back to straightforward PRs with a file or two that are trivial to review that don't get caught in the gravity of the sun. I know these are a pain to review, but that's the nature of tackling some of these deep issues that span multiple systems. (Serial esoterica, non-blocking sockets, flow control on telnet while not flow crashing the device, memory allocation/fragmentation, accidentally changing the interrupt model while holding a mutex, poring through up foundational RFC's from the 80's, crazy build issues, etc.) There is a crumb that I'd like your advice/help to pick up. I have implemented tools/audit* to help with some of the system-wide issues I've encountered. They're pretty fast to run. Can you please recommend (or just implement) a way to integrate those into the build to help ensure we don't regress? |
|
I said I'd stop buf I found two important crashes under heavy load.
I haven't been able to crash it since, after scripting over 10K opens/closes to the telnet port where before it would croak after a few hundred. I'm done with this PR. Anything from here comes in on a new one. |
|
Predictably, this PR is now suffering from a merge conflict. I'll start reviewing "around it", so to speak. |
Removed remote debugging definitions and includes. Rats. Phone UI tripped me up. Accept both. Accept neither. Whatever. Sorry.
|
Ptal |
rbergen
left a comment
There was a problem hiding this comment.
I've made a few comments, some of which I care far more about than others; I'm sure you can figure out which are which.
As for the audit scrips: those you want to run, you can add to the extra_scripts directive in platformio.ini, which is at line 338 in the updated version. To not bloat platformio.ini too much (yeah, I know...) you could write and only invoke a post-build audit utility Python script that invokes them.
|
@robertlipe In part because I see a stack of new PRs from you coming in (some of which are drafts, it seems... brrr), can we please move forward with this one? |
* Move new networking wrappers (only) into dedicated namespaces.
** (I might have indented some things to prepare for
yet other incomgin namespace additions.
* Rollback audio from this PR
* Various ordering and logical grouping tweaks.
* Whitespace fixes. (seemingly always network.cpp still _feels_ wrong,
though I can't figure out why)
I don't _think_ there's any actual logic changes since the last push.
Tested:
Mesmerizer. telnet and serial debugging look great!
Move two more network functions to "have always" prototypes since only their bodies are conditional. Group prototypes in nd_network.h more logically.
Working: spectrumlite SUCCESS 00:00:12.683 mesmerizer SUCCESS 00:00:23.778 laserline SUCCESS 00:00:12.498 insulators SUCCESS 00:00:12.329 magicmirror SUCCESS 00:00:13.195 platecover SUCCESS 00:00:09.017
|
PTAL This is my new happy place with this PR. I know I'm headed for a merge collision with ... myself. I just moved around a bunch of stuff in nd_network.h (stuff that used to make sense, but that was before the giant IWYU and Networking patches around the holidays.) That busy work about the MAC fetcher that gets a tweak here, gets torched in the P4 world. We don't HAVE networking on P4, so we can't print a MAC address at boot. We don't even know if we have a chip yet that can load code that can have a MAC. So #836 gets a whole load of logic that allows async discovery of the MAC address as we bring up the APB, enumerate networking devices, and discover MACs post-boot. It's also increasingly clear that the existing scheme of "decl vs. body" based on if have_wifi is just not working. ...but I can't keep recursively patching/developing these. I'm making myself crazy and I can tell that my efforts to get some of this work cleaned up and stable are making you a bit crazy (that's OK!) and I don't want to do that. I think this is the largest single piece of atomic outstanding work and while it's veered a bit beyond "replace RemoteDebug" I think it's actually quite good now. Please feel free to submit a ticket and assign it to me. I'll tend to it after #836 and a few others land. I'll even make it easy for you to ask: Title: [DEBT] Refactor nd_network for Arduino3
|
I'm actually okay on the crazy part. But yes, I'm not a fan of six somewhat interconnected PRs from one author open at the same time - with two in draft status - exactly because I know it tends to lead to merge conflicts which then delay the whole process of reviewing, fixing and merging across at least some of them.
Haha, I've opened issues for myself before, and I think what you wrote after that line was a prime candidate. I was insufficiently unhappy with the previous state of our WIFI code to change it and I am happy with merging what's in this PR as it now is, so I don't have a strong opinion about future follow-ups from a standpoint of necessity. But that said, what you wrote does look like a very good idea. 😉 |
|
Thanx!
You know that most everything I've opened in the last couple of quarters Is
'sort of connected' and why. It's been pretty weird trying to keep things
separate enough to be submittable.
I've kept the 'nullptr deref' as a draft because I KNOW it will collide
hard with this one; everything else is now marked ready to go. (That wasn't
true even a few hours ago.) The SIOF PR is necessary for GCC14 (undefined
behaviour changed) but I plan to come back and eliminate most of that
code, too. That's another task for "later," or else we can't keep pushing
the whole project forward.
Now that we've both seen that crack in the wall of network.*, though, with
or without a ticket one of us is going to have to return to it, though. :-)
…On Wed, Apr 8, 2026 at 9:46 AM Rutger van Bergen ***@***.***> wrote:
Merged #824
<#824> into
main.
—
Reply to this email directly, view it on GitHub
<#824 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ACCSD3ZJLUGQJUTU4EYNPS34UZQ3DAVCNFSM6AAAAACWK5KVF6VHI2DSMVQWIX3LMV45UABCJFZXG5LFIV3GK3TUJZXXI2LGNFRWC5DJN5XDWMRUGI4TSNZQGYYTQMY>
.
You are receiving this because you were mentioned.Message ID:
<PlummersSoftwareLLC/NightDriverStrip/pull/824/issue_event/24299706183@
github.com>
|
Description
This PR replaces the
RemoteDebuglibrary with a custom-built, lightweight logging and console management system. WhileRemoteDebugserved us well, it brought along unnecessary complexity and dependencies that didn't perfectly align with the project's long-term architectural goals.Key Improvements
ConsoleManager,ConsoleSession,Logger) that fits the project's specific needs.Loggerhooks directly into the ESP-IDFesp_logsystem. This means that logs from the system, third-party libraries, and our owndebugXmacros are all consistently captured and broadcast.std::string_viewfor zero-allocation parsing, and tab completion has been improved for both commands and effect names.Technical Details
vprintfhook uses a two-pass approach to measure and then allocate exactly the required heap memory for log lines.std::recursive_mutexinConsoleManagerto ensure thread-safe access to sinks during broadcasts and session management.\r\0/\r\nsequences correctly, even when split across packet boundaries.Validation
Verified on hardware: