Skip to content

esp32c6 default env: Serial silently routed to UART0 instead of USB-Serial/JTAG → AutoResearch RPC unreachable on FH4 boards #2665

Closed

Description

@zackees

Symptom

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.

Why the workaround in #2664 is not enough

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

Environment

  • Branch: fix-esp32c6-parlio (commit 5fcddee)
  • ESP32-C6FH4 (QFN32), MAC 8c:bf:ea:cf:87:b4, USB-Serial/JTAG, COM9 on Windows 10
  • arduino-esp32 from pioarduino 55.03.35 (IDF 5.5.1)

Activity

  1. zackees commented on May 31, 2026

    @zackees
    MemberAuthor

    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"
    
    static size_t usj_write_nonblocking(const uint8_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

    Verified from arduino-esp32/cores/esp32/HWCDC.cpp:

    static uint32_t tx_timeout_ms = 100;  // default
    ...
    xRingbufferSend(tx_ring_buf, ..., tx_timeout_ms / portTICK_PERIOD_MS);

    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)

    1. ci/boards.py — ESP32_C6_DEVKITC_1.build_flags:

      build_flags=[
          "-funwind-tables",
          "-DARDUINO_USB_MODE=1",
          "-DARDUINO_USB_CDC_ON_BOOT=1",
      ],

      (Mirror the May-2026 P4 fix from commit 3ccfe93ac.)

    2. 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
    3. Do not add Serial.flush() calls on HWCDC platforms (per upstream issue #7554, flush() can still hang).

    4. (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.

    References


    Research compiled by parallel sub-agents covering ROM/LL API surface, HWCDC blocking semantics, and current FastLED repo state.

  2. zackees commented on May 31, 2026

    @zackees
    MemberAuthor

    Comprehensive design: fl::print / fl::flush / fl::write contract

    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.

    Current API surface (verified from the tree)

    Symbol Where Signature
    fl::print src/fl/stl/cstdio.h:107 void print(const char* str) FL_NOEXCEPT;
    fl::println src/fl/stl/cstdio.h:108 void println(const char* str) FL_NOEXCEPT;
    fl::flush src/fl/stl/cstdio.h:161 bool flush(u32 timeoutMs = 1000) FL_NOEXCEPT;
    fl::write_bytes src/fl/stl/cstdio.h:118 size_t write_bytes(const u8* buffer, size_t size) FL_NOEXCEPT;
    fl::cout src/fl/stl/ostream.h global ostream with operator<<
    fl::platforms::print etc. src/platforms/io.h 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)

    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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)

    namespace fl {
    
    // 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.
    void print(const char* str) noexcept;
    
    // Same as print + newline. Newline is emitted as a single atomic chunk so
    // it cannot be split across a drop.
    void println(const char* 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_t write_bytes(const u8* 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).
    bool flush(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).
    bool is_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_t emergency_write(const u8* 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.isPlugged() -> usb_serial_jtag_is_connected() usb_serial_jtag_ll_write_txfifo + usb_serial_jtag_ll_txfifo_flush
    ESP32 USBCDC (S2/S3) setTxTimeoutMs(0) check Serial truthy first (bool)Serial TinyUSB tud_cdc_n_write_flush (best effort)
    ESP32 UART0 (legacy) UART TX FIFO write with 10ms cap block on UART TX done bit, capped always true esp_rom_uart_tx_one_char (ROM, no driver)
    Arduino AVR 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.

    1. 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
    2. 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.

      bool EspIO::flush(u32 timeoutMs) {
          if (!is_connected()) return true;   // nothing to wait for
          u32 deadline = millis() + timeoutMs;
          Serial.flush();   // bounded by tx_timeout_ms, but we still cap
          return millis() <= deadline;
      }
    3. src/platforms/io.h — add the two new contract members:

      bool is_connected() noexcept;
      size_t emergency_write(const u8* buf, size_t size) noexcept;

      Default impl in a cpp.hpp: is_connected() { return true; } and emergency_write aliases write_bytes. Backends override as needed.

    4. 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
      namespace fl::esp32::detail {
          inline size_t usj_emergency_write(const u8* 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;
          }
      }
    5. 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.
    6. 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.

    7. ci/boards.py ESP32_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:

    1. print() returns within kMaxWriteStallMs even when sink reports backpressure (inject a sink that always returns 0 bytes accepted).
    2. flush(timeoutMs) returns within timeoutMs + kEpsilon regardless of sink state.
    3. flush(0) returns immediately.
    4. is_connected() reflects injected sink state.
    5. emergency_write bypasses the sink mock and goes through a separate raw path.
    6. 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::print itself 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.

  3. zackees commented on May 31, 2026

    @zackees
    MemberAuthor

    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
    ESP32 UART0 (classic S0) ✅ uart_tx_chars() (IDF non-blocking) ✅ uart_wait_tx_done(port, ms) honors timeout n/a — return true ✅ esp_rom_uart_tx_one_char() (ROM, pre-app_main, ISR, panic, flash-cache-off) Strongest panic primitive of any backend
    Arduino AVR (ATmega) ✅ guard via availableForWrite() ✅ wrap blocking flush() with millis() cap ✅ (bool)Serial on 32u4; true on 328/2560 ✅ UDR0 = b; while(!(UCSR0A & (1<<UDRE0))) Direct register write, ISR-safe
    Arduino ATtiny (Trinket etc.) ⚠ no hardware Serial; SoftwareSerial blocks ❌ SoftwareSerial cannot honor timeout n/a ❌ no ROM path Mark unsupported; degrade to no-op
    ESP8266 ✅ availableForWrite() + cap ✅ wrap Serial.flush() with deadline n/a — true ✅ ROM uart_tx_one_char() (IRAM/ISR-safe) Serial blocks in ISR — emergency path mandatory there
    Teensy 3.x (Kinetis) ⚠ default TX_TIMEOUT_MSEC=70 ms — wrap with own deadline + usb_serial_write_buffer_free() ⚠ wrap with deadline ✅ Serial.dtr() ✅ UART0_D = b; while(!(UART0_S1 & UART_S1_TDRE)) (Serial1) 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)

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

    2. 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:

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

    2. 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_*.

    3. 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).

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

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

    6. 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 not std::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.

  4. zackees commented on May 31, 2026

    @zackees
    MemberAuthor

    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.

    Public API (unchanged from today)

    namespace fl {
        void print(const char* str) noexcept;
        void println(const char* str) noexcept;
        size_t write_bytes(const u8* buf, size_t size) noexcept;   // kept for binary
        bool flush(u32 timeoutMs = 1000) noexcept;                 // kept; bounded
    }

    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)
    
    void platforms::print(const char* 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)
    Arduino AVR / ESP8266 / Teensy / STM32 / nRF52 / SAMD / RP2040 / Apollo3 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:

    1. Always produce output if a sink exists. Don't silently drop because the user happens to have CDC misconfigured.
    2. Never block. A disconnected host must not stall LED rendering.
    3. 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.py ESP32_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"

  5. zackees commented on May 31, 2026

    @zackees
    MemberAuthor

    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:

    1. 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).

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

    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:

    1. 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."

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

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

    File Change Approx LOC
    ci/boards.py ESP32_C6_DEVKITC_1.build_flags -DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT=1 +2
    src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp Set setTxTimeoutMs(0) at init; tier ladder in print with usb_serial_jtag_ll_* fallback ~25
    src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp flush(): skip Serial.flush() when !isPlugged() (avoid #7554) ~5
    src/platforms/esp/32/detail/usj_emergency.hpp (new) Header-only usb_serial_jtag_ll_* wrapper ~30
    src/fl/stl/cstdio.cpp.hpp Debug-only FL_DEBUG_ASSERT(!xPortInIsrContext()) guard +3
    src/platforms/wasm/io_wasm.cpp.hpp Fix write_bytes to emit raw bytes, not hex text ~5
    src/platforms/posix/io_posix.cpp.hpp Honor timeoutMs in flush() ~5

    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.

  6. zackees commented on May 31, 2026

    @zackees
    MemberAuthor

    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
    • Debug-only FL_DEBUG_ASSERT(!xPortInIsrContext()) catches ISR misuse

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions