You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
esp32c6 default env: Serial silently routed to UART0 instead of USB-Serial/JTAG → AutoResearch RPC unreachable on FH4 boards #2665
bash autoresearch esp32c6 --parlio against an ESP32-C6FH4 (embedded 4 MB flash, USB-Serial/JTAG is the only host link) appears to flash successfully, but the host then sees zero serial output from the device — no boot banner, no RPC reply to ping. autoresearch concludes the device is dead and exits.
The chip is actually running. The bootloader's own log lines DO come through (because IDF console is routed to USB-Serial/JTAG via CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG), but everything the Arduino sketch prints via Serial.print is invisible.
Root cause
The pre-existing esp32c6 env in ci/boards.py and platformio.ini enables ARDUINO_USB_MODE=1 (CDC vs OTG mode select) but does not enable ARDUINO_USB_CDC_ON_BOOT=1. Without the latter, Arduino-ESP32 leaves Serial aliased to HardwareSerial Serial0 (UART0 on the chip's TX/RX pads). The FH4 SKU exposes neither of those pads to the USB connector, so the host literally cannot see UART0 output.
For boards that DO expose UART0 (e.g. an actual DevKitC-1 wired to a separate UART-to-USB bridge) the default works. For FH4 / Xiao-C6-like boards with USB-Serial/JTAG as the only link, the default is broken.
This makes the JSON-RPC layer in AutoResearch.ino unusable, which in turn makes the entire #2548 follow-up validation suite (parlioStreamValidate, parlioEncodeBenchmark, …) untestable on the most common bring-up hardware.
Proposed fix
Add -DARDUINO_USB_CDC_ON_BOOT=1 to the default esp32c6 build flags. Done on fix-esp32c6-parlio (commit 5fcddee) in ci/boards.py ESP32_C6_DEVKITC_1.build_flags. After this change Serial resolves to HWCDC (the USB-Serial/JTAG class), and JSON-RPC ping returns within ~16 ms.
The objection in platformio.ini ('ARDUINO_USB_CDC_ON_BOOT=1 // WAIT ON BOOT ! DANGEROUS') doesn't apply here: AutoResearch.ino already gates the wait behind while (!Serial && millis() < SERIAL_TIMEOUT_MS) with a 120 s timeout, so a host that never opens the port falls through cleanly.
#2664 is about flag propagation. Even when the bash-compile path correctly carries the build flags, ARDUINO_USB_CDC_ON_BOOT=1 was missing from the source of truth entirely. That gap is what this issue tracks; #2664 is the orthogonal infrastructure bug.
Research synthesis: ROM path + non-blocking CDC-on-boot — both are achievable
Investigated three angles in parallel: (a) ROM/LL-level USB-Serial/JTAG without HWCDC, (b) what ARDUINO_USB_CDC_ON_BOOT=1 actually blocks on, (c) prior FastLED attempts at this flag.
TL;DR
The // WAIT ON BOOT ! DANGEROUS comment is stale advice for ESP32-C6 specifically. On C3/C6/H2 (which use HWCDC, not TinyUSB USBCDC):
HWCDC::begin() does not block waiting for a host — it just sets up the ring buffer and IRQ.
The only blocking is in write()/flush() when the TX ring fills with no host draining it. This is bounded to ~100 ms per write, ~2 s worst case, and is disabled by a one-line call: Serial.setTxTimeoutMs(0);.
Upstream PR espressif/arduino-esp32#7583 already made tx_timeout=0 the default while unplugged and 100 ms only after the host connects. So even without our own call, modern arduino-esp32 is mostly safe.
Serial.flush() is the one remaining hazard (issue #7554) — don't call it on HWCDC. AutoResearch.ino doesn't.
Answer to ❶ — "can we have a ROM code path instead?"
Yes. IDF exposes inline register-level functions in hal/usb_serial_jtag_ll.h that compile into the binary with no driver, no FreeRTOS, no Arduino layer:
#include"hal/usb_serial_jtag_ll.h"staticsize_tusj_write_nonblocking(constuint8_t* p, size_t n) {
size_t written = 0;
while (written < n && usb_serial_jtag_ll_txfifo_writable()) {
written += usb_serial_jtag_ll_write_txfifo(p + written, n - written);
}
usb_serial_jtag_ll_txfifo_flush();
return written; // may be < n; caller decides whether to drop
}
This is what HWCDC itself calls under the hood. It is safe to invoke before setup(), before USB enumeration, and from panic/abort contexts. Useful as an emergency print path that never blocks regardless of host state. Companion: usb_serial_jtag_is_connected() for host detection (the same primitive HWCDC::isPlugged() wraps).
Answer to ❷ — "can we have CDC on boot but NOT block when USB is not connected?"
Yes — one line. After Serial.begin(...), call:
Serial.begin(115200);
Serial.setTxTimeoutMs(0); // writes drop instead of blocking when no host
The setTxTimeoutMs setter just stores the value, and 0 means "give up immediately, drop the chunk." This is the official Espressif workaround in issues #9172, #7779.
For the while (!Serial) pattern, HWCDC::operator bool() returns usb_serial_jtag_is_connected() — so the bounded-timeout wait AutoResearch.ino already does (SERIAL_TIMEOUT_MS = 120000) is correct. Optionally tighten to 1–2 s since the ESP32-C6's USJ controller enumerates fast.
Current FastLED state (as of master)
ci/boards.py:801–808 — ESP32_C6_DEVKITC_1.build_flags = ["-funwind-tables"] — no ARDUINO_USB_CDC_ON_BOOT=1 in the board definition.
platformio.ini:150 — flag is commented out with the // WAIT ON BOOT ! DANGEROUS warning.
The flag was removed in commit 8bc311a0 (Apr 2026) from both C6 and P4.
ESP32-P4 had the same bug, restored via ci/boards.py (not platformio.ini) in commit 3ccfe93ac (May 2026, issue #2541/#2620).
ESP32-C6 was never restored — that's the gap this issue documents.
examples/AutoResearch/AutoResearch.ino:293 — already uses bounded while (!Serial && millis() < SERIAL_TIMEOUT_MS) with a 120 s timeout. Falls through cleanly.
Recommended fix (minimal, mirrors the ESP32-P4 fix)
(Mirror the May-2026 P4 fix from commit 3ccfe93ac.)
examples/AutoResearch/AutoResearch.ino — right after Serial.begin(...), add a guard for C3/C6/H2/P4:
#if ARDUINO_USB_CDC_ON_BOOT
Serial.setTxTimeoutMs(0); // never block on prints when host absent
#endif
Do not add Serial.flush() calls on HWCDC platforms (per upstream issue #7554, flush() can still hang).
(Optional) For panic/early-boot diagnostics that must work without any driver, expose a fl::usj::write_nonblocking() helper in src/platforms/esp/32/drivers/usb_serial_jtag_esp32.h that wraps the usb_serial_jtag_ll_* inlines. Suitable for assertion handlers, stack trace dumps, and pre-app_main hooks.
Why the original concern was overblown
The WAIT ON BOOT ! DANGEROUS warning conflated two failure modes:
begin() blocking — never happened on HWCDC; this is a TinyUSB (S2/S3) concern.
Unbounded while (!Serial) — only blocks if the sketch forgets the timeout. AutoResearch.ino already has one.
With setTxTimeoutMs(0) plus the existing bounded wait, the field-deployment failure mode (boot stalls on host-less devices) is fully closed.
Surveyed the current state of the print API and designed a contract that makes it safe-by-default on HWCDC platforms (ESP32-C3/C6/H2/P4) and every other backend. The good news: most of the plumbing already exists. This is a contract specification + targeted patches, not a rewrite.
per-platform impls in io_arduino.hpp, io_esp_idf.hpp, io_posix.cpp.hpp, io_wasm.cpp.hpp, detail/io_esp_jtag_or_uart.hpp
The split is already correct. The issue is semantics not yet pinned down — specifically what flush() waits on and what write_bytes() does when the sink can't drain.
Design goals (in priority order)
No primitive blocks indefinitely. Every print/write_bytes call returns in bounded time, even with no host attached. flush respects its timeoutMs argument and never exceeds it.
Best-effort delivery, lossy on backpressure. A disconnected host must not stall LED rendering. If the sink ring buffer is full, oldest bytes drop. This matches usb_serial_jtag and printf semantics, and is what setTxTimeoutMs(0) enforces upstream.
No silent data loss when a host is connected. When isConnected() is true, writes block up to a small bound (~10–20 ms) so log lines are not fragmented mid-line.
ROM-level emergency path. A panic/abort context can call a never-blocks, no-driver path. This is the answer to "ROM code path" in the original question.
Same contract on every platform. Posix, WASM, AVR, ESP32 — all observe rules 1–4. Tests exercise the contract, not the backend.
Contract (the part that needs locking down)
namespacefl {
// Best-effort write of a null-terminated string. NEVER blocks longer than// kMaxWriteStallMs (default 10ms) regardless of host state. Returns silently// on partial drop. Safe from ISR? No — uses ring buffer, scheduler-bound.voidprint(constchar* str) noexcept;
// Same as print + newline. Newline is emitted as a single atomic chunk so// it cannot be split across a drop.voidprintln(constchar* str) noexcept;
// Best-effort raw write. Returns BYTES ACCEPTED into the sink ring buffer,// which may be < size on backpressure. Never blocks > kMaxWriteStallMs.// Caller decides retry/drop policy.size_twrite_bytes(constu8* buf, size_t size) noexcept;
// Block until ring buffer is drained OR timeoutMs elapses, whichever first.// timeoutMs == 0 -> poll once, no wait. Returns true if fully drained.// On HWCDC, this is the dangerous primitive — implementation MUST honour// the timeout and return false rather than spin (see upstream issue #7554).boolflush(u32 timeoutMs = 1000) noexcept;
// True if a host is observably reading (USB CDC enumerated and DTR asserted,// UART always returns true since we cannot know).boolis_connected() noexcept;
// Emergency / panic path. Bypasses ring buffer, writes directly to chip// peripheral registers. Never blocks. May lose bytes if FIFO full.// Safe to call from panic handler, ISR, pre-main constructors.size_temergency_write(constu8* buf, size_t size) noexcept;
} // namespace fl
Key invariant: kMaxWriteStallMs (compile-time constant, default 10ms) is the only knob users care about. Everything else is policy.
Per-backend implementation matrix
Backend
print/write_bytes non-block
flush bounded
is_connected
emergency_write
ESP32 HWCDC (C3/C6/H2/P4)
Serial.setTxTimeoutMs(0) at init
call Serial.flush() ONLY when is_connected() (skip otherwise — bug #7554)
Serial.write (already non-blocking for short writes)
Serial.flush() is bounded by hardware (~1ms per byte)
(bool)Serial (mega32u4) or true
direct UDR0 = register write
Posix host tests
already ::write(2, ...) non-blocking on tty
::fsync(2) capped via alarm or just bypass
check isatty(2)
same path as normal write
WASM
::printf — already buffered to JS
no-op
always true
same path
What changes in the tree
Tiny edits, no rewrites. The abstraction layer is already there.
src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp — in the EspIO::instance() initializer, after Serial.begin(...) (or equivalent for the USJ driver path):
#if defined(ARDUINO) && ARDUINO_USB_CDC_ON_BOOT
Serial.setTxTimeoutMs(0); // never block when host absent
#endif
src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp — flush() impl: guard Serial.flush() behind Serial.isPlugged() (or is_connected()). Without a host, return true immediately — there is no host to drain to.
boolEspIO::flush(u32 timeoutMs) {
if (!is_connected()) returntrue; // nothing to wait foru32 deadline = millis() + timeoutMs;
Serial.flush(); // bounded by tx_timeout_ms, but we still capreturnmillis() <= deadline;
}
src/platforms/io.h — add the two new contract members:
Default impl in a cpp.hpp: is_connected() { return true; } and emergency_write aliases write_bytes. Backends override as needed.
New file src/platforms/esp/32/detail/usj_rom.hpp — header-only wrapper around usb_serial_jtag_ll_* for the emergency path. Used by:
EspIO::emergency_write (override)
The IRQ-safe assertion handler
Stack trace dumper
namespacefl::esp32::detail {
inlinesize_tusj_emergency_write(constu8* p, size_t n) {
size_t w = 0;
while (w < n && usb_serial_jtag_ll_txfifo_writable()) {
w += usb_serial_jtag_ll_write_txfifo(p + w, n - w);
}
usb_serial_jtag_ll_txfifo_flush();
return w;
}
}
src/fl/stl/cstdio.cpp.hpp — update fl::print/println/write_bytes/flush to:
Pass through to platforms::* (already the case)
Cap print/write_bytes runtime: if platforms::write_bytes reports partial, do NOT retry. Drop is a feature.
flush(0) is documented as "poll, do not wait" — useful before sleep, useless otherwise.
src/fl/stl/ostream.h — endl calls flush(0) (poll), not flush(1000). The current implementation flushes synchronously; on HWCDC without a host this can stall ~2s per line. The fix is single-line: endl should print("\n") only, no flush.
ci/boards.pyESP32_C6_DEVKITC_1.build_flags — add -DARDUINO_USB_MODE=1, -DARDUINO_USB_CDC_ON_BOOT=1 (the patch from the previous comment). This is what makes Serial == HWCDCSerial in the first place.
Test plan
Add tests/fl/stl/cstdio_contract.cpp:
print() returns within kMaxWriteStallMs even when sink reports backpressure (inject a sink that always returns 0 bytes accepted).
flush(timeoutMs) returns within timeoutMs + kEpsilon regardless of sink state.
flush(0) returns immediately.
is_connected() reflects injected sink state.
emergency_write bypasses the sink mock and goes through a separate raw path.
Sequence: print("A"); print("B"); against a sink that accepts only 1 byte -> no deadlock, second print does not block.
These run under Posix/WASM with the existing test injection handler at src/fl/stl/cstdio.cpp.hpp:44-65. The HWCDC-specific paths get covered by bash autoresearch esp32c6 --parlio once the ci/boards.py patch lands.
Open question (one)
Should fl::printitself be a variadic that accepts integers/floats (à la printf), or should the typed convenience be left to fl::cout << and a hypothetical fl::format()? Current code is const char*-only, which is the simplest and most embedded-friendly. I would keep it that way — the cost of dragging in printf formatters on AVR is real (~1.4 KB) and fl::cout already covers the typed case via ostream.
Summary
The contract is: bounded latency, lossy on backpressure, has an ROM escape hatch. The plumbing exists; the missing pieces are (a) setTxTimeoutMs(0) at init, (b) flush() gated by is_connected(), (c) an emergency_write ROM path on USJ chips, (d) endl not flushing. All four are sub-twenty-line patches. Once landed, every backend obeys the same contract and the WAIT ON BOOT! DANGEROUS warning becomes truly stale.
Cross-platform verification: contract is supportable everywhere FastLED ships
Fanned out four sub-agents to verify the proposed contract — print/write_bytes bounded latency, flush(timeoutMs) honors timeout, is_connected() host detection, emergency_write() ROM/register panic path — against every platform family FastLED currently targets.
Headline result: every platform family can support the contract. Two require minor caveats. The FastLED tree itself has six fixable gaps in the host-side implementations of the existing API.
Per-platform support matrix
Platform / backend
print bounded
flush(timeoutMs)
is_connected()
emergency_write()
Notes
ESP32 HWCDC (C3/C6/H2/P4)
✅ Serial.setTxTimeoutMs(0)
✅ guard on isPlugged() (avoid #7554)
✅ usb_serial_jtag_is_connected()
✅ usb_serial_jtag_ll_* ROM inlines
Best-case backend. IRAM/ISR-safe ROM path
ESP32 USBCDC (S2, S3 default)
✅ setTxTimeoutMs(0) (default 250 ms)
⚠ wrap tud_cdc_n_write_flush in xSemaphoreTake(... , ms)
✅ tud_cdc_n_connected()
⚠ requires TinyUSB initialized — no true pre-app_main ROM path
Document gap; fall back to UART1 for pre-init panic
Native USB-CDC has no ROM panic path; falls to UART pin
Teensy 4.x (i.MX RT)
⚠ default TX_TIMEOUT_MSEC=120 ms — wrap
⚠ wrap with deadline
✅ Serial.dtr()
✅ LPUART6->DATA = b (Serial1)
Same caveat as 3.x
STM32duino USB-CDC
✅ wrap availableForWrite() w/ millis() cap
✅ wrap tud_cdc_* flush
✅ dtrState (after 10 ms settle)
✅ USARTx->TDR + USART_ISR_TXE poll
STM32duino UART
✅ wrap
✅ already has Uart::flush(uint32_t timeout) native
n/a — true
✅ same as above
Only core with native timeout-aware flush
nRF52 (Adafruit/TinyUSB)
✅ shorten yield() loop w/ deadline
✅ tud_cdc_n_write_flush (non-blocking)
✅ tud_cdc_n_connected()
✅ NRF_UARTE0->TASKS_STARTTX (UARTE) or TinyUSB raw
UART Uart.cpp uses portMAX_DELAY — must replace with pdMS_TO_TICKS(10)
SAMD (Zero/MKR/XIAO M0)
✅ wrap usb.send() with bound
✅ wrap
✅ _usbLineInfo.lineState > 0 (DTR)
⚠ direct USB->DEVICE.DeviceEndpoint[ep] is impractical from panic; use SERCOM UART register
RP2040 (arduino-pico)
⚠ current 1 s timeout — reimplement on tud_cdc_write_available() w/ 10 ms cap
✅ wrap
✅ tud_cdc_connected()
✅ pico-sdk uart_get_hw(uart0)->dr = c (ISR-safe)
Apollo3 (Artemis)
⚠ replace while(!_tx_idle) spin with millis()-bounded wait
✅ wrap am_hal_uart_tx_flush
n/a — true
✅ UARTn->DR = c + poll UARTn->FR
No USB; external bridge
POSIX host (tests)
⚠ ::write(2) can block on slow pipe; add O_NONBLOCK opt
⚠ flush() currently ignores timeoutMs (see gap #3 below)
n/a — true (or isatty(2))
✅ ::write(2) is POSIX async-signal-safe
WASM (emscripten)
✅ ::printf already buffers to JS
✅ no-op
n/a — true
✅ EM_ASM({console.error(UTF8ToString($0));}, str)
Existing bug: write_bytes emits hex text, not raw bytes — see gap #4
Windows (_write)
⚠ no timeout on _write(2)
⚠ flush() ignores timeoutMs
n/a — true
✅ _write(2)
Same POSIX gaps
Legend: ✅ supported as-is or with trivial wrap, ⚠ supported but needs work, ❌ cannot support (escape hatch: degrade to no-op).
Two genuine caveats (worth calling out)
ESP32-S2/S3 USBCDC has no true ROM panic path. TinyUSB must be initialized before tud_cdc_n_write works. Pre-app_main constructors and very early panics on these chips cannot use emergency_write over USB. Recommended fallback: route emergency_write to UART0 on these variants and document the caveat. Every other ESP32 (HWCDC and classic UART) is fine.
ATtiny + SoftwareSerial is genuinely unsupportable. SoftwareSerial blocks bit-bang style and cannot honor a millisecond timeout (bit times are microseconds, but a full byte at 9600 baud is ~1 ms — close to but not bounded by the contract). Practical answer: detect this case at compile time and emit emergency_write = no-op, print = no-op, flush = return true. Logging on ATtiny was already a poor fit; the contract simply formalizes that.
Six gaps in the current FastLED tree (mostly host-side)
These were found by inspecting the existing fl::platforms impls:
is_connected() missing everywhere — src/platforms/io.h:13-41 declares serial_ready() (init-done semantics) but no host-presence primitive. Add bool is_connected() noexcept with per-platform overrides.
emergency_write() missing everywhere — same file. Add size_t emergency_write(const u8*, size_t) noexcept. POSIX/Win default-impl can alias write_bytes (already signal-safe). WASM default-impl uses EM_ASM/emscripten_log. ESP32 HWCDC overrides with usb_serial_jtag_ll_*.
flush(timeoutMs) ignores the timeout on POSIX/Win/WASM.src/platforms/posix/io_posix.cpp.hpp:63-68 calls fsync(2) then returns true unconditionally; same shape in io_win.cpp.hpp. Should honor the deadline (POSIX: fsync is fast on a tty/pipe; wrap with alarm(2) or just bypass).
WASM write_bytes emits hex-encoded text, not raw bytes.src/platforms/wasm/io_wasm.cpp.hpp:62-70 does printf("%02X ", b) per byte. This is a contract violation — binary write_bytes must round-trip. Fix: route through fwrite(stdout) or hold a per-process buffer flushed on newline.
POSIX print lacks O_NONBLOCK on fd 2. A slow log consumer (pipe back-pressure) can stall past the 10 ms cap. Either fcntl(F_SETFL, O_NONBLOCK) on init or use writev/send with MSG_DONTWAIT. Tests using stderr pipe redirection are the affected case.
fl::endl does NOT currently flush (src/fl/stl/ostream.h:99-102 just emits "\n"). This is good — the prior design comment incorrectly suggested it did. Leave it alone. Document that fl::cout << fl::endl is notstd::endl; it's a line-break alias.
Test injection layer
src/fl/stl/cstdio.cpp.hpp:44-65 already provides inject_print_handler / inject_println_handler / inject_available_handler / inject_read_handler (lazy function-local statics, force-initialized via FL_INIT(cstdio_init_wrapper) to dodge a known macOS static-init recursion). Missing: no injection handlers for flush, write_bytes, serial_ready. Add inject_flush_handler and inject_write_bytes_handler to enable the contract test plan from the previous comment. No tests/fl/stl/cstdio_contract.cpp exists yet.
Already-correct upstream patterns to reuse
STM32duino Uart::flush(uint32_t timeout) — the only core that already implements the contract natively. Cite as the reference implementation.
arduino-esp32 PR #7583 — already shipped tx_timeout=0 as the default when unplugged for HWCDC. We benefit without writing any code.
Teensy usb_serial_write_buffer_free() — exemplar of the "probe before write" pattern we want on every backend.
Summary
Every platform family except ATtiny+SoftwareSerial can implement the proposed contract. ESP32-S2/S3 USBCDC has a documented caveat around pre-init emergency writes. The remaining work is per-backend wrapping of existing primitives plus six small fixes to the host-side implementations in the FastLED tree. The contract holds.
Verification by four parallel sub-agents covering ESP32 family · AVR/ESP8266/Teensy · STM32/nRF52/SAMD/RP2040/Apollo3 · POSIX/WASM/Win + FastLED tree state.
Alternative design: minimal surface fl::print that "just does the right thing"
Reconsidering after feedback. The prior design (comment 4587446387) added five public symbols (is_connected, emergency_write, plus the existing four). That's API surface that users will have to know about and that we'll have to keep consistent across every backend forever.
Alternative: keep the surface as small as it is today — fl::print and fl::println — and make the function itself responsible for choosing the right backend at runtime based on CDC/USB state. Users never see the policy; the function does the right thing.
No is_connected(). No emergency_write(). No new symbols. The four functions that already exist in src/fl/stl/cstdio.h keep their signatures.
How fl::print "does the right thing" internally on ESP32
The policy lives entirely inside platforms::print for the ESP32 family. Three-tier fallback ladder, evaluated per call:
// src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp (impl sketch)voidplatforms::print(constchar* str) noexcept {
// Tier 1: HWCDC (or USBCDC) when CDC-on-boot is the configured Serial.// Already auto-non-blocks via setTxTimeoutMs(0) set at init.// Serial.write() returns 0 on backpressure without blocking.
#if ARDUINO_USB_CDC_ON_BOOT
// is the host actually reading?if (Serial.isPlugged()) {
Serial.print(str); // non-blocking (tx_timeout=0)return;
}
// host absent: fall through to tier 3 ROM path so log lines// are still visible if the user opens a viewer mid-run.
#else// CDC not configured: Serial is UART0. Write only if it'll fit.if (Serial.availableForWrite() >= (int)strlen(str)) {
Serial.print(str);
return;
}
#endif// Tier 3: ROM fallback. Works in EVERY scenario:// - CDC misconfigured / never began// - CDC begun but host absent// - Bootloader hasn't run the Arduino init yet// - We're inside a panic handler// - Flash cache is disabled// esp_rom_printf goes wherever IDF's ROM console putc is bound, which// includes USB-Serial/JTAG when CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y.// The ROM driver has a built-in 50 ms one-time wait, then drops.esp_rom_printf("%s", str);
}
The chip's own ROM is the guaranteed-safe sink. The IDF doc explicitly promises a bounded 50 ms stall:
The ESP first writes to a small internal buffer. After this buffer becomes full (e.g. no PC terminal connected), the ESP does a one-time 50 ms wait, then drops.
— esp-idf docs, USB-Serial/JTAG console
So even the worst case — ARDUINO_USB_CDC_ON_BOOT=1 set but the host never opens the port — is bounded to 50 ms once, then zero overhead per subsequent call.
Per-platform behavior collapses to three lines of intent
Platform
What fl::print does internally
ESP32 HWCDC (C3/C6/H2/P4)
Tier 1 if Serial.isPlugged(), else esp_rom_printf (which routes to USJ via secondary console config)
ESP32 USBCDC (S2/S3)
Tier 1 if (bool)Serial, else esp_rom_printf (which routes to UART0 ROM console)
ESP32 UART0 (classic)
availableForWrite() probe, else esp_rom_printf (which is UART0 anyway)
availableForWrite() probe, else drop. (No ROM printf analogue, but UART naturally drains at baud rate ~ μs/byte.)
POSIX / Win
::write(2, ...) (signal-safe, already bounded by tty)
WASM
::printf (already buffered to JS)
Notice every platform stays inside its platforms::print implementation. The user never sees a tier choice.
What this trades vs the expanded contract
Aspect
Expanded contract
Minimal "just works"
Public symbols
6
4 (today's surface)
User can query "is host present"?
Yes (is_connected())
No — but they rarely need it; fl::print already drops cleanly
User can force ROM path explicitly?
Yes (emergency_write())
No — but fl::print falls back to ROM automatically
Per-backend code complexity
Medium (each backend implements 6 methods)
Low (each backend implements 1 method with a tier ladder)
Test surface
6 contract tests
1 test ("never blocks > 100 ms; always produces output through some path")
Footprint on AVR
+~80 B per added symbol
0 — surface unchanged
Failure mode if CDC misconfigured
Output is silently lost unless user explicitly calls emergency_write
Output appears via ROM path automatically
Discoverability of host presence
Explicit API
Hidden — fine for FastLED's use case (no FastLED code asks "is host there?")
Why ROM-as-fallback is the right call for FastLED specifically
FastLED's logging is operator-diagnostic: boot banner, frame timing on demand, error prints. It is never used as a data channel where loss matters. So the right policy is:
Always produce output if a sink exists. Don't silently drop because the user happens to have CDC misconfigured.
Never block. A disconnected host must not stall LED rendering.
Don't make the user reason about connection state. They want to call fl::print("ready") and have the message land somewhere — host, UART pin, JTAG viewer, doesn't matter.
ROM-as-fallback gives all three. The chip vendors already shipped the safety net (50 ms timeout, drop on full); we just use it.
What about flush()?
Same minimal trick: fl::flush(timeoutMs) returns true immediately if the active sink is the ROM path (nothing to flush — ROM already drained or dropped). Returns the bounded flush result if the active sink is HWCDC/USBCDC with a connected host. Never spins.
What about write_bytes()?
Same fallback ladder, but the ROM fallback is a problem: esp_rom_printf is text-only and will choke on \0 and non-printable bytes. Recommendation: write_bytes does NOT fall back to ROM. If the tier-1 sink is unavailable, it returns 0 (bytes dropped) and the caller decides. Binary payloads are a niche use case in FastLED (mostly serial RPC in AutoResearch.ino); the user controls when they enable it.
Migration from today's tree
ci/boards.pyESP32_C6_DEVKITC_1.build_flags: still need -DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT=1. The minimal design needs CDC-on-boot to be enabled for Tier 1 to even exist. (Same as expanded design.)
src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp: at init, set Serial.setTxTimeoutMs(0) (same as expanded). In print, add the isPlugged() check and ROM fallback (new; ~10 lines).
src/platforms/io.h: unchanged. No new declarations.
src/fl/stl/cstdio.h: unchanged. No new declarations.
All other backends: existing impls keep working; add availableForWrite() probe to AVR/ESP8266/etc. paths defensively (1-line addition each).
One genuine downside
If a user needs to know whether the host is reading (e.g. to decide between two log verbosities), they cannot — there's no fl::is_connected(). The minimal design says: that's not FastLED's job. Users who need it can call Serial.isPlugged() directly when targeting ESP32 (it's already an arduino-esp32 API). FastLED doesn't add to its surface area to wrap something the platform already provides.
Open question
Do we want the minimal design at all, or is the expanded contract worth its weight in test coverage and explicit-ness? I'm asking a code-reviewer sub-agent to give an independent take comparing the two designs. Will post their opinion in the next comment.
Alternative design framed in response to: "keep the minimal surface area of fl::print but instead it just does the right thing depending CDC USB status and more. falling back to esp_rom_print if misconfigured and not locking the device if CDC USB is not plugged in"
Independent second opinion (from a sub-agent that read both designs without prior context)
Asked an independent reviewer to read both designs cold and recommend one. Their verdict, posted verbatim:
Recommendation: ship the minimal fl::print design, but tighten two things before merging
Drop the ROM fallback for ISR/panic contexts (it is not documented signal-safe), and keep is_connected() available as an internal helper used by the impl, not as public API.
Why the minimal design wins for FastLED
FastLED's print system is operator diagnostics — boot banner, frame-rate prints, "this strip failed to init." It is never a data channel where loss matters. The expanded contract optimizes for a use case FastLED does not have: applications that need to reason explicitly about host connection state and route panic logs through a documented escape hatch. None of FastLED's call sites care.
The expanded contract's 6 symbols also push policy onto the user. Any user who reaches for emergency_write() has to first know that ordinary fl::print is unreliable in some context, then know which context, then remember to switch — that's a foot-gun matrix. The minimal design says: you write fl::print("ready") and the runtime picks the safe sink. That is the correct division of labor for a library.
The other tell: the cross-platform verification table shows ESP32-S2/S3 USBCDC has no true pre-app_main ROM path and ATtiny+SoftwareSerial cannot honor the contract at all. So the "guarantee" emergency_write() advertises is already platform-conditional. A public symbol that silently degrades on two of the supported platforms is worse than no symbol — it sets an expectation the library cannot universally meet.
Where the minimal design is wrong as written
The esp_rom_printf fallback is not safe as a general "always works" answer. Two real problems:
The 50 ms bound is a property of the IDF VFS driver, not esp_rom_printf itself. The IDF docs (USB-Serial/JTAG console) describe a one-time 50 ms wait when the internal buffer fills and no PC is connected. That's the driver layer. esp_rom_printf routes through esp_rom_output_to_channels and the configured putc — its blocking behavior depends on whether the channel is bound to UART (drains at baud rate, ~μs/byte, effectively non-blocking) or USJ (uses the FIFO writable check, but with no documented timeout in the ROM symbol itself).
esp_rom_printf is not documented signal-safe, ISR-safe, or reentrant. The header in esp_rom_sys.h documents only "Print formatted string to console device. Note float and long long not supported." The ESP-IDF logging docs explicitly warn "it is not advised to use printf and other output functions in ISRs"; the recommended ISR primitive is ESP_EARLY_LOGx, which expands to esp_rom_printf only outside the constrained-env-safe build flag. Treating ROM printf as a universal panic sink is plausible (it's what ESP_DRAM_LOGx uses) but not contractually guaranteed by Espressif. We should not advertise it as one.
Failure modes the minimal design overlooks
Calling fl::print from an ISR: under the minimal design, the user has no warning. Document this as undefined behavior and add a FL_DEBUG_ASSERT(!xPortInIsrContext()) in debug builds.
ARDUINO_USB_CDC_ON_BOOT=0 on a board with no UART pins: tier 1 fails, ROM fallback writes to whatever the IDF secondary console is configured to — often nothing. Output is silently lost. The expanded design has the same gap.
Calling fl::print before any Serial.begin(): on HWCDC, the isPlugged() check returns false and we fall through to ROM, which works fine. Good.
The hybrid I would actually ship
Keep the public surface at 4 symbols (minimal). Internally, factor the policy into a static bool host_connected() helper used only by the impl. Replace the ROM fallback with a non-blocking direct write to usb_serial_jtag_ll_write_txfifo (the inlines from hal/usb_serial_jtag_ll.h) — these are register-level, in IRAM via the LL header, have no host-state dependency, and were verified usable from panic contexts in the first comment of the issue. This gives you the same "always have a sink" property as ROM printf, but with a documented IRAM-safe primitive instead of a ROM symbol whose safety is folklore.
For non-ESP32 platforms, the availableForWrite() probe-then-drop pattern in the table is correct as written.
Net result: 4 public symbols, deterministic IRAM-safe fallback on ESP32 USJ chips, no API surface for users to misuse, no claim we can't back up.
The reviewer's hybrid is the right answer. Summarizing the three deltas from the minimal-design comment above:
Replace esp_rom_printf fallback with usb_serial_jtag_ll_write_txfifo on USJ chips. Same "always works" guarantee, but with documented IRAM/ISR/panic-safety from the chip vendor's LL header instead of a ROM symbol whose safety is folklore. The 50 ms bound comes from the IDF VFS driver, not the ROM call — we'd have been advertising a guarantee we don't own. Use the LL inlines instead and document the bound ourselves: "up to 100 bytes per call, fixed-FIFO drop semantics, never blocks > 100 μs."
Keep is_connected() as an internal helper, not public API. It's the right primitive for the impl's tier-selection logic, but exposing it invites users to write if (fl::is_connected()) { fl::print(...) } — which is both racy and redundant (the impl already does the right thing internally). Make it static inside io_esp_jtag_or_uart.hpp.
Add an ISR debug assertion.FL_DEBUG_ASSERT(!xPortInIsrContext()) in debug builds. Production builds drop the check; UB on ISR-call is consistent with the rest of FastLED's threading model.
Resulting public surface is exactly today's cstdio.h — print, println, write_bytes, flush(timeoutMs). Zero new symbols. All the policy is invisible to callers.
Total: ~75 lines, single PR, no public API surface change. The "WAIT ON BOOT! DANGEROUS" warning becomes truly stale.
Status of the design discussion
I think we're done. The three comment chain — expanded contract → platform matrix → minimal alternative → second opinion → hybrid — converges on the hybrid as the right answer. Ready to implement when you give the go-ahead.
Superseded by #2668, which captures the converged minimal-surface design agreed in this issue's comment chain (expanded contract → cross-platform verification → minimal alternative → independent second opinion → hybrid).
Summary of the convergence:
Public surface stays at today's 4 symbols (fl::print, fl::println, fl::write_bytes, fl::flush) — zero new API
ESP32 USJ chips (C3/C6/H2/P4) fall back to usb_serial_jtag_ll_write_txfifo (LL inlines, documented IRAM/ISR-safe) instead of esp_rom_printf (whose safety is undocumented folklore)
is_connected() lives as a static helper inside the impl, not as public API
Closing this as 'not planned' because the original 'add the flag' fix in this issue is now part of the broader #2668 spec. The ARDUINO_USB_CDC_ON_BOOT=1 flag is one bullet in #2668's implementation checklist.
Activity
zackees commentedon May 31, 2026
Research synthesis: ROM path + non-blocking CDC-on-boot — both are achievable
Investigated three angles in parallel: (a) ROM/LL-level USB-Serial/JTAG without HWCDC, (b) what
ARDUINO_USB_CDC_ON_BOOT=1actually blocks on, (c) prior FastLED attempts at this flag.TL;DR
The
// WAIT ON BOOT ! DANGEROUScomment is stale advice for ESP32-C6 specifically. On C3/C6/H2 (which useHWCDC, not TinyUSBUSBCDC):HWCDC::begin()does not block waiting for a host — it just sets up the ring buffer and IRQ.write()/flush()when the TX ring fills with no host draining it. This is bounded to ~100 ms per write, ~2 s worst case, and is disabled by a one-line call:Serial.setTxTimeoutMs(0);.tx_timeout=0the default while unplugged and100 msonly after the host connects. So even without our own call, modern arduino-esp32 is mostly safe.Serial.flush()is the one remaining hazard (issue #7554) — don't call it on HWCDC.AutoResearch.inodoesn't.Answer to ❶ — "can we have a ROM code path instead?"
Yes. IDF exposes inline register-level functions in
hal/usb_serial_jtag_ll.hthat compile into the binary with no driver, no FreeRTOS, no Arduino layer:This is what HWCDC itself calls under the hood. It is safe to invoke before
setup(), before USB enumeration, and from panic/abort contexts. Useful as an emergency print path that never blocks regardless of host state. Companion:usb_serial_jtag_is_connected()for host detection (the same primitiveHWCDC::isPlugged()wraps).Answer to ❷ — "can we have CDC on boot but NOT block when USB is not connected?"
Yes — one line. After
Serial.begin(...), call:Verified from arduino-esp32/cores/esp32/HWCDC.cpp:
The
setTxTimeoutMssetter just stores the value, and0means "give up immediately, drop the chunk." This is the official Espressif workaround in issues #9172, #7779.For the
while (!Serial)pattern,HWCDC::operator bool()returnsusb_serial_jtag_is_connected()— so the bounded-timeout waitAutoResearch.inoalready does (SERIAL_TIMEOUT_MS = 120000) is correct. Optionally tighten to 1–2 s since the ESP32-C6's USJ controller enumerates fast.Current FastLED state (as of
master)ci/boards.py:801–808—ESP32_C6_DEVKITC_1.build_flags = ["-funwind-tables"]— noARDUINO_USB_CDC_ON_BOOT=1in the board definition.platformio.ini:150— flag is commented out with the// WAIT ON BOOT ! DANGEROUSwarning.8bc311a0(Apr 2026) from both C6 and P4.ci/boards.py(notplatformio.ini) in commit3ccfe93ac(May 2026, issue #2541/#2620).examples/AutoResearch/AutoResearch.ino:293— already uses boundedwhile (!Serial && millis() < SERIAL_TIMEOUT_MS)with a 120 s timeout. Falls through cleanly.Recommended fix (minimal, mirrors the ESP32-P4 fix)
ci/boards.py—ESP32_C6_DEVKITC_1.build_flags:(Mirror the May-2026 P4 fix from commit
3ccfe93ac.)examples/AutoResearch/AutoResearch.ino— right afterSerial.begin(...), add a guard for C3/C6/H2/P4:Do not add
Serial.flush()calls on HWCDC platforms (per upstream issue #7554,flush()can still hang).(Optional) For panic/early-boot diagnostics that must work without any driver, expose a
fl::usj::write_nonblocking()helper insrc/platforms/esp/32/drivers/usb_serial_jtag_esp32.hthat wraps theusb_serial_jtag_ll_*inlines. Suitable for assertion handlers, stack trace dumps, and pre-app_mainhooks.Why the original concern was overblown
The
WAIT ON BOOT ! DANGEROUSwarning conflated two failure modes:begin()blocking — never happened on HWCDC; this is a TinyUSB (S2/S3) concern.while (!Serial)— only blocks if the sketch forgets the timeout.AutoResearch.inoalready has one.With
setTxTimeoutMs(0)plus the existing bounded wait, the field-deployment failure mode (boot stalls on host-less devices) is fully closed.References
Serialmacro switchtx_timeout=0when unpluggedflush()hangs without hostsetTxTimeoutMs(0)workaroundcomponents/hal/esp32c6/include/hal/usb_serial_jtag_ll.h8bc311a0(removal) and3ccfe93ac(P4 restoration, issues bug(esp32p4): testSimd RPC write-timeout — Serial routes to UART0 instead of USB-Serial-JTAG #2541/fix(esp32p4): route Serial to USB-Serial-JTAG so AutoResearch RPC works #2620)Research compiled by parallel sub-agents covering ROM/LL API surface, HWCDC blocking semantics, and current FastLED repo state.
zackees commentedon May 31, 2026
Comprehensive design:
fl::print/fl::flush/fl::writecontractSurveyed the current state of the print API and designed a contract that makes it safe-by-default on HWCDC platforms (ESP32-C3/C6/H2/P4) and every other backend. The good news: most of the plumbing already exists. This is a contract specification + targeted patches, not a rewrite.
Current API surface (verified from the tree)
fl::printsrc/fl/stl/cstdio.h:107void print(const char* str) FL_NOEXCEPT;fl::printlnsrc/fl/stl/cstdio.h:108void println(const char* str) FL_NOEXCEPT;fl::flushsrc/fl/stl/cstdio.h:161bool flush(u32 timeoutMs = 1000) FL_NOEXCEPT;fl::write_bytessrc/fl/stl/cstdio.h:118size_t write_bytes(const u8* buffer, size_t size) FL_NOEXCEPT;fl::coutsrc/fl/stl/ostream.hostreamwithoperator<<fl::platforms::printetc.src/platforms/io.hio_arduino.hpp,io_esp_idf.hpp,io_posix.cpp.hpp,io_wasm.cpp.hpp,detail/io_esp_jtag_or_uart.hppThe split is already correct. The issue is semantics not yet pinned down — specifically what
flush()waits on and whatwrite_bytes()does when the sink can't drain.Design goals (in priority order)
print/write_bytescall returns in bounded time, even with no host attached.flushrespects itstimeoutMsargument and never exceeds it.usb_serial_jtagandprintfsemantics, and is whatsetTxTimeoutMs(0)enforces upstream.isConnected()is true, writes block up to a small bound (~10–20 ms) so log lines are not fragmented mid-line.Contract (the part that needs locking down)
Key invariant:
kMaxWriteStallMs(compile-time constant, default 10ms) is the only knob users care about. Everything else is policy.Per-backend implementation matrix
print/write_bytesnon-blockflushboundedis_connectedemergency_writeSerial.setTxTimeoutMs(0)at initSerial.flush()ONLY whenis_connected()(skip otherwise — bug #7554)Serial.isPlugged()->usb_serial_jtag_is_connected()usb_serial_jtag_ll_write_txfifo+usb_serial_jtag_ll_txfifo_flushsetTxTimeoutMs(0)Serialtruthy first(bool)Serialtud_cdc_n_write_flush(best effort)trueesp_rom_uart_tx_one_char(ROM, no driver)Serial.write(already non-blocking for short writes)Serial.flush()is bounded by hardware (~1ms per byte)(bool)Serial(mega32u4) ortrueUDR0 =register write::write(2, ...)non-blocking on tty::fsync(2)capped viaalarmor just bypassisatty(2)::printf— already buffered to JStrueWhat changes in the tree
Tiny edits, no rewrites. The abstraction layer is already there.
src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp— in theEspIO::instance()initializer, afterSerial.begin(...)(or equivalent for the USJ driver path):src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp—flush()impl: guardSerial.flush()behindSerial.isPlugged()(oris_connected()). Without a host, returntrueimmediately — there is no host to drain to.src/platforms/io.h— add the two new contract members:Default impl in a
cpp.hpp:is_connected() { return true; }andemergency_writealiaseswrite_bytes. Backends override as needed.New file
src/platforms/esp/32/detail/usj_rom.hpp— header-only wrapper aroundusb_serial_jtag_ll_*for the emergency path. Used by:EspIO::emergency_write(override)src/fl/stl/cstdio.cpp.hpp— updatefl::print/println/write_bytes/flushto:platforms::*(already the case)print/write_bytesruntime: ifplatforms::write_bytesreports partial, do NOT retry. Drop is a feature.flush(0)is documented as "poll, do not wait" — useful before sleep, useless otherwise.src/fl/stl/ostream.h—endlcallsflush(0)(poll), notflush(1000). The current implementation flushes synchronously; on HWCDC without a host this can stall ~2s per line. The fix is single-line:endlshouldprint("\n")only, no flush.ci/boards.pyESP32_C6_DEVKITC_1.build_flags— add-DARDUINO_USB_MODE=1,-DARDUINO_USB_CDC_ON_BOOT=1(the patch from the previous comment). This is what makesSerial == HWCDCSerialin the first place.Test plan
Add
tests/fl/stl/cstdio_contract.cpp:print()returns withinkMaxWriteStallMseven when sink reports backpressure (inject a sink that always returns 0 bytes accepted).flush(timeoutMs)returns withintimeoutMs + kEpsilonregardless of sink state.flush(0)returns immediately.is_connected()reflects injected sink state.emergency_writebypasses the sink mock and goes through a separate raw path.print("A"); print("B");against a sink that accepts only 1 byte -> no deadlock, secondprintdoes not block.These run under Posix/WASM with the existing test injection handler at
src/fl/stl/cstdio.cpp.hpp:44-65. The HWCDC-specific paths get covered bybash autoresearch esp32c6 --parlioonce theci/boards.pypatch lands.Open question (one)
Should
fl::printitself be a variadic that accepts integers/floats (à laprintf), or should the typed convenience be left tofl::cout <<and a hypotheticalfl::format()? Current code isconst char*-only, which is the simplest and most embedded-friendly. I would keep it that way — the cost of dragging inprintfformatters on AVR is real (~1.4 KB) andfl::coutalready covers the typed case viaostream.Summary
The contract is: bounded latency, lossy on backpressure, has an ROM escape hatch. The plumbing exists; the missing pieces are (a)
setTxTimeoutMs(0)at init, (b)flush()gated byis_connected(), (c) anemergency_writeROM path on USJ chips, (d)endlnot flushing. All four are sub-twenty-line patches. Once landed, every backend obeys the same contract and theWAIT ON BOOT! DANGEROUSwarning becomes truly stale.zackees commentedon May 31, 2026
Cross-platform verification: contract is supportable everywhere FastLED ships
Fanned out four sub-agents to verify the proposed contract —
print/write_bytesbounded latency,flush(timeoutMs)honors timeout,is_connected()host detection,emergency_write()ROM/register panic path — against every platform family FastLED currently targets.Headline result: every platform family can support the contract. Two require minor caveats. The FastLED tree itself has six fixable gaps in the host-side implementations of the existing API.
Per-platform support matrix
printboundedflush(timeoutMs)is_connected()emergency_write()Serial.setTxTimeoutMs(0)isPlugged()(avoid #7554)usb_serial_jtag_is_connected()usb_serial_jtag_ll_*ROM inlinessetTxTimeoutMs(0)(default 250 ms)tud_cdc_n_write_flushinxSemaphoreTake(... , ms)tud_cdc_n_connected()app_mainROM pathuart_tx_chars()(IDF non-blocking)uart_wait_tx_done(port, ms)honors timeouttrueesp_rom_uart_tx_one_char()(ROM, pre-app_main, ISR, panic, flash-cache-off)availableForWrite()flush()withmillis()cap(bool)Serialon 32u4;trueon 328/2560UDR0 = b; while(!(UCSR0A & (1<<UDRE0)))Serial; SoftwareSerial blocksavailableForWrite()+ capSerial.flush()with deadlinetrueuart_tx_one_char()(IRAM/ISR-safe)Serialblocks in ISR — emergency path mandatory thereTX_TIMEOUT_MSEC=70 ms— wrap with own deadline +usb_serial_write_buffer_free()Serial.dtr()UART0_D = b; while(!(UART0_S1 & UART_S1_TDRE))(Serial1)TX_TIMEOUT_MSEC=120 ms— wrapSerial.dtr()LPUART6->DATA = b(Serial1)availableForWrite()w/millis()captud_cdc_*flushdtrState(after 10 ms settle)USARTx->TDR+USART_ISR_TXEpollUart::flush(uint32_t timeout)nativetrueflushyield()loop w/ deadlinetud_cdc_n_write_flush(non-blocking)tud_cdc_n_connected()NRF_UARTE0->TASKS_STARTTX(UARTE) or TinyUSB rawUart.cppusesportMAX_DELAY— must replace withpdMS_TO_TICKS(10)usb.send()with bound_usbLineInfo.lineState > 0(DTR)USB->DEVICE.DeviceEndpoint[ep]is impractical from panic; use SERCOM UART registertud_cdc_write_available()w/ 10 ms captud_cdc_connected()uart_get_hw(uart0)->dr = c(ISR-safe)while(!_tx_idle)spin withmillis()-bounded waitam_hal_uart_tx_flushtrueUARTn->DR = c+ pollUARTn->FR::write(2)can block on slow pipe; addO_NONBLOCKoptflush()currently ignorestimeoutMs(see gap #3 below)true(orisatty(2))::write(2)is POSIX async-signal-safe::printfalready buffers to JStrueEM_ASM({console.error(UTF8ToString($0));}, str)write_bytesemits hex text, not raw bytes — see gap #4_write)_write(2)flush()ignorestimeoutMstrue_write(2)Legend: ✅ supported as-is or with trivial wrap, ⚠ supported but needs work, ❌ cannot support (escape hatch: degrade to no-op).
Two genuine caveats (worth calling out)
ESP32-S2/S3 USBCDC has no true ROM panic path. TinyUSB must be initialized before
tud_cdc_n_writeworks. Pre-app_mainconstructors and very early panics on these chips cannot useemergency_writeover USB. Recommended fallback: routeemergency_writeto UART0 on these variants and document the caveat. Every other ESP32 (HWCDC and classic UART) is fine.ATtiny + SoftwareSerial is genuinely unsupportable. SoftwareSerial blocks bit-bang style and cannot honor a millisecond timeout (bit times are microseconds, but a full byte at 9600 baud is ~1 ms — close to but not bounded by the contract). Practical answer: detect this case at compile time and emit
emergency_write = no-op, print = no-op, flush = return true. Logging on ATtiny was already a poor fit; the contract simply formalizes that.Six gaps in the current FastLED tree (mostly host-side)
These were found by inspecting the existing
fl::platformsimpls:is_connected()missing everywhere —src/platforms/io.h:13-41declaresserial_ready()(init-done semantics) but no host-presence primitive. Addbool is_connected() noexceptwith per-platform overrides.emergency_write()missing everywhere — same file. Addsize_t emergency_write(const u8*, size_t) noexcept. POSIX/Win default-impl can aliaswrite_bytes(already signal-safe). WASM default-impl usesEM_ASM/emscripten_log. ESP32 HWCDC overrides withusb_serial_jtag_ll_*.flush(timeoutMs)ignores the timeout on POSIX/Win/WASM.src/platforms/posix/io_posix.cpp.hpp:63-68callsfsync(2)then returnstrueunconditionally; same shape inio_win.cpp.hpp. Should honor the deadline (POSIX:fsyncis fast on a tty/pipe; wrap withalarm(2)or just bypass).WASM
write_bytesemits hex-encoded text, not raw bytes.src/platforms/wasm/io_wasm.cpp.hpp:62-70doesprintf("%02X ", b)per byte. This is a contract violation — binarywrite_bytesmust round-trip. Fix: route throughfwrite(stdout)or hold a per-process buffer flushed on newline.POSIX
printlacksO_NONBLOCKon fd 2. A slow log consumer (pipe back-pressure) can stall past the 10 ms cap. Eitherfcntl(F_SETFL, O_NONBLOCK)on init or usewritev/sendwithMSG_DONTWAIT. Tests using stderr pipe redirection are the affected case.fl::endldoes NOT currently flush (src/fl/stl/ostream.h:99-102just emits"\n"). This is good — the prior design comment incorrectly suggested it did. Leave it alone. Document thatfl::cout << fl::endlis notstd::endl; it's a line-break alias.Test injection layer
src/fl/stl/cstdio.cpp.hpp:44-65already providesinject_print_handler/inject_println_handler/inject_available_handler/inject_read_handler(lazy function-local statics, force-initialized viaFL_INIT(cstdio_init_wrapper)to dodge a known macOS static-init recursion). Missing: no injection handlers forflush,write_bytes,serial_ready. Addinject_flush_handlerandinject_write_bytes_handlerto enable the contract test plan from the previous comment. Notests/fl/stl/cstdio_contract.cppexists yet.Already-correct upstream patterns to reuse
Uart::flush(uint32_t timeout)— the only core that already implements the contract natively. Cite as the reference implementation.tx_timeout=0as the default when unplugged for HWCDC. We benefit without writing any code.usb_serial_write_buffer_free()— exemplar of the "probe before write" pattern we want on every backend.Summary
Every platform family except ATtiny+SoftwareSerial can implement the proposed contract. ESP32-S2/S3 USBCDC has a documented caveat around pre-init emergency writes. The remaining work is per-backend wrapping of existing primitives plus six small fixes to the host-side implementations in the FastLED tree. The contract holds.
Verification by four parallel sub-agents covering ESP32 family · AVR/ESP8266/Teensy · STM32/nRF52/SAMD/RP2040/Apollo3 · POSIX/WASM/Win + FastLED tree state.
zackees commentedon May 31, 2026
Alternative design: minimal surface
fl::printthat "just does the right thing"Reconsidering after feedback. The prior design (comment 4587446387) added five public symbols (
is_connected,emergency_write, plus the existing four). That's API surface that users will have to know about and that we'll have to keep consistent across every backend forever.Alternative: keep the surface as small as it is today —
fl::printandfl::println— and make the function itself responsible for choosing the right backend at runtime based on CDC/USB state. Users never see the policy; the function does the right thing.Public API (unchanged from today)
No
is_connected(). Noemergency_write(). No new symbols. The four functions that already exist insrc/fl/stl/cstdio.hkeep their signatures.How
fl::print"does the right thing" internally on ESP32The policy lives entirely inside
platforms::printfor the ESP32 family. Three-tier fallback ladder, evaluated per call:The chip's own ROM is the guaranteed-safe sink. The IDF doc explicitly promises a bounded 50 ms stall:
So even the worst case —
ARDUINO_USB_CDC_ON_BOOT=1set but the host never opens the port — is bounded to 50 ms once, then zero overhead per subsequent call.Per-platform behavior collapses to three lines of intent
fl::printdoes internallySerial.isPlugged(), elseesp_rom_printf(which routes to USJ via secondary console config)(bool)Serial, elseesp_rom_printf(which routes to UART0 ROM console)availableForWrite()probe, elseesp_rom_printf(which is UART0 anyway)availableForWrite()probe, else drop. (No ROMprintfanalogue, but UART naturally drains at baud rate ~ μs/byte.)::write(2, ...)(signal-safe, already bounded by tty)::printf(already buffered to JS)Notice every platform stays inside its
platforms::printimplementation. The user never sees a tier choice.What this trades vs the expanded contract
is_connected())fl::printalready drops cleanlyemergency_write())fl::printfalls back to ROM automaticallyemergency_writeWhy ROM-as-fallback is the right call for FastLED specifically
FastLED's logging is operator-diagnostic: boot banner, frame timing on demand, error prints. It is never used as a data channel where loss matters. So the right policy is:
fl::print("ready")and have the message land somewhere — host, UART pin, JTAG viewer, doesn't matter.ROM-as-fallback gives all three. The chip vendors already shipped the safety net (50 ms timeout, drop on full); we just use it.
What about
flush()?Same minimal trick:
fl::flush(timeoutMs)returns true immediately if the active sink is the ROM path (nothing to flush — ROM already drained or dropped). Returns the bounded flush result if the active sink is HWCDC/USBCDC with a connected host. Never spins.What about
write_bytes()?Same fallback ladder, but the ROM fallback is a problem:
esp_rom_printfis text-only and will choke on\0and non-printable bytes. Recommendation:write_bytesdoes NOT fall back to ROM. If the tier-1 sink is unavailable, it returns 0 (bytes dropped) and the caller decides. Binary payloads are a niche use case in FastLED (mostly serial RPC inAutoResearch.ino); the user controls when they enable it.Migration from today's tree
ci/boards.pyESP32_C6_DEVKITC_1.build_flags: still need-DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT=1. The minimal design needs CDC-on-boot to be enabled for Tier 1 to even exist. (Same as expanded design.)src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp: at init, setSerial.setTxTimeoutMs(0)(same as expanded). Inprint, add theisPlugged()check and ROM fallback (new; ~10 lines).src/platforms/io.h: unchanged. No new declarations.src/fl/stl/cstdio.h: unchanged. No new declarations.availableForWrite()probe to AVR/ESP8266/etc. paths defensively (1-line addition each).One genuine downside
If a user needs to know whether the host is reading (e.g. to decide between two log verbosities), they cannot — there's no
fl::is_connected(). The minimal design says: that's not FastLED's job. Users who need it can callSerial.isPlugged()directly when targeting ESP32 (it's already an arduino-esp32 API). FastLED doesn't add to its surface area to wrap something the platform already provides.Open question
Do we want the minimal design at all, or is the expanded contract worth its weight in test coverage and explicit-ness? I'm asking a code-reviewer sub-agent to give an independent take comparing the two designs. Will post their opinion in the next comment.
Alternative design framed in response to: "keep the minimal surface area of fl::print but instead it just does the right thing depending CDC USB status and more. falling back to esp_rom_print if misconfigured and not locking the device if CDC USB is not plugged in"
zackees commentedon May 31, 2026
Independent second opinion (from a sub-agent that read both designs without prior context)
Asked an independent reviewer to read both designs cold and recommend one. Their verdict, posted verbatim:
Recommendation: ship the minimal
fl::printdesign, but tighten two things before mergingDrop the ROM fallback for ISR/panic contexts (it is not documented signal-safe), and keep
is_connected()available as an internal helper used by the impl, not as public API.Why the minimal design wins for FastLED
FastLED's print system is operator diagnostics — boot banner, frame-rate prints, "this strip failed to init." It is never a data channel where loss matters. The expanded contract optimizes for a use case FastLED does not have: applications that need to reason explicitly about host connection state and route panic logs through a documented escape hatch. None of FastLED's call sites care.
The expanded contract's 6 symbols also push policy onto the user. Any user who reaches for
emergency_write()has to first know that ordinaryfl::printis unreliable in some context, then know which context, then remember to switch — that's a foot-gun matrix. The minimal design says: you writefl::print("ready")and the runtime picks the safe sink. That is the correct division of labor for a library.The other tell: the cross-platform verification table shows ESP32-S2/S3 USBCDC has no true pre-
app_mainROM path and ATtiny+SoftwareSerial cannot honor the contract at all. So the "guarantee"emergency_write()advertises is already platform-conditional. A public symbol that silently degrades on two of the supported platforms is worse than no symbol — it sets an expectation the library cannot universally meet.Where the minimal design is wrong as written
The
esp_rom_printffallback is not safe as a general "always works" answer. Two real problems:The 50 ms bound is a property of the IDF VFS driver, not
esp_rom_printfitself. The IDF docs (USB-Serial/JTAG console) describe a one-time 50 ms wait when the internal buffer fills and no PC is connected. That's the driver layer.esp_rom_printfroutes throughesp_rom_output_to_channelsand the configured putc — its blocking behavior depends on whether the channel is bound to UART (drains at baud rate, ~μs/byte, effectively non-blocking) or USJ (uses the FIFO writable check, but with no documented timeout in the ROM symbol itself).esp_rom_printfis not documented signal-safe, ISR-safe, or reentrant. The header inesp_rom_sys.hdocuments only "Print formatted string to console device. Note float and long long not supported." The ESP-IDF logging docs explicitly warn "it is not advised to use printf and other output functions in ISRs"; the recommended ISR primitive isESP_EARLY_LOGx, which expands toesp_rom_printfonly outside the constrained-env-safe build flag. Treating ROM printf as a universal panic sink is plausible (it's whatESP_DRAM_LOGxuses) but not contractually guaranteed by Espressif. We should not advertise it as one.Failure modes the minimal design overlooks
fl::printfrom an ISR: under the minimal design, the user has no warning. Document this as undefined behavior and add aFL_DEBUG_ASSERT(!xPortInIsrContext())in debug builds.ARDUINO_USB_CDC_ON_BOOT=0on a board with no UART pins: tier 1 fails, ROM fallback writes to whatever the IDF secondary console is configured to — often nothing. Output is silently lost. The expanded design has the same gap.fl::printbefore anySerial.begin(): on HWCDC, theisPlugged()check returns false and we fall through to ROM, which works fine. Good.The hybrid I would actually ship
Keep the public surface at 4 symbols (minimal). Internally, factor the policy into a
static bool host_connected()helper used only by the impl. Replace the ROM fallback with a non-blocking direct write tousb_serial_jtag_ll_write_txfifo(the inlines fromhal/usb_serial_jtag_ll.h) — these are register-level, in IRAM via the LL header, have no host-state dependency, and were verified usable from panic contexts in the first comment of the issue. This gives you the same "always have a sink" property as ROM printf, but with a documented IRAM-safe primitive instead of a ROM symbol whose safety is folklore.For non-ESP32 platforms, the
availableForWrite()probe-then-drop pattern in the table is correct as written.Net result: 4 public symbols, deterministic IRAM-safe fallback on ESP32 USJ chips, no API surface for users to misuse, no claim we can't back up.
Sources:
My take on the second opinion
The reviewer's hybrid is the right answer. Summarizing the three deltas from the minimal-design comment above:
Replace
esp_rom_printffallback withusb_serial_jtag_ll_write_txfifoon USJ chips. Same "always works" guarantee, but with documented IRAM/ISR/panic-safety from the chip vendor's LL header instead of a ROM symbol whose safety is folklore. The 50 ms bound comes from the IDF VFS driver, not the ROM call — we'd have been advertising a guarantee we don't own. Use the LL inlines instead and document the bound ourselves: "up to 100 bytes per call, fixed-FIFO drop semantics, never blocks > 100 μs."Keep
is_connected()as an internal helper, not public API. It's the right primitive for the impl's tier-selection logic, but exposing it invites users to writeif (fl::is_connected()) { fl::print(...) }— which is both racy and redundant (the impl already does the right thing internally). Make itstaticinsideio_esp_jtag_or_uart.hpp.Add an ISR debug assertion.
FL_DEBUG_ASSERT(!xPortInIsrContext())in debug builds. Production builds drop the check; UB on ISR-call is consistent with the rest of FastLED's threading model.Resulting public surface is exactly today's
cstdio.h—print,println,write_bytes,flush(timeoutMs). Zero new symbols. All the policy is invisible to callers.Updated change set
ci/boards.pyESP32_C6_DEVKITC_1.build_flags-DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT=1src/platforms/esp/32/detail/io_esp_jtag_or_uart.hppsetTxTimeoutMs(0)at init; tier ladder inprintwithusb_serial_jtag_ll_*fallbacksrc/platforms/esp/32/detail/io_esp_jtag_or_uart.hppflush(): skipSerial.flush()when!isPlugged()(avoid #7554)src/platforms/esp/32/detail/usj_emergency.hpp(new)usb_serial_jtag_ll_*wrappersrc/fl/stl/cstdio.cpp.hppFL_DEBUG_ASSERT(!xPortInIsrContext())guardsrc/platforms/wasm/io_wasm.cpp.hppwrite_bytesto emit raw bytes, not hex textsrc/platforms/posix/io_posix.cpp.hpptimeoutMsinflush()Total: ~75 lines, single PR, no public API surface change. The "WAIT ON BOOT! DANGEROUS" warning becomes truly stale.
Status of the design discussion
I think we're done. The three comment chain — expanded contract → platform matrix → minimal alternative → second opinion → hybrid — converges on the hybrid as the right answer. Ready to implement when you give the go-ahead.
zackees commentedon May 31, 2026
Superseded by #2668, which captures the converged minimal-surface design agreed in this issue's comment chain (expanded contract → cross-platform verification → minimal alternative → independent second opinion → hybrid).
Summary of the convergence:
fl::print,fl::println,fl::write_bytes,fl::flush) — zero new APIusb_serial_jtag_ll_write_txfifo(LL inlines, documented IRAM/ISR-safe) instead ofesp_rom_printf(whose safety is undocumented folklore)is_connected()lives as astatichelper inside the impl, not as public APIFL_DEBUG_ASSERT(!xPortInIsrContext())catches ISR misuseClosing this as 'not planned' because the original 'add the flag' fix in this issue is now part of the broader #2668 spec. The
ARDUINO_USB_CDC_ON_BOOT=1flag is one bullet in #2668's implementation checklist.fix(esp32c6): route Serial to HWCDC + non-blocking writes (#2665) (#2669