Skip to content

Refactor: Replace RemoteDebug with custom Logger and Telnet server - #824

Merged
rbergen merged 16 commits into
PlummersSoftwareLLC:mainfrom
robertlipe:feature/replace-remotedebug
Apr 8, 2026
Merged

rbergen merged 16 commits into
PlummersSoftwareLLC:mainfrom
robertlipe:feature/replace-remotedebug

Conversation

@robertlipe

Copy link
Copy Markdown
Collaborator

Description

This PR replaces the RemoteDebug library with a custom-built, lightweight logging and console management system. While RemoteDebug served us well, it brought along unnecessary complexity and dependencies that didn't perfectly align with the project's long-term architectural goals.

Key Improvements

  1. Lightweight Infrastructure: Replaced a heavy third-party library with a tailored implementation (ConsoleManager, ConsoleSession, Logger) that fits the project's specific needs.
  2. Global Logging: The new Logger hooks directly into the ESP-IDF esp_log system. This means that logs from the system, third-party libraries, and our own debugX macros are all consistently captured and broadcast.
  3. RFC 854 Telnet Server: Implemented a solid, BSD-socket based Telnet server. It properly handles Telnet negotiation (WILL ECHO for server-side echo, WILL SGA for character-at-a-time mode) and RFC 854 line ending conventions.
  4. Enhanced Debug CLI: The CLI has been rewritten to be more memory-efficient. The new tokenizer uses std::string_view for zero-allocation parsing, and tab completion has been improved for both commands and effect names.
  5. Clean Multiplexing: Output is now intelligently routed. Commands executed over Telnet stay on Telnet, while global broadcasts (like system logs) reach all active sessions.

Technical Details

  • Memory Efficiency: The new system avoids unnecessary string copies and large stack buffers. The vprintf hook uses a two-pass approach to measure and then allocate exactly the required heap memory for log lines.
  • Concurrency: Uses std::recursive_mutex in ConsoleManager to ensure thread-safe access to sinks during broadcasts and session management.
  • Standard Compliance: The Telnet server includes a state machine to handle IAC sequences and RFC 854 \r\0 / \r\n sequences correctly, even when split across packet boundaries.

Validation

Verified on hardware:

  • Serial console remains fully functional with Improv support.
  • Telnet server accepts connections, handles multiple commands, and supports tab completion.
  • System logs are correctly interleaved with CLI output.
  • ANSI color coding works correctly in modern terminal emulators.

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.
@robertlipe
robertlipe force-pushed the feature/replace-remotedebug branch 9 times, most recently from 8c6b82d to 6359906 Compare March 17, 2026 06:33
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.
@robertlipe
robertlipe force-pushed the feature/replace-remotedebug branch from 6359906 to f962da4 Compare March 17, 2026 06:43
@rbergen

rbergen commented Mar 17, 2026

Copy link
Copy Markdown
Collaborator

@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.

@robertlipe

Copy link
Copy Markdown
Collaborator Author

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,
https://docs.espressif.com/projects/esp-idf/en/v5.5.3/esp32s3/api-guides/tools/idf-monitor.html#output-filtering actually
works. For telnet, that just isn't an option. Honestly, I grep faster than I can look up that syntax. I might consider tags as potential future work. (LEDs, REMOTE, NET, AUDIO, etc.), but I'm really not sure they're more useful than "add a debug with 'ZZZZ' and grep for ZZZZ", as every time I've started tags, they've devolved uncommittable into special cases unworth committing anyway.

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?

@robertlipe

Copy link
Copy Markdown
Collaborator Author

I said I'd stop buf I found two important crashes under heavy load.

  1. If we had a lot of FDs open and got FD > 64, we dutifully memsetted right off the end of an fd_set, trouncing our own stack. Just rearchitct to not DO that.

  2. If the telnet connection was closed WHILE you had messages queued, we'd try to use TelnetSession to get to the TelnetSink, which is pointing into a now freed task. Hilarity ensued. Change it to a shared_ptr and more mindfully pass it between functions instead of assuming it's Just There.

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.

@rbergen

rbergen commented Mar 21, 2026

Copy link
Copy Markdown
Collaborator

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.
@robertlipe

Copy link
Copy Markdown
Collaborator Author

Ptal

@rbergen rbergen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread include/nd_network.h Resolved
Comment thread include/nd_network.h Resolved
Comment thread src/logger.cpp Resolved
Comment thread src/telnetserver.cpp Resolved
Comment thread include/globals.h Resolved
Comment thread include/soundanalyzer.h Resolved
Comment thread src/audio.cpp Resolved
@rbergen

rbergen commented Apr 7, 2026

Copy link
Copy Markdown
Collaborator

@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?

robertlipe and others added 5 commits April 7, 2026 07:52
* 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
@robertlipe

Copy link
Copy Markdown
Collaborator Author

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
Followup from #824.

  1. Refactor nd_network namespace. Transition from nd_network:: getters to a structured WiFiStatus object or std::optional or something to handle ENABLE_WIFI states gracefullly.
  2. Clean up identity vs. telemetry groupings.
  3. Reconsider split of decls based on ENEABLE_WIFI so maybe we get rid of a ton of ifdefs and weird logic.
  4. Think harder about cases where we just plain don't HAVE WiFi. (Whate if you ENABLE_WIFI on something like the WaveShare boards that don't HAVE Wifi? Made sense for ESP32-nothing, but something's gotta give way to new world orders.
  5. Generally better integrate the new boot-time MAC APIs to prevent crashes when printing identity before the network coprocessor is ready. Maybe Include pointer to PlatformIO in README.md #4 being "never" is a special case of this one.

@rbergen

rbergen commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator

...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'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.

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:

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. 😉

@rbergen rbergen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@rbergen
rbergen merged commit 7041d07 into PlummersSoftwareLLC:main Apr 8, 2026
52 checks passed
@robertlipe
robertlipe deleted the feature/replace-remotedebug branch April 8, 2026 14:55
@robertlipe

robertlipe commented Apr 8, 2026 via email

Copy link
Copy Markdown
Collaborator Author

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants