Skip to content

fl::print: minimal-surface contract — non-blocking on missing CDC host, USJ LL fallback on ESP32 USJ chips #2668

Closed

Description

@zackees

Goal

Make fl::print "just work" on every platform — never block when the host is absent, never lose output when the host is present, automatically fall back to a register-level sink when the configured Serial is misconfigured or unavailable. Zero new public symbols. All policy lives inside the platform impls.

This issue supersedes #2665, which converged on this design after a four-comment discussion chain (expanded contract → cross-platform verification → minimal alternative → independent second opinion → hybrid). Read that chain for the full reasoning; this issue captures the agreed implementation spec.

Public API surface (unchanged from today)

namespace fl {
    void   print(const char* str) noexcept;                 // src/fl/stl/cstdio.h:107
    void   println(const char* str) noexcept;               // src/fl/stl/cstdio.h:108
    size_t write_bytes(const u8* buf, size_t size) noexcept;// src/fl/stl/cstdio.h:118
    bool   flush(u32 timeoutMs = 1000) noexcept;            // src/fl/stl/cstdio.h:161
}

No new symbols. No is_connected(). No emergency_write(). Users keep writing fl::print("ready") and the runtime picks the safe sink.

Behavioral contract (semantics, not new API)

  • print / println / write_bytes never block longer than ~10 ms regardless of host state.
  • flush(timeoutMs) honors its timeout — returns false rather than spin past the deadline.
  • Output appears via some sink whenever a sink exists — even if Serial was never begin()'d, even if the host never opened the port.
  • No silent data loss when a host is present — writes block up to ~10 ms so log lines aren't fragmented mid-line.
  • Calling from an ISR is undefined behavior. Debug builds will catch this via FL_DEBUG_ASSERT(!xPortInIsrContext()). (Consistent with existing FastLED threading model.)

How ESP32 backends implement the contract internally

Three-tier fallback ladder inside platforms::print, hidden from users:

// src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp (sketch)

namespace { // internal helper, NOT public API
    inline bool host_connected() noexcept {
    #if ARDUINO_USB_CDC_ON_BOOT
        return Serial.isPlugged();       // usb_serial_jtag_is_connected()
    #else
        return true;                      // UART has no host concept
    #endif
    }
}

void platforms::print(const char* str) noexcept {
    // Tier 1: HWCDC/USBCDC when host is reading.
    //         Already non-blocking due to setTxTimeoutMs(0) set at init.
    if (host_connected()) {
        Serial.print(str);
        return;
    }

    // Tier 2 (ESP32-C3/C6/H2/P4 only): direct USJ LL write.
    //   Register-level, IRAM-safe, never blocks, drops on FIFO full.
    //   No driver / no FreeRTOS dependency — works pre-app_main, post-panic.
    #if FASTLED_ESP32_USJ_AVAILABLE
        fl::esp32::detail::usj_emergency_write(
            reinterpret_cast<const u8*>(str), strlen(str));
        return;
    #endif

    // Tier 3 (ESP32-S2/S3, classic S0): drop silently. UART naturally
    //   drains at baud rate; USBCDC without a host has nowhere to go.
}

Why USJ LL inlines and not esp_rom_printf: the 50 ms bound the IDF docs describe is a property of the IDF VFS driver layer, not of esp_rom_printf itself. The ROM symbol's signal-safety/ISR-safety is undocumented folklore. The usb_serial_jtag_ll_* inlines from hal/usb_serial_jtag_ll.h are register-level, in IRAM via the LL header, and documented usable from panic contexts. Same guarantee, real warranty.

Implementation checklist

Required (~75 lines total)

  • ci/boards.py — ESP32_C6_DEVKITC_1.build_flags: add -DARDUINO_USB_MODE=1 and -DARDUINO_USB_CDC_ON_BOOT=1. Mirrors the May-2026 ESP32-P4 fix (commit 3ccfe93ac).
  • New file src/platforms/esp/32/detail/usj_emergency.hpp — header-only wrapper around usb_serial_jtag_ll_txfifo_writable + usb_serial_jtag_ll_write_txfifo + usb_serial_jtag_ll_txfifo_flush. Compile-time gated on USJ-equipped chips (C3/C6/H2/P4, optionally S3 when ARDUINO_USB_MODE=1).
  • src/platforms/esp/32/detail/io_esp_jtag_or_uart.hpp — at init, call Serial.setTxTimeoutMs(0). In print, add the tier ladder above. In flush, skip Serial.flush() when !host_connected() to avoid upstream issue arduino-esp32#7554.
  • src/fl/stl/cstdio.cpp.hpp — add debug-only FL_DEBUG_ASSERT(!xPortInIsrContext()) guard at top of fl::print / fl::println / fl::write_bytes.
  • src/platforms/wasm/io_wasm.cpp.hpp:62-70 — fix write_bytes to emit raw bytes instead of printf("%02X ", b) hex-encoded text. Current code is a contract violation found during verification.
  • src/platforms/posix/io_posix.cpp.hpp:63-68 — honor timeoutMs in flush() (currently ignored). Same change for src/platforms/win/io_win.cpp.hpp.

Optional (defensive, do later if needed)

  • Add availableForWrite() probe to AVR / ESP8266 / Teensy / STM32 / nRF52 / SAMD / RP2040 / Apollo3 print paths. Already correct by accident on most (UART drains fast); explicit probe makes the contract uniform.
  • Add inject_flush_handler / inject_write_bytes_handler to the test injection layer at src/fl/stl/cstdio.cpp.hpp:44-65 to enable the contract test.

Test plan

Add tests/fl/stl/cstdio_contract.cpp with these cases. All run under Posix/WASM using the existing injection handler:

  1. print() returns within 10 ms even when sink reports backpressure (inject a sink that accepts 0 bytes).
  2. flush(timeoutMs) returns within timeoutMs + ε regardless of sink state.
  3. flush(0) returns immediately.
  4. print("A"); print("B"); against a sink that accepts only 1 byte — no deadlock; second print does not block.
  5. write_bytes round-trips raw bytes including \0 and 0xFF (this catches the WASM hex bug).

ESP32-specific paths get covered by bash autoresearch esp32c6 --parlio once the ci/boards.py patch lands.

Acceptance criteria

  • bash autoresearch esp32c6 --parlio against an ESP32-C6FH4 returns the boot banner within ~16 ms of port open (currently: zero output).
  • bash autoresearch esp32c6 --parlio against an ESP32-C6 with no host attached returns a clean "no device" within 120 s — boot does not stall the LED loop.
  • The ; -D ARDUINO_USB_CDC_ON_BOOT=1 // WAIT ON BOOT ! DANGEROUS comment in platformio.ini:150 is deleted as part of this PR.
  • All existing FastLED tests pass; one new contract test (tests/fl/stl/cstdio_contract.cpp) passes.

Out of scope

  • Adding is_connected() to the public API. Users who need it can call Serial.isPlugged() directly when targeting ESP32 — it's already an arduino-esp32 API. FastLED doesn't wrap things the platform already provides.
  • Adding emergency_write() to the public API. The internal tier ladder handles every case emergency_write would have handled, and exposing it would advertise a guarantee FastLED can't uniformly back up (ESP32-S2/S3 USBCDC has no true pre-app_main ROM path; ATtiny + SoftwareSerial can't honor it at all).
  • Variadic fl::print(fmt, args...). Stays as const char*-only. The typed convenience case is already covered by fl::cout << in src/fl/stl/ostream.h.

Background / prior art

  • Upstream PR arduino-esp32#7583 made tx_timeout=0 the default while unplugged for HWCDC. We benefit without writing code.
  • Upstream bug arduino-esp32#7554 — Serial.flush() hangs without host on HWCDC. The reason our flush must skip Serial.flush() when !host_connected().
  • STM32duino's Uart::flush(uint32_t timeout) already implements the contract natively — reference impl for "what we want".
  • FastLED ESP32-P4 had the identical problem and was fixed in commit 3ccfe93ac (issue #2541 / #2620). This PR applies the same fix to ESP32-C6 and lifts the policy into the platform layer so future chips don't repeat the cycle.

Supersedes

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