FastLED 3.10.10
Loading...
Searching...
No Matches
AutoResearchTest.cpp
Go to the documentation of this file.
1// AutoResearchTest.cpp - Generic LED autoresearch testing infrastructure
2// Driver-agnostic test function implementations
3
4// Gate out under low-memory mode -- this file pulls in <FastLED.h> and
5// the full chipset / encoder matrix (UCS7604, wave3, pixel iterators).
6// LowMemory targets don't use those (their RPC surface is in
7// AutoResearchLowMemory.h, which only uses fl::Remote + the LPC SCT
8// driver). Matches the conditional structure in AutoResearch.ino itself.
10#if FL_PLATFORM_HAS_LARGE_MEMORY
11
12#include "AutoResearchTest.h"
13
14#include "platforms/arm/rp/is_rp.h"
15#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
16// kRpPioRxEdgeCapacity bounds the static DMA/edge pool the RP PIO RX device
17// writes into; the capture request must never exceed it.
18#include "platforms/arm/rp/rpcommon/rx_pio_channel.h" // IWYU pragma: keep
19#endif
20#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
21#include "fl/stl/atomic.h"
22#include "fl/stl/isr.h"
23// lastActualBaud() identifies the UART geometry the transmitter actually ran,
24// which is what the capture has to be decoded against.
25#include "platforms/arm/rp/rpcommon/rp_uart_bus_traits.h"
26#endif
29#include "platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_diagnostics.h"
30#include <FastLED.h>
31#include "fl/stl/cstdio.h"
32#include "fl/stl/chrono.h"
33#include "fl/system/delay.h"
34#include "fl/stl/sstream.h"
36
37// PR #3421 framework-hang fix:
38// FL_WARN expansion ALWAYS constructs `fl::sstream() << X` regardless
39// of log level -- `fl::ScopedLogDisable` only suppresses OUTPUT inside
40// `log_emit`. Under autoresearch's RPC ASYNC handler (which wraps the
41// test in ScopedLogDisable), the cumulative `fl::sstream`/`fl::string`
42// heap alloc/free cycles across this file's many FL_WARN sites leave
43// the Teensy 4 heap in a state where a later function-exit destructor
44// of a heap-backed fl::string hangs indefinitely (~80% of runs on
45// LPUART, FlexIO, and ObjectFLED autoresearch tests).
46//
47// AR_FL_WARN gates the FL_WARN expansion at log level so the sstream
48// is never constructed when output is suppressed. Used for every
49// FL_WARN in this file. Marker-narrowed investigation confirmed the
50// fix moves LPUART from ~1/5 success to 5/5 -- see session research.
51#define AR_FL_WARN(...) do { \
52 if (fl::getLogLevel() >= static_cast<fl::u8>(fl::LogLevel::FL_LOG_LEVEL_WARN)) { \
53 FL_WARN(__VA_ARGS__); \
54 } \
55} while (0)
59#include "fl/channels/wave3.h"
61#include "fl/math/ease.h"
62#include "pixel_controller.h"
63#include "color.h"
64#include "fl/stl/vector.h"
65#include "fl/stl/iterator.h"
66
67#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
68void countRpPioRxRisingEdges(void* user_data) {
69 auto* edges = static_cast<fl::atomic_int*>(user_data);
70 if (edges != nullptr) {
71 edges->fetch_add(1);
72 }
73}
74#endif
75
76// Phase 0: Include PARLIO debug instrumentation
77#if defined(ESP32) && FASTLED_ESP32_HAS_PARLIO
78#include "platforms/esp/32/drivers/parlio/channel_driver_parlio.h"
79#endif
80
85void dumpRawEdgeTiming(fl::shared_ptr<fl::RxChannel> rx_channel,
86 const fl::ChipsetTimingConfig& timing,
87 fl::EdgeRange range) {
88 if (!rx_channel) {
89 AR_FL_WARN("[RAW EDGE TIMING] ERROR: RX channel is null");
90 return;
91 }
92
93 // Heap-allocated edge buffer (was a 2 KB FixedVector on the stack —
94 // the capture path already runs the loopTask close to its limit,
95 // FastLED#3569).
97 size_t buffer_size = range.count < 256 ? range.count : 256;
98 edges.resize(buffer_size); // Default initializes to EdgeTime()
99
100 // Get edges starting at offset
101 size_t edge_count = rx_channel->getRawEdgeTimes(edges, range.offset);
102
103 if (edge_count == 0) {
104 AR_FL_WARN("[RAW EDGE TIMING] WARNING: No edge data captured at offset " << range.offset);
105 return;
106 }
107
108 // Calculate actual range printed (start from offset)
109 size_t start_idx = range.offset;
110 size_t end_idx = range.offset + edge_count;
111
112 // Single-line collated edge dump. Was one FL_WARN per edge (~32-256
113 // lines per call) which dominated the Teensy 4 UART TX FIFO on every
114 // decode-failure path. Compact format keeps the diagnostic value
115 // (each edge as `H580` or `L640`) while shipping in a single WS
116 // frame. See fbuild#755 follow-up FL_WARN audit.
117 {
118 fl::sstream edge_dump;
119 edge_dump << "[RAW EDGES " << start_idx << ".." << (end_idx - 1) << "]";
120 for (size_t i = 0; i < edge_count; i++) {
121 edge_dump << " " << (edges[i].high ? "H" : "L") << edges[i].ns;
122 }
123 AR_FL_WARN(edge_dump.str());
124 }
125
126 // Pattern analysis (only if showing edges from start)
127 if (range.offset == 0 && edge_count >= 16) {
128 // Calculate expected timings from config (3-phase to 4-phase conversion)
129 uint32_t expected_bit0_high = timing.t1_ns;
130 uint32_t expected_bit0_low = timing.t2_ns + timing.t3_ns;
131 uint32_t expected_bit1_high = timing.t1_ns + timing.t2_ns;
132 uint32_t expected_bit1_low = timing.t3_ns;
133
134 const uint32_t tolerance = 150;
135
136 bool has_short_high = false, has_long_high = false;
137 bool has_short_low = false, has_long_low = false;
138
139 for (size_t i = 0; i < edge_count; i++) {
140 uint32_t ns = edges[i].ns;
141 if (edges[i].high) {
142 if (ns >= expected_bit0_high - tolerance && ns <= expected_bit0_high + tolerance)
143 has_short_high = true;
144 if (ns >= expected_bit1_high - tolerance && ns <= expected_bit1_high + tolerance)
145 has_long_high = true;
146 } else {
147 if (ns >= expected_bit1_low - tolerance && ns <= expected_bit1_low + tolerance)
148 has_short_low = true;
149 if (ns >= expected_bit0_low - tolerance && ns <= expected_bit0_low + tolerance)
150 has_long_low = true;
151 }
152 }
153
154 fl::sstream ss;
155 ss << "\n[RAW EDGE TIMING] Pattern Analysis:\n";
156 ss << " Short HIGH (~" << expected_bit0_high << "ns, Bit 0): " << (has_short_high ? "FOUND ✓" : "MISSING ✗") << "\n";
157 ss << " Long HIGH (~" << expected_bit1_high << "ns, Bit 1): " << (has_long_high ? "FOUND ✓" : "MISSING ✗") << "\n";
158 ss << " Short LOW (~" << expected_bit1_low << "ns, Bit 1): " << (has_short_low ? "FOUND ✓" : "MISSING ✗") << "\n";
159 ss << " Long LOW (~" << expected_bit0_low << "ns, Bit 0): " << (has_long_low ? "FOUND ✓" : "MISSING ✗");
160 AR_FL_WARN(ss.str());
161
162 if (has_short_high && has_long_high && has_short_low && has_long_low) {
163 AR_FL_WARN("\n[RAW EDGE TIMING] ✓ Encoder appears to be working correctly (varied timing patterns)");
164 } else if (!has_short_high && !has_long_high) {
165 ss.clear();
166 ss << "[RAW EDGE TIMING] ✗ ENCODER BROKEN: No valid HIGH pulses detected!\n";
167 ss << "[RAW EDGE TIMING] Possible causes:\n";
168 ss << "[RAW EDGE TIMING] 1. Encoder not reading pixel buffer data\n";
169 ss << "[RAW EDGE TIMING] 2. Bytes encoder state machine stuck\n";
170 ss << "[RAW EDGE TIMING] 3. Data pointer not passed correctly to encoder";
171 FL_ERROR(ss.str());
172 } else if (!has_short_low && !has_long_low) {
173 // Use FL_WARN to avoid triggering bash autoresearch early exit
174 AR_FL_WARN("[RAW EDGE TIMING] ✗ ENCODER BROKEN: No valid LOW pulses detected!");
175 } else {
176 AR_FL_WARN("[RAW EDGE TIMING] ⚠ Partial pattern match - encoder may have issues");
177 }
178 }
179 AR_FL_WARN("");
180}
181
183static bool isUCS7604(fl::ClocklessEncoder encoder) {
187}
188
189static bool legacyLaneUsesRgbw(const fl::AutoResearchConfig& config,
190 fl::size lane) {
191 if (config.legacy_rgbw) {
192 return true;
193 }
194 return lane < config.legacy_chipsets.size() &&
196 config.legacy_chipsets[lane]);
197}
198
199static fl::vector<uint8_t> buildExpectedClockless(
200 fl::span<CRGB> leds, bool rgbw) {
202 leds.data(), static_cast<int>(leds.size()),
204 PixelIterator iterator = pixels.as_iterator(
206 fl::vector<uint8_t> expected;
207 iterator.writeWS2812(&expected);
208 return expected;
209}
210
215static fl::vector<uint8_t> buildExpectedUCS7604(fl::span<CRGB> leds, fl::ClocklessEncoder encoder) {
216 fl::vector<uint8_t> expected;
217
218 // Map encoder to UCS7604Mode
219 fl::UCS7604Mode mode;
220 switch (encoder) {
223 break;
226 break;
229 break;
230 default:
231 return expected;
232 }
233
234 // Default current control (0x0F for all channels) matching channel.cpp.hpp defaults
235 fl::UCS7604CurrentControl current; // defaults to 0xF for all channels
236
237 // Create PixelIterator from LED data (RGB order, no color adjustment, no dithering)
239 auto pixel_iter = pc.as_iterator(RgbwInvalid());
240
241 // For 16-bit modes, use default gamma 2.8
243 bool use_gamma = (mode != fl::UCS7604Mode::UCS7604_MODE_8BIT_800KHZ);
244 if (use_gamma) {
246 }
247
248 // Encode using the same function the driver uses
249 fl::encodeUCS7604(pixel_iter, leds.size(), fl::back_inserter(expected),
250 mode, current, false /* is_rgbw */, gamma.get());
251
252 return expected;
253}
254
255// Decode SPI bit stream from raw RMT edges into LED RGB bytes
256// The SPI data pin carries APA102 encoded data clocked by PCLK.
257// RMT RX captures edges on the data pin. Each edge duration / bit_period_ns
258// gives the number of consecutive same-value bits.
259// Returns number of LED RGB bytes written to rx_buffer, or 0 on error.
260static size_t decodeSpiEdges(fl::shared_ptr<fl::RxChannel> rx_channel,
261 fl::span<uint8_t> rx_buffer,
262 uint32_t clock_hz) {
263 if (!rx_channel || clock_hz == 0) {
264 AR_FL_WARN("[SPI DECODE] Invalid parameters");
265 return 0;
266 }
267
268 const uint32_t bit_period_ns = static_cast<uint32_t>(1000000000ULL / clock_hz);
269 const uint32_t half_bit_ns = bit_period_ns / 2;
270 AR_FL_WARN("[SPI DECODE] clock=" << clock_hz << " Hz, bit_period=" << bit_period_ns << " ns");
271
272 // Read raw edges (up to 4096 to handle large strips)
273 constexpr size_t MAX_EDGES = 4096;
274 fl::vector<fl::EdgeTime> edges(MAX_EDGES);
275 fl::span<fl::EdgeTime> edge_span(edges.data(), edges.size());
276 size_t edge_count = rx_channel->getRawEdgeTimes(edge_span, 0);
277
278 if (edge_count == 0) {
279 AR_FL_WARN("[SPI DECODE] No edges captured");
280 return 0;
281 }
282 AR_FL_WARN("[SPI DECODE] Captured " << edge_count << " edges");
283
284 // Reconstruct bit stream from edges
285 // Each edge has a level (high/low) and duration in ns.
286 // Number of bits = round(duration_ns / bit_period_ns)
288 bits.reserve(edge_count * 4); // Rough estimate
289
290 for (size_t i = 0; i < edge_count; i++) {
291 uint32_t duration = edges[i].ns;
292 uint32_t num_bits = (duration + half_bit_ns) / bit_period_ns;
293 if (num_bits == 0) num_bits = 1; // At least 1 bit per edge
294 uint8_t bit_val = edges[i].high ? 1 : 0;
295 for (uint32_t b = 0; b < num_bits; b++) {
296 bits.push_back(bit_val);
297 }
298 }
299
300 AR_FL_WARN("[SPI DECODE] Reconstructed " << bits.size() << " bits");
301
302 if (bits.size() < 32) {
303 AR_FL_WARN("[SPI DECODE] Too few bits for APA102 frame");
304 return 0;
305 }
306
307 // Convert bits to bytes (MSB first)
308 size_t total_bytes = bits.size() / 8;
309 fl::vector<uint8_t> raw_bytes(total_bytes);
310 for (size_t i = 0; i < total_bytes; i++) {
311 uint8_t byte_val = 0;
312 for (int bit = 7; bit >= 0; bit--) {
313 size_t bit_idx = i * 8 + (7 - bit);
314 if (bit_idx < bits.size() && bits[bit_idx]) {
315 byte_val |= (1 << bit);
316 }
317 }
318 raw_bytes[i] = byte_val;
319 }
320
321 AR_FL_WARN("[SPI DECODE] Decoded " << total_bytes << " raw bytes");
322
323 // Log first few bytes for debugging
324 {
325 fl::sstream dbg;
326 dbg << "[SPI DECODE] First bytes:";
327 size_t show = total_bytes < 20 ? total_bytes : 20;
328 for (size_t i = 0; i < show; i++) {
329 dbg << " 0x";
330 uint8_t hi = raw_bytes[i] >> 4;
331 uint8_t lo = raw_bytes[i] & 0xF;
332 dbg << (char)(hi < 10 ? '0' + hi : 'A' + hi - 10);
333 dbg << (char)(lo < 10 ? '0' + lo : 'A' + lo - 10);
334 }
335 AR_FL_WARN(dbg.str());
336 }
337
338 // Find APA102 start frame (4 bytes of 0x00)
339 // The RMT may not capture the start frame since it's all zeros and
340 // the idle state is also LOW. In that case, the first captured data
341 // is the first LED frame header (0xE0 | brightness).
342 size_t data_start = 0;
343
344 // Check if we captured the start frame
345 if (total_bytes >= 4 && raw_bytes[0] == 0x00 && raw_bytes[1] == 0x00 &&
346 raw_bytes[2] == 0x00 && raw_bytes[3] == 0x00) {
347 data_start = 4; // Skip start frame
348 AR_FL_WARN("[SPI DECODE] Found start frame at offset 0");
349 } else {
350 // No start frame captured (RMT started at first edge = first HIGH bit)
351 // First byte should be 0xE0|brightness or 0xFF
352 AR_FL_WARN("[SPI DECODE] No start frame (first edge = first LED data)");
353 }
354
355 // Extract LED RGB data from APA102 frames
356 // Each LED: [0xE0|brightness] [color0] [color1] [color2] (4 bytes)
357 // With EOrder=RGB in the validation config, the wire order after the
358 // brightness header is [R, G, B] — we copy these directly to rx_buffer.
359 // NOTE: The APA102 end frame (all 0xFF) also has (0xFF & 0xE0) == 0xE0,
360 // so we cannot distinguish end frame from a max-brightness LED purely
361 // from the header byte. We stop after we've exhausted captured data.
362 size_t led_bytes_written = 0;
363 size_t pos = data_start;
364
365 while (pos + 4 <= total_bytes) {
366 uint8_t header = raw_bytes[pos];
367
368 // Check for valid LED frame header (top 3 bits must be 111)
369 if ((header & 0xE0) != 0xE0) {
370 AR_FL_WARN("[SPI DECODE] End of LED data at byte " << pos
371 << " (header=0x" << ((header >> 4) < 10 ? '0' + (header >> 4) : 'A' + (header >> 4) - 10)
372 << ((header & 0xF) < 10 ? '0' + (header & 0xF) : 'A' + (header & 0xF) - 10) << ")");
373 break;
374 }
375
376 uint8_t c0 = raw_bytes[pos + 1];
377 uint8_t c1 = raw_bytes[pos + 2];
378 uint8_t c2 = raw_bytes[pos + 3];
379
380 if (led_bytes_written + 3 <= rx_buffer.size()) {
381 rx_buffer[led_bytes_written + 0] = c0;
382 rx_buffer[led_bytes_written + 1] = c1;
383 rx_buffer[led_bytes_written + 2] = c2;
384 led_bytes_written += 3;
385 } else {
386 AR_FL_WARN("[SPI DECODE] rx_buffer full at LED " << (led_bytes_written / 3));
387 break;
388 }
389 pos += 4;
390 }
391
392 size_t num_leds = led_bytes_written / 3;
393 AR_FL_WARN("[SPI DECODE] Extracted " << num_leds << " LEDs (" << led_bytes_written << " RGB bytes)");
394 return led_bytes_written;
395}
396
397// Collect expensive raw-edge evidence only for a failed run. The normal RPC
398// soak path must remain allocation-quiet, but a failed decode or byte compare
399// still needs the same postmortem snapshot as a failed RX wait.
400void collectRawEdgeDiagnostics(fl::shared_ptr<fl::RxChannel> rx_channel,
401 fl::RunResult* diagnostics) {
402 if (!rx_channel || !diagnostics || !diagnostics->rawEdgeSample.empty()) {
403 return;
404 }
405
407 edges.resize(256);
408 diagnostics->rawEdgesAfterWait =
409 static_cast<int>(rx_channel->getRawEdgeTimes(edges, 0));
410
411 fl::vector<fl::EdgeTime> sample_edges;
412 sample_edges.resize(32);
413 const size_t sample_count = rx_channel->getRawEdgeTimes(sample_edges, 0);
415 for (size_t i = 0; i < sample_count; ++i) {
416 if (i > 0) {
417 sample << ' ';
418 }
419 sample << (sample_edges[i].high ? 'H' : 'L') << sample_edges[i].ns;
420 }
421 diagnostics->rawEdgeSample = sample.str();
422}
423
424// Resolve the UART wire geometry the RX decoder must match.
425//
426// Take the geometry the engine recorded when it transmitted, rather than
427// re-deriving it. Which geometry gets chosen depends on the backend's
428// *maximum* baud, not on anything visible here, and the achieved baud is the
429// wrong input: it is allowed to sit up to 1% under the requested one, and fed
430// back as a ceiling that shortfall makes the transmitted geometry look
431// infeasible and selects the other. Re-deriving from the generic ceiling is
432// the fallback for backends that do not report one.
433static fl::ChipsetTiming resolveUartWireTiming(const fl::ChipsetTimingConfig& timing,
434 const char* driver_name) {
435 (void)driver_name;
436 fl::ChipsetTiming uart_timing{0, 0, 0, 0, nullptr};
437#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
438 if (fl::strcmp(driver_name, "UART0") == 0) {
439 uart_timing =
441 } else if (fl::strcmp(driver_name, "UART1") == 0) {
442 uart_timing =
444 }
445#endif
446 if (uart_timing.T1 == 0) {
447 // uartWireTiming() carries timing.reset_us and names the result
448 // "uart_wire", so nothing further needs setting here.
449 uart_timing = fl::uartWireTiming(timing, fl::kMaxUartBaudRate);
450 }
451 return uart_timing;
452}
453
454// Build the 4-phase RX decode thresholds for a TX driver's waveform.
455static fl::ChipsetTiming4Phase buildRxDecodeTiming(const fl::ChipsetTimingConfig& timing,
456 const char* driver_name) {
457 // Create 4-phase RX timing from the TX timing
458 //
459 // Wave8 drivers (SPI, PARLIO, I2S) use 8-bit expansion encoding:
460 // Bit 0: round(T1/(T1+T2+T3)*8) HIGH pulses, rest LOW
461 // Bit 1: round((T1+T2)/(T1+T2+T3)*8) HIGH pulses, rest LOW
462 // The actual pulse widths are quantized to tick boundaries, so we must
463 // compute the exact wave8 timing for RX decode thresholds.
464 // Without this correction, the RX decoder may reject valid waveforms when
465 // the nominal timing period differs from the quantized 8-tick period.
466 // Example: WS2812_800KHZ has T0L=1000ns nominal but PARLIO wave8 produces 750ns.
467 //
468 // Clock sources differ by driver:
469 // SPI/I2S: clock = 8/(T1+T2+T3) Hz, tick = (T1+T2+T3)/8 ns (variable)
470 // PARLIO: clock = 8 MHz fixed, tick = 125 ns (fixed)
471 bool is_spi_driver = (fl::strcmp(driver_name, "SPI") == 0);
472 bool is_parlio_driver = (fl::strcmp(driver_name, "PARLIO") == 0);
473 bool is_i2s_driver = (fl::strcmp(driver_name, "I2S") == 0);
474 // LCD_CLOCKLESS auto-selects wave3 vs wave8 based on canUseWave3() of the
475 // chipset timing. Compute the same eligibility check on the host side so
476 // the RX decoder reconstructs the correct quantized waveform.
477 bool is_lcd_clockless_driver = (fl::strcmp(driver_name, "LCD_CLOCKLESS") == 0);
478 bool lcd_clockless_uses_wave3 = false;
479 if (is_lcd_clockless_driver) {
480 fl::ChipsetTiming probe{timing.t1_ns, timing.t2_ns, timing.t3_ns, timing.reset_us, timing.name};
481 lcd_clockless_uses_wave3 = fl::canUseWave3(probe);
482 }
483 bool uses_wave8 = is_spi_driver || is_parlio_driver || is_i2s_driver
484 || (is_lcd_clockless_driver && !lcd_clockless_uses_wave3);
485 bool uses_wave3 = is_lcd_clockless_driver && lcd_clockless_uses_wave3;
486 fl::ChipsetTiming tx_timing;
487 if (uses_wave8) {
488 // Compute actual wave8 timing from chipset timing
489 const uint32_t period = timing.t1_ns + timing.t2_ns + timing.t3_ns;
490 // PARLIO uses fixed 8MHz clock (125ns/tick), not derived from period
491 // SPI/I2S/LCD_CLOCKLESS derive clock from period: tick = period/8
492 const uint32_t tick_ns = is_parlio_driver ? 125 : (period / 8);
493 // Wave8 LUT computes: pulses = round(fraction * 8)
494 const uint32_t pulses_bit0 = static_cast<uint32_t>(
495 static_cast<float>(timing.t1_ns) / period * 8.0f + 0.5f);
496 const uint32_t pulses_bit1 = static_cast<uint32_t>(
497 static_cast<float>(timing.t1_ns + timing.t2_ns) / period * 8.0f + 0.5f);
498 // Convert back to 3-phase timing (T1=T0H, T2=T1H-T0H, T3=actual_period-T1H)
499 const uint32_t actual_t0h = pulses_bit0 * tick_ns;
500 const uint32_t actual_t1h = pulses_bit1 * tick_ns;
501 const uint32_t actual_period = 8 * tick_ns;
502 const char* wave8_name = is_spi_driver ? "SPI_wave8" :
503 is_parlio_driver ? "PARLIO_wave8" :
504 is_lcd_clockless_driver ? "LCD_CLOCKLESS_wave8" : "I2S_wave8";
505 tx_timing = fl::ChipsetTiming{
506 actual_t0h, // T1 = T0H
507 actual_t1h - actual_t0h, // T2 = T1H - T0H
508 actual_period - actual_t1h, // T3 = actual_period - T1H
509 timing.reset_us,
510 wave8_name
511 };
512 AR_FL_WARN("[RX TIMING] " << wave8_name << ": pulses_bit0=" << pulses_bit0
513 << " pulses_bit1=" << pulses_bit1
514 << " tick_ns=" << tick_ns
515 << " -> T1=" << tx_timing.T1 << " T2=" << tx_timing.T2
516 << " T3=" << tx_timing.T3);
517 } else if (uses_wave3) {
518 // Wave3 encoding: 3 ticks per LED bit, clock = 3/(T1+T2+T3) Hz
519 const uint32_t period = timing.t1_ns + timing.t2_ns + timing.t3_ns;
520 const uint32_t tick_ns = period / 3;
521 const uint32_t ticks_bit0 = static_cast<uint32_t>(
522 static_cast<float>(timing.t1_ns) / period * 3.0f + 0.5f);
523 const uint32_t ticks_bit1 = static_cast<uint32_t>(
524 static_cast<float>(timing.t1_ns + timing.t2_ns) / period * 3.0f + 0.5f);
525 const uint32_t actual_t0h = ticks_bit0 * tick_ns;
526 const uint32_t actual_t1h = ticks_bit1 * tick_ns;
527 const uint32_t actual_period = 3 * tick_ns;
528 tx_timing = fl::ChipsetTiming{
529 actual_t0h,
530 actual_t1h - actual_t0h,
531 actual_period - actual_t1h,
532 timing.reset_us,
533 "LCD_CLOCKLESS_wave3"
534 };
535 AR_FL_WARN("[RX TIMING] LCD_CLOCKLESS_wave3: ticks_bit0=" << ticks_bit0
536 << " ticks_bit1=" << ticks_bit1
537 << " tick_ns=" << tick_ns
538 << " -> T1=" << tx_timing.T1 << " T2=" << tx_timing.T2
539 << " T3=" << tx_timing.T3);
540 } else {
541 tx_timing = fl::ChipsetTiming{timing.t1_ns, timing.t2_ns, timing.t3_ns, timing.reset_us, timing.name};
542 }
543 // Wave8/wave3 encoding has timing jitter due to clock quantization and GPIO matrix latency
544 // Use wider tolerance (200ns) to accommodate clock rounding
545 const uint32_t tolerance = (uses_wave8 || uses_wave3) ? 200 : 170;
546 auto rx_timing = fl::make4PhaseTiming(tx_timing, tolerance);
547
548 // Enable gap tolerance for PARLIO/SPI DMA gaps
549 // PARLIO: ~20µs typical gaps during buffer transitions
550 // SPI: Can have longer inter-frame gaps due to software encoding timing
551 // Increased to 100µs to accommodate SPI driver timing variations
552 rx_timing.gap_tolerance_ns = 100000; // 100µs (was 30µs)
553 return rx_timing;
554}
555
556// Capture transmitted LED data via RX loopback
557// - rx_channel: Shared pointer to RX device (persistent across calls)
558// - rx_buffer: Buffer to store received bytes
559// - expected_data_bytes: bytes in the current frame
560// - tx_pin: GPIO driven by the tested TX controller
561// - timing: Chipset timing configuration for RX decoder
562// - driver_name: Name of the TX driver being tested (e.g., "RMT", "PARLIO")
563// Returns number of bytes captured, or 0 on error
564size_t capture(fl::shared_ptr<fl::RxChannel> rx_channel,
565 fl::span<uint8_t> rx_buffer,
566 size_t expected_data_bytes,
567 int tx_pin,
568 const fl::ChipsetTimingConfig& timing,
569 const char* driver_name,
570 fl::RunResult* diagnostics) {
571 // The RPC runner disables log output for normal tests. Keep successful
572 // captures allocation-quiet too: constructing diagnostic strings and
573 // copying edge snapshots on every frame defeats that guard during a
574 // repeated-frame soak. Failure paths still collect full evidence below.
575 const bool logs_enabled = fl::getLogLevel() >=
577 if (diagnostics) {
578 diagnostics->captureWaitResult = -1;
579 diagnostics->rawEdgesAfterWait = 0;
580 diagnostics->rpPioGpioTransitions = -1;
581 diagnostics->rxBeginError.clear();
582 }
583
584 if (!rx_channel) {
585 FL_ERROR("RX channel is null");
586 return 0;
587 }
588
589 // Clear RX buffer
590 fl::memset(rx_buffer.data(), 0, rx_buffer.size());
591
592 // Prepare RX config (but don't arm yet to avoid locking TX resources)
593 fl::RxChannelConfig rx_config(rx_channel->getPin());
594 rx_config.hz = 40000000; // 40MHz for high-precision LED timing capture
595
596 // Buffer size: 1 LED byte = 8 bits = 8 RMT symbols
597 // UART with TX inversion produces standard WS2812 waveform, same symbol count
598 bool is_uart_driver = (fl::strcmp(driver_name, "UART") == 0)
599 || (fl::strcmp(driver_name, "LPUART") == 0)
600 || (fl::strcmp(driver_name, "UART0") == 0)
601 || (fl::strcmp(driver_name, "UART1") == 0);
602 bool is_object_fled_driver = (fl::strcmp(driver_name, "OBJECT_FLED") == 0);
603 rx_config.edge_capacity = fl::validation::captureEdgeCapacity(
604 rx_buffer.size(), expected_data_bytes, rx_channel->backend());
605#if defined(FL_IS_TEENSY_4X)
606 // Teensy 4.x FlexPWM RX streams captures through a small DMA ring and
607 // keeps only decoded bytes, so size it to this frame rather than to the
608 // shared result buffer. FlexIO RX still stores edges: leave it alone.
609 if (rx_channel->backend() != fl::RxBackend::FLEXIO) {
610 rx_config.edge_capacity = fl::validation::captureEdgeCapacity(
611 rx_buffer.size(), expected_data_bytes, fl::RxBackend::ISR);
612 }
613#endif
614 if (rx_config.edge_capacity == 0) {
615 FL_ERROR("[CAPTURE] RX edge-capacity overflow");
616 return 0;
617 }
618#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
619 // RP's platform-default RX resolves to PIO, while RxChannel retains the
620 // requested PLATFORM_DEFAULT enum. Recognize both that public default and
621 // an explicit PIO backend so the DMA capture is sized per frame.
622 const bool is_rp_pio_capture =
623 rx_channel->backend() == fl::RxBackend::PLATFORM_DEFAULT ||
624 rx_channel->backend() == fl::RxBackend::PIO ||
625 fl::strcmp(driver_name, "PIO0") == 0 || fl::strcmp(driver_name, "PIO1") == 0 ||
626 fl::strcmp(driver_name, "PIO2") == 0;
627 if (is_rp_pio_capture) {
628 // The shared result buffer is intentionally sized for the largest
629 // AutoResearch run, not this frame. PIO DMA stores one word for each
630 // high and low phase, so using that whole buffer here would request
631 // several MiB on a Pico and leave DMA with an invalid destination.
632 constexpr size_t kPioPhasesPerDataByte = 16;
633 // The guard must cover the headroom multiplier too: checking only
634 // against kPioPhasesPerDataByte would let an oversized byte count
635 // wrap during the *2 below and produce a small `requested` that
636 // sails past the clamp into RpPioRxDevice::begin().
637 constexpr size_t kPioPhaseHeadroomNumerator = 2;
638 constexpr size_t kPioPhasesPerDataByteWithHeadroom =
639 kPioPhasesPerDataByte * kPioPhaseHeadroomNumerator;
640 if (expected_data_bytes >
641 (static_cast<size_t>(-1) - 1u) / kPioPhasesPerDataByteWithHeadroom) {
642 FL_ERROR("[CAPTURE] PIO edge-capacity overflow");
643 return 0;
644 }
645 // 16 phases per byte is a *clean* frame: 8 bits x (high + low). Slower
646 // chipsets exceed it -- a 400 kHz capture overflows and is discarded
647 // (RxWaitResult::BUFFER_OVERFLOW), because long runs do not always
648 // land in one entry. Ask for headroom, then clamp to the static pool
649 // so the request can never exceed the FixedVector backing it:
650 // over-requesting authorises appendDuration() to write past the end.
651 size_t requested =
652 expected_data_bytes * kPioPhasesPerDataByteWithHeadroom + 1u;
653 if (requested > fl::kRpPioRxEdgeCapacity) {
654 requested = fl::kRpPioRxEdgeCapacity;
655 }
656 rx_config.edge_capacity = requested;
657 }
658#endif
659
660 bool is_rmt_driver = (fl::strcmp(driver_name, "RMT") == 0);
661 const int rx_pin = rx_channel->getPin();
662 // ESP-IDF's RMT io_loop_back path requires TX and RX to share one GPIO.
663 // AutoResearch normally discovers a physical TX->RX jumper on two
664 // different pins; enabling io_loop_back in that case disconnects the RX
665 // channel from the external GPIO path and yields a successful wait with
666 // zero edges on ESP32-C6. Keep the ESP32-S3 same-pin workaround, but use
667 // the physical jumper whenever TX and RX are distinct.
668 const bool use_rmt_internal_loopback =
670 is_rmt_driver, tx_pin, rx_pin);
671 rx_config.io_loop_back = use_rmt_internal_loopback;
672 // RX DMA streaming: extends capture past the non-DMA cap by sizing
673 // mem_block_symbols = 14336 so ESP-IDF allocates ~14 DMA descriptor
674 // nodes (each 4092 bytes), yielding a 57 KB user-buffer cap — enough to
675 // capture ~583 WS2812B LEDs in a single rmt_receive() call. Safe for
676 // non-RMT TX paths (SPI, PARLIO, I2S, UART, LCD_*) that don't contend
677 // for the shared ESP32-S3 DMA slot. RMT loopback stays non-DMA.
678 // See issue #2254.
679 rx_config.use_dma = !is_rmt_driver;
680 // Preserve the channel's explicitly-selected capture backend —
681 // RxChannel::begin() recreates the device when the backend field
682 // differs, and this config is built fresh (default =
683 // PLATFORM_DEFAULT), which silently reverted rxBackend overrides
684 // like I2S_RX back to RMT (FastLED#3576 Phase 3).
685 rx_config.backend = rx_channel->backend();
686 // Backends that decode while capturing (Teensy 4.x FlexPWM) need the
687 // decode thresholds up front.
688 //
689 // Stream and decode must share the same thresholds (FastLED#5197,
690 // CodeRabbit on #4723): a backend that classifies bits while capturing
691 // against one timing and is then decoded against another can split a gap
692 // bit differently and report INVALID_ARGUMENT or an inexact stream. So
693 // the UART timing is resolved here, once, and reused by the UART decode.
694 fl::ChipsetTiming uart_timing{0, 0, 0, 0, nullptr};
695 fl::ChipsetTiming4Phase uart_rx_timing{};
696 if (is_uart_driver) {
697 // On RP2040/RP2350 lastWireTiming() read before this frame's TX holds
698 // the previous frame's geometry, or zero on the first frame (then the
699 // uartWireTiming() fallback applies). The chipset timing does not
700 // change between frames, so either answer matches this frame.
701 uart_timing = resolveUartWireTiming(timing, driver_name);
702 if (uart_timing.T1 == 0 && uart_timing.T2 == 0) {
703 // No representable geometry. Decoding against zeros would reject
704 // every symbol and report it as a capture fault; say what it is.
705 AR_FL_WARN("[CAPTURE] UART: no representable wave geometry for "
706 << timing.name);
707 return 0;
708 }
709 // Use wider tolerance (250ns) for UART because the UART clock and RMT
710 // sample clock are asynchronous, and GPIO matrix adds ~10-20ns jitter
711 uart_rx_timing = fl::make4PhaseTiming(uart_timing, 250);
712 uart_rx_timing.gap_tolerance_ns = 100000; // 100µs for UART inter-frame gaps
713 }
714 const fl::ChipsetTiming4Phase rx_timing =
715 is_uart_driver ? uart_rx_timing : buildRxDecodeTiming(timing, driver_name);
716 rx_config.stream_timing = rx_timing;
717 if (use_rmt_internal_loopback) {
718 AR_FL_WARN("[CAPTURE] RMT TX -> RMT RX: Same-pin internal loopback enabled");
719 } else {
720 // The RX peripheral is platform-dependent (RMT on ESP32, FlexPWM on
721 // Teensy 4, LPC_SCT on LPC845, …). Don't claim "RMT RX" on platforms
722 // that have no RMT — that label burned an hour of Teensy-4 debug
723 // (FastLED#3059). Just say "external RX" so the label stays correct
724 // regardless of backend.
725 if (logs_enabled) {
726 AR_FL_WARN("[CAPTURE] " << driver_name
727 << " TX GPIO " << tx_pin << " -> RX GPIO " << rx_pin
728 << ": External jumper "
729 << "(io_loop_back=false, use_dma="
730 << (rx_config.use_dma ? "true" : "false") << ")");
731 }
732 }
733
734 // Driver-aware capture strategy:
735 // - RMT: Two-TX approach (ESP32-S3 workaround - TX GPIO blocked when RX active)
736 // - PARLIO/SPI/other: Single-TX approach (arm RX first, then TX)
737
738 // TX wait timeout: 1 second max per frame - prevents infinite hang if driver stalls
739 // Even a 10000-LED strip at 800kbps takes only ~300ms, so 1s is very safe
740 const uint32_t TX_WAIT_TIMEOUT_MS = 1000;
741
742 if (is_rmt_driver) {
743 // RMT: Two-TX approach for ESP32-S3 compatibility
744 // First TX without RX armed (diagnostics), then arm RX, then second TX
745 if (logs_enabled) {
746 AR_FL_WARN("[CAPTURE] RMT: Two-TX approach (ESP32-S3 workaround)");
747 }
748 FastLED.show();
749 if (!FastLED.wait(TX_WAIT_TIMEOUT_MS)) {
750 FL_ERROR("[CAPTURE] TX wait timeout (pre-arm) - driver may be stalled");
751 return 0;
752 }
753
754 // Arm RX for capture
755 if (!rx_channel->begin(rx_config)) {
756 if (diagnostics) diagnostics->rxBeginError = rx_channel->lastBeginError();
757 FL_ERROR("Failed to arm RX receiver");
758 return 0;
759 }
760 // Second TX with RX armed
761 FastLED.show();
762 if (!FastLED.wait(TX_WAIT_TIMEOUT_MS)) {
763 FL_ERROR("[CAPTURE] TX wait timeout (capture) - driver may be stalled");
764 return 0;
765 }
766 } else {
767 // Non-RMT (PARLIO, SPI, etc.): Single-TX approach
768 if (!rx_channel->begin(rx_config)) {
769 if (diagnostics) diagnostics->rxBeginError = rx_channel->lastBeginError();
770 AR_FL_WARN("[CAPTURE] RX begin() failed for pin " << rx_channel->getPin());
771 return 0;
772 }
773 if (logs_enabled) {
774 AR_FL_WARN("[CAPTURE] RX armed, calling FastLED.show()...");
775 }
776
777#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
778 fl::atomic_int rising_edges(0);
779 fl::isr::handle edge_counter;
780 bool edge_counter_attached = false;
781 const bool measure_rp_pio =
782 (fl::strcmp(driver_name, "PIO0") == 0 || fl::strcmp(driver_name, "PIO1") == 0 ||
783 fl::strcmp(driver_name, "PIO2") == 0) &&
784 diagnostics != nullptr;
785 if (measure_rp_pio) {
786 // FastLED.show() drives the channel engine until it reaches its
787 // terminal state, so polling GPIO after show() is too late to
788 // observe a short clockless frame. Count rising edges through the
789 // shared FastLED ISR dispatcher while show() is running instead.
790 // This is deliberately a binary physical oracle: an IRQ count
791 // above zero proves the jumper carries TX activity, while the PIO
792 // RX backend remains responsible for exact-byte verification.
793 fl::isr::config edge_config;
794 edge_config.handler = countRpPioRxRisingEdges;
795 edge_config.user_data = &rising_edges;
797 edge_counter_attached = fl::isr::attach_external_handler(
798 static_cast<fl::u8>(rx_channel->getPin()), edge_config, &edge_counter) == 0;
799 }
800#endif
801 FastLED.show();
802 if (logs_enabled) {
803 AR_FL_WARN("[CAPTURE] FastLED.show() returned, calling wait...");
804 }
805#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
806 if (edge_counter_attached && edge_counter.is_valid()) {
807 fl::isr::detach_handler(edge_counter);
808 }
809 if ((fl::strcmp(driver_name, "PIO0") == 0 || fl::strcmp(driver_name, "PIO1") == 0 ||
810 fl::strcmp(driver_name, "PIO2") == 0) &&
811 diagnostics != nullptr) {
812 diagnostics->rpPioGpioTransitions = edge_counter_attached ? rising_edges.load() : -1;
813 }
814#endif
815 if (!FastLED.wait(TX_WAIT_TIMEOUT_MS)) {
816 if (is_object_fled_driver) {
817 fl::objectFledDiagnosticsRecord("afterFastLedWaitTimeout");
818 }
819 AR_FL_WARN("[CAPTURE] FastLED.wait() timed out");
820 return 0;
821 }
822 if (is_object_fled_driver) {
823 fl::objectFledDiagnosticsRecord("afterFastLedWait");
824 }
825 if (logs_enabled) {
826 AR_FL_WARN("[CAPTURE] FastLED.wait() done");
827 }
828 }
829
830
831
832
833 // Wait for RX completion
834 // WS2812B: ~30μs per LED → 3000 LEDs = 90ms, use 150ms
835 // UART with inverted TX produces same waveform timing as WS2812
836 const uint32_t rx_wait_ms = is_uart_driver ? 500 : 150;
837 if (logs_enabled) {
838 AR_FL_WARN("[CAPTURE] Waiting for RX completion (" << rx_wait_ms
839 << "ms timeout)...");
840 }
841 auto wait_result = rx_channel->wait(rx_wait_ms);
842 if (diagnostics) {
843 diagnostics->captureWaitResult = static_cast<int>(wait_result);
844 diagnostics->decodeOutputCapacity = static_cast<int>(rx_buffer.size());
845 if (wait_result != fl::RxWaitResult::SUCCESS) {
846 collectRawEdgeDiagnostics(rx_channel, diagnostics);
847 }
848 }
849 if (logs_enabled) {
850 AR_FL_WARN("[CAPTURE] RX wait returned: "
851 << static_cast<int>(wait_result));
852 }
853
854 if (wait_result != fl::RxWaitResult::SUCCESS) {
855 AR_FL_WARN("RX wait failed (timeout or no data received)");
856 fl::sstream ss;
857 ss << "\n⚠️ TROUBLESHOOTING:\n";
858 ss << " 1. Connect physical jumper wire from TX GPIO to RX GPIO " << rx_channel->getPin() << "\n";
859 ss << " 2. Check that both TX and RX pins are correctly configured\n";
860 ss << " 3. Verify the GPIO connection is working (GPIO baseline test should pass)\n";
861 ss << " 4. RMT internal loopback requires TX and RX to use the same GPIO";
862 AR_FL_WARN(ss.str());
863 if (!is_uart_driver) {
864 return 0;
865 }
866 // UART: still attempt decode with captured edges (timeout may be expected)
867 AR_FL_WARN("[CAPTURE] UART: attempting decode with captured edges despite timeout");
868 }
869
870 // UART TX with inversion puts a WS2812-shaped waveform on the wire, but
871 // quantized onto the UART pulse grid -- exactly like the wave8 and wave3
872 // cases handled above, and for the same reason: the decoder has to be told
873 // what the transmitter actually emitted, not what the datasheet says.
874 //
875 // This used to hardcode T0H=250 / T1H=750 / T1L=500, the shape an ESP32
876 // UART produces at 4 Mbps for a WS2812. That is right for one chipset on
877 // one platform and wrong everywhere else. At 400 kHz the real wire is
878 // 625 / 1250 / 1250, every phase of which falls outside those hardcoded
879 // windows -- so a correct frame decoded to nothing. See FastLED#4379.
880 if (is_uart_driver) {
881 AR_FL_WARN("[CAPTURE] UART (inverted TX): using standard WS2812 decoder with UART timing...");
882 // uart_timing / uart_rx_timing were resolved (resolveUartWireTiming())
883 // before RX was armed and already fed rx_config.stream_timing; decode
884 // against the same thresholds (FastLED#5197).
885
886 AR_FL_WARN("[CAPTURE] UART RX timing: T0H=" << uart_timing.T1
887 << " T1H=" << (uart_timing.T1 + uart_timing.T2)
888 << " T0L=" << (uart_timing.T2 + uart_timing.T3)
889 << " T1L=" << uart_timing.T3);
890
891 auto decode_result = rx_channel->decode(uart_rx_timing, rx_buffer);
892 if (!decode_result.ok()) {
893 AR_FL_WARN("[CAPTURE] UART decode failed (error: " << static_cast<int>(decode_result.error()) << ")");
894 // Was EdgeRange(0, 256) -- 257 FL_WARN lines per decode failure
895// drowned the Teensy 4 UART TX FIFO and stalled autoresearch
896// between patterns (fbuild#755). 32 edges is enough to see whether
897// the first transition is a clean bit-0 or a glitch.
898dumpRawEdgeTiming(rx_channel, timing, fl::EdgeRange(0, 32));
899 return 0;
900 }
901 AR_FL_WARN("[CAPTURE] UART decoded " << decode_result.value() << " LED bytes");
902 return decode_result.value();
903 }
904
905 // SPI chipset drivers: decode raw SPI bit stream.
906 // These drivers use platform hardware SPI/I80/I2S to output APA102 data.
907 // RMT RX captures edges on the data pin; clock pin is ignored.
908 bool is_lcd_spi_driver = (fl::strcmp(driver_name, "LCD_SPI") == 0);
909 bool is_i2s_spi_driver = (fl::strcmp(driver_name, "I2S_SPI") == 0);
910 bool is_spi_unified_driver = (fl::strcmp(driver_name, "SPI_UNIFIED") == 0);
911 if (is_lcd_spi_driver || is_i2s_spi_driver || is_spi_unified_driver) {
912 // SPI clock used for validation: 2.4MHz (matches ValidationRemote.cpp)
913 const uint32_t spi_clock_hz = 2400000;
914 AR_FL_WARN("[CAPTURE] SPI chipset decode: clock=" << spi_clock_hz << " Hz");
915 size_t decoded = decodeSpiEdges(rx_channel, rx_buffer, spi_clock_hz);
916 if (decoded == 0) {
917 AR_FL_WARN("[CAPTURE] SPI decode failed");
918 // Was EdgeRange(0, 256) -- 257 FL_WARN lines per decode failure
919// drowned the Teensy 4 UART TX FIFO and stalled autoresearch
920// between patterns (fbuild#755). 32 edges is enough to see whether
921// the first transition is a clean bit-0 or a glitch.
922dumpRawEdgeTiming(rx_channel, timing, fl::EdgeRange(0, 32));
923 }
924 return decoded;
925 }
926
927 // Decode received data directly into rx_buffer (rx_timing built above).
928
929 AR_FL_WARN("[CAPTURE] Decoding...");
930 auto decode_result = rx_channel->decode(rx_timing, rx_buffer);
931 if (diagnostics) {
932 diagnostics->decodeOk = decode_result.ok() ? 1 : 0;
933 diagnostics->decodeError =
934 decode_result.ok() ? -1 : static_cast<int>(decode_result.error());
935 diagnostics->decodeBytes =
936 decode_result.ok() ? static_cast<int>(decode_result.value()) : 0;
937 }
938
939 if (!decode_result.ok()) {
940 // Use FL_WARN instead of FL_ERROR to avoid triggering bash autoresearch exit
941 // This can happen during warmup/setup and is not fatal
942 AR_FL_WARN("Decode failed (error code: " << static_cast<int>(decode_result.error()) << ")");
943 // Print raw edge timing on decode failure to diagnose the issue
944 // Was EdgeRange(0, 256) -- 257 FL_WARN lines per decode failure
945// drowned the Teensy 4 UART TX FIFO and stalled autoresearch
946// between patterns (fbuild#755). 32 edges is enough to see whether
947// the first transition is a clean bit-0 or a glitch.
948dumpRawEdgeTiming(rx_channel, timing, fl::EdgeRange(0, 32));
949 return 0;
950 }
951
952 AR_FL_WARN("[CAPTURE] Decoded " << decode_result.value() << " bytes");
953 return decode_result.value();
954}
955
956// Generic driver-agnostic autoresearch test runner
957// Tests all channels using the specified configuration
958void runTest(const char* test_name,
960 int& total, int& passed) {
961 // Multi-lane limitation: Only test Lane 0 (first channel)
962 // Hardware constraint: Only one TX channel can be read from via RX loopback
963 size_t channels_to_test = config.tx_configs.size() > 1 ? 1 : config.tx_configs.size();
964
965 if (config.tx_configs.size() > 1) {
966 AR_FL_WARN("\n[MULTI-LANE] Testing " << config.tx_configs.size() << " lanes, testing Lane 0 only (hardware limitation)");
967 }
968
969 // Test enabled configs (Lane 0 only for multi-lane)
970 for (size_t config_idx = 0; config_idx < channels_to_test; config_idx++) {
971 total++;
972
973 // Build test context for detailed error reporting
974 const auto& leds = config.tx_configs[config_idx].mLeds;
975 size_t num_leds = leds.size();
976 const bool lane_uses_rgbw =
977 legacyLaneUsesRgbw(config, config_idx);
978 // UCS7604 puts a 15-byte preamble and 16-bit channels on the wire, so
979 // its frame runs several times the pixel byte count. This number sizes
980 // the RX edge capacity as well as the comparison below, so deriving it
981 // from the pixel count truncates the capture (FastLED#4373).
982 const bool lane_uses_ucs7604 = isUCS7604(config.encoder);
983 fl::vector<uint8_t> expected_encoded;
984 if (lane_uses_ucs7604) {
985 expected_encoded = buildExpectedUCS7604(
986 config.tx_configs[config_idx].mLeds, config.encoder);
987 }
988 const size_t expected_data_bytes =
989 lane_uses_ucs7604 ? expected_encoded.size()
990 : num_leds * (lane_uses_rgbw ? 4u : 3u);
991
992 fl::TestContext ctx{
993 config.driver_name,
994 config.timing_name,
995 fl::toString(config.rx_type),
996 test_name,
997 static_cast<int>(config.tx_configs.size()),
998 static_cast<int>(config_idx),
999 config.base_strip_size,
1000 static_cast<int>(num_leds),
1001 config.tx_configs[config_idx].getDataPin()
1002 };
1003
1004 AR_FL_WARN("\n=== " << test_name << " [Lane " << config_idx << "/" << config.tx_configs.size()
1005 << ", Pin " << config.tx_configs[config_idx].getDataPin()
1006 << ", LEDs " << config.tx_configs[config_idx].mLeds.size() << "] ===");
1007
1008 // Use RX channel provided via config (created in .ino file, never created dynamically here)
1009 if (!config.rx_channel) {
1010 FL_ERROR("[" << ctx.driver_name << "/" << ctx.timing_name << "/" << ctx.pattern_name
1011 << " | Lane " << ctx.lane_index << "/" << ctx.lane_count
1012 << " (Pin " << ctx.pin_number << ", " << ctx.num_leds << " LEDs) | RX:" << ctx.rx_type_name << "] "
1013 << "RX channel is null - must be created in .ino and passed via AutoResearchConfig");
1014 FL_ERROR("Result: FAIL ✗ (RX channel not provided)");
1015 continue;
1016 }
1017
1018 size_t bytes_captured = capture(config.rx_channel, config.rx_buffer,
1019 expected_data_bytes,
1020 config.tx_configs[config_idx].getDataPin(),
1021 config.timing, config.driver_name);
1022
1023 if (bytes_captured == 0) {
1024 FL_ERROR("[" << ctx.driver_name << "/" << ctx.timing_name << "/" << ctx.pattern_name
1025 << " | Lane " << ctx.lane_index << "/" << ctx.lane_count
1026 << " (Pin " << ctx.pin_number << ", " << ctx.num_leds << " LEDs) | RX:" << ctx.rx_type_name << "] "
1027 << "Result: FAIL ✗ (capture failed)");
1028 continue;
1029 }
1030
1031 int mismatches = 0;
1032
1033 if (lane_uses_ucs7604) {
1034 // UCS7604: Compare full encoded frame (preamble + padding + pixel data) byte-for-byte
1035 size_t expected_len = expected_encoded.size();
1036
1037 AR_FL_WARN("UCS7604 encoded comparison: expected " << expected_len << " bytes, captured " << bytes_captured);
1038
1039 size_t compare_len = (bytes_captured < expected_len) ? bytes_captured : expected_len;
1040 for (size_t i = 0; i < compare_len; i++) {
1041 if (expected_encoded[i] != config.rx_buffer[i]) {
1042 mismatches++;
1043 }
1044 }
1045 // Count any missing bytes as mismatches
1046 if (bytes_captured < expected_len) {
1047 mismatches += static_cast<int>(expected_len - bytes_captured);
1048 }
1049
1050 AR_FL_WARN("Bytes Captured: " << bytes_captured << " (expected: " << expected_len << ")");
1051 int total_bytes = static_cast<int>(expected_len);
1052 AR_FL_WARN("Accuracy: " << (100.0 * (total_bytes - mismatches) / total_bytes) << "% ("
1053 << (total_bytes - mismatches) << "/" << total_bytes << " bytes match)");
1054 } else if (lane_uses_rgbw) {
1055 const fl::vector<uint8_t> expected =
1056 buildExpectedClockless(
1057 config.tx_configs[config_idx].mLeds, true);
1058 const size_t expected_len = expected.size();
1059 const size_t compare_len =
1060 bytes_captured < expected_len ? bytes_captured : expected_len;
1061 for (size_t i = 0; i < compare_len; ++i) {
1062 if (expected[i] != config.rx_buffer[i]) {
1063 ++mismatches;
1064 }
1065 }
1066 if (bytes_captured < expected_len) {
1067 mismatches +=
1068 static_cast<int>(expected_len - bytes_captured);
1069 }
1070
1071 AR_FL_WARN("RGBW bytes captured: " << bytes_captured
1072 << " (expected: " << expected_len << ")");
1073 AR_FL_WARN("Accuracy: "
1074 << (100.0 * (expected_len - mismatches) / expected_len)
1075 << "% (" << (expected_len - mismatches) << "/"
1076 << expected_len << " bytes match)");
1077 } else {
1078 // WS2812: Compare raw RGB per-LED
1079 size_t bytes_expected = num_leds * 3;
1080
1081 // NEVER EVER CHANGE THIS!!!!!
1082 const size_t front_padding_bytes = 0; // No front padding: PARLIO FRONT_PAD_BYTES=0
1083 const size_t rx_buffer_offset = front_padding_bytes;
1084
1085 if (bytes_captured > bytes_expected + front_padding_bytes) {
1086 AR_FL_WARN("Info: Captured " << bytes_captured << " bytes ("
1087 << front_padding_bytes << " front pad + "
1088 << bytes_expected << " LED data + "
1089 << (bytes_captured - bytes_expected - front_padding_bytes) << " back pad/RESET)");
1090 }
1091
1092 // Compare: byte-level comparison (COLOR_ORDER is RGB, so no reordering)
1093 size_t bytes_to_check = (bytes_captured < bytes_expected + rx_buffer_offset) ?
1094 (bytes_captured > rx_buffer_offset ? bytes_captured - rx_buffer_offset : 0) :
1095 bytes_expected;
1096 (void)bytes_to_check;
1097
1098 for (size_t i = 0; i < num_leds; i++) {
1099 size_t byte_offset = rx_buffer_offset + i * 3; // Skip front padding
1100 if (byte_offset + 2 >= bytes_captured) { // Check against total captured bytes
1101 FL_ERROR("[" << ctx.driver_name << "/" << ctx.timing_name << "/" << ctx.pattern_name
1102 << " | Lane " << ctx.lane_index << "/" << ctx.lane_count
1103 << " (Pin " << ctx.pin_number << ", " << ctx.num_leds << " LEDs) | RX:" << ctx.rx_type_name << "] "
1104 << "Incomplete data for LED[" << static_cast<int>(i)
1105 << "] (only " << bytes_captured << " bytes captured)");
1106 break;
1107 }
1108
1109 uint8_t expected_r = leds[i].r;
1110 uint8_t expected_g = leds[i].g;
1111 uint8_t expected_b = leds[i].b;
1112
1113 uint8_t actual_r = config.rx_buffer[byte_offset + 0];
1114 uint8_t actual_g = config.rx_buffer[byte_offset + 1];
1115 uint8_t actual_b = config.rx_buffer[byte_offset + 2];
1116
1117 if (expected_r != actual_r || expected_g != actual_g || expected_b != actual_b) {
1118 mismatches++;
1119 }
1120 }
1121
1122 AR_FL_WARN("Bytes Captured: " << bytes_captured << " (expected: " << bytes_expected << ")");
1123 AR_FL_WARN("Accuracy: " << (100.0 * (num_leds - mismatches) / num_leds) << "% ("
1124 << (num_leds - mismatches) << "/" << num_leds << " LEDs match)");
1125 }
1126
1127 if (mismatches == 0) {
1128 AR_FL_WARN("Result: PASS ✓");
1129 passed++;
1130 } else {
1131 FL_ERROR("[" << ctx.driver_name << "/" << ctx.timing_name << "/" << ctx.pattern_name
1132 << " | Lane " << ctx.lane_index << "/" << ctx.lane_count
1133 << " (Pin " << ctx.pin_number << ", " << ctx.num_leds << " LEDs) | RX:" << ctx.rx_type_name << "] "
1134 << "Result: FAIL ✗");
1135 }
1136 }
1137}
1138
1139// Multi-run autoresearch test runner
1140// Runs the same test multiple times and tracks errors across runs
1141void runMultiTest(const char* test_name,
1142 fl::AutoResearchConfig& config,
1143 const fl::MultiRunConfig& multi_config,
1144 int& total, int& passed,
1145 fl::vector<fl::RunResult>* out_results) {
1146
1147 // PR #3421 framework-hang fix:
1148 // FL_WARN expansion ALWAYS constructs `fl::sstream() << X` regardless
1149 // of log level -- `ScopedLogDisable` only suppresses the OUTPUT inside
1150 // `log_emit`. Under autoresearch's RPC ASYNC handler (which wraps the
1151 // test in `ScopedLogDisable`), the cumulative `fl::sstream`/`fl::string`
1152 // heap alloc/free cycles in runMultiTest's banner + per-run + summary
1153 // FL_WARNs were leaving the Teensy 4 heap in a state where the
1154 // function-exit destructor of the heap-backed `fl::string` hangs
1155 // indefinitely (reproduced ~80% of runs on LPUART, FlexIO, and
1156 // ObjectFLED autoresearch tests). Skipping the sstream construction
1157 // when log level is below WARN avoids the heap thrash entirely.
1158 // See: marker-narrowed investigation in PR #3421 / session research.
1159 const bool kLogsEnabled = fl::getLogLevel() >=
1161
1162 fl::sstream ss;
1163 if (kLogsEnabled) {
1164 ss << "\n╔════════════════════════════════════════════════════════════════╗\n";
1165 ss << "║ MULTI-RUN TEST: " << test_name << "\n";
1166 ss << "║ Runs: " << multi_config.num_runs << " | Print Mode: "
1167 << (multi_config.print_all_runs ? "All" : "Errors ONLY") << "\n";
1168 ss << "╚════════════════════════════════════════════════════════════════╝";
1169 AR_FL_WARN(ss.str());
1170 }
1171
1172 fl::vector<fl::RunResult> run_results;
1173 int total_passed = 0;
1174 int total_failed = 0;
1175 bool retained_success = false;
1176
1177 // Multi-lane limitation: Only test Lane 0
1178 size_t channels_to_test = config.tx_configs.size() > 1 ? 1 : config.tx_configs.size();
1179
1180 if (config.tx_configs.size() > 1) {
1181 AR_FL_WARN("[MULTI-LANE] Testing " << config.tx_configs.size() << " lanes, testing Lane 0 only");
1182 }
1183
1184 // The tested lane and its pixel buffer are stable across repeated frames,
1185 // so construct the RGBW wire-order expectation once instead of allocating
1186 // and rebuilding it for every capture.
1187 fl::vector<uint8_t> expected_rgbw;
1188 if (channels_to_test > 0 && legacyLaneUsesRgbw(config, 0)) {
1189 expected_rgbw =
1190 buildExpectedClockless(config.tx_configs[0].mLeds, true);
1191 }
1192
1193 // Same reasoning for the UCS7604 encoded frame, plus one more: its length
1194 // is what sizes the RX edge capacity in capture(). UCS7604 carries a
1195 // 15-byte preamble and 16-bit channels, so the pixel byte count is several
1196 // times short of the wire frame and truncates the capture (FastLED#4373).
1197 const bool lane_uses_ucs7604 = isUCS7604(config.encoder);
1198 fl::vector<uint8_t> expected_ucs7604;
1199 if (channels_to_test > 0 && lane_uses_ucs7604) {
1200 expected_ucs7604 =
1201 buildExpectedUCS7604(config.tx_configs[0].mLeds, config.encoder);
1202 }
1203
1204 // Execute multiple runs
1205 for (int run = 1; run <= multi_config.num_runs; run++) {
1206 // runSingleTest executes synchronously inside the RPC task, so the
1207 // sketch loop cannot feed its five-second watchdog while a legitimate
1208 // repeated-frame soak is in progress. Each capture is independently
1209 // bounded by the TX/RX waits below; feed between them rather than
1210 // relaxing the watchdog or adding serial progress chatter.
1211 FastLED.watchdog().feed();
1212 // Do not construct progress strings under ScopedLogDisable: a long
1213 // hardware soak otherwise performs throwaway heap allocations.
1214 if (kLogsEnabled && (run % 3 == 1 || multi_config.num_runs <= 5)) {
1215 AR_FL_WARN("[Run " << run << "/" << multi_config.num_runs << "] Testing...");
1216 }
1217
1219 result.run_number = run;
1220
1221 // Test Lane 0 only
1222 for (size_t config_idx = 0; config_idx < channels_to_test; config_idx++) {
1223 const auto& leds = config.tx_configs[config_idx].mLeds;
1224 size_t num_leds = leds.size();
1225 const bool lane_uses_rgbw =
1226 legacyLaneUsesRgbw(config, config_idx);
1227 const size_t expected_data_bytes =
1228 lane_uses_ucs7604 ? expected_ucs7604.size()
1229 : num_leds * (lane_uses_rgbw ? 4u : 3u);
1230 result.total_leds = num_leds;
1231 result.totalBytes = static_cast<int>(expected_data_bytes);
1232
1233 // Power-limit mode: record the limiter's decision for this frame
1234 // before show() so the wire bytes can be checked against it. The
1235 // reported full/baseline model lane 0 alone, which is the whole
1236 // draw list here (one lane is enforced) with dither off (so no
1237 // dither reserve).
1238 // Legacy controllers and Channel API lanes both reach the wire
1239 // through the classic scalar (the Channel frame plan's Q16 flux
1240 // is not what show() applies), so one oracle serves both.
1241 if (config.max_power_mw != 0) {
1242 const CRGB black = CRGB::Black;
1243 const uint32_t dark_per_led =
1245 result.baselineMw = fl::framePowerMCUBaselineMilliwatts() +
1246 dark_per_led * static_cast<uint32_t>(num_leds);
1247 result.fullDemandMw = fl::framePowerMCUBaselineMilliwatts() +
1249 fl::span<const CRGB>(leds.data(), num_leds));
1250 result.expectedScale =
1252 }
1253
1254 // Capture RX data
1255 size_t bytes_captured =
1256 capture(config.rx_channel, config.rx_buffer,
1257 expected_data_bytes,
1258 config.tx_configs[config_idx].getDataPin(),
1259 config.timing,
1260 config.driver_name, &result);
1261 result.capturedBytes = static_cast<int>(bytes_captured);
1262
1263 if (bytes_captured == 0) {
1264 AR_FL_WARN("[Run " << run << "] Capture failed");
1265 result.mismatches = static_cast<int>(num_leds);
1266 result.mismatchedBytes = static_cast<int>(result.totalBytes);
1267 result.captureFailed = true;
1268 result.passed = false;
1269 // This also covers decoder failures after a successful RX
1270 // wait: capture() reports zero bytes, so preserve the raw
1271 // edge snapshot before this run exits.
1272 collectRawEdgeDiagnostics(config.rx_channel, &result);
1273 break;
1274 }
1275
1276 // Check pixel data
1277 int mismatches = 0;
1278
1279 // Diagnostic: single-line driver + first-24-bytes dump. Was 26
1280 // FL_WARNs (one per byte) -- on a 4-pattern test that produced 104
1281 // serial lines of pure hex dump, which dominated the Teensy 4 UART
1282 // TX FIFO under bursty autoresearch loads (fbuild#755 followup,
1283 // FastLED#3219 stack of fixes). Collapsing into a single
1284 // space-separated hex string keeps the diagnostic value while
1285 // dropping per-pattern serial overhead from ~2.1 KB to ~80 bytes.
1286 if (kLogsEnabled) {
1287 fl::sstream hex_dump;
1288 size_t dump_count = (bytes_captured < 24) ? bytes_captured : 24;
1289 for (size_t i = 0; i < dump_count; i++) {
1290 if (i > 0) hex_dump << " ";
1291 hex_dump << fl::hex << static_cast<int>(config.rx_buffer[i]) << fl::dec;
1292 }
1293 AR_FL_WARN("[RUN " << run << "] Driver=" << config.driver_name
1294 << " bytes_captured=" << bytes_captured
1295 << " first" << static_cast<int>(dump_count) << "=" << hex_dump.str());
1296 }
1297
1298 if (lane_uses_ucs7604) {
1299 // UCS7604: Compare full encoded frame byte-for-byte
1300 const fl::vector<uint8_t>& expected_encoded = expected_ucs7604;
1301 size_t expected_len = expected_encoded.size();
1302 result.totalBytes = static_cast<int>(expected_len);
1303
1304 size_t compare_len = (bytes_captured < expected_len) ? bytes_captured : expected_len;
1305 for (size_t i = 0; i < compare_len; i++) {
1306 if (expected_encoded[i] != config.rx_buffer[i]) {
1307 result.mismatchedBytes++;
1308 if ((expected_encoded[i] ^ config.rx_buffer[i]) == 0x01) {
1309 result.lsbOnlyErrors++;
1310 }
1311 mismatches++;
1312
1313 // Print corruption context for first mismatch only
1314 if (mismatches == 1) {
1315 AR_FL_WARN("\n[CORRUPTION @ byte " << static_cast<int>(i) << ", Run " << run
1316 << "] expected=0x" << fl::hex << static_cast<int>(expected_encoded[i])
1317 << " actual=0x" << static_cast<int>(config.rx_buffer[i]) << fl::dec);
1318 }
1319
1320 // Store first N errors (using byte-level reporting)
1321 if (result.errors.size() < static_cast<size_t>(multi_config.max_errors_per_run)) {
1322 result.errors.push_back(fl::LEDError(
1323 static_cast<int>(i), expected_encoded[i], 0, 0,
1324 config.rx_buffer[i], 0, 0
1325 ));
1326 }
1327 }
1328 }
1329 // Count missing bytes as mismatches
1330 if (bytes_captured < expected_len) {
1331 mismatches += static_cast<int>(expected_len - bytes_captured);
1332 }
1333 } else if (lane_uses_rgbw) {
1334 const fl::vector<uint8_t>& expected = expected_rgbw;
1335 size_t verified_leds = 0;
1336 for (size_t i = 0; i < num_leds; ++i) {
1337 const size_t byte_offset = i * 4;
1338 if (byte_offset + 3 >= bytes_captured) {
1339 break;
1340 }
1341 verified_leds = i + 1;
1342
1343 bool led_mismatch = false;
1344 for (size_t channel = 0; channel < 4; ++channel) {
1345 const uint8_t expected_byte =
1346 expected[byte_offset + channel];
1347 const uint8_t actual_byte =
1348 config.rx_buffer[byte_offset + channel];
1349 if (expected_byte != actual_byte) {
1350 ++result.mismatchedBytes;
1351 if ((expected_byte ^ actual_byte) == 0x01) {
1352 ++result.lsbOnlyErrors;
1353 }
1354 led_mismatch = true;
1355 }
1356 }
1357
1358 if (led_mismatch) {
1359 if (mismatches == 0) {
1360 AR_FL_WARN("\n[RGBW CORRUPTION @ LED "
1361 << static_cast<int>(i) << ", Run "
1362 << run << "]");
1363 const size_t corruption_edge_index = i * 64;
1364 const size_t offset =
1365 corruption_edge_index > 4
1366 ? corruption_edge_index - 4
1367 : 0;
1368 dumpRawEdgeTiming(
1369 config.rx_channel, config.timing,
1370 fl::EdgeRange(offset, 9));
1371 }
1372 ++mismatches;
1373
1374 if (result.errors.size() <
1375 static_cast<size_t>(
1376 multi_config.max_errors_per_run)) {
1377 result.errors.push_back(fl::LEDError(
1378 static_cast<int>(i),
1379 expected[byte_offset + 0],
1380 expected[byte_offset + 1],
1381 expected[byte_offset + 2],
1382 expected[byte_offset + 3],
1383 config.rx_buffer[byte_offset + 0],
1384 config.rx_buffer[byte_offset + 1],
1385 config.rx_buffer[byte_offset + 2],
1386 config.rx_buffer[byte_offset + 3]));
1387 }
1388 }
1389 }
1390
1391 if (verified_leds < num_leds) {
1392 const size_t unchecked = num_leds - verified_leds;
1393 mismatches += static_cast<int>(unchecked);
1394 result.mismatchedBytes +=
1395 static_cast<int>(unchecked * 4);
1396 AR_FL_WARN("[TRUNCATED RGBW CAPTURE] Only verified "
1397 << verified_leds << "/" << num_leds
1398 << " LEDs (" << bytes_captured
1399 << " bytes captured, needed "
1400 << expected_data_bytes << "). Marking "
1401 << unchecked
1402 << " unchecked LEDs as mismatches.");
1403 }
1404 } else {
1405 // WS2812: Per-LED RGB comparison
1406 size_t bytes_expected = num_leds * 3;
1407
1408 // Determine front padding offset (PARLIO only)
1409 const size_t rx_buffer_offset = 0; // No front padding: PARLIO FRONT_PAD_BYTES=0
1410
1411 size_t bytes_to_check = (bytes_captured < bytes_expected + rx_buffer_offset) ?
1412 (bytes_captured > rx_buffer_offset ? bytes_captured - rx_buffer_offset : 0) :
1413 bytes_expected;
1414 (void)bytes_to_check;
1415
1416 size_t verified_leds = 0;
1417 for (size_t i = 0; i < num_leds; i++) {
1418 size_t byte_offset = rx_buffer_offset + i * 3; // Apply offset for PARLIO front padding
1419 if (byte_offset + 2 >= bytes_captured) { // Check against total captured bytes
1420 break;
1421 }
1422 verified_leds = i + 1;
1423
1424 uint8_t expected_r = leds[i].r;
1425 uint8_t expected_g = leds[i].g;
1426 uint8_t expected_b = leds[i].b;
1427
1428 uint8_t actual_r = config.rx_buffer[byte_offset + 0];
1429 uint8_t actual_g = config.rx_buffer[byte_offset + 1];
1430 uint8_t actual_b = config.rx_buffer[byte_offset + 2];
1431
1432 // Power-limit mode: the wire carries the source scaled by
1433 // the limiter's brightness. Colour adjustment rounds the
1434 // scalar, so allow 2 codes either way.
1435 int tolerance = 0;
1436 if (config.max_power_mw != 0) {
1437 result.sumRaw += static_cast<uint32_t>(expected_r) + expected_g + expected_b;
1438 result.sumWire += static_cast<uint32_t>(actual_r) + actual_g + actual_b;
1439 const uint8_t s = static_cast<uint8_t>(result.expectedScale);
1440 expected_r = scale8(expected_r, s);
1441 expected_g = scale8(expected_g, s);
1442 expected_b = scale8(expected_b, s);
1443 tolerance = 2;
1444 }
1445
1446 // Per-byte comparison for byte-level stats
1447 uint8_t exp_bytes[3] = {expected_r, expected_g, expected_b};
1448 uint8_t act_bytes[3] = {actual_r, actual_g, actual_b};
1449 bool led_mismatch = false;
1450 for (int ch = 0; ch < 3; ch++) {
1451 const int diff = static_cast<int>(exp_bytes[ch]) - act_bytes[ch];
1452 if (diff > tolerance || diff < -tolerance) {
1453 result.mismatchedBytes++;
1454 if ((exp_bytes[ch] ^ act_bytes[ch]) == 0x01) {
1455 result.lsbOnlyErrors++;
1456 }
1457 led_mismatch = true;
1458 }
1459 }
1460
1461 if (led_mismatch) {
1462 // Print corruption context for first mismatch only
1463 if (mismatches == 0) {
1464 AR_FL_WARN("\n[CORRUPTION @ LED " << static_cast<int>(i) << ", Run " << run << "]");
1465
1466 // Calculate edge index and print timing around corruption point
1467 size_t corruption_edge_index = i * 48;
1468 size_t offset = corruption_edge_index > 4 ? corruption_edge_index - 4 : 0;
1469
1470 // Dump raw edge timing around corruption point (9 edges: -4 to +4)
1471 dumpRawEdgeTiming(config.rx_channel, config.timing, fl::EdgeRange(offset, 9));
1472 }
1473
1474 mismatches++;
1475
1476 // Store first N errors
1477 if (result.errors.size() < static_cast<size_t>(multi_config.max_errors_per_run)) {
1478 result.errors.push_back(fl::LEDError(
1479 i, expected_r, expected_g, expected_b,
1480 actual_r, actual_g, actual_b
1481 ));
1482 }
1483 }
1484 }
1485
1486 // Truncated capture: RX returned fewer bytes than expected. Count
1487 // the unchecked LEDs as mismatches rather than silently passing.
1488 // A short capture means we did NOT verify those LEDs, so the run
1489 // MUST fail. The old silent break hid real bugs on strips longer
1490 // than the RMT DMA buffer (~170 LEDs for WS2812B). See issue #2254.
1491 if (verified_leds < num_leds) {
1492 size_t unchecked = num_leds - verified_leds;
1493 mismatches += static_cast<int>(unchecked);
1494 result.mismatchedBytes += static_cast<int>(unchecked * 3);
1495 AR_FL_WARN("[TRUNCATED CAPTURE] Only verified " << verified_leds
1496 << "/" << num_leds << " LEDs (" << bytes_captured
1497 << " bytes captured, needed " << (num_leds * 3)
1498 << "). Marking " << unchecked
1499 << " unchecked LEDs as mismatches.");
1500 }
1501 }
1502
1503 result.mismatches = mismatches;
1504 result.passed = (mismatches == 0);
1505 if (!result.passed) {
1506 collectRawEdgeDiagnostics(config.rx_channel, &result);
1507 }
1508 }
1509
1510 // Print run result if configured (sstream construction skipped
1511 // when logs disabled -- see kLogsEnabled note at function top).
1512 if (kLogsEnabled && (multi_config.print_all_runs || !result.passed)) {
1513 AR_FL_WARN("[Run " << run << "/" << multi_config.num_runs << "] "
1514 << (result.passed ? "PASS" : "FAIL")
1515 << " | Errors: " << result.mismatches << "/" << result.total_leds
1516 << " (" << (100.0 * (result.total_leds - result.mismatches) / result.total_leds) << "%)");
1517
1518 // Print error details if enabled
1519 if (!result.passed && multi_config.print_per_led_errors && !result.errors.empty()) {
1520 AR_FL_WARN(" First " << result.errors.size() << " error(s):");
1521 for (size_t i = 0; i < result.errors.size(); i++) {
1522 const auto& err = result.errors[i];
1523 AR_FL_WARN(" LED[" << err.led_index << "]: expected RGB("
1524 << static_cast<int>(err.expected_r) << ","
1525 << static_cast<int>(err.expected_g) << ","
1526 << static_cast<int>(err.expected_b) << ") got RGB("
1527 << static_cast<int>(err.actual_r) << ","
1528 << static_cast<int>(err.actual_g) << ","
1529 << static_cast<int>(err.actual_b) << ")");
1530 }
1531 }
1532 }
1533
1534 if (result.passed) {
1535 ++total_passed;
1536 } else {
1537 ++total_failed;
1538 }
1539
1540 // The RPC response includes only failed pattern details. Keeping every
1541 // successful result during a long frame soak needlessly grows the
1542 // transient heap (and used to make the 16-frame RP PIO run wedge).
1543 // Retain one representative successful capture for byte-evidence;
1544 // retain every failure so its full postmortem remains available.
1545 if (!result.passed || !retained_success || multi_config.num_runs == 1) {
1546 if (result.passed) {
1547 retained_success = true;
1548 }
1549 run_results.push_back(fl::move(result));
1550 }
1551 FastLED.watchdog().feed();
1552 }
1553
1554 // Summary statistics
1555 // Summary FL_WARN -- gated on log level (see kLogsEnabled note above)
1556 // to prevent heap thrash under autoresearch ScopedLogDisable.
1557 if (kLogsEnabled) {
1558 ss.clear();
1559 ss << "\n╔════════════════════════════════════════════════════════════════╗\n";
1560 ss << "║ MULTI-RUN SUMMARY\n";
1561 ss << "╚════════════════════════════════════════════════════════════════╝\n";
1562 ss << "Total Runs: " << multi_config.num_runs << "\n";
1563 ss << "Passed: " << total_passed << " (" << (100.0 * total_passed / multi_config.num_runs) << "%)\n";
1564 ss << "Failed: " << total_failed << " (" << (100.0 * total_failed / multi_config.num_runs) << "%)";
1565 AR_FL_WARN(ss.str());
1566
1567 if (total_failed > 0) {
1568 ss.clear();
1569 ss << "\nFailed Run Numbers:\n";
1570 for (const auto& r : run_results) {
1571 if (!r.passed) {
1572 ss << " Run #" << r.run_number << " - " << r.mismatches << " errors\n";
1573 if (!r.errors.empty()) {
1574 ss << " First error at LED[" << r.errors[0].led_index << "]: "
1575 << "expected RGB(" << static_cast<int>(r.errors[0].expected_r) << ","
1576 << static_cast<int>(r.errors[0].expected_g) << ","
1577 << static_cast<int>(r.errors[0].expected_b) << ") got RGB("
1578 << static_cast<int>(r.errors[0].actual_r) << ","
1579 << static_cast<int>(r.errors[0].actual_g) << ","
1580 << static_cast<int>(r.errors[0].actual_b) << ")\n";
1581 }
1582 }
1583 }
1584 AR_FL_WARN(ss.str());
1585 }
1586 }
1587
1588 // Copy results to caller if requested
1589 if (out_results) {
1590 for (const auto& r : run_results) {
1591 out_results->push_back(r);
1592 }
1593 }
1594
1595 // Update totals
1596 total++;
1597 if (total_failed == 0) {
1598 passed++;
1599 if (kLogsEnabled) {
1600 AR_FL_WARN("\n[OVERALL] PASS ✓ - All " << multi_config.num_runs << " runs succeeded");
1601 }
1602 } else {
1603 if (kLogsEnabled) {
1604 AR_FL_WARN("\n[OVERALL] FAIL ✗ - " << total_failed << "/" << multi_config.num_runs << " runs failed");
1605 }
1606 }
1607}
1608
1609// AutoResearch a specific chipset timing configuration
1610// Creates channels, runs tests, destroys channels
1611// Applies an AutoResearch power budget for one chipset run and always
1612// restores unlimited power and the default dither on exit. Dither is off so
1613// the wire bytes are a pure function of the limiter's scalar (#5139).
1614class ScopedAutoResearchPowerLimit {
1615 public:
1616 explicit ScopedAutoResearchPowerLimit(uint32_t max_power_mw) FL_NO_EXCEPT
1617 : mActive(max_power_mw != 0) {
1618 if (mActive) {
1620 FastLED.setMaxPowerInMilliWatts(max_power_mw);
1621 }
1622 }
1623 // CFastLED has no dither getter, so this restores BINARY_DITHER, FastLED's
1624 // default; nothing else in AutoResearch changes the global dither mode.
1625 // The harness never sets a power budget either, so clearing is a restore.
1626 ~ScopedAutoResearchPowerLimit() FL_NO_EXCEPT {
1627 if (mActive) {
1630 }
1631 }
1632 private:
1633 bool mActive;
1634};
1635
1637 int& driver_total, int& driver_passed,
1638 uint32_t& out_show_duration_ms,
1639 fl::vector<fl::RunResult>* out_results,
1640 int num_runs_per_pattern) {
1641 fl::sstream ss;
1642 ss << "\n========================================\n";
1643 ss << "Testing: " << config.timing_name << "\n";
1644 bool has_spi_config = config.tx_configs.size() > 0 && config.tx_configs[0].isSpi();
1645 if (has_spi_config) {
1646 const auto* spi_cfg = config.tx_configs[0].getSpiChipset();
1647 ss << " Protocol: SPI (APA102)\n";
1648 ss << " Clock: " << (spi_cfg ? spi_cfg->timing.clock_hz : 0) << " Hz\n";
1649 } else {
1650 ss << " T0H: " << config.timing.t1_ns << "ns\n";
1651 ss << " T1H: " << (config.timing.t1_ns + config.timing.t2_ns) << "ns\n";
1652 ss << " T0L: " << config.timing.t3_ns << "ns\n";
1653 ss << " RESET: " << config.timing.reset_us << "us\n";
1654 }
1655 ss << " Channels: " << config.tx_configs.size() << "\n";
1656 ss << "========================================";
1657 AR_FL_WARN(ss.str());
1658
1659 // Create ALL channels from tx_configs (multi-channel support)
1661 for (size_t i = 0; i < config.tx_configs.size(); i++) {
1663 if (config.tx_configs[i].isSpi()) {
1664 // SPI chipset: pass through the SPI config directly
1665 channel = FastLED.add(config.tx_configs[i]);
1666 } else {
1667 // Clockless chipset: re-create with runtime timing. The encoder
1668 // has to come with it. ChannelConfig(pin, timing, ...) defaults
1669 // the encoder to WS2812, so a UCS7604 timing used to put raw
1670 // pixel bytes on the wire while the comparison below expected the
1671 // encoded frame -- every UCS7604 run failed at every LED count
1672 // with a captured pattern that looked like a driver fault
1673 // (FastLED#4373).
1674 fl::ClocklessChipset clockless_chipset(
1675 config.tx_configs[i].getDataPin(), config.timing, config.encoder);
1676 fl::ChannelConfig channel_config(clockless_chipset,
1677 config.tx_configs[i].mLeds, config.tx_configs[i].rgb_order,
1678 config.tx_configs[i].options);
1679 channel = FastLED.add(channel_config);
1680 }
1681 if (!channel) {
1682 FL_ERROR("Failed to create channel " << i << " (pin " << config.tx_configs[i].getDataPin() << ") - platform not supported");
1683 // Clean up previously created channels
1684 for (auto& ch : channels) {
1685 ch.reset();
1686 }
1687 return;
1688 }
1689 channels.push_back(channel);
1690 }
1691
1692 FastLED.setBrightness(255);
1693 ScopedAutoResearchPowerLimit power_limit(config.max_power_mw);
1694
1695 // Pre-initialize the TX engine to avoid first-call setup delays
1696 for (size_t i = 0; i < config.tx_configs.size(); i++) {
1697 fill_solid(config.tx_configs[i].mLeds.data(), config.tx_configs[i].mLeds.size(), CRGB::Black);
1698 }
1699 FastLED.show();
1700 if (!FastLED.wait(1000)) { // 1s timeout - driver stall guard
1701 FL_ERROR("[PREINIT] TX wait timeout - driver may be stalled on this platform");
1703 return;
1704 }
1705 // TX engine pre-init logging silenced for speed
1706
1707 // CRITICAL: Wait for PARLIO streaming transmission to complete before starting tests
1708 // Without this delay, the RX will capture the pre-initialization BLACK frame instead of the test pattern
1709 // PARLIO is a streaming engine with ring buffers - need time to drain the initial frame
1710 fl::delay(5); // Reduced from 100ms - just enough for buffer drain
1711
1712 // Run test patterns (mixed bit patterns to test MSB vs LSB handling)
1713 int total = 0;
1714 int passed = 0;
1715
1716 // Multi-run configuration - optimized for speed
1717 fl::MultiRunConfig multi_config;
1718 // num_runs=1: Python orchestrates retries (default).
1719 // num_runs>=2: Back-to-back captures of the same buffer to expose second-frame
1720 // degradation (e.g., SPI driver zeroing its DMA buffer after the first show()).
1721 multi_config.num_runs = (num_runs_per_pattern > 0) ? num_runs_per_pattern : 1;
1722 multi_config.print_all_runs = (multi_config.num_runs > 1);
1723 multi_config.print_per_led_errors = false; // Errors reported via JSON-RPC
1724 multi_config.max_errors_per_run = 10; // Store first 10 errors for JSON response
1725
1726 // Measure show-only duration (excludes setup/teardown overhead)
1727 uint32_t show_start_ms = fl::millis();
1728
1729 // Test all 4 bit patterns (0-3)
1730 for (int pattern_id = 0; pattern_id < 4; pattern_id++) {
1731 // Apply pattern to all lanes
1732 for (size_t i = 0; i < config.tx_configs.size(); i++) {
1734 config.tx_configs[i].mLeds.data(),
1735 config.tx_configs[i].mLeds.size(),
1736 pattern_id
1737 );
1738 }
1739 runMultiTest(getBitPatternName(pattern_id), config, multi_config, total, passed, out_results);
1740 }
1741
1742 out_show_duration_ms += fl::millis() - show_start_ms;
1743
1744 // Results reported via JSON-RPC (verbose logging silenced for speed)
1745
1746 // Accumulate results for driver-level tracking
1747 driver_total += total;
1748 driver_passed += passed;
1749
1750 // Destroy ALL channels before testing next timing configuration
1751 // CRITICAL: Clear FastLED's global channel registry to prevent accumulation
1752 // If we only destroy local shared_ptrs, FastLED still holds references
1754 if (fl::strcmp(config.driver_name, "OBJECT_FLED") == 0) {
1755 fl::objectFledDiagnosticsRecord("afterFastLedClear");
1756 }
1757 // Channel destruction is synchronous - no delay needed
1758}
1759
1760// AutoResearch using the legacy template addLeds API (supports multi-lane)
1761// Nearly identical to autoResearchChipsetTiming() — only channel creation differs:
1762// Normal: FastLED.add(channel_config) → Channel
1763// Legacy: LegacyClocklessProxy(pin, leds, numLeds) -> CHIPSET<PIN> -> ClocklessIdf5 -> SlimBridgeController -> RMT5 driver
1765 int& driver_total, int& driver_passed,
1766 uint32_t& out_show_duration_ms,
1767 fl::vector<fl::RunResult>* out_results,
1768 int num_runs_per_pattern) {
1769 fl::sstream ss;
1770 ss << "\n========================================\n";
1771 ss << "Testing (LEGACY API): " << config.timing_name << "\n";
1772 ss << " T0H: " << config.timing.t1_ns << "ns\n";
1773 ss << " T1H: " << (config.timing.t1_ns + config.timing.t2_ns) << "ns\n";
1774 ss << " T0L: " << config.timing.t3_ns << "ns\n";
1775 ss << " RESET: " << config.timing.reset_us << "us\n";
1776 ss << " Lanes: " << config.tx_configs.size() << "\n";
1777 for (size_t i = 0; i < config.tx_configs.size(); i++) {
1778 ss << " Lane " << i << ": pin=" << config.tx_configs[i].getDataPin()
1779 << " LEDs=" << config.tx_configs[i].mLeds.size() << "\n";
1780 }
1781 ss << "========================================";
1782 AR_FL_WARN(ss.str());
1783
1784 // Create one legacy proxy per lane. By default every lane uses WS2812B,
1785 // but AutoResearch can supply per-lane chipsets to exercise multiple
1786 // ObjectFLED timing groups in a single FastLED.show().
1788 for (size_t i = 0; i < config.tx_configs.size(); i++) {
1789 int pin = config.tx_configs[i].getDataPin();
1790 CRGB* leds = config.tx_configs[i].mLeds.data();
1791 int numLeds = static_cast<int>(config.tx_configs[i].mLeds.size());
1793 if (!config.legacy_chipsets.empty() &&
1794 i < config.legacy_chipsets.size()) {
1795 chipset = config.legacy_chipsets[i];
1796 }
1797
1799 pin, leds, numLeds, chipset, config.legacy_rgbw,
1800 fl::strcmp(config.driver_name, "LCD_CLOCKLESS") == 0);
1801 if (!proxy->valid()) {
1802 FL_ERROR("Legacy proxy invalid for lane " << i << " (pin " << pin
1803 << ", chipset " << legacyClocklessChipsetName(chipset)
1804 << " not in supported set)");
1805 return; // vector destructor cleans up already-created proxies
1806 }
1807 proxies.push_back(fl::move(proxy));
1808 }
1809
1810 FastLED.setBrightness(255);
1811 ScopedAutoResearchPowerLimit power_limit(config.max_power_mw);
1812
1813 // Pre-initialize the TX engine to avoid first-call setup delays
1814 for (size_t i = 0; i < config.tx_configs.size(); i++) {
1815 fill_solid(config.tx_configs[i].mLeds.data(), config.tx_configs[i].mLeds.size(), CRGB::Black);
1816 }
1817 FastLED.show();
1818 if (!FastLED.wait(1000)) {
1819 FL_ERROR("[LEGACY] TX wait timeout - driver may be stalled");
1820 return; // vector destructor cleans up proxies
1821 }
1822
1823 fl::delay(5); // Buffer drain (same as autoResearchChipsetTiming)
1824
1825 // Run test patterns (identical to autoResearchChipsetTiming)
1826 int total = 0;
1827 int passed = 0;
1828
1829 fl::MultiRunConfig multi_config;
1830 multi_config.num_runs = (num_runs_per_pattern > 0) ? num_runs_per_pattern : 1;
1831 multi_config.print_all_runs = (multi_config.num_runs > 1);
1832 multi_config.print_per_led_errors = false;
1833 multi_config.max_errors_per_run = 10;
1834
1835 // Measure show-only duration (excludes setup/teardown overhead)
1836 uint32_t show_start_ms = fl::millis();
1837
1838 const bool ws2814_visual_validation =
1839 !config.legacy_chipsets.empty() &&
1841 const int pattern_count = ws2814_visual_validation ? 8 : 4;
1842 for (int pattern_id = 0; pattern_id < pattern_count; pattern_id++) {
1843 // Apply pattern to all lanes
1844 for (size_t i = 0; i < config.tx_configs.size(); i++) {
1846 config.tx_configs[i].mLeds.data(),
1847 config.tx_configs[i].mLeds.size(),
1848 pattern_id
1849 );
1850 }
1851 runMultiTest(getBitPatternName(pattern_id), config, multi_config, total, passed, out_results);
1852 if (ws2814_visual_validation && pattern_id >= 4) {
1853 // Leave each isolated R/G/B/W frame visible long enough for the
1854 // attached physical strip to be checked while RX independently
1855 // verifies the exact four-byte frame.
1856 fl::delay(250);
1857 }
1858 }
1859
1860 out_show_duration_ms += fl::millis() - show_start_ms;
1861
1862 driver_total += total;
1863 driver_passed += passed;
1864
1865 // proxies vector destructor deletes all controllers → ~CLEDController removes from draw list
1866}
1867
1868// Set mixed RGB bit patterns to test MSB vs LSB handling
1869void setMixedBitPattern(CRGB* leds, size_t count, int pattern_id) {
1870 switch (pattern_id) {
1871 case 0:
1872 // Pattern A: R=0xF0 (high nibble), G=0x0F (low nibble), B=0xAA (alternating)
1873 // Tests: High bits in R, low bits in G, mixed bits in B
1874 for (size_t i = 0; i < count; i++) {
1875 leds[i] = CRGB(0xF0, 0x0F, 0xAA);
1876 }
1877 break;
1878
1879 case 1:
1880 // Pattern B: R=0x55 (alternating 01010101), G=0xFF (all high), B=0x00 (all low)
1881 // Tests: Alternating bits, all-high boundary, all-low boundary
1882 for (size_t i = 0; i < count; i++) {
1883 leds[i] = CRGB(0x55, 0xFF, 0x00);
1884 }
1885 break;
1886
1887 case 2:
1888 // Pattern C: R=0x0F (low nibble), G=0xAA (alternating), B=0xF0 (high nibble)
1889 // Tests: Rotated pattern from A, ensures driver handles different channel values
1890 for (size_t i = 0; i < count; i++) {
1891 leds[i] = CRGB(0x0F, 0xAA, 0xF0);
1892 }
1893 break;
1894
1895 case 3:
1896 // Pattern D: Solid colors alternating (Red, Green, Blue repeating)
1897 // Baseline test - ensures basic RGB transmission works
1898 for (size_t i = 0; i < count; i++) {
1899 int color_index = i % 3;
1900 if (color_index == 0) {
1901 leds[i] = CRGB::Red; // RGB(255, 0, 0)
1902 } else if (color_index == 1) {
1903 leds[i] = CRGB::Green; // RGB(0, 255, 0)
1904 } else {
1905 leds[i] = CRGB::Blue; // RGB(0, 0, 255)
1906 }
1907 }
1908 break;
1909
1910 case 4:
1911 fill_solid(leds, count, CRGB::Red);
1912 break;
1913
1914 case 5:
1915 fill_solid(leds, count, CRGB::Green);
1916 break;
1917
1918 case 6:
1919 fill_solid(leds, count, CRGB::Blue);
1920 break;
1921
1922 case 7:
1923 fill_solid(leds, count, CRGB::White);
1924 break;
1925
1926 default:
1927 // Fallback: all black
1928 fill_solid(leds, count, CRGB::Black);
1929 break;
1930 }
1931}
1932
1933// Get name of bit pattern for logging
1934const char* getBitPatternName(int pattern_id) {
1935 switch (pattern_id) {
1936 case 0: return "Pattern A (R=0xF0, G=0x0F, B=0xAA)";
1937 case 1: return "Pattern B (R=0x55, G=0xFF, B=0x00)";
1938 case 2: return "Pattern C (R=0x0F, G=0xAA, B=0xF0)";
1939 case 3: return "Pattern D (RGB Solid Alternating)";
1940 case 4: return "Pattern E (Isolated Red)";
1941 case 5: return "Pattern F (Isolated Green)";
1942 case 6: return "Pattern G (Isolated Blue)";
1943 case 7: return "Pattern H (Isolated White)";
1944 default: return "Unknown Pattern";
1945 }
1946}
1947
1948#endif // FL_PLATFORM_HAS_LARGE_MEMORY
CRGB leds[1]
size_t capture(fl::shared_ptr< fl::RxChannel > rx_channel, fl::span< uint8_t > rx_buffer, size_t expected_data_bytes, int tx_pin, const fl::ChipsetTimingConfig &timing, const char *driver_name, fl::RunResult *diagnostics=nullptr)
void runMultiTest(const char *test_name, fl::AutoResearchConfig &config, const fl::MultiRunConfig &multi_config, int &total, int &passed, fl::vector< fl::RunResult > *out_results=nullptr)
void autoResearchChipsetTimingLegacy(fl::AutoResearchConfig &config, int &total, int &passed, uint32_t &out_show_duration_ms, fl::vector< fl::RunResult > *out_results=nullptr, int num_runs_per_pattern=1)
const char * getBitPatternName(int pattern_id)
void runTest(const char *test_name, fl::AutoResearchConfig &config, int &total, int &passed)
void autoResearchChipsetTiming(fl::AutoResearchConfig &config, int &total, int &passed, uint32_t &out_show_duration_ms, fl::vector< fl::RunResult > *out_results=nullptr, int num_runs_per_pattern=1)
void setMixedBitPattern(CRGB *leds, size_t count, int pattern_id)
uint8_t pos
Definition Blur.ino:11
FastLED show()
FL_DISABLE_WARNING_PUSH FL_DISABLE_WARNING_GLOBAL_CONSTRUCTORS CFastLED FastLED
Global LED strip management instance.
@ CHANNELS
Remove all channels from controller list.
Definition FastLED.h:665
@ POWER_SETTINGS
Reset power management (setMaxPowerInMilliWatts)
Definition FastLED.h:666
LegacyClocklessChipset
const char * legacyClocklessChipsetName(LegacyClocklessChipset chipset)
bool legacyClocklessChipsetHasAutomaticRgbw(LegacyClocklessChipset chipset)
Rgbw rgbw
Runtime chipset timing configuration for clockless LED drivers.
FastLED chrono implementation - duration types for time measurements.
void clear(bool writeData=false) FL_NO_EXCEPT
Clear the leds, wiping the local array of data.
void setMaxPowerInMilliWatts(fl::u32 milliwatts) FL_NO_EXCEPT
Set the maximum power to be used, given in milliwatts.
Definition FastLED.h:1746
void setDither(fl::u8 ditherMode=BINARY_DITHER) FL_NO_EXCEPT
Set the dithering mode.
static fl::shared_ptr< const Gamma8 > getOrCreate(float gamma) FL_NO_EXCEPT
Definition ease.cpp.hpp:460
void writeWS2812(CONTAINER_UIN8_T *out) FL_NO_EXCEPT
void clear(bool freeMemory=false) FL_NO_EXCEPT
bool empty() const FL_NO_EXCEPT
constexpr bool empty() const FL_NO_EXCEPT
Definition span.h:535
const T * data() const FL_NO_EXCEPT
Definition span.h:486
constexpr fl::size size() const FL_NO_EXCEPT
Definition span.h:483
void clear() FL_NO_EXCEPT
Definition strstream.h:366
string str() const FL_NO_EXCEPT
Definition strstream.h:43
fl::size size() const FL_NO_EXCEPT
void reserve(fl::size n) FL_NO_EXCEPT
Definition vector.h:591
void resize(fl::size n) FL_NO_EXCEPT
Definition vector.h:593
T * data() FL_NO_EXCEPT
Definition vector.h:619
void push_back(const T &value) FL_NO_EXCEPT
Definition vector.h:624
void fill_solid(CRGB *targetArray, int numToFill, const CRGB &color) FL_NO_EXCEPT
Fill a range of LEDs with a solid color.
Definition fill.cpp.hpp:10
Delay utilities for FastLED Includes nanosecond-precision delays, cycle counting, and microsecond del...
fl::UISlider offset("Offset", 0.0f, 0.0f, 1.0f, 0.01f)
#define BINARY_DITHER
Enable dithering using binary dithering (only option)
Definition dither_mode.h:16
#define DISABLE_DITHER
Disable dithering.
Definition dither_mode.h:14
UCS7604 LED chipset encoder implementation.
Non-templated low level pixel data writing class.
fl::CRGB CRGB
Definition crgb.h:25
fl::u32 calculate_unscaled_power_mW(fl::span< const CRGB > leds) FL_NO_EXCEPT
fl::u8 calculate_max_brightness_for_power_mW(const CRGB *ledbuffer, fl::u16 numLeds, fl::u8 target_brightness, fl::u32 max_power_mW) FL_NO_EXCEPT
Determines the highest brightness level you can use and still stay under the specified power budget f...
Umbrella header for ISR subsystem.
Centralized LED chipset timing definitions with nanosecond precision.
#define FL_ERROR(...)
Definition log.h:373
constexpr remove_reference< T >::type && move(T &&t) FL_NO_EXCEPT
Definition move.h:30
fl::enable_if<!fl::is_array< T >::value, unique_ptr< T > >::type make_unique(Args &&... args) FL_NO_EXCEPT
Definition unique_ptr.h:263
constexpr u32 ISR_FLAG_EDGE_RISING
Definition constants.h:22
int attach_external_handler(u8 pin, const config &cfg, handle *out_handle) FL_NO_EXCEPT
Attach an external interrupt handler (GPIO-based).
int detach_handler(handle &h) FL_NO_EXCEPT
Detach an ISR handler.
bool useRmtInternalLoopback(bool is_rmt_driver, int tx_pin, int rx_pin) FL_NO_EXCEPT
Whether an RMT validation capture should use ESP-IDF loopback.
Definition validation.h:33
size_t captureEdgeCapacity(size_t shared_buffer_bytes, size_t expected_data_bytes, RxBackend backend) FL_NO_EXCEPT
Compute the RX edge-buffer capacity for a validation frame.
Definition validation.h:65
back_insert_iterator< Container > back_inserter(Container &c) FL_NO_EXCEPT
Helper function to create a back_insert_iterator.
Definition iterator.h:139
unsigned char u8
Definition stdint.h:132
u8 getLogLevel() FL_NO_EXCEPT
Get the current global log level.
ClocklessEncoder
Identifies which encoder to use for clockless chipsets in the Channel API.
@ CLOCKLESS_ENCODER_UCS7604_8BIT
UCS7604 8-bit 800KHz.
@ CLOCKLESS_ENCODER_UCS7604_16BIT
UCS7604 16-bit 800KHz.
@ CLOCKLESS_ENCODER_UCS7604_16BIT_1600
UCS7604 16-bit 1600KHz.
const dec_t dec
Definition ios.cpp.hpp:13
void delay(u32 ms, bool run_async=true) FL_NO_EXCEPT
Public delay wrapper that keeps bare Arduino delay() preferred after using fl::delay; while still all...
Definition delay.h:98
CRGB sample(const CRGB *grid, const XYMap &xyMap, float x, float y, SampleMode mode) FL_NO_EXCEPT
Sample a pixel from a 2D CRGB grid at floating-point coordinates.
fl::u32 uint32_t
Definition s16x16x4.h:219
constexpr u32 gamma(float g) FL_NO_EXCEPT
Definition gamma_lut.h:36
FASTLED_FORCE_INLINE int strcmp(const char *s1, const char *s2) FL_NO_EXCEPT
Definition cstring.h:60
fl::u32 millis() FL_NO_EXCEPT
Universal millisecond timer - returns milliseconds since system startup.
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
constexpr u32 kMaxUartBaudRate
Maximum UART baud rate supported by ESP32 variants.
FASTLED_FORCE_INLINE void * memset(void *s, int c, size_t n) FL_NO_EXCEPT
Definition cstring.h:148
@ PIO
RP2040/RP2350 PIO receive backend.
Definition types.h:9
@ FLEXIO
Teensy 4.x-only FlexIO capture backend (FLEXIO1 — FLEXIO2 is owned by the WS2812 TX driver)....
Definition types.h:14
@ PLATFORM_DEFAULT
Use the recommended backend for the active platform (RMT on ESP32; FlexPWM on Teensy 4....
Definition types.h:10
@ ISR
Platform-neutral interrupt-driven edge capture backend when available.
Definition types.h:12
constexpr size_t kRpPioRxEdgeCapacity
Phase slots in the shared capture pool.
@ FL_LOG_LEVEL_WARN
Errors and warnings.
Definition cstdio.h:40
const hex_t hex
Definition ios.cpp.hpp:11
expected< T, E > result
Alias for expected (Rust-style naming)
Definition result.h:31
const char * toString(RxBackend backend) FL_NO_EXCEPT
Definition types.h:20
UCS7604Mode
UCS7604 protocol configuration modes.
Definition ucs7604.h:30
@ UCS7604_MODE_8BIT_800KHZ
Definition ucs7604.h:31
@ UCS7604_MODE_16BIT_1600KHZ
Definition ucs7604.h:33
@ UCS7604_MODE_16BIT_800KHZ
Definition ucs7604.h:32
FL_OPTIMIZE_FUNCTION bool canUseWave3(const ChipsetTiming &timing) FL_NO_EXCEPT
Check if a chipset timing is eligible for wave3 encoding.
Definition wave3.cpp.hpp:26
void encodeUCS7604(PixelIterator &pixel_iter, size_t num_leds, OutputIterator out, UCS7604Mode mode, const UCS7604CurrentControl &current, bool is_rgbw, const Gamma8 *gamma=nullptr, bool wide_source=false) FL_NO_EXCEPT
Encode complete UCS7604 frame (preamble + padding + pixel data)
Definition ucs7604.h:273
@ SUCCESS
Operation completed successfully.
Definition rx.h:153
ChipsetTiming uartWireTiming(const ChipsetTimingConfig &timing, u32 max_baud_rate) FL_NO_EXCEPT
The wire timing the UART encoder actually produces for a chipset.
atomic< int > atomic_int
Definition atomic.h:30
unsigned char uint8_t
Definition s16x16x4.h:209
u32 T2
Additional high time for bit 1 (nanoseconds)
Definition led_timing.h:88
u32 T3
Low tail duration (nanoseconds)
Definition led_timing.h:89
u32 T1
High time for bit 0 (nanoseconds)
Definition led_timing.h:87
4-phase RX timing thresholds for chipset detection
Definition rx.h:88
Test context for detailed error reporting Aggregates all test configuration parameters for error mess...
Primary template — intentionally undefined.
Definition bus_traits.h:31
Generic chipset timing entry Provides T1, T2, T3 timing parameters in nanoseconds for any LED protoco...
Definition led_timing.h:86
Low level pixel data writing class.
fl::PixelIterator PixelIterator
#define FL_NO_EXCEPT
static ColorAdjustment noAdjustment() FL_NO_EXCEPT
the per-channel scale values premixed with brightness.
Pixel controller class.
static Rgbw value() FL_NO_EXCEPT
Definition rgbw.h:290
static Rgbw value() FL_NO_EXCEPT
Definition rgbw.h:279
const fl::ChipsetTimingConfig & timing
Chipset timing configuration to test.
fl::RxDeviceType rx_type
RX device type (RMT or ISR)
const char * timing_name
Timing name for logging (e.g., "WS2812B-V5")
const char * driver_name
Driver name for logging (e.g., "RMT", "SPI", "PARLIO")
int base_strip_size
Base strip size (10 or 300 LEDs)
bool legacy_rgbw
Enable RGBW on legacy controllers.
fl::span< fl::ChannelConfig > tx_configs
TX channel configurations to test (mutable for LED manipulation)
fl::ClocklessEncoder encoder
Encoder selector (peer of timing; see issue #2467)
fl::shared_ptr< fl::RxChannel > rx_channel
RX channel for loopback capture (created in .ino, passed in)
fl::span< uint8_t > rx_buffer
Buffer to store received bytes.
uint32_t max_power_mw
Power budget for FastLED.setMaxPowerInMilliWatts(); 0 = unlimited.
fl::span< const LegacyClocklessChipset > legacy_chipsets
Optional per-lane legacy templates.
Configuration for driver-agnostic autoresearch testing Contains all input parameters needed for autor...
@ Green
<div style='background:#008000;width:4em;height:4em;'></div>
Definition crgb.h:565
@ Red
<div style='background:#FF0000;width:4em;height:4em;'></div>
Definition crgb.h:629
@ Blue
<div style='background:#0000FF;width:4em;height:4em;'></div>
Definition crgb.h:519
@ White
<div style='background:#FFFFFF;width:4em;height:4em;'></div>
Definition crgb.h:653
@ Black
<div style='background:#000000;width:4em;height:4em;'></div>
Definition crgb.h:517
Configuration for a single LED channel.
Definition config.h:167
u32 t1_ns
T0H: High time for bit 0 (nanoseconds)
u32 t2_ns
T1H-T0H: Additional high time for bit 1 (nanoseconds)
u32 reset_us
Reset/latch time (microseconds)
const char * name
Human-readable chipset name.
u32 t3_ns
T0L: Low tail duration (nanoseconds)
Runtime bit-period timing for a clockless chipset.
Clockless chipset configuration (single data pin)
Definition config.h:33
size_t offset
Starting edge index.
Definition rx.h:57
size_t count
Number of edges to extract.
Definition rx.h:58
Edge range specification for getRawEdgeTimes() debugging.
Definition rx.h:56
LED error information for a single run.
bool print_per_led_errors
Print every LED error (default: false)
int max_errors_per_run
Max errors to store per run (default: 5)
bool print_all_runs
Print all run results (default: only errors)
int num_runs
Number of runs to execute.
Multi-run test configuration.
int captureWaitResult
RxWaitResult value, or -1 before wait.
int decodeOutputCapacity
Output span size passed to decode()
int rawEdgesAfterWait
Raw edges visible after RX wait/decode.
int decodeError
DecodeError value, or -1 when decode succeeded/not run.
fl::string rawEdgeSample
Compact first-edge sample for failures.
fl::string rxBeginError
Machine-readable reason when RX begin() fails.
int decodeBytes
Bytes reported directly by decode()
int rpPioGpioTransitions
CPU-observed RX-pin transitions during RP PIO TX.
int decodeOk
1 if RX decode returned success, 0 on error, -1 before decode
Single run result with error tracking.
UCS7604 current control structure with 4-bit fields for each channel.
Definition ucs7604.h:37
handler_fn handler
Definition handler.h:20
void * user_data
Definition handler.h:21
Configuration for ISR attachment.
Definition handler.h:19
bool is_valid() const FL_NO_EXCEPT
Definition handler.h:49
Opaque handle to an attached ISR.
Definition handler.h:36
Platform-neutral UART wave4/wave5 encoder API.