FastLED 3.10.10
Loading...
Searching...
No Matches
AutoResearchLowMemory.h
Go to the documentation of this file.
1#pragma once
2//
3// examples/AutoResearch/AutoResearchLowMemory.h
4//
5// Low-memory AutoResearch bring-up surface for parts whose flash budget
6// cannot fit the full ESP32 / Teensy LED-protocol matrix. Originally lived
7// as the standalone `examples/AutoResearchLpc/AutoResearchLpc.ino` sketch;
8// retired and folded in here per FastLED #3030 once the soft-FP cascade
9// from #3022 phase 2 freed up the budget on LPC8xx.
10//
11// Included from the main `AutoResearch.ino` when
12// `FL_PLATFORM_HAS_LARGE_MEMORY == 0` (Low + Tiny tiers per the FastLED
13// #3000 memory classification).
14//
15// Same JSON-RPC contract as the retired LPC sketch:
16// echo: [int] -> int
17// findConnectedPins: [] -> "pairs=..;stuck=..;skip=..;od=.." (LPC)
18// pinToggleRx: [tx_pin, rx_pin, freq_hz, duration_ms] -> CSV
19// ws2812SctTest: [test_case, tx_pin, rx_pin, capture_ms] -> CSV (10 fields)
20// See FastLED #3021 for the SCT-RX bring-up flags.
21//
22
23#include "platforms/arm/lpc/is_lpc.h" // ok platform headers - LPC RX driver gate
24
25// Gate FL_DBG to no-op. Without `RELEASE`, fl/log/log.h auto-sets
26// FASTLED_FORCE_DBG=1, which expands every FL_DBG call site (inside
27// fl::Remote etc.) through the fl::println formatting machinery and
28// blows ~4 KB of flash budget. fbuild's nxplpc orchestrator does not
29// yet propagate platformio.ini's `build_flags`, so it's defined here.
30#ifndef RELEASE
31#define RELEASE 1
32#endif
33
34// Dedicated #3039 codec-test builds keep the low-memory surface to echo +
35// IEEE754 only. The SCT/WS2812 handlers are useful diagnostics, but they are
36// unrelated to the codec and push LPC845 past its flash budget when combined.
37#if defined(FL_AUTORESEARCH_IEEE754) && FL_AUTORESEARCH_IEEE754
38#define FASTLED_AUTORESEARCH_IEEE754_MODE 1
39#endif
40
41// ESP8266 has 4 MB of flash but too little DRAM for the full harness, so its
42// low-memory build always carries the IEEE754 codec check next to echo.
43#include "platforms/esp/is_esp.h" // ok platform headers // ok platform specific - ESP8266 surface gate
44#if defined(FL_IS_ESP8266) && !defined(FASTLED_AUTORESEARCH_IEEE754_MODE) // ok platform specific - ESP8266 low-DRAM build always carries IEEE754 check
45#define FASTLED_AUTORESEARCH_IEEE754_MODE 1
46#endif
47// The clockless bench reports the driver's frame/retry counters.
48#if defined(FL_IS_ESP8266) && !defined(FASTLED_DEBUG_COUNT_FRAME_RETRIES) // ok platform specific - clockless bench reads ESP8266 retry counters
49#define FASTLED_DEBUG_COUNT_FRAME_RETRIES 1
50#endif
51
52#if !defined(FASTLED_AUTORESEARCH_LPC_UART_DMA)
53#define FASTLED_AUTORESEARCH_LPC_UART_DMA 0
54#endif
55
56// Opt in to the SCT input-capture RX backend (FastLED #3021). With this
57// flag set, `LpcSctRxChannel::begin()` programs the SCT for hardware
58// edge-capture; without it the driver is a no-op stub (host tests still
59// work via `injectEdges()`).
60#if !defined(FASTLED_AUTORESEARCH_IEEE754_MODE) && \
61 !defined(FASTLED_AUTORESEARCH_FAULT_TEST)
62#ifndef FASTLED_LPC_RX_SCT
63#define FASTLED_LPC_RX_SCT 1
64#endif
65#endif
66
67// The LPC845-BRK low-memory build fits FastLED + Remote + the WS2812 loopback
68// RPC in normal mode. The dedicated IEEE754 mode deliberately omits it. The
69// loopback drives the default clockless bus (UART DMA), so a
70// FASTLED_LPC_UART_DMA=0 (bit-bang) build leaves it out.
71#if defined(FL_IS_ARM_LPC_845) && !defined(FASTLED_AUTORESEARCH_IEEE754_MODE) && \
72 !defined(FASTLED_AUTORESEARCH_FAULT_TEST) && !defined(FASTLED_LPC_SPI_DMA) && \
73 !defined(FASTLED_LPC_PWM_DMA) && !FASTLED_AUTORESEARCH_LPC_UART_DMA && \
74 FASTLED_LPC_UART_DMA // ok platform specific - bench exists only for the LPC845 UART-DMA clockless TX captured by the SCT
75#define FASTLED_AUTORESEARCH_LPC_WS2812 1
76#endif
77
78// The WS2812 loopback uses the SCT->DMA RX capture path. The UART clockless
79// verifier uses USART RX-DMA instead, so keep SCT-DMA out of that build;
80// UM11029 Table 296 fixes USART1_RX/USART1_TX on DMA channels 2/3.
81#if defined(FASTLED_AUTORESEARCH_LPC_WS2812) && \
82 !defined(FASTLED_LPC_RX_SCT_DMA)
83#define FASTLED_LPC_RX_SCT_DMA 1
84#endif
85
86#include <Arduino.h>
87#include "fl/remote/remote.h"
90#include "fl/wdt/watchdog.h"
91#include "fl/log/log.h"
92#include "fl/stl/cstdio.h" // fl::serial_begin -- HWCDC-safe Serial.begin wrapper
93#include "fl/stl/singleton.h"
94
95#if defined(FASTLED_AUTORESEARCH_IEEE754_MODE)
96#include "AutoResearchIeee754.h"
97#endif
98
99// The host-stub example DLL build (`tests/shared/example_dll_wrapper_template.cpp`)
100// compiles this sketch on Linux to surface ABI breaks. The RX SCT driver
101// types are platform-gated behind `FL_IS_ARM_LPC` -- they only exist on
102// the real LPC build. So the include + every RX usage below must be gated
103// the same way.
104#if defined(FL_IS_ARM_LPC) && !defined(FASTLED_AUTORESEARCH_IEEE754_MODE) && \
105 !defined(FASTLED_AUTORESEARCH_FAULT_TEST)
107#include "fl/stl/strstream.h"
108#include "fl/system/pin.h" // fl::pinMode/digitalWrite/digitalRead
109#include "fl/system/pin_probe.h" // fl::pinProbeSkipReason
110#include "platforms/arm/lpc/led_sysdefs_arm_lpc.h" // ok platform headers - vendor CMSIS SysTick for pinToggleRx edge timing
111#endif
112
113#if defined(FASTLED_AUTORESEARCH_LPC_WS2812)
114#include "FastLED.h"
116#include "fl/channels/config.h"
117#include "fl/channels/data.h"
118#include "fl/channels/driver.h"
120#endif
121
122// FastLED #3468: channels-API SCT+DMA clockless AutoResearch harness.
123// Opt-in via `-DFASTLED_LPC_PWM_DMA=1`; the header self-gates on
124// `FL_IS_ARM_LPC_845 && FASTLED_LPC_PWM_DMA` so unrelated builds are
125// unaffected. Note: exclusive with FASTLED_AUTORESEARCH_LPC_WS2812 —
126// both target the same SCT peripheral and would collide at runtime.
127// The host-side `bash autoresearch --pwm-dma-cl` wrapper enforces
128// mutual exclusion with `--dma-spi` and the legacy `ws2812SctTest`.
129#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_LPC_PWM_DMA)
131#endif
132
133// FastLED #3456: LPC845 SPI+DMA async AutoResearch harness (Phase 1 of
134// #3453 bench bring-up). Opt-in via `-DFASTLED_LPC_SPI_DMA=1`; the
135// header self-gates on `FL_IS_ARM_LPC_845 && FASTLED_LPC_SPI_DMA`.
136// LPC804 is NOT supported — silicon has no DMA peripheral. See
137// `agents/docs/peripheral-existence.md`. Mutually exclusive with
138// FASTLED_LPC_PWM_DMA (both claim DMA0 channels and the LowMemory
139// flash budget doesn't fit both). Enforced host-side by
140// `bash autoresearch` refusing `--dma-spi --pwm-dma-cl`.
141#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_LPC_SPI_DMA) && \
142 defined(FASTLED_LPC_PWM_DMA)
143#error "FASTLED_LPC_SPI_DMA and FASTLED_LPC_PWM_DMA are mutually exclusive on LPC845: both claim DMA0 channels and the LowMemory flash budget doesn't fit both. Pick one for the AutoResearch build."
144#endif
145#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_LPC_SPI_DMA)
146#include "AutoResearchSpiDma.h"
147#endif
148
149// #3453 follow-up: LPC845 async UART TX harness (DMA + ISR chunk chain) and
150// #3611 UART clockless loopback verifier. The UART DMA driver is now the
151// LPC845 library default, so the AutoResearch RPC harness has its own flag.
152#if defined(FL_IS_ARM_LPC_845) && FASTLED_AUTORESEARCH_LPC_UART_DMA && \
153 !FASTLED_LPC_UART_DMA
154#error "FASTLED_AUTORESEARCH_LPC_UART_DMA requires FASTLED_LPC_UART_DMA=1."
155#endif
156#if defined(FL_IS_ARM_LPC_845) && FASTLED_AUTORESEARCH_LPC_UART_DMA && \
157 (defined(FASTLED_LPC_SPI_DMA) || defined(FASTLED_LPC_PWM_DMA))
158#error "FASTLED_AUTORESEARCH_LPC_UART_DMA is mutually exclusive with the SPI/PWM DMA harnesses on LPC845: the LowMemory flash budget fits one bench at a time. Pick one for the AutoResearch build."
159#endif
160#if defined(FL_IS_ARM_LPC_845) && FASTLED_AUTORESEARCH_LPC_UART_DMA
161#include "AutoResearchUartDma.h"
162#endif
163
164// ESP8266 UART WS2812 driver benches (pad self-capture, no jumper needed).
165#if defined(FL_IS_ESP8266) // ok platform specific - ESP8266 bring-up benches
166#include "AutoResearchEsp8266.h"
167#endif
168
169namespace autoresearch {
170namespace low_memory {
171
174
176 : remote(fl::createSerialRequestSource(),
177 fl::createSerialResponseSink("REMOTE: ")) {}
178};
179
183
184#if defined(FL_IS_ARM_LPC) && !defined(FASTLED_AUTORESEARCH_IEEE754_MODE) && \
185 !defined(FASTLED_AUTORESEARCH_FAULT_TEST)
186struct PinToggleState {
187 fl::EdgeTime edges[64];
188};
189
190inline PinToggleState& pinToggleState() {
192}
193#endif
194
195#if defined(FASTLED_AUTORESEARCH_LPC_WS2812)
196struct Ws2812State {
197 uint8_t decoded[300];
198 fl::EdgeTime probe[64];
199};
200
201inline Ws2812State& ws2812State() {
203}
204#endif
205
206} // namespace low_memory
207} // namespace autoresearch
208
209namespace {
210
211#if defined(FL_IS_ARM_LPC) && !defined(FASTLED_AUTORESEARCH_IEEE754_MODE) && \
212 !defined(FASTLED_AUTORESEARCH_FAULT_TEST)
213// Period-stat helpers for `pinToggleRx`. Mirrors the FlexIO RX benchmark
214// logic in `examples/AutoResearch/AutoResearchRemote.cpp::flexioRxBenchmark`
215// but inline so we don't pull in the AutoResearch ObjectFLED bus.
216struct LowMemPinTogglePeriodStats {
217 fl::u32 periods;
218 fl::u32 mean_ns;
219 fl::u32 sigma_ns;
220 fl::u32 min_ns;
221 fl::u32 max_ns;
222};
223
224inline LowMemPinTogglePeriodStats computeLowMemPeriodStats(
225 const fl::EdgeTime* edges, fl::size edge_count) FL_NO_EXCEPT {
226 LowMemPinTogglePeriodStats s{0, 0, 0, 0, 0};
227 // Two passes: sum of squared deviations from the mean. The one-pass
228 // E[x^2] - floor(mean)^2 form lost ~1.4 us of sigma to the floor at a
229 // 1 ms period -- more than the bench's 1 us sigma budget.
230 fl::u64 sum = 0;
231 fl::u32 min_ns = 0xFFFFFFFFu;
232 fl::u32 max_ns = 0;
233 fl::u32 count = 0;
234 for (fl::size i = 0; i + 1 < edge_count; i += 2) {
235 const fl::u32 period_ns =
236 static_cast<fl::u32>(edges[i].ns) +
237 static_cast<fl::u32>(edges[i + 1].ns);
238 if (period_ns == 0) continue;
239 sum += period_ns;
240 if (period_ns < min_ns) min_ns = period_ns;
241 if (period_ns > max_ns) max_ns = period_ns;
242 ++count;
243 }
244 if (count == 0) return s;
245 const fl::u32 mean = static_cast<fl::u32>(sum / static_cast<fl::u64>(count));
246 fl::u64 dev_sq = 0;
247 for (fl::size i = 0; i + 1 < edge_count; i += 2) {
248 const fl::u32 period_ns =
249 static_cast<fl::u32>(edges[i].ns) +
250 static_cast<fl::u32>(edges[i + 1].ns);
251 if (period_ns == 0) continue;
252 const fl::u64 d = (period_ns > mean) ? (period_ns - mean) : (mean - period_ns);
253 const fl::u64 sq = d * d; // d < 2^32
254 // Saturate: a few edges clamped to ~2.1 s would wrap the sum and
255 // report a tiny sigma.
256 dev_sq = (dev_sq > ~fl::u64(0) - sq) ? ~fl::u64(0) : dev_sq + sq;
257 }
258 const fl::u64 var = dev_sq / static_cast<fl::u64>(count);
259 // Bitwise integer sqrt: 32 steps whatever `var` is. A linear search ran
260 // for billions of steps on a wide spread and tripped the watchdog.
261 fl::u64 rem = var;
262 fl::u64 root = 0;
263 fl::u64 bit = fl::u64(1) << 62;
264 while (bit > rem) bit >>= 2;
265 while (bit != 0) {
266 if (rem >= root + bit) {
267 rem -= root + bit;
268 root = (root >> 1) + bit;
269 } else {
270 root >>= 1;
271 }
272 bit >>= 2;
273 }
274 const fl::u32 sig = static_cast<fl::u32>(root);
275 s.periods = count;
276 s.mean_ns = mean;
277 s.sigma_ns = sig;
278 s.min_ns = (min_ns == 0xFFFFFFFFu) ? 0u : min_ns;
279 s.max_ns = max_ns;
280 return s;
281}
282// Core-clock tick counter for pinToggleRx edge scheduling, built on the
283// SysTick down-counter (reloads every 1 ms). micros() costs ~19 us per call
284// on the 24 MHz M0+ (two software divides), which capped the bench near
285// 7 kHz and added ~10 us of jitter to every edge. Valid while now() is
286// called at least once per SysTick period.
287struct LowMemTickClock {
288 // millis() starts the core's SysTick (core clock, 1 ms reload) if
289 // nothing has yet; a stopped SysTick would never reach a deadline.
290 fl::u32 last = (static_cast<void>(millis()), SysTick->VAL);
291 fl::u32 elapsed = 0;
292 fl::u32 now() FL_NO_EXCEPT {
293 const fl::u32 v = SysTick->VAL;
294 elapsed += (last >= v) ? (last - v) : (last + SysTick->LOAD + 1u - v);
295 last = v;
296 return elapsed;
297 }
298};
299
300// findConnectedPins for the low-memory LPC build: discovers bench jumpers
301// through FastLED's own pin backend (fl::pinMode/digitalWrite/digitalRead,
302// #5260) -- the LPC8xx Arduino core's pinMode puts pulls on the wrong IOCON
303// slot (FastLED/framework-arduino-lpc8xx#40). Every pin is tested against
304// every other pin, and every connected direction is reported.
305//
306// LPC845 PIO0_10/PIO0_11 are true open-drain pads: no pulls, sink only. They
307// are probed as drivers (pulled LOW against the other pin's pull-up) but can
308// never be the observed end, so a jumper between the two of them is invisible
309// without an external pull-up.
310inline bool lowMemOpenDrainPin(int pin) FL_NO_EXCEPT {
311#if defined(FL_IS_ARM_LPC_845) // ok platform specific - PIO0_10/PIO0_11 are the LPC845's pull-less open-drain pads; no core API reports pad type
312 return pin == 10 || pin == 11;
313#else
314 (void)pin;
315 return false;
316#endif
317}
318
319inline bool lowMemSettledHigh(int pin) FL_NO_EXCEPT {
320 delayMicroseconds(100); // internal pulls are ~50 kOhm; 100 us settles a jumper
321 return fl::digitalRead(pin) == fl::PinValue::High;
322}
323
324// tx drives, rx observes. Connected only if rx follows its own pull while tx
325// is released AND follows tx against that pull, in both directions.
326inline bool lowMemPinPairConnected(int tx, int rx) FL_NO_EXCEPT {
327 bool ok = true;
330 ok = ok && lowMemSettledHigh(rx); // control: released -> pull-up
333 ok = ok && !lowMemSettledHigh(rx); // tx sinks the pull-up
334 if (ok && !lowMemOpenDrainPin(tx)) {
337 ok = lowMemSettledHigh(rx); // tx sources the pull-down
339 ok = ok && !lowMemSettledHigh(rx); // control: released -> pull-down
340 }
343 return ok;
344}
345
346// Reply: "pairs=<tx>><rx>[od] ...;stuck=<pin><H|L|X> ...;skip=<pin>:<why> ...;od=<pin> ..."
347inline fl::string lowMemFindConnectedPins() FL_NO_EXCEPT {
348 constexpr int kPinCount = 32; // PIO0_0..PIO0_31, the runtime pin grid
349 fl::sstream skip;
350 fl::sstream stuck;
351 fl::sstream od;
352 fl::u32 probe = 0;
353 for (int p = 0; p < kPinCount; ++p) {
354 if (const char* why = fl::pinProbeSkipReason(p)) {
355 skip << p << ':' << why << ' ';
356 continue;
357 }
358 probe |= 1u << p;
359 fl::pinMode(p, fl::PinMode::Input); // no pull: a partner's pull wins
360 }
361 // Per-pin control: with every other pin released, a free pin follows its
362 // own pull. One that does not is externally driven or loaded; it would
363 // fake connections, so it is reported and left out of the pair sweep.
364 fl::u32 usable = 0;
365 for (int p = 0; p < kPinCount; ++p) {
366 if (!(probe & (1u << p))) continue;
367 if (lowMemOpenDrainPin(p)) {
368 od << p << ' ';
369 usable |= 1u << p;
370 continue;
371 }
373 const bool up = lowMemSettledHigh(p);
375 const bool down = lowMemSettledHigh(p);
377 if (up && !down) {
378 usable |= 1u << p;
379 } else {
380 stuck << p << (up ? 'H' : (down ? 'X' : 'L')) << ' ';
381 }
382 }
383 fl::sstream pairs;
384 for (int tx = 0; tx < kPinCount; ++tx) {
385 if (!(usable & (1u << tx))) continue;
387 for (int rx = 0; rx < kPinCount; ++rx) {
388 if (rx == tx || !(usable & (1u << rx)) || lowMemOpenDrainPin(rx)) continue;
389 if (lowMemPinPairConnected(tx, rx)) {
390 pairs << tx << '>' << rx << (lowMemOpenDrainPin(tx) ? "od" : "") << ' ';
391 }
392 }
393 }
394 // Leave normal pads at their reset state (pull-up), open-drain released.
395 for (int p = 0; p < kPinCount; ++p) {
396 if (!(probe & (1u << p))) continue;
397 fl::pinMode(p, lowMemOpenDrainPin(p) ? fl::PinMode::Input
399 }
400 fl::sstream out;
401 out << "pairs=" << pairs.str() << ";stuck=" << stuck.str()
402 << ";skip=" << skip.str() << ";od=" << od.str();
403 return out.str();
404}
405
406// Compiled only into the `--pin-toggle-rx` bench build: phases.py passes
407// FASTLED_AUTORESEARCH_LPC_CORE_PULL_CHECK there. It tests the vendor core's
408// ::pinMode, which FastLED itself never calls (it uses fl::pinMode), so the
409// shared LPC845 image does not carry it.
410#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_AUTORESEARCH_LPC_CORE_PULL_CHECK) // ok platform specific - checks the LPC8xx Arduino core's IOCON pull mapping (framework-arduino-lpc8xx#40)
411// corePullCheck: checks that the vendor Arduino core's ::pinMode puts the
412// pull on the requested pad (FastLED/framework-arduino-lpc8xx#40). Use
413// unconnected pins from findConnectedPins. FastLED's own backend first sets
414// the opposite pull, so a core that writes the wrong IOCON slot reads back
415// the opposite level. Appends "<pin>:up=<0|1>,down=<0|1> " per pin; a
416// correct core gives "up=1,down=0". Pads the core cannot pull (outside its
417// pin map, open-drain, probe-skipped) report "<pin>:skip ".
418//
419// On a core with the #40 bug the probe itself changes some other pad's pull,
420// as any ::pinMode call there would. A core without INPUT_PULLDOWN treats
421// mode 3 as "no pull", so it reports down=1 too.
422inline void lowMemCorePullCheck(int pin, fl::sstream& out) FL_NO_EXCEPT {
423#ifdef INPUT_PULLDOWN // ok platform specific - vendor core constant; the check targets the core itself
424 constexpr PinMode kCorePulldown = INPUT_PULLDOWN; // ok platform specific - vendor core constant under test
425#else
426 constexpr PinMode kCorePulldown = 0x3; // older cores lack the define
427#endif
428 out << pin << ':';
429 if (pin < 0 || pin >= static_cast<int>(variant_pin_count) || // ok platform specific - vendor core's pin-map size bounds the pins it can pull
430 lowMemOpenDrainPin(pin) || fl::pinProbeSkipReason(pin)) {
431 out << "skip ";
432 return;
433 }
434 const pin_size_t p = static_cast<pin_size_t>(pin);
436 ::pinMode(p, INPUT_PULLUP); // ok platform specific - the vendor core call under test
437 const int up = lowMemSettledHigh(pin) ? 1 : 0;
439 ::pinMode(p, kCorePulldown); // ok platform specific - the vendor core call under test
440 const int down = lowMemSettledHigh(pin) ? 1 : 0;
441 fl::pinMode(pin, fl::PinMode::InputPullup); // reset-state pull
442 out << "up=" << up << ",down=" << down << ' ';
443}
444#endif // FL_IS_ARM_LPC_845 && FASTLED_AUTORESEARCH_LPC_CORE_PULL_CHECK
445
446#endif // FL_IS_ARM_LPC && !FASTLED_AUTORESEARCH_IEEE754_MODE && !FAULT_TEST
447
448#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_AUTORESEARCH_FAULT_TEST)
449FL_NO_RETURN FL_NO_INLINE void triggerLowMemoryNullFault() FL_NO_EXCEPT {
450 volatile fl::u32* const p =
451 reinterpret_cast<volatile fl::u32*>(0u); // ok reinterpret cast - fault test
452 *p = 0x3302u;
453 while (true) {}
454}
455
457FL_DISABLE_WARNING(infinite-recursion)
458FL_NO_INLINE int recurseLowMemoryStackBlow(int depth) FL_NO_EXCEPT {
459 volatile fl::u8 pad[64] = {0};
460 pad[static_cast<fl::u8>(depth) & 0x3Fu] = static_cast<fl::u8>(depth);
461 // LPC845/M0+ has no stack-limit trap; unbounded recursion can corrupt the
462 // runtime before the HardFault handler can emit. Burn stack frames, then
463 // force the HardFault path while the diagnostic surface is still intact.
464 if (depth >= 32) {
465 triggerLowMemoryNullFault();
466 }
467 return recurseLowMemoryStackBlow(depth + 1) + pad[depth & 0x3F];
468}
470#endif // FL_IS_ARM_LPC_845 && FASTLED_AUTORESEARCH_FAULT_TEST
471
472} // namespace
473
475 fl::serial_begin(115200);
476
477 // Arm the watchdog so a hung sketch unbricks itself on crash.
479
480 // Emit a literal-only warning so the autoresearch harness can verify
481 // the FL_WARN log pipeline reaches the host.
482 FL_WARN_LIT("FL_WARN: low-memory bring-up OK");
483
484 // The C++ inline-ODR rule guarantees a single shared instance across
485 // every translation unit that calls this inline function, which is
486 // exactly what we want (one Remote bound to the singleton Serial
487 // transport). The included-once-per-sketch model of `.ino` builds
488 // also reduces to a single TU in practice.
490 remote.bind("echo", [](int v) -> int {
491 FL_WARN_LIT("FL_WARN: echo invoked");
492 return v;
493 });
494
495#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_AUTORESEARCH_FAULT_TEST)
496 remote.bind("trigger_oom", []() -> bool {
497 // Intentional #3302 fault input: ask the 16 KB SRAM target for
498 // far more RAM than exists. If the platform allocator returns null
499 // instead of trapping, dereference null to exercise HardFault emit.
500 volatile char* const p = new char[16UL * 1024UL * 1024UL]; // ok bare allocation
501 if (p == nullptr) {
502 triggerLowMemoryNullFault();
503 }
504 p[0] = 0x33;
505 triggerLowMemoryNullFault();
506 return false;
507 });
508 remote.bind("trigger_stackblow", []() -> bool {
509 (void)recurseLowMemoryStackBlow(0);
510 triggerLowMemoryNullFault();
511 return false;
512 });
513#endif // FL_IS_ARM_LPC_845 && FASTLED_AUTORESEARCH_FAULT_TEST
514
515#if defined(FL_IS_ESP8266) // ok platform specific - ESP8266 bring-up benches
516 autoresearch::esp8266::bindEsp8266Benches(remote);
517#endif
518
519#if defined(FASTLED_AUTORESEARCH_IEEE754_MODE)
520 remote.bind("ieee754CodecTest", [](const fl::json& args) -> fl::json {
521 (void)args;
522 const auto r = autoresearch::ieee754_check::run();
523 fl::json response = fl::json::object();
524 response.set("success", r.success);
525 response.set("tests_run", static_cast<int64_t>(r.tests_run));
526 response.set("tests_failed", static_cast<int64_t>(r.tests_failed));
527 response.set("first_failure", r.first_failure ? r.first_failure : "");
528 response.set("expected_bits", static_cast<int64_t>(r.expected_bits));
529 response.set("actual_bits", static_cast<int64_t>(r.actual_bits));
530 return response;
531 });
532#endif
533
534#if defined(FL_IS_ARM_LPC) && !defined(FASTLED_AUTORESEARCH_IEEE754_MODE) && \
535 !defined(FASTLED_AUTORESEARCH_FAULT_TEST)
536#if defined(FL_IS_ARM_LPC_845) // ok platform specific - only the LPC845 has a pin-probe skip table
537 // LPC845 only: it is the LPC with a pin-probe skip table (SWD, RESET,
538 // ISP, console USART). Elsewhere the scan would drive those pads.
539 remote.bind("findConnectedPins",
540 []() -> fl::string { return lowMemFindConnectedPins(); });
541#endif
542
543 // pinToggleRx (FastLED #3021 Phase 1) — bit-bang square wave on tx_pin
544 // and capture SCT edges on rx_pin. CSV stats out.
545#if !defined(FASTLED_AUTORESEARCH_LPC_DMA_LOOPBACK)
546 // Left out of the RX-DMA loopback builds (--ws2812-loopback/--pwm-dma-cl):
547 // with the DMA capture linked, the 64 KB LPC845 has no room for this
548 // unrelated ~1 KB diagnostic. --pin-toggle-rx builds keep it.
549 remote.bind("pinToggleRx",
550 [](int tx_pin, int rx_pin, int freq_hz, int duration_ms) -> fl::string {
551 if (tx_pin < 0 || rx_pin < 0 || freq_hz <= 0 || duration_ms <= 0) {
552 return fl::string("0,0,0,0,0,0,0");
553 }
554 const fl::u32 expected_edges =
555 2u * static_cast<fl::u32>(freq_hz) *
556 static_cast<fl::u32>(duration_ms) / 1000u;
557 // Keep both the RX vector and diagnostic copy buffer small on
558 // 16 KB SRAM LPC8xx parts. Larger static buffers regressed early
559 // init by leaving too little room for stack/heap (FastLED #3200),
560 // while stack buffers previously overflowed during this handler
561 // (FastLED #3125).
562 constexpr fl::u32 kLowMemEdgeBufSize = 64u;
563 fl::u32 cap = expected_edges + (expected_edges / 2u);
564 if (cap < 2u) cap = 2u;
565 if (cap > kLowMemEdgeBufSize) cap = kLowMemEdgeBufSize;
566
567 // FastLED's own pin backend (#5260), not the Arduino core's:
568 // this bench is the on-silicon check of fl::pinMode/digitalWrite.
569 // TX settles LOW before capture starts, so the first captured
570 // edge is the first square-wave edge, not a pull-up -> LOW step.
573
574 auto rx = fl::LpcSctRxChannel::create(rx_pin);
575 if (!rx) return fl::string("0,0,0,0,0,0,0");
576
577 fl::RxConfig cfg;
578 cfg.buffer_size = cap;
579 cfg.start_low = true;
580 if (!rx->begin(cfg)) return fl::string("0,0,0,0,0,0,0");
581
582 const fl::u32 half_us = 500000u / static_cast<fl::u32>(freq_hz);
583 const fl::u32 cycles = static_cast<fl::u32>(freq_hz) *
584 static_cast<fl::u32>(duration_ms) / 1000u;
585
586 // Edges are scheduled on absolute SysTick deadlines. Measured on
587 // LPC845-BRK: delayMicroseconds(half_us) after each write and poll
588 // added that overhead to every half period (+20% at 1 kHz).
589 //
590 // The capture is polled once right after every write: the SCT
591 // holds one capture per direction, so a half period without a
592 // poll loses edges. Near the deadline only the clock is read, so
593 // a poll (~3 us) does not delay the next edge.
594 const fl::u32 ticks_per_us = F_CPU / 1000000u;
595 const fl::u32 half_ticks = half_us * ticks_per_us;
596 const fl::i32 poll_guard = static_cast<fl::i32>(6u * ticks_per_us);
597 LowMemTickClock clock;
598 fl::u32 deadline = clock.now();
599 for (fl::u32 i = 0; i < 2u * cycles; ++i) {
600 fl::digitalWrite(tx_pin, (i & 1u) ? fl::PinValue::Low
602 rx->pollOnce();
603 deadline += half_ticks;
604 for (;;) {
605 const fl::i32 left = static_cast<fl::i32>(deadline - clock.now());
606 if (left <= 0) break;
607 if (left > poll_guard) rx->pollOnce();
608 }
609 if ((i & 0xFFu) == 0u) {
611 }
612 }
613 rx->wait(1);
614
615 // Static storage keeps this off the stack; the small fixed size
616 // keeps .bss below the LPC845-BRK early-init failure threshold.
617 // Size from the array, not a pointer to it: sizeof(pointer) /
618 // sizeof(EdgeTime) is 1, which capped every capture at one edge.
619 auto& edges_buf = autoresearch::low_memory::pinToggleState().edges;
620 const fl::size n_read = rx->getRawEdgeTimes(
621 fl::span<fl::EdgeTime>(edges_buf, sizeof(edges_buf) / sizeof(edges_buf[0])));
622
623 LowMemPinTogglePeriodStats stats = computeLowMemPeriodStats(edges_buf, n_read);
624
625 fl::sstream s;
626 const bool success = (stats.periods > 0);
627 s << (success ? 1 : 0) << ',' << static_cast<fl::u32>(n_read) << ','
628 << stats.periods << ',' << stats.mean_ns << ',' << stats.sigma_ns << ','
629 << stats.min_ns << ',' << stats.max_ns;
630 return s.str();
631 });
632#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_AUTORESEARCH_LPC_CORE_PULL_CHECK) // ok platform specific - LPC8xx core pull check, --pin-toggle-rx build only
633 // corePullCheck: [pin_a, pin_b, pin_c, pin_d] -> "<pin>:up=..,down=.. ..."
634 // (pin < 0 = unused slot); `bash autoresearch lpc845 --pin-toggle-rx`
635 // defines FASTLED_AUTORESEARCH_LPC_CORE_PULL_CHECK and runs it on
636 // scan-idle pins. Other builds leave it unbound; only --pin-toggle-rx
637 // calls it, and there a missing binding fails the run.
638 remote.bind("corePullCheck",
639 [](int pin_a, int pin_b, int pin_c, int pin_d) -> fl::string {
640 fl::sstream out;
641 const int pins[] = {pin_a, pin_b, pin_c, pin_d};
642 for (int pin : pins) {
643 if (pin >= 0) {
644 lowMemCorePullCheck(pin, out);
645 }
646 }
647 return out.str();
648 });
649#endif
650#endif // !FASTLED_AUTORESEARCH_LPC_DMA_LOOPBACK
651
652#if defined(FASTLED_AUTORESEARCH_LPC_WS2812)
653 // ws2812SctTest (FastLED #3021 Phase 2) -- WS2812 byte-match loopback.
654 remote.bind("ws2812SctTest",
655 [](int test_case, int tx_pin, int rx_pin, int capture_ms) -> fl::string {
656 // TX/RX come from the host's findConnectedPins scan. An
657 // open-drain pad cannot drive TX: it only sinks, and its rising
658 // edge is the ~1.7 us pull-up, longer than any WS2812 HIGH.
659 // Reserved pads (SWD, ISP, console) are refused: routing USART
660 // TXD or the SCT input onto them cuts the link to the host.
661 // A rejected request replies with num_leds=0.
662 if (test_case < 0 || test_case > 4 || tx_pin < 0 || tx_pin > 31 ||
663 rx_pin < 0 || rx_pin > 31 || tx_pin == rx_pin ||
664 lowMemOpenDrainPin(tx_pin) || fl::pinProbeSkipReason(tx_pin) ||
665 fl::pinProbeSkipReason(rx_pin) || capture_ms <= 0) {
666 return fl::string("0,0,0,0,0,0,0,0,0,0");
667 }
668 int num_leds = 1;
669 switch (test_case) {
670 case 1: num_leds = 3; break;
671 case 4: num_leds = 100; break;
672 default: num_leds = 1; break;
673 }
674 const int expected_bytes = num_leds * 3;
675 // Setup failures keep the case fields, with nothing decoded and
676 // tx_done=2 (TX never started; 0 means it started but timed out).
677 auto setupFailed = [&]() -> fl::string {
678 fl::sstream f;
679 f << "0," << test_case << ',' << num_leds << ',' << expected_bytes
680 << ",0,0,0,0,0,2";
681 return f.str();
682 };
683
684 // Wire bytes in WS2812 GRB order: what addLeds<WS2812, PIN, GRB>
685 // would hand the driver for these colors at full brightness.
686 fl::vector_psram<u8> grb(static_cast<fl::size>(expected_bytes));
687 for (int i = 0; i < num_leds; ++i) {
688 u8 r = 0, g = 0, b = 0;
689 switch (test_case) {
690 case 0: r = 0xFF; break;
691 case 1: r = (i == 0) ? 0xFF : 0; g = (i == 1) ? 0xFF : 0;
692 b = (i == 2) ? 0xFF : 0; break;
693 case 3: r = g = b = 0xFF; break;
694 case 4: r = (i % 3 == 0) ? 0xFF : 0; g = (i % 3 == 1) ? 0xFF : 0;
695 b = (i % 3 == 2) ? 0xFF : 0; break;
696 default: break; // case 2: all zeros
697 }
698 grb[i * 3 + 0] = g;
699 grb[i * 3 + 1] = r;
700 grb[i * 3 + 2] = b;
701 }
702 autoresearch::low_memory::Ws2812State& ws_state =
703 autoresearch::low_memory::ws2812State();
704
705 // The TX pin is a run-time value (from the jumper scan), which
706 // addLeds<WS2812, PIN>() cannot take, and the 64 KB part has no
707 // room for the runtime Channel API (+21 KB). So drive the frame
708 // the way addLeds<> does on a low-memory part (SlimBridgeController
709 // direct show): GRB bytes in a ChannelData for the pin, handed to
710 // the platform default clockless driver.
712 fl::IChannelDriver& tx = TxBus::instance();
713 auto frame = fl::ChannelData::create(
715 fl::move(grb));
716 if (!frame || !tx.canHandle(frame)) return setupFailed();
717 // The engine has no abort, so a frame left over from a timed-out
718 // case must drain first, or show() would skip this case's frame.
719 constexpr fl::u32 kTxDeadlineMs = 100u;
720 if (!tx.waitForReady(kTxDeadlineMs)) return setupFailed();
721 const u8* expected_buf = frame->getData().data();
722
723 auto rx = fl::LpcSctRxChannel::create(rx_pin);
724 if (!rx) return setupFailed();
725 fl::RxConfig cfg;
726 const fl::u32 expected_edges = (fl::u32)num_leds * 24u * 2u;
727 fl::u32 cap = expected_edges + (expected_edges / 2u);
728 // The low-memory sketch cannot afford the old 2048-edge reserve
729 // on a 16 KB SRAM LPC845. 192 edges covers the 1- and 3-LED
730 // cases; the 100-LED case (4800 edges) is checked on the prefix
731 // that fits, reported in the `cap` field.
732 constexpr fl::u32 kLowMemWs2812EdgeCapacity = 192u;
733 if (cap < 48u) cap = 48u;
734 if (cap > kLowMemWs2812EdgeCapacity) cap = kLowMemWs2812EdgeCapacity;
735 cfg.buffer_size = cap;
736 cfg.start_low = true;
737 if (!rx->begin(cfg)) return setupFailed();
738
739 // TX gets its own deadline: a 100-LED frame is ~3 ms on the
740 // wire, whatever the RX window. A frame that does not finish
741 // fails the case.
742 tx.enqueue(frame);
743 tx.show();
744 const bool tx_done = tx.waitForReady(kTxDeadlineMs);
745 rx->wait(capture_ms);
746 // Give the TX pad back to GPIO once the frame is out (re-checked
747 // after the RX wait), so a later findConnectedPins in this boot
748 // sees the jumper, not a USART-held pin.
750 fl::lpc::LpcUartDmaRuntime::releaseTxPin(); // ok platform specific - only the LPC845 UART-DMA TX holds the pad on a movable SWM function between frames
751 }
752
753 uint8_t* decoded_buf = ws_state.decoded;
754 for (int i = 0; i < expected_bytes; ++i) decoded_buf[i] = 0;
755
756 // The second argument is the window half-width, not a reset
757 // time (passing 0 demanded exact widths). The UART encoder sends
758 // whole 250 ns slots -- a 1 is H750/L500 against the nominal
759 // T1H 875/T1L 375 -- so the window must exceed that 125 ns.
760 constexpr fl::u32 kWs2812DecodeToleranceNs = 200u;
764 kWs2812DecodeToleranceNs);
765
766 auto dec = rx->decode(timing, fl::span<u8>(decoded_buf, expected_bytes));
767 const fl::u32 decoded_bytes = dec.ok() ? dec.value() : 0u;
768
769 // mismatched counts decoded bytes that differ; bytes that were
770 // never decoded are exp_bytes - dec_bytes.
771 fl::u32 matched = 0;
772 fl::u32 mismatched = 0;
773 for (fl::u32 i = 0; i < decoded_bytes && i < (fl::u32)expected_bytes; ++i) {
774 if (decoded_buf[i] == expected_buf[i]) ++matched;
775 else ++mismatched;
776 }
777
778 // Count every captured edge, reading through a small .bss window
779 // (one read would stop at the window size).
780 constexpr fl::size kLowMemWs2812ProbeSize = 64u;
781 fl::span<fl::EdgeTime> probe(ws_state.probe, kLowMemWs2812ProbeSize);
782 fl::size edges_captured = 0;
783 for (fl::size n; (n = rx->getRawEdgeTimes(probe, edges_captured)) > 0;) {
784 edges_captured += n;
785 }
786
787 // A capture of `cap` edges holds cap / 16 bytes (16 edges per
788 // byte), so the 100-LED frame is checked on that prefix; the
789 // smaller frames fit whole. Same rule as the host bench.
790 fl::u32 need = cap / 16u;
791 if (need > (fl::u32)expected_bytes) need = (fl::u32)expected_bytes;
792 const bool success =
793 tx_done && mismatched == 0 && need > 0 && matched >= need;
794
795 fl::sstream s;
796 s << (success ? 1 : 0) << ',' << test_case << ',' << num_leds << ','
797 << expected_bytes << ',' << decoded_bytes << ','
798 << matched << ',' << mismatched << ','
799 << static_cast<fl::u32>(edges_captured) << ',' << cap << ','
800 << (tx_done ? 1 : 0);
801 return s.str();
802 });
803#endif // FASTLED_AUTORESEARCH_LPC_WS2812
804
805 // FastLED #3468: channels-API SCT+DMA clockless AutoResearch
806 // harness. Binds pwmDmaClFrameOnce / pwmDmaClFrameBurst /
807 // pwmDmaClCaptureSelf / pwmDmaClDmaError / pwmDmaClCaptureStress (the
808 // last two from #5278). Header self-gates on
809 // FL_IS_ARM_LPC_845 && FASTLED_LPC_PWM_DMA.
810#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_LPC_PWM_DMA)
811 autoresearch::pwm_dma_cl::bind(remote);
812#endif
813
814 // FastLED #3456: SPI+DMA async AutoResearch harness. Binds
815 // dmaSpiTransferOnce / dmaSpiTransferOverlap / dmaSpiMeasureSck.
816 // Header self-gates on FL_IS_ARM_LPC_845 && FASTLED_LPC_SPI_DMA.
817#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_LPC_SPI_DMA)
818 autoresearch::dma_spi::bind(remote);
819#endif
820
821 // #3453/#3611: UART DMA AutoResearch harness. Binds either the raw
822 // UART DMA stream bench or the clockless loopback verifier, depending
823 // on the build flags injected by `bash autoresearch`.
824#if defined(FL_IS_ARM_LPC_845) && FASTLED_AUTORESEARCH_LPC_UART_DMA
825 autoresearch::uart_dma::bind(remote);
826#endif
827
828#endif // FL_IS_ARM_LPC && !FASTLED_AUTORESEARCH_IEEE754_MODE
829}
830
On-device verification for the integer-only IEEE 754 decimal codec.
void autoResearchLowMemoryLoop()
void autoResearchLowMemorySetup()
fl::unique_ptr< fl::Remote > remote
Definition RpcClient.ino:43
int pins[]
Definition Spi.ino:11
Per-driver traits keyed on fl::Bus.
static ChannelDataPtr create(const ChipsetVariant &chipset, fl::vector_psram< u8 > &&encodedData=fl::vector_psram< u8 >(), ChannelPixelFormat pixelFormat=ChannelPixelFormat::RGB) FL_NO_EXCEPT
Create channel transmission data (modern variant-based API)
Definition data.cpp.hpp:12
virtual bool canHandle(const ChannelDataPtr &data) const FL_NO_EXCEPT=0
Check if this driver can handle the given channel data.
virtual void enqueue(ChannelDataPtr channelData) FL_NO_EXCEPT=0
Enqueue channel data for transmission.
virtual void show() FL_NO_EXCEPT=0
Trigger transmission of enqueued data.
virtual DriverState poll() FL_NO_EXCEPT=0
Query driver state and perform maintenance.
bool waitForReady(u32 timeoutMs=1000) FL_NO_EXCEPT
Wait for driver to become READY.
Minimal interface for LED channel transmission drivers.
Definition driver.h:53
size_t update(u32 currentTimeMs) FL_NO_EXCEPT
Main update: pull + tick + push (overrides Server::update)
JSON-RPC server with scheduling support.
Definition remote.h:42
static T & instance() FL_NO_EXCEPT
Definition singleton.h:81
static Watchdog & instance() FL_NO_EXCEPT
void begin(fl::u32 timeout_ms) FL_NO_EXCEPT
void feed() FL_NO_EXCEPT
static json object() FL_NO_EXCEPT
Definition json.h:864
string str() const FL_NO_EXCEPT
Definition strstream.h:43
Channel transmission data - lightweight DTO for driver transmission.
unsigned char u8
Definition stdint.h:132
fl::u64 u64
Definition s16x16x4.h:221
#define FL_WARN_LIT(LITERAL)
Definition log.h:455
Centralized logging categories for FastLED hardware interfaces and subsystems.
constexpr remove_reference< T >::type && move(T &&t) FL_NO_EXCEPT
Definition move.h:30
unsigned char u8
Definition stdint.h:132
constexpr ChipsetTiming to_runtime_timing() FL_NO_EXCEPT
Convert enum-based timing type to runtime ChipsetTiming struct.
Definition led_timing.h:616
ChipsetTiming4Phase make4PhaseTiming(const ChipsetTiming &timing_3phase, u32 tolerance_ns) FL_NO_EXCEPT
Create 4-phase RX timing from 3-phase chipset timing with tolerance.
Definition rx.cpp.hpp:78
void serial_begin(u32 baudRate) FL_NO_EXCEPT
@ Low
Logic low (0V / GND)
Definition pin.h:51
@ High
Logic high (3.3V / 5V, platform-dependent)
Definition pin.h:52
fl::variant< ClocklessChipset, SpiChipsetConfig > ChipsetVariant
Definition config.h:157
const char * pinProbeSkipReason(int pin) FL_NO_EXCEPT
Why a probe must not touch pin at all (no pinMode, read or write), or nullptr when it may.
constexpr ClocklessChipset makeClockless(int pin) FL_NO_EXCEPT
Build a ClocklessChipset from a compile-time TIMING trait.
Definition config.h:95
fl::u64 u64
Definition s16x16x4.h:221
void digitalWrite(int pin, PinValue val) FL_NO_EXCEPT
Write digital value to pin.
Definition pin.cpp.hpp:51
PinValue digitalRead(int pin) FL_NO_EXCEPT
Read digital value from pin.
Definition pin.cpp.hpp:55
@ Output
Digital output (push-pull)
Definition pin.h:44
@ Input
Digital input (high impedance)
Definition pin.h:43
@ InputPullup
Digital input with internal pull-up resistor.
Definition pin.h:45
@ InputPulldown
Digital input with internal pull-down resistor.
Definition pin.h:46
void pinMode(int pin, PinMode mode) FL_NO_EXCEPT
Set pin mode (input, output, pull-up, pull-down)
Definition pin.cpp.hpp:398
unsigned char uint8_t
Definition s16x16x4.h:209
Base definition for an LED controller.
4-phase RX timing thresholds for chipset detection
Definition rx.h:88
Primary template — intentionally undefined.
Definition bus_traits.h:31
corkscrew_args args
Definition old.h:149
Platform-neutral "may a pin probe touch this pin?" API.
Public re-export of the LPC SCT-capture RX driver (FastLED#3015).
#define FL_DISABLE_WARNING(warning)
#define FL_DISABLE_WARNING_PUSH
#define FL_NO_INLINE
#define FL_DISABLE_WARNING_POP
#define FL_NO_EXCEPT
#define FL_NO_RETURN
u32 ns
Duration in nanoseconds (31 bits, max ~2.1s)
Definition rx.h:35
Universal edge timing representation (platform-agnostic)
Definition rx.h:34
Value state
Current driver state.
Definition driver.h:177
@ READY
Hardware idle; ready to accept new transmissions.
Definition driver.h:171
size_t buffer_size
Buffer size in symbols/edges (default: 512)
Definition rx.h:225
bool start_low
Pin idle state: true=LOW (WS2812B), false=HIGH (inverted)
Definition rx.h:232
Configuration for RX device initialization.
Definition rx.h:223
Compile-time timing extraction from ChipsetTiming structs.
Unified cross-platform Watchdog Timer API for FastLED.