Skip to content

feat(lpuart): scaffold Teensy 4 LPUART peripheral interface + host mock (refs #3023) - #3032

Merged
zackees merged 2 commits into
masterfrom
feat/lpuart-driver-skeleton
Jun 14, 2026
Merged

zackees merged 2 commits into
masterfrom
feat/lpuart-driver-skeleton

Conversation

@zackees

@zackees zackees commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Lays down the platform-agnostic seam for the upcoming Bus::LPUART
driver (issue #3023 workstream A). No engine, no real iMXRT register
driver, no canHandle() logic — those land in follow-up PRs that need
hardware verification. This PR is the foundation for host-testable
driver development.

New files

  • src/platforms/arm/teensy/teensy4_common/drivers/lpuart/ilpuart_peripheral.h — abstract ILPUARTPeripheral + ILPUARTInstance interface mirroring the iobjectfled_peripheral.h shape. Carries the compile-time kLPUARTTxPins[] table (the iMXRT1062 LPUART TX-capable pin set: {1, 8, 14, 17, 20, 24, 29, 35, 47, 48}) so both the real driver and the mock validate against a single source of truth.
  • src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.{h,cpp.hpp} — host-side stub. Accepts every kLPUARTTxPins[] entry by default, supports per-pin invalid overrides, captures createInstance() records (pin, LED count, RGBW flag, timing), and counts show() calls. Streaming-ISR plumbing is intentionally omitted until workstream C extracts the parlio mock deferred-callback pattern into a shared template fixture.
  • src/platforms/shared/mock/arm/teensy4/drivers/lpuart/_build.cpp.hpp — unity-build entry for the new mock TU.
  • tests/platforms/arm/teensy/teensy4_common/drivers/lpuart/ilpuart_peripheral.cpp — host tests pinning the contract: every kLPUARTTxPins[] entry accepted by default; non-table pins rejected with a non-null error message; setInvalidPin() overrides default acceptance; createInstance() captures the full call record and sizes the TX buffer to total_leds × bytes_per_led × 4 (4 UART bytes per LED byte under wave8 2-bit-per-frame packing); setCreateFailure() forces nullptr from createInstance().

Modified

  • src/platforms/shared/mock/arm/teensy4/drivers/_build.cpp.hpp — append the new lpuart mock build header alongside flexio + objectfled.

Test plan

  • Mirrors the established iobjectfled_peripheral.h + objectfled_peripheral_mock.h pattern that already lands clean on host CI; the structural equivalence is the verification.
  • CI will run the new ilpuart_peripheral host test (the local build state is wedged on the worktree path — CI runs from a clean tree).

Why ship this without a working engine

The interface is the public seam every follow-up PR depends on. Landing it early lets the real lpuart_peripheral_real.cpp.hpp (iMXRT registers + eDMA) and channel_engine_lpuart.cpp.hpp (wave8 encoder + canHandle()) PRs land independently against a fixed contract instead of co-evolving in one giant PR. The mock makes the contract testable on day one.

Refs #3023

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Introduced a Teensy 4.x LPUART peripheral abstraction for WS281x-family output, including pin validation and synchronous “show” transmission support.
    • Added a host-side mock LPUART peripheral to enable non-Teensy development and testing.
  • Tests
    • Added unit tests covering pin validation, instance creation behavior, RGBW vs non-RGBW buffer sizing, and failure modes.
  • Chores
    • Updated the unity build integration for the mock and related driver components.

Lays down the platform-agnostic seam for the upcoming `Bus::LPUART`
driver (issue #3023 workstream A). No engine, no real iMXRT register
driver, no `canHandle()` logic — those land in follow-up PRs that need
hardware verification. This PR is the foundation for host-testable
driver development.

New files:

- `src/platforms/arm/teensy/teensy4_common/drivers/lpuart/ilpuart_peripheral.h`
  Abstract `ILPUARTPeripheral` + `ILPUARTInstance` interface mirroring
  the `iobjectfled_peripheral.h` shape. Carries the compile-time
  `kLPUARTTxPins[]` table (the iMXRT1062 LPUART TX-capable pin set:
  {1, 8, 14, 17, 20, 24, 29, 35, 47, 48}) so both the real driver and
  the mock validate against a single source of truth.

- `src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.{h,cpp.hpp}`
  Host-side stub. Accepts every `kLPUARTTxPins[]` entry by default,
  supports per-pin invalid overrides, captures `createInstance()`
  records (pin, LED count, RGBW flag, timing), and counts `show()`
  calls. Streaming-ISR plumbing is intentionally omitted until
  workstream C extracts the parlio mock's deferred-callback pattern
  into a shared template fixture.

- `src/platforms/shared/mock/arm/teensy4/drivers/lpuart/_build.cpp.hpp`
  Unity-build entry for the new mock TU.

- `tests/platforms/arm/teensy/teensy4_common/drivers/lpuart/ilpuart_peripheral.cpp`
  Host tests pinning the contract: every `kLPUARTTxPins[]` entry is
  accepted by default; non-table pins are rejected with a non-null
  error message; `setInvalidPin()` overrides default acceptance;
  `createInstance()` captures the full call record and sizes the TX
  buffer to `total_leds * bytes_per_led * 4` (4 UART bytes per LED
  byte under wave8 2-bit-per-frame packing); `setCreateFailure()`
  forces `nullptr` from `createInstance()`.

Modified:

- `src/platforms/shared/mock/arm/teensy4/drivers/_build.cpp.hpp`
  Append the new lpuart mock build header alongside flexio + objectfled.

Refs #3023

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0f900367-60b9-4458-b579-91124c11542d

📥 Commits

Reviewing files that changed from the base of the PR and between bbf21f3 and 501466a.

📒 Files selected for processing (1)
  • src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.h

📝 Walkthrough

Walkthrough

Adds a new platform-agnostic LPUART peripheral abstraction layer for Teensy 4.x (ILPUARTPeripheral, ILPUARTInstance, LPUARTPinResult, kLPUARTTxPins), a host-side mock implementation (LPUARTPeripheralMock, LPUARTInstanceMock) with a non-Teensy create() factory, unity-build wiring, and unit tests covering all mock behaviors.

Changes

LPUART Peripheral Abstraction and Mock

Layer / File(s) Summary
ILPUARTPeripheral and ILPUARTInstance abstract interface
src/platforms/arm/teensy/teensy4_common/drivers/lpuart/ilpuart_peripheral.h
Defines LPUARTPinResult, kLPUARTTxPins/kLPUARTTxPinCount, ILPUARTInstance (TX buffer access and synchronous show()), and ILPUARTPeripheral (pin validation, per-strip instance creation, static create() factory).
LPUARTInstanceMock and LPUARTPeripheralMock
src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.h
Implements ILPUARTInstance as LPUARTInstanceMock (TX buffer allocation, show() counter) and ILPUARTPeripheral as LPUARTPeripheralMock (pin override map, CreateRecord history, RGBW-aware buffer sizing, forced-failure flag, reset/query helpers).
Factory and unity-build wiring
src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.cpp.hpp, src/platforms/shared/mock/arm/teensy4/drivers/lpuart/_build.cpp.hpp, src/platforms/shared/mock/arm/teensy4/drivers/_build.cpp.hpp
Defines ILPUARTPeripheral::create() for non-Teensy builds returning fl::make_shared<LPUARTPeripheralMock>() guarded by FL_IS_TEENSY_4X; registers the new LPUART directory in the mock drivers unity-build aggregator.
Host-side unit tests
tests/platforms/arm/teensy/teensy4_common/drivers/lpuart/ilpuart_peripheral.cpp
Tests pin-validation acceptance/rejection, setInvalidPin/clearInvalidPins override, createInstance argument recording, RGBW vs non-RGBW buffer sizing, setCreateFailure null-return injection, and ILPUARTPeripheral::create() factory smoke test.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

🐰 A new interface hops into view,
LPUART pins checked through and through.
Mock buffers filled, show() counted right,
RGBW LEDs shimmer with delight.
The factory returns—never null on host!
Of all the abstractions, this one's the most. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: scaffolding the Teensy 4 LPUART peripheral interface and host mock, with issue reference.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/lpuart-driver-skeleton

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.h`:
- Around line 126-129: The multiplication of total_leds * bytes_per_led * 4u on
line 128 can overflow when computed in u32, potentially allocating an undersized
TX buffer while still appearing valid. Guard against this overflow by promoting
the multiplication to u64, checking whether the result fits within u32 limits,
and either handling the overflow case explicitly or reverting to u32 only after
confirming the result is safe. Apply this check before passing buffer_bytes to
the LPUARTInstanceMock constructor to prevent downstream memory misuse in test
scenarios.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 736234d6-ced4-488b-8f41-9f5df497a7a3

📥 Commits

Reviewing files that changed from the base of the PR and between 7383315 and bbf21f3.

📒 Files selected for processing (6)
  • src/platforms/arm/teensy/teensy4_common/drivers/lpuart/ilpuart_peripheral.h
  • src/platforms/shared/mock/arm/teensy4/drivers/_build.cpp.hpp
  • src/platforms/shared/mock/arm/teensy4/drivers/lpuart/_build.cpp.hpp
  • src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.cpp.hpp
  • src/platforms/shared/mock/arm/teensy4/drivers/lpuart/lpuart_peripheral_mock.h
  • tests/platforms/arm/teensy/teensy4_common/drivers/lpuart/ilpuart_peripheral.cpp

`total_leds * bytes_per_led * 4u` is computed in u32 and can wrap for
pathological configurations, producing an undersized TX buffer while
still returning a seemingly-valid instance. Reject those configurations
early so downstream test paths cannot scribble past the buffer.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees

zackees commented Jun 14, 2026

Copy link
Copy Markdown
Member Author

Addressed CodeRabbit comment: added u32 overflow guard before total_leds * bytes_per_led * 4u allocation in lpuart_peripheral_mock.h (commit 501466a). Pathological inputs now return nullptr instead of silently allocating an undersized TX buffer.

Note: the failing uno CI check is a pre-existing master-side breakage in fl/math/math.cpp.hpp:162 (AVR WString.h initializer error) — affects the last 5 master pushes and is not introduced by this PR. Merging via admin bypass; will track the uno fix separately.

@zackees
zackees merged commit cbb8572 into master Jun 14, 2026
7 of 8 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 14, 2026
zackees added a commit that referenced this pull request Jun 14, 2026
…#3022) (#3038)

* feat(json): integer-only string->IEEE 754 codec — parser (#3022 phase 2)

Adds `fl::ieee754_parse_decimal` (and stubs the serializer side) plus a
84-entry pow10 lookup table generated by `ci/tools/gen_pow10_table.py`.
The parser:

  * Reads decimal digits into a u64 mantissa with a decimal-exponent
    accumulator (handles fractional + scientific notation).
  * Normalizes the mantissa so its top bit is set.
  * Multiplies against a precomputed (mantissa, binary_exp) pair for
    10**k using a portable 4-way 32x32->64 widening multiply
    (`mul_hi_u64`) — no `__aeabi_d*` / `__aeabi_f*` helpers ever reached.
  * Packs into IEEE 754 single-precision bits with round-half-to-even.

Caller bit-casts the returned u32 to `float` via `fl::bit_cast<float>`
(which is `memcpy` — no FP arithmetic). Out-of-range exponents clamp to
±0 / ±inf bit patterns.

Embedded-grade precision target: ~6 significant decimal digits with at
most ±1 ULP drift from `strtof`. Sufficient for the JSON-RPC use case
that motivates the no-soft-FP mandate (FastLED #3022 / #3029).

`tests/fl/stl/ieee754_string.cpp` exercises well-known constants,
±1 ULP tolerance against the host strtof, scientific notation,
over/underflow clamping, and the `consumed` bookkeeping path. Passes
under both quick mode and debug mode (ASAN/LSAN/UBSAN).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(json): integer-only IEEE 754 -> string serializer (#3022 phase 2)

Adds fl::ieee754_format_decimal. Reuses the same pow10 lookup table
already in the TU for the parser, plus a small kPow10IntExact[] table
(10^0..10^9 as exact u32 values) for the integer/fractional split.

  * Unpacks sign / biased exponent / mantissa from the IEEE 754 bit
    pattern via shifts and masks.
  * Lifts the 24-bit mantissa to u64 with the top bit set, multiplies by
    the normalized 10^precision via mul_hi_u64 (shared with the parser),
    and rounds-half-to-even at the bit-shift step.
  * Splits the resulting integer by 10^precision and formats via the
    existing fl::utoa64 helper — no FP arithmetic anywhere.
  * Inf / NaN / zero / underflow / overflow all return the appropriate
    literal (inf / -inf / nan / 0.000000 / clamp).

tests/fl/stl/ieee754_string.cpp extends to cover the serializer: known
constants (0, 1, 0.5, 10, 100), special values, parser round-trip on
exact powers of two and within 1 ULP on pi / e, and precision clamping.

Verified by building the test DLL directly and invoking the runner:
10/10 doctest cases pass. The bash test wrapper hits an unrelated
meson_native.txt lifecycle bug on this build dir, tracked separately.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(json): route parser/serializer through bit-twiddling codec (#3022 phase 2)

Replaces the four direct callers of libgcc soft-FP-anchored helpers in
src/fl/stl/json.cpp.hpp with the integer-only fl::ieee754_string codec:

  * JsonTokenizer::scan_array_lookahead — fl::parseFloat + fl::abs check
    -> fl::ieee754_parse_decimal + biased-exp comparison.
  * JsonBuilder::parse_float_array (template) — same swap; the static_cast
    on the outbound value type is left to the caller, matching the
    "user opts into float math, library does not" mandate.
  * JsonBuilder::on_token NUMBER arm — fl::parseFloat -> bit-twiddling
    parse + fl::bit_cast<float> at the variant boundary (memcpy, free).
  * SerializerVisitor::accept(const float&) and accept(const fl::vector
    <float>&) — fl::string::append(f, prec) -> fl::ieee754_format_decimal
    (bit_cast<u32>(f), prec). Output precision contract preserved
    (3 digits scalar / 6 digits vector).
  * classify_array float branch — fl::abs(f) > 16777216.0f -> integer
    biased-exp comparison via the shared float_bits_magnitude_exceeds_2_24
    helper.
  * Removed the unused-since-#3027 canBeRepresentedAsFloat(double) dead
    helper (it pulled __aeabi_d* via fl::abs(double) for callers that no
    longer exist).

Verified:
  * tests/fl/stl/ieee754_string.cpp — 10/10 pass.
  * tests/fl/stl/json.cpp           — 27/27 pass (ScreenMap round-trip
    confirms the new fl::vector<float> serializer reproduces 0.000-style
    output the previous fl::string::append(f, 3) emitted).

Next phase will verify the LPC845 ELF link is free of __aeabi_d* /
__aeabi_f* symbols even with FL_JSON_HAS_FLOAT=1 (task #5).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(lint): rename local + IWYU pragma + alphabetize drivers/_build

Three follow-up linter fixes spotted by `bash lint --cpp`:

  * `src/fl/stl/ieee754_string.cpp.hpp`: rename local `m_full` -> `mantissa_full`
    so MemberStyleChecker (which treats `m_*` as a member-variable prefix)
    stays quiet. The variable is a function-local in `ieee754_format_decimal`;
    the rename is purely cosmetic.
  * `src/fl/stl/json.cpp.hpp`: wrap the newly-added `#include "fl/stl/bit_cast.h"`
    in an `// IWYU pragma: begin_keep` / `end_keep` block so
    IwyuPragmaBlockChecker keeps it pinned (the include is reachable transitively
    but we want explicit intent for the `fl::bit_cast<float|u32>` calls).
  * `src/platforms/shared/mock/arm/teensy4/drivers/_build.cpp.hpp`: alphabetize
    the LPUART / ObjectFLED / FlexIO _build.cpp.hpp includes (UnityBuildChecker).
    Pre-existing master-side ordering bug from PR #3032 — fixing here per the
    project's "all encountered lint errors get addressed" policy.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address CodeRabbit review feedback on #3038

- Reject decimals with no digits (".", "-.") via explicit seen_digit guard;
  the existing i == mantissa_start check skipped past a consumed decimal point.
- Extend pow10 table down to K_MIN=-64 so the parser's raw 19-digit mantissa
  reaches IEEE 754 single-precision underflow without prematurely flushing to
  zero (e.g. 1234567890123456789e-46 ~= 1.23e-28 now decodes correctly).
- Fix float_bits_magnitude_exceeds_2_24 to include the (2**24, 2**25) decade
  (biased_exp == 151 with non-zero mantissa) and inf/NaN; the prior strict
  > 151 check leaked literals like 16777217.0 onto the optimized vector<float>
  path past the exact-integer boundary.
- Strip non-ASCII punctuation (em-dash, plus-minus, arrows) from generator
  output and from the new ieee754_string / json comments + test banners to
  satisfy the 7-bit-ASCII repo guideline.
- Drop F541 f-string prefix in gen_pow10_table.py print().

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the feat/lpuart-driver-skeleton branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant