FastLED 3.10.10
Loading...
Searching...
No Matches
AutoResearchRemoteRunSingleTest.cpp
Go to the documentation of this file.
1// runSingleTestImpl + anonymous-namespace helpers used by it (measureTightTiming etc).
2// Extracted from AutoResearchRemote.cpp as part of #3132 / meta #3127.
3
5#if FL_PLATFORM_HAS_LARGE_MEMORY
6
7// Legacy debug macros (no-ops, kept for debugTest RPC function)
8#define DEBUG_PRINT(x) do {} while(0)
9#define DEBUG_PRINTLN(x) do {} while(0)
10
11#include "AutoResearchRemote.h"
12#include "AutoResearchBle.h"
13#include "AutoResearchNet.h"
14#include "AutoResearchOta.h"
16#include "fl/system/heap.h"
17#include "Common.h"
18#include "AutoResearchTest.h"
19#include "AutoResearchHelpers.h"
20#include "fl/stl/sstream.h"
21#include "fl/stl/unique_ptr.h"
22#include "fl/stl/optional.h"
23#include "fl/stl/json.h"
24#include "fl/stl/cstdio.h"
25#include "fl/stl/chrono.h"
26#include "fl/system/delay.h"
27#include "fl/task/task.h"
28#include "fl/task/executor.h"
30#include "fl/stl/atomic.h"
31#include "fl/task/promise.h"
32#include "fl/math/simd.h"
33#include "AutoResearchSimd.h"
39#include "platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_diagnostics.h"
40#include "platforms/arm/rp/is_rp.h"
41#if defined(FL_IS_TEENSY_4X)
42#include "platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.h"
43#include "platforms/arm/teensy/teensy4_common/drivers/flexio/flexio_driver.h"
44#endif
45#include "fl/chipsets/spi.h"
46#include "fl/channels/config.h"
47#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
48#include "platforms/arm/rp/rpcommon/rp_pio_tx_bus_traits.h"
49#include "platforms/arm/rp/rpcommon/rp_uart_bus_traits.h"
50#include "platforms/arm/rp/rpcommon/rx_pio_channel.h"
51#endif
54#include <Arduino.h>
55
56#include "fl/net/ble.h"
57
58#include "fl/codec/h264.h"
59#include "fl/codec/mp4_parser.h"
61#include "fl/fx/frame.h"
62
63namespace {
64
65// A priority-5 Core-0 workload makes the isolation exercised by #5001
66// observable. This is synthetic CPU work, not a network latency benchmark.
67class WorkerCoreLoad {
68 struct State {
71 fl::atomic<fl::u32> passes{0};
72 fl::atomic<fl::u32> maxPassUs{0};
73 };
74 fl::shared_ptr<State> mState;
75 fl::task::Handle mTask;
76 bool mStarted = false;
77
78public:
79 bool start() FL_NO_EXCEPT {
80 mState = fl::make_shared<State>();
81 if (!mState) { return false; }
82 fl::task::CoroutineConfig task;
83 task.name = "fl-core-load";
84 task.priority = 5;
85 task.core_id = 0;
86 task.stack_size = 2048;
87 const auto state = mState;
88 task.func = [state]() {
89 while (!state->stop.load(fl::memory_order_acquire)) {
90 const fl::u32 start = fl::micros();
91 while (fl::micros() - start < 1000) {}
92 const fl::u32 elapsed = fl::micros() - start;
93 if (elapsed > state->maxPassUs.load(fl::memory_order_relaxed)) {
94 state->maxPassUs.store(elapsed, fl::memory_order_relaxed);
95 }
96 state->passes.fetch_add(1);
97 fl::delay(1, false);
98 }
99 state->done.store(true, fl::memory_order_release);
100 };
101 mTask = fl::task::coroutine(task);
102 mStarted = mTask.is_valid() && mTask.isRunning();
103 return mStarted;
104 }
105 void stop() FL_NO_EXCEPT {
106 if (mStarted) {
107 mState->stop.store(true, fl::memory_order_release);
108 while (!mState->done.load(fl::memory_order_acquire)) {
109 fl::delay(1, false);
110 }
111 mTask.stop();
112 mStarted = false;
113 }
114 }
115 fl::u32 passes() const FL_NO_EXCEPT { return mState ? mState->passes.load() : 0; }
116 fl::u32 maxPassUs() const FL_NO_EXCEPT { return mState ? mState->maxPassUs.load() : 0; }
117 ~WorkerCoreLoad() FL_NO_EXCEPT { stop(); }
118};
119
129class StandingRxChannelSwap {
130 public:
131 explicit StandingRxChannelSwap(AutoResearchState* state)
132 : mState(state), mReleased(false) {}
133
137 void release(fl::shared_ptr<fl::RxChannel>* alias) {
138 if (mReleased || mState == nullptr) {
139 return;
140 }
141 if (alias != nullptr) {
142 alias->reset();
143 }
144 mState->rx_channel.reset();
145 mReleased = true;
146 }
147
148 ~StandingRxChannelSwap() {
149 if (!mReleased || mState == nullptr || mState->rx_factory == nullptr) {
150 return;
151 }
152 // Rebuild, do not restore: the previous device is gone. A failure here
153 // leaves rx_channel null, which the next call reports as a missing RX
154 // channel rather than as a mystery zero capture.
155 mState->rx_channel = mState->rx_factory(mState->pin_rx);
156 }
157
158 StandingRxChannelSwap(const StandingRxChannelSwap&) = delete;
159 StandingRxChannelSwap& operator=(const StandingRxChannelSwap&) = delete;
160
161 private:
162 AutoResearchState* mState;
163 bool mReleased;
164};
165
166#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
167
172bool ucs7604ModeForEncoder(fl::ClocklessEncoder encoder,
173 fl::UCS7604Mode* out_mode) {
174 switch (encoder) {
177 return true;
180 return true;
183 return true;
187 return false;
188 }
189 return false;
190}
191
203fl::size rpPioWireFrameBytes(fl::size leds, fl::ClocklessEncoder encoder,
204 bool rgbw) {
205 fl::UCS7604Mode mode;
206 if (ucs7604ModeForEncoder(encoder, &mode)) {
207 return fl::ucs7604FrameBytes(leds, mode, rgbw);
208 }
210 return leds * (rgbw ? 4u : 3u);
211 }
212 return 0;
213}
214
216fl::size rpPioMaxLedsForWireBytes(fl::size wire_bytes,
217 fl::ClocklessEncoder encoder, bool rgbw) {
218 fl::UCS7604Mode mode;
219 if (ucs7604ModeForEncoder(encoder, &mode)) {
220 constexpr fl::size kPreambleLen = 15;
221 if (wire_bytes <= kPreambleLen) {
222 return 0;
223 }
224 return (wire_bytes - kPreambleLen) / fl::ucs7604BytesPerLed(mode, rgbw);
225 }
226 return wire_bytes / (rgbw ? 4u : 3u);
227}
228
229#endif // FL_IS_RP2040 || FL_IS_RP2350
230
231uint32_t expectedClocklessWireUs(const fl::ChipsetTimingConfig& timing,
232 uint32_t max_leds) {
233 const uint64_t bit_period_ns = timing.total_period_ns();
234 const uint64_t payload_ns =
235 static_cast<uint64_t>(max_leds) * 24ULL * bit_period_ns;
236 return static_cast<uint32_t>((payload_ns + 999ULL) / 1000ULL) +
237 timing.reset_us;
238}
239
240uint32_t maxLaneLeds(const fl::vector<fl::ChannelConfig>& tx_configs) {
241 uint32_t max_leds = 0;
242 for (fl::size i = 0; i < tx_configs.size(); i++) {
243 const uint32_t count =
244 static_cast<uint32_t>(tx_configs[i].mLeds.size());
245 if (count > max_leds) {
246 max_leds = count;
247 }
248 }
249 return max_leds;
250}
251
252class ScopedFastLedBrightness {
253 public:
254 explicit ScopedFastLedBrightness(uint8_t brightness) FL_NO_EXCEPT
255 : mSavedBrightness(FastLED.getBrightness()) {
257 }
258
259 ~ScopedFastLedBrightness() FL_NO_EXCEPT {
260 FastLED.setBrightness(mSavedBrightness);
261 }
262
263 private:
264 uint8_t mSavedBrightness;
265};
266
267bool contaminateTxMuxWithPwm(int pin) {
268#if defined(FL_IS_TEENSY_4X)
269 analogWriteFrequency(pin, 1000.0f);
270 analogWrite(pin, 128);
271 delay(2);
272 return true;
273#else
274 (void)pin;
275 return false;
276#endif
277}
278
279// Diagnostic probe (Teensy 4.x): manually drive TX via the standard GPIO1-4
280// alias and read RX with digitalRead, so we can tell whether the
281// IOMUXC_GPR_GPR26..29 fast->standard remap that ObjectFLED relies on
282// actually reaches the pad on the connected board. Saves and restores all
283// touched IOMUXC/GPIO state; never modifies FlexPWM or DMA.
284fl::json probeStandardGpioPad(int tx_pin, int rx_pin) {
285 fl::json probe = fl::json::object();
286 probe.set("supported", false);
287 probe.set("txPin", static_cast<int64_t>(tx_pin));
288 probe.set("rxPin", static_cast<int64_t>(rx_pin));
289#if !defined(FL_IS_TEENSY_4X)
290 probe.set("message", "Teensy 4.x only");
291 return probe;
292#else
293 probe.set("supported", true);
294 if (tx_pin < 0 || tx_pin >= NUM_DIGITAL_PINS ||
295 rx_pin < 0 || rx_pin >= NUM_DIGITAL_PINS) {
296 probe.set("success", false);
297 probe.set("error", "InvalidPin");
298 return probe;
299 }
300
301 volatile uint32_t* fast_output = portOutputRegister(tx_pin);
302 volatile uint32_t* standard_output = reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
303 reinterpret_cast<uintptr_t>(fast_output) - 0x01E48000u);
304 volatile uint32_t* fast_mode = portModeRegister(tx_pin);
305 volatile uint32_t* standard_mode = reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
306 reinterpret_cast<uintptr_t>(fast_mode) - 0x01E48000u);
307 volatile uint32_t* tx_mux = portConfigRegister(tx_pin);
308 volatile uint32_t* tx_pad = portControlRegister(tx_pin);
309 volatile uint32_t* rx_mux = portConfigRegister(rx_pin);
310 volatile uint32_t* rx_pad = portControlRegister(rx_pin);
311
312 const uint32_t gpio6_base =
313 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(&GPIO6_DR));
314 const uint32_t output_addr =
315 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(fast_output));
316 const uint8_t offset =
317 static_cast<uint8_t>((output_addr - gpio6_base) >> 14);
318 const uint8_t bit = digitalPinToBit(tx_pin);
319 const uint32_t mask = 1u << bit;
320 probe.set("txBit", static_cast<int64_t>(bit));
321 probe.set("txMask", static_cast<int64_t>(mask));
322 probe.set("txOffset", static_cast<int64_t>(offset));
323 if (offset > 3) {
324 probe.set("success", false);
325 probe.set("error", "UnsupportedGpioBank");
326 return probe;
327 }
328
329 volatile uint32_t* gpr = &IOMUXC_GPR_GPR26 + offset;
330 // Save state we are about to clobber.
331 const uint32_t saved_gpr = *gpr;
332 const uint32_t saved_tx_mux = *tx_mux;
333 const uint32_t saved_tx_pad = *tx_pad;
334 const uint32_t saved_rx_mux = *rx_mux;
335 const uint32_t saved_rx_pad = *rx_pad;
336 const uint32_t saved_fast_mode = *fast_mode;
337 const uint32_t saved_standard_mode = *standard_mode;
338 const uint32_t saved_fast_out = *fast_output;
339 const uint32_t saved_standard_out = *standard_output;
340
341 // Make sure standard GPIO1-4 banks are clocked. Teensy startup usually
342 // leaves them on, but assert it explicitly so this probe is independent
343 // of boot order.
344 CCM_CCGR1 |= CCM_CCGR1_GPIO1(CCM_CCGR_ON);
345 CCM_CCGR0 |= CCM_CCGR0_GPIO2(CCM_CCGR_ON);
346 CCM_CCGR2 |= CCM_CCGR2_GPIO3(CCM_CCGR_ON);
347 CCM_CCGR3 |= CCM_CCGR3_GPIO4(CCM_CCGR_ON);
348
349 // RX pin: simple input, no pull, so we can sample what the pad sees.
350 *rx_mux = 5 | 0x10;
351 *rx_pad = (5u << 3) | (3u << 6); // DSE=5, SPEED=3, no pull/keeper
352 pinMode(rx_pin, INPUT);
353
354 // TX pin: ALT5 (GPIO) + SION, mapped to standard bank.
355 *tx_mux = 5 | 0x10;
356 *tx_pad = (3u << 3) | (3u << 6); // DSE=3 (matches ObjectFLED), SPEED=3
357 *gpr &= ~mask; // route pad to standard alias
358 *standard_mode |= mask; // output mode in standard bank
359 // DR_CLEAR = +0x88, DR_SET = +0x84
360 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
361 reinterpret_cast<uintptr_t>(standard_output) + 0x88u) = mask;
363 const int rx_initial = digitalReadFast(rx_pin);
364
365 int rx_high_count = 0;
366 int rx_low_count = 0;
367 for (int i = 0; i < 5; ++i) {
368 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
369 reinterpret_cast<uintptr_t>(standard_output) + 0x84u) = mask;
371 if (digitalReadFast(rx_pin) == HIGH) {
372 ++rx_high_count;
373 }
374 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
375 reinterpret_cast<uintptr_t>(standard_output) + 0x88u) = mask;
377 if (digitalReadFast(rx_pin) == LOW) {
378 ++rx_low_count;
379 }
380 }
381
382 probe.set("standardGpioRxInitial",
383 rx_initial == HIGH ? "HIGH" : "LOW");
384 probe.set("standardGpioRxHighCount", static_cast<int64_t>(rx_high_count));
385 probe.set("standardGpioRxLowCount", static_cast<int64_t>(rx_low_count));
386 probe.set("standardGpioConnected",
387 (rx_high_count == 5) && (rx_low_count == 5));
388
389 // Tight-loop fast toggle: write HIGH, read RX, write LOW, read RX, with
390 // no delay between write and read. Measures whether the standard GPIO
391 // alias propagates to the pad and back to digitalReadFast within a
392 // CPU-bus-cycle window comparable to ObjectFLED's DMA write rate.
393 int fast_high_count = 0;
394 int fast_low_count = 0;
395 int fast_high_zero_delay = 0;
396 int fast_low_zero_delay = 0;
397 constexpr int kFastIters = 50;
398 for (int i = 0; i < kFastIters; ++i) {
399 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
400 reinterpret_cast<uintptr_t>(standard_output) + 0x84u) = mask;
401 if (digitalReadFast(rx_pin) == HIGH) {
402 ++fast_high_zero_delay;
403 }
404 delayNanoseconds(200);
405 if (digitalReadFast(rx_pin) == HIGH) {
406 ++fast_high_count;
407 }
408 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
409 reinterpret_cast<uintptr_t>(standard_output) + 0x88u) = mask;
410 if (digitalReadFast(rx_pin) == LOW) {
411 ++fast_low_zero_delay;
412 }
413 delayNanoseconds(200);
414 if (digitalReadFast(rx_pin) == LOW) {
415 ++fast_low_count;
416 }
417 }
418 probe.set("fastToggleHighSettled", static_cast<int64_t>(fast_high_count));
419 probe.set("fastToggleLowSettled", static_cast<int64_t>(fast_low_count));
420 probe.set("fastToggleHighZeroDelay",
421 static_cast<int64_t>(fast_high_zero_delay));
422 probe.set("fastToggleLowZeroDelay",
423 static_cast<int64_t>(fast_low_zero_delay));
424 probe.set("fastToggleIterations", static_cast<int64_t>(kFastIters));
425
426 // Restore TX/RX pad state.
427 if ((saved_fast_out & mask) != 0) {
428 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
429 reinterpret_cast<uintptr_t>(fast_output) + 0x84u) = mask;
430 } else {
431 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
432 reinterpret_cast<uintptr_t>(fast_output) + 0x88u) = mask;
433 }
434 if ((saved_standard_out & mask) != 0) {
435 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
436 reinterpret_cast<uintptr_t>(standard_output) + 0x84u) = mask;
437 } else {
438 *reinterpret_cast<volatile uint32_t*>( // ok reinterpret cast - Teensy GPIO alias address map
439 reinterpret_cast<uintptr_t>(standard_output) + 0x88u) = mask;
440 }
441 *fast_mode = saved_fast_mode;
442 *standard_mode = saved_standard_mode;
443 *gpr = saved_gpr;
444 *tx_pad = saved_tx_pad;
445 *tx_mux = saved_tx_mux;
446 *rx_pad = saved_rx_pad;
447 *rx_mux = saved_rx_mux;
448
449 probe.set("success", true);
450 return probe;
451#endif
452}
453
454fl::json measureTightTiming(const fl::string& driver_name,
455 const fl::ChipsetTimingConfig& timing,
456 const fl::vector<fl::ChannelConfig>& tx_configs,
457 int iterations,
458 uint32_t max_allowed_overhead_us,
459 bool& out_passed) {
460 fl::json metric = fl::json::object();
461 out_passed = false;
462
463 metric.set("requested", true);
464 metric.set("supported", false);
465 metric.set("driver", driver_name.c_str());
466
467 if (iterations < 1) {
468 metric.set("message", "iterations must be >= 1");
469 return metric;
470 }
471 if (tx_configs.empty()) {
472 metric.set("message", "no channel configs");
473 return metric;
474 }
475 for (fl::size i = 0; i < tx_configs.size(); i++) {
476 if (tx_configs[i].isSpi()) {
477 metric.set("message", "clocked SPI timing metric is not supported");
478 return metric;
479 }
480 }
481
482 fl::vector<fl::ChannelConfig> sample_configs = tx_configs;
484 for (fl::size i = 0; i < sample_configs.size(); i++) {
485 fl::ChannelConfig channel_config(
486 sample_configs[i].getDataPin(),
487 timing,
488 sample_configs[i].mLeds,
489 sample_configs[i].rgb_order);
490 fl::shared_ptr<fl::Channel> channel = FastLED.add(channel_config);
491 if (!channel) {
493 metric.set("message", "failed to create channel");
494 return metric;
495 }
496 channels.push_back(channel);
497 }
498
499 ScopedFastLedBrightness scoped_brightness(255);
500 for (fl::size lane = 0; lane < sample_configs.size(); lane++) {
501 fill_solid(sample_configs[lane].mLeds.data(),
502 sample_configs[lane].mLeds.size(),
504 }
505 FastLED.show();
506 if (!FastLED.wait(1000)) {
508 metric.set("message", "warmup wait timeout");
509 return metric;
510 }
511 delay(2);
512
513 const uint32_t expected_wire_us =
514 expectedClocklessWireUs(timing, maxLaneLeds(sample_configs));
515 uint32_t min_show_us = 0xFFFFFFFFu;
516 uint32_t max_show_us = 0;
517 uint32_t min_wait_us = 0xFFFFFFFFu;
518 uint32_t max_wait_us = 0;
519 uint32_t min_total_us = 0xFFFFFFFFu;
520 uint32_t max_total_us = 0;
521 uint32_t min_overhead_us = 0xFFFFFFFFu;
522 uint32_t max_overhead_us = 0;
523 uint64_t sum_show_us = 0;
524 uint64_t sum_wait_us = 0;
525 uint64_t sum_total_us = 0;
526 uint64_t sum_overhead_us = 0;
527 int samples = 0;
528 bool timed_out = false;
529
530 for (int sample = 0; sample < iterations; sample++) {
531 for (fl::size lane = 0; lane < sample_configs.size(); lane++) {
532 const uint8_t r = static_cast<uint8_t>(31 + sample * 17 + lane * 11);
533 const uint8_t g = static_cast<uint8_t>(67 + sample * 23 + lane * 7);
534 const uint8_t b = static_cast<uint8_t>(103 + sample * 29 + lane * 5);
535 fill_solid(sample_configs[lane].mLeds.data(),
536 sample_configs[lane].mLeds.size(),
537 CRGB(r, g, b));
538 }
539
540 const uint32_t t0 = micros();
541 FastLED.show();
542 const uint32_t t1 = micros();
543 const bool ok = FastLED.wait(1000);
544 const uint32_t t2 = micros();
545 if (!ok) {
546 timed_out = true;
547 break;
548 }
549
550 const uint32_t show_us = t1 - t0;
551 const uint32_t wait_us = t2 - t1;
552 const uint32_t total_us = t2 - t0;
553 const uint32_t overhead_us =
554 total_us > expected_wire_us ? total_us - expected_wire_us : 0;
555
556 if (show_us < min_show_us) min_show_us = show_us;
557 if (show_us > max_show_us) max_show_us = show_us;
558 if (wait_us < min_wait_us) min_wait_us = wait_us;
559 if (wait_us > max_wait_us) max_wait_us = wait_us;
560 if (total_us < min_total_us) min_total_us = total_us;
561 if (total_us > max_total_us) max_total_us = total_us;
562 if (overhead_us < min_overhead_us) min_overhead_us = overhead_us;
563 if (overhead_us > max_overhead_us) max_overhead_us = overhead_us;
564
565 sum_show_us += show_us;
566 sum_wait_us += wait_us;
567 sum_total_us += total_us;
568 sum_overhead_us += overhead_us;
569 samples++;
570 }
571
573
574 metric.set("supported", true);
575 metric.set("samples", static_cast<int64_t>(samples));
576 metric.set("iterations", static_cast<int64_t>(iterations));
577 metric.set("expected_wire_us", static_cast<int64_t>(expected_wire_us));
578 metric.set("max_allowed_overhead_us",
579 static_cast<int64_t>(max_allowed_overhead_us));
580
581 if (samples == 0) {
582 metric.set("passed", false);
583 metric.set("message", timed_out ? "timing wait timeout" : "no samples");
584 return metric;
585 }
586
587 metric.set("min_show_us", static_cast<int64_t>(min_show_us));
588 metric.set("max_show_us", static_cast<int64_t>(max_show_us));
589 metric.set("avg_show_us",
590 static_cast<int64_t>(sum_show_us / static_cast<uint64_t>(samples)));
591 metric.set("min_wait_us", static_cast<int64_t>(min_wait_us));
592 metric.set("max_wait_us", static_cast<int64_t>(max_wait_us));
593 metric.set("avg_wait_us",
594 static_cast<int64_t>(sum_wait_us / static_cast<uint64_t>(samples)));
595 metric.set("min_total_us", static_cast<int64_t>(min_total_us));
596 metric.set("max_total_us", static_cast<int64_t>(max_total_us));
597 metric.set("avg_total_us",
598 static_cast<int64_t>(sum_total_us / static_cast<uint64_t>(samples)));
599 metric.set("min_overhead_us", static_cast<int64_t>(min_overhead_us));
600 metric.set("max_overhead_us", static_cast<int64_t>(max_overhead_us));
601 metric.set("avg_overhead_us",
602 static_cast<int64_t>(sum_overhead_us / static_cast<uint64_t>(samples)));
603
604 out_passed = !timed_out && max_overhead_us <= max_allowed_overhead_us;
605 metric.set("passed", out_passed);
606 if (timed_out) {
607 metric.set("message", "timing wait timeout");
608 } else {
609 metric.set("message", out_passed ? "tight timing within budget"
610 : "tight timing exceeded budget");
611 }
612 return metric;
613}
614
615} // namespace
616
617// ============================================================================
618// AutoResearchRemoteControl Private Helper Functions
619// ============================================================================
620
622 fl::json response = fl::json::object();
623
624 // RPC system unwraps single-element arrays, so args is the config object directly
625 if (!args.is_object()) {
626 response.set("success", false);
627 response.set("error", "InvalidArgs");
628 response.set("message", "Expected {driver, laneSizes, pattern?, iterations?, pinTx?, pinRx?, timing?}");
629 return response;
630 }
631
632 fl::json config = args;
633
634 // ========== REQUIRED PARAMETERS ==========
635
636 // 1. Extract driver (required)
637 if (!config.contains("driver") || !config["driver"].is_string()) {
638 response.set("success", false);
639 response.set("error", "MissingDriver");
640 response.set("message", "Required field 'driver' (string) missing");
641 return response;
642 }
643 fl::string driver_name = config["driver"].as_string().value();
644 const bool is_object_fled_driver = (driver_name == "OBJECT_FLED");
645
646 // Validate driver exists
647 bool driver_found = false;
648 for (fl::size i = 0; i < mState->drivers_available.size(); i++) {
649 if (mState->drivers_available[i].name == driver_name) {
650 driver_found = true;
651 break;
652 }
653 }
654 if (!driver_found) {
655 response.set("success", false);
656 response.set("error", "UnknownDriver");
657 fl::sstream msg;
658 msg << "Driver '" << driver_name.c_str() << "' not available";
659 response.set("message", msg.str().c_str());
660 return response;
661 }
662
663 // 2. Extract laneSizes (required)
664 if (!config.contains("laneSizes") || !config["laneSizes"].is_array()) {
665 response.set("success", false);
666 response.set("error", "MissingLaneSizes");
667 response.set("message", "Required field 'laneSizes' (array) missing");
668 return response;
669 }
670
671 fl::json lane_sizes_json = config["laneSizes"];
672 if (lane_sizes_json.size() == 0 || lane_sizes_json.size() > 16) {
673 response.set("success", false);
674 response.set("error", "InvalidLaneCount");
675 response.set("message", "laneSizes must have 1-16 elements");
676 return response;
677 }
678
679 fl::vector<int> lane_sizes;
680 // A coarse, platform-independent backstop, kept only so an absurd request
681 // is rejected before anything is allocated. It is not the capture limit:
682 // on RP the real, encoder- and timing-aware bound is applied further down,
683 // once the timing is resolved, and is strictly tighter than this one
684 // (FastLED#4371).
685 const int max_leds_per_lane = mState->rx_buffer.size() / 32;
686 for (fl::size i = 0; i < lane_sizes_json.size(); i++) {
687 if (!lane_sizes_json[i].is_int()) {
688 response.set("success", false);
689 response.set("error", "InvalidLaneSizeType");
690 fl::sstream msg;
691 msg << "laneSizes[" << i << "] must be integer";
692 response.set("message", msg.str().c_str());
693 return response;
694 }
695 int size = static_cast<int>(lane_sizes_json[i].as_int().value());
696 if (size <= 0) {
697 response.set("success", false);
698 response.set("error", "InvalidLaneSize");
699 fl::sstream msg;
700 msg << "laneSizes[" << i << "] = " << size << " must be > 0";
701 response.set("message", msg.str().c_str());
702 return response;
703 }
704 if (size > max_leds_per_lane) {
705 response.set("success", false);
706 response.set("error", "LaneSizeTooLarge");
707 fl::sstream msg;
708 msg << "laneSizes[" << i << "] = " << size << " exceeds max " << max_leds_per_lane;
709 response.set("message", msg.str().c_str());
710 return response;
711 }
712 lane_sizes.push_back(size);
713 }
714
715 // ========== OPTIONAL PARAMETERS ==========
716
717 // 3. Extract pattern (optional, default: "MSB_LSB_A")
718 fl::string pattern = "MSB_LSB_A";
719 if (config.contains("pattern") && config["pattern"].is_string()) {
720 pattern = config["pattern"].as_string().value();
721 }
722
723 // 4. Extract iterations (optional, default: 1)
724 int iterations = 1;
725 if (config.contains("iterations") && config["iterations"].is_int()) {
726 iterations = static_cast<int>(config["iterations"].as_int().value());
727 if (iterations < 1) {
728 response.set("success", false);
729 response.set("error", "InvalidIterations");
730 response.set("message", "iterations must be >= 1");
731 return response;
732 }
733 }
734
735 // 4b. Extract frameCount (optional, default: 1)
736 // Number of back-to-back captures of the SAME LED buffer within a single
737 // pattern. frameCount >= 2 exposes second-frame degradation bugs where a
738 // driver corrupts or zeroes its DMA buffer after the first show() — see
739 // issues #2254 and #2288 (ESP32-S3 SPI \"black frame between displays\").
740 int frame_count = 1;
741 if (config.contains("frameCount") && config["frameCount"].is_int()) {
742 frame_count = static_cast<int>(config["frameCount"].as_int().value());
743 if (frame_count < 1 || frame_count > 16) {
744 response.set("success", false);
745 response.set("error", "InvalidFrameCount");
746 response.set("message", "frameCount must be in [1, 16]");
747 return response;
748 }
749 }
750
751 // 4c. Extract maxPowerMw (optional, default: 0 = unlimited). Applies
752 // FastLED.setMaxPowerInMilliWatts() for the run and checks the wire
753 // against the limiter's brightness (#5139). Single clockless RGB lane
754 // only: the oracle models lane 0's pixels and the MCU baseline alone.
755 uint32_t max_power_mw = 0;
756 if (config.contains("maxPowerMw")) {
757 if (!config["maxPowerMw"].is_int() ||
758 config["maxPowerMw"].as_int().value() < 0 ||
759 config["maxPowerMw"].as_int().value() > 10000000) {
760 response.set("success", false);
761 response.set("error", "InvalidMaxPowerMw");
762 response.set("message", "maxPowerMw must be an integer in [0, 10000000]");
763 return response;
764 }
765 max_power_mw = static_cast<uint32_t>(config["maxPowerMw"].as_int().value());
766 }
767
768 // 5. Extract pinTx (optional, default: use mState->pin_tx)
769 int pin_tx = mState->pin_tx;
770 if (config.contains("pinTx") && config["pinTx"].is_int()) {
771 pin_tx = static_cast<int>(config["pinTx"].as_int().value());
772 if (pin_tx < 0 || pin_tx > 48) {
773 response.set("success", false);
774 response.set("error", "InvalidPinTx");
775 response.set("message", "pinTx must be 0-48");
776 return response;
777 }
778 }
779
780 // 6. Extract pinRx (optional, default: use mState->pin_rx)
781 int pin_rx = mState->pin_rx;
782 if (config.contains("pinRx") && config["pinRx"].is_int()) {
783 pin_rx = static_cast<int>(config["pinRx"].as_int().value());
784 if (pin_rx < 0 || pin_rx > 48) {
785 response.set("success", false);
786 response.set("error", "InvalidPinRx");
787 response.set("message", "pinRx must be 0-48");
788 return response;
789 }
790 }
791
792 fl::vector<int> lane_pins;
793 const bool explicit_lane_pins = config.contains("lanePins");
794 if (explicit_lane_pins && (!config["lanePins"].is_array() ||
795 config["lanePins"].size() != lane_sizes.size())) {
796 response.set("success", false);
797 response.set("error", "InvalidLanePins");
798 response.set("message", "lanePins must contain one GPIO per lane");
799 return response;
800 }
801 for (fl::size i = 0; i < lane_sizes.size(); ++i) {
802 const auto pin_value = explicit_lane_pins ? config["lanePins"][i] : fl::json(pin_tx + static_cast<int>(i));
803 if (!pin_value.is_int()) {
804 response.set("success", false);
805 response.set("error", "InvalidLanePins");
806 return response;
807 }
808 const auto raw_pin = pin_value.as_int().value();
809 if (explicit_lane_pins && (raw_pin < 0 || raw_pin > 48)) {
810 response.set("success", false);
811 response.set("error", "InvalidLanePins");
812 return response;
813 }
814 const int pin = static_cast<int>(raw_pin);
815 bool duplicate = false;
816 for (const int previous : lane_pins) { duplicate = duplicate || previous == pin; }
817 if (explicit_lane_pins && (pin == pin_rx ||
818 duplicate || (i == 0 && pin != pin_tx))) {
819 response.set("success", false);
820 response.set("error", "InvalidLanePins");
821 response.set("message", "lanePins must be unique GPIOs 0-48 excluding RX, with lane 0 matching TX");
822 return response;
823 }
824 lane_pins.push_back(pin);
825 }
826
827 // 7. Extract timing (optional, default: "WS2812B-V5")
828 fl::string timing_name = "WS2812B-V5";
829 if (config.contains("timing") && config["timing"].is_string()) {
830 timing_name = config["timing"].as_string().value();
831 }
832
833 // 8. Extract useLegacyApi (optional, default: false)
834 bool use_legacy_api = false;
835 if (config.contains("useLegacyApi") && config["useLegacyApi"].is_bool()) {
836 use_legacy_api = config["useLegacyApi"].as_bool().value();
837 }
838
839 bool legacy_rgbw = false;
840 if (config.contains("legacyRgbw")) {
841 if (!use_legacy_api) {
842 response.set("success", false);
843 response.set("error", "LegacyRgbwRequiresLegacyApi");
844 response.set("message", "legacyRgbw requires useLegacyApi=true");
845 return response;
846 }
847 if (!config["legacyRgbw"].is_bool()) {
848 response.set("success", false);
849 response.set("error", "InvalidLegacyRgbw");
850 response.set("message", "legacyRgbw must be a boolean");
851 return response;
852 }
853 legacy_rgbw = config["legacyRgbw"].as_bool().value();
854 }
855
856 fl::vector<LegacyClocklessChipset> legacy_chipsets;
857 if (config.contains("legacyChipsets") && !use_legacy_api) {
858 response.set("success", false);
859 response.set("error", "LegacyChipsetsRequireLegacyApi");
860 response.set("message", "legacyChipsets requires useLegacyApi=true");
861 return response;
862 }
863 if (use_legacy_api) {
864 for (fl::size i = 0; i < lane_sizes.size(); i++) {
866 }
867 if (config.contains("legacyChipsets")) {
868 if (!config["legacyChipsets"].is_array()) {
869 response.set("success", false);
870 response.set("error", "InvalidLegacyChipsets");
871 response.set("message", "legacyChipsets must be an array");
872 return response;
873 }
874 fl::json legacy_chipsets_json = config["legacyChipsets"];
875 if (legacy_chipsets_json.size() != lane_sizes.size()) {
876 response.set("success", false);
877 response.set("error", "InvalidLegacyChipsetCount");
878 response.set("message", "legacyChipsets length must match laneSizes");
879 return response;
880 }
881 for (fl::size i = 0; i < legacy_chipsets_json.size(); i++) {
882 if (!legacy_chipsets_json[i].is_string()) {
883 response.set("success", false);
884 response.set("error", "InvalidLegacyChipsetType");
885 response.set("message", "legacyChipsets entries must be strings");
886 return response;
887 }
888 fl::string chipset_name =
889 legacy_chipsets_json[i].as_string().value();
891 if (!legacyClocklessChipsetFromName(chipset_name, &chipset)) {
892 response.set("success", false);
893 response.set("error", "UnsupportedLegacyChipset");
894 response.set(
895 "message",
896 "supported legacyChipsets: WS2812B, WS2814, WS2818, SK6812");
897 return response;
898 }
899 legacy_chipsets[i] = chipset;
900 }
901 }
902 }
903
904 fl::Core worker_core = fl::Core::Auto;
905 const bool worker_core_test = config.contains("workerCore");
906 if (worker_core_test) {
907 const fl::string requested = config["workerCore"] | fl::string("");
908 if (driver_name != "LCD_CLOCKLESS" ||
909 (requested != "auto" && requested != "0" && requested != "1" &&
910 requested != "any" && requested != "calling")) {
911 response.set("success", false);
912 response.set("error", "InvalidWorkerCore");
913 response.set("message", "workerCore requires LCD_CLOCKLESS and auto, 0, 1, any or calling");
914 return response;
915 }
916 worker_core = requested == "auto" ? fl::Core::Auto :
917 requested == "0" ? fl::Core::Core0 :
918 requested == "1" ? fl::Core::Core1 :
919 requested == "any" ? fl::Core::Any : fl::Core::CallingCore;
920 if (use_legacy_api && worker_core != fl::Core::Auto) {
921 response.set("success", false);
922 response.set("error", "UnsupportedWorkerCoreLegacyApi");
923 response.set("message", "Explicit worker core selection requires the Channels API");
924 return response;
925 }
926 bool plain_ws2812b = !legacy_rgbw;
927 for (const auto chipset : legacy_chipsets) {
928 plain_ws2812b = plain_ws2812b &&
930 }
931 if (use_legacy_api && !plain_ws2812b) {
932 response.set("success", false);
933 response.set("error", "UnsupportedWorkerCoreLegacyChipset");
934 response.set("message", "workerCore legacy validation supports plain WS2812B only");
935 return response;
936 }
938 response.set("success", false);
939 response.set("error", "WorkerCoreUnsupportedPlatform");
940 return response;
941 }
942 }
943
944 const char* legacy_driver_name = nullptr;
945 if (use_legacy_api) {
946 legacy_driver_name = worker_core_test ? "LCD_CLOCKLESS" : legacyClocklessBoundDriverName();
947 if (legacy_driver_name != nullptr &&
948 driver_name != legacy_driver_name) {
949 response.set("success", false);
950 response.set("error", "LegacyDriverMismatch");
951 fl::sstream msg;
952 msg << "Legacy templates are compile-time bound to "
953 << legacy_driver_name << ", but the request selected "
954 << driver_name.c_str();
955 response.set("message", msg.str().c_str());
956 return response;
957 }
958 }
959
960 // 9. Extract contaminateTxMux (optional, default: false)
961 bool contaminate_tx_mux = false;
962 if (config.contains("contaminateTxMux") &&
963 config["contaminateTxMux"].is_bool()) {
964 contaminate_tx_mux = config["contaminateTxMux"].as_bool().value();
965 }
966
967 // 10. Extract tightTiming (optional, default: false)
968 bool measure_tight_timing = false;
969 if (config.contains("tightTiming") && config["tightTiming"].is_bool()) {
970 measure_tight_timing = config["tightTiming"].as_bool().value();
971 }
972
973 int tight_timing_iterations = 8;
974 if (config.contains("tightTimingIterations") &&
975 config["tightTimingIterations"].is_int()) {
976 tight_timing_iterations =
977 static_cast<int>(config["tightTimingIterations"].as_int().value());
978 if (tight_timing_iterations < 1 || tight_timing_iterations > 64) {
979 response.set("success", false);
980 response.set("error", "InvalidTightTimingIterations");
981 response.set("message", "tightTimingIterations must be in [1, 64]");
982 return response;
983 }
984 }
985
986 uint32_t tight_timing_max_overhead_us = 2000;
987 if (config.contains("tightTimingMaxOverheadUs") &&
988 config["tightTimingMaxOverheadUs"].is_int()) {
989 const int max_overhead =
990 static_cast<int>(config["tightTimingMaxOverheadUs"].as_int().value());
991 if (max_overhead < 1) {
992 response.set("success", false);
993 response.set("error", "InvalidTightTimingMaxOverheadUs");
994 response.set("message", "tightTimingMaxOverheadUs must be >= 1");
995 return response;
996 }
997 tight_timing_max_overhead_us = static_cast<uint32_t>(max_overhead);
998 }
999
1000 // Legacy API: pins 0-8 are the historical compile-time template range.
1001 // On Teensy 4.x, pin 22 is also included for current ObjectFLED loopback
1002 // wiring. Other targets may mark GPIO22 invalid at compile time.
1003 // Multi-lane uses consecutive pins starting at pin_tx.
1004 if (use_legacy_api) {
1005 int max_pin = pin_tx;
1006 for (const int pin : lane_pins) { if (pin > max_pin) { max_pin = pin; } }
1007 const bool historical_pin_range = pin_tx >= 0 && max_pin <= 8;
1008#if AUTORESEARCH_LEGACY_SUPPORTS_PIN_22
1009 const bool current_loopback_pin =
1010 lane_sizes.size() == 1 && pin_tx == 22;
1011#else
1012 const bool current_loopback_pin = false;
1013#endif
1014 if (!historical_pin_range && !current_loopback_pin) {
1015 response.set("success", false);
1016 response.set("error", "LegacyApiPinRange");
1017 fl::sstream msg;
1018 msg << "Legacy template API supports pins 0-8";
1019#if AUTORESEARCH_LEGACY_SUPPORTS_PIN_22
1020 msg << ", plus single-lane pin 22 for current ObjectFLED loopback";
1021#endif
1022 msg << ", got pins " << pin_tx << "-" << max_pin;
1023 response.set("message", msg.str().c_str());
1024 return response;
1025 }
1026 }
1027
1028 // ========== EXECUTION ==========
1029
1030 uint32_t start_ms = millis();
1031 const auto heap_before = fl::getFreeHeap();
1032
1033 fl::json standard_gpio_pad_probe;
1034 if (is_object_fled_driver) {
1035 standard_gpio_pad_probe = probeStandardGpioPad(pin_tx, pin_rx);
1036 }
1037
1038 if (contaminate_tx_mux) {
1039 if (!is_object_fled_driver) {
1040 response.set("success", false);
1041 response.set("error", "MuxContaminationDriverUnsupported");
1042 response.set("message", "contaminateTxMux is only supported for OBJECT_FLED");
1043 return response;
1044 }
1045 if (!contaminateTxMuxWithPwm(pin_tx)) {
1046 response.set("success", false);
1047 response.set("error", "MuxContaminationUnsupported");
1048 response.set("message", "contaminateTxMux requires Teensy 4.x analogWriteFrequency support");
1049 return response;
1050 }
1051 }
1052
1053 // Set driver as exclusive (by-name path: driver_name comes from RPC)
1054 if (!autoResearchSetExclusiveDriverByName(driver_name.c_str())) {
1055 response.set("success", false);
1056 response.set("error", "DriverSetupFailed");
1057 fl::sstream msg;
1058 msg << "Failed to set " << driver_name.c_str() << " as exclusive driver";
1059 response.set("message", msg.str().c_str());
1060 return response;
1061 }
1062
1063 // Get timing configuration
1064 // Legacy API: resolve timing from the selected public chipset template.
1065 // If mixed legacy chipsets are requested, lane 0 timing is used for RX
1066 // decode because AutoResearch captures only lane 0.
1067 // Channel API: Uses timing_name from RPC (default: WS2812B-V5)
1068 // RX decode timing MUST match actual TX timing for correct capture
1069 fl::ChipsetTimingConfig resolved_timing;
1071 if (use_legacy_api) {
1073 if (!legacy_chipsets.empty()) {
1074 first_chipset = legacy_chipsets[0];
1075 }
1076 if (first_chipset == LegacyClocklessChipset::WS2814) {
1077 resolved_timing = fl::makeTimingConfig<fl::TIMING_WS2814>();
1078 resolved_encoder = fl::encoder_for<fl::TIMING_WS2814>();
1079 } else if (first_chipset == LegacyClocklessChipset::WS2818) {
1080 resolved_timing = fl::makeTimingConfig<fl::TIMING_WS2818>();
1081 resolved_encoder = fl::encoder_for<fl::TIMING_WS2818>();
1082 } else if (first_chipset == LegacyClocklessChipset::SK6812) {
1083 resolved_timing = fl::makeTimingConfig<fl::TIMING_SK6812>();
1084 resolved_encoder = fl::encoder_for<fl::TIMING_SK6812>();
1085 } else {
1087 resolved_encoder = fl::encoder_for<fl::TIMING_WS2812_800KHZ>();
1088 }
1089 timing_name = legacyClocklessChipsetName(first_chipset);
1090 } else if (timing_name == "UCS7604-800KHZ") {
1092 resolved_encoder = fl::encoder_for<fl::TIMING_UCS7604_800KHZ>();
1093 } else if (timing_name == "WS2811-400KHZ") {
1094 // 2500 ns period. The RP PL011 tops out at clk_peri/16 = 3.0 Mbaud,
1095 // below the >=3.2 Mbaud that WS2812's 1250 ns needs at the coarsest
1096 // (4 pulses/bit) UART geometry -- so 800 kHz parts cannot be driven
1097 // over UART there at all. At 2500 ns the requirement drops to
1098 // 1.6 Mbaud, which fits, and exercises the backend on RP for the
1099 // first time. See FastLED#3899.
1101 resolved_encoder = fl::encoder_for<fl::TIMING_WS2811_400KHZ>();
1102 } else if (timing_name == "SK6812") {
1103 // SK6812 exercises the UART wave8-frame geometry (its T0H/T1H
1104 // are exact multiples of period/4 — FastLED#3572 follow-up).
1105 resolved_timing = fl::makeTimingConfig<fl::TIMING_SK6812>();
1106 resolved_encoder = fl::encoder_for<fl::TIMING_SK6812>();
1107 } else if (timing_name == "WS2818") {
1108 resolved_timing = fl::makeTimingConfig<fl::TIMING_WS2818>();
1109 resolved_encoder = fl::encoder_for<fl::TIMING_WS2818>();
1110 } else {
1112 resolved_encoder = fl::encoder_for<fl::TIMING_WS2812B_V5>();
1113 }
1114 fl::NamedTimingConfig timing_config(resolved_timing, timing_name.c_str(), resolved_encoder);
1115
1116 // Dynamically allocate LED arrays for each lane
1117 fl::vector<fl::unique_ptr<fl::vector<CRGB>>> led_arrays;
1118 fl::vector<fl::ChannelConfig> tx_configs;
1119
1120 // SPI chipset drivers use APA102 protocol with data+clock pins.
1121 // Clockless drivers use WS2812B timing on a single data pin
1122 bool is_spi_chipset_driver = (driver_name == "LCD_SPI" ||
1123 driver_name == "I2S_SPI" ||
1124 driver_name == "SPI_UNIFIED");
1125
1126 for (fl::size i = 0; i < lane_sizes.size(); i++) {
1127 auto leds = fl::make_unique<fl::vector<CRGB>>(lane_sizes[i]);
1128 if (is_spi_chipset_driver) {
1129 // SPI chipset: APA102 with data pin = pin_tx (lane 0 only)
1130 // Multi-lane SPI validation is not currently supported because
1131 // the I80 bus transposes all lanes onto a single bus — only
1132 // lane 0 (D0) can be captured via the TX→RX jumper wire.
1133 // Clock pin must avoid TX, RX, and DC (21) pins.
1134 int data_pin = pin_tx;
1135 int clock_pin = pin_rx + 1;
1136 // Use 2.4MHz SPI clock (matches I2S LCD_CAM default, ~417ns/bit)
1137 // Lower frequencies (e.g., 800kHz) fail with ESP_ERR_NOT_SUPPORTED
1138 // on the I80 panel IO.
1139 fl::SpiChipsetConfig spi_cfg(data_pin, clock_pin, fl::SpiEncoder::apa102(2400000));
1140 tx_configs.push_back(fl::ChannelConfig(
1141 spi_cfg,
1142 fl::span<CRGB>(leds->data(), leds->size()),
1143 RGB
1144 ));
1145 } else {
1146 tx_configs.push_back(fl::ChannelConfig(
1147 lane_pins[i],
1148 timing_config.timing,
1149 fl::span<CRGB>(leds->data(), leds->size()),
1150 RGB // Default color order
1151 ));
1152 }
1153 if (worker_core_test) {
1154 tx_configs.back().options.mBus = fl::Bus::FLEX_IO;
1155 tx_configs.back().options.mWorker.core = worker_core;
1156 tx_configs.back().options.mWorker.priority = fl::Priority::High;
1157 }
1158 led_arrays.push_back(fl::move(leds));
1159 }
1160
1161 // Create temporary RX channel if pinRx differs from default
1162 fl::shared_ptr<fl::RxChannel> rx_channel_to_use = mState->rx_channel;
1163
1164 // Optional rxBackend override (FastLED#3576 Phase 3) — lets the
1165 // host select a specific capture backend per test, e.g. "I2S_RX"
1166 // (classic-ESP32 oversampler, no 10-LED ceiling) vs "RMT".
1167 fl::RxBackend rx_backend_override = fl::RxBackend::PLATFORM_DEFAULT;
1168 bool have_backend_override = false;
1169 if (config.contains("rxBackend") && config["rxBackend"].is_string()) {
1170 fl::string rb = config["rxBackend"].as_string().value();
1171 if (rb == "RMT") { rx_backend_override = fl::RxBackend::RMT; have_backend_override = true; }
1172 else if (rb == "ISR") { rx_backend_override = fl::RxBackend::ISR; have_backend_override = true; }
1173 else if (rb == "I2S_RX") { rx_backend_override = fl::RxBackend::I2S_RX; have_backend_override = true; }
1174 else if (rb != "PLATFORM_DEFAULT") {
1175 response.set("success", false);
1176 response.set("error", "UnknownRxBackend");
1177 response.set("message", "rxBackend must be PLATFORM_DEFAULT, RMT, ISR or I2S_RX");
1178 return response;
1179 }
1180 }
1181
1182 // ESP32-C6 RMT RX merges PARLIO's waveform into its frame envelope even
1183 // while the GPIO input sees every edge (FastLED#3586). Keep explicit
1184 // backend overrides available for diagnostics, but use the independent
1185 // GPIO ISR timestamp path for normal C6 PARLIO wire validation.
1186#if defined(FL_IS_ESP_32C6)
1187 constexpr bool is_esp32_c6 = true;
1188#else
1189 constexpr bool is_esp32_c6 = false;
1190#endif
1191 rx_backend_override = fl::validation::resolveCaptureBackend(
1192 rx_backend_override, have_backend_override,
1193 driver_name == "PARLIO", is_esp32_c6);
1194 if (rx_backend_override != fl::RxBackend::PLATFORM_DEFAULT) {
1195 have_backend_override = true;
1196 }
1197
1198 // A per-call RX channel has to displace the standing one, not sit
1199 // alongside it.
1200 //
1201 // The RP PIO capture buffer is a single global, claimed by whichever
1202 // device calls begin() first and released only in stop() -- so a standing
1203 // channel that has already captured once still owns it. A second channel
1204 // built next to it fails begin() with `dma_buffer_busy` and captures
1205 // nothing, while the response echoes the requested pins back through
1206 // actualRxPin as though the change took effect. `setPins` never hit this
1207 // because it *replaces* mState->rx_channel, destroying the old device and
1208 // releasing the claim. Confirmed on an RP2350W: the failing run reports
1209 // rxBeginError='dma_buffer_busy'. See FastLED#4374.
1210 //
1211 // Restoring it afterwards keeps inline pins scoped to the one call, which
1212 // is what a caller probing alternative wiring means by them -- adopting
1213 // the pin as standing state would trade a silent failure for a silent
1214 // reconfiguration.
1215 StandingRxChannelSwap standing_rx_swap(mState.get());
1216 if (have_backend_override) {
1217 standing_rx_swap.release(&rx_channel_to_use);
1218 fl::RxChannelConfig rx_cfg(pin_rx, rx_backend_override);
1219 rx_channel_to_use = FastLED.addRx(rx_cfg);
1220 if (!rx_channel_to_use) {
1221 response.set("success", false);
1222 response.set("error", "RxChannelCreationFailed");
1223 response.set("message", "Failed to create RX channel for requested rxBackend");
1224 return response;
1225 }
1226 } else if (pin_rx != mState->pin_rx && mState->rx_factory) {
1227 standing_rx_swap.release(&rx_channel_to_use);
1228 rx_channel_to_use = mState->rx_factory(pin_rx);
1229 if (!rx_channel_to_use) {
1230 response.set("success", false);
1231 response.set("error", "RxChannelCreationFailed");
1232 response.set("message", "Failed to create RX channel on custom pin");
1233 return response;
1234 }
1235 }
1236
1237#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
1238 // The `laneSizes` guard above bounds the request with
1239 // `rx_buffer.size() / 32`, which measures the wrong thing: `rx_buffer` is
1240 // the decode *output*, and 32 has no relation to the capture. It advertised
1241 // 103 LEDs, and 101, 102 and 103 were all accepted and then failed in
1242 // capture with no error at all -- the outcome a bounds check exists to
1243 // prevent (FastLED#4371).
1244 //
1245 // Two things decide where this check can live. The real ceiling needs the
1246 // resolved timing and encoder, so it cannot sit with the rest of the
1247 // argument validation; and it belongs to the backend that *captures*, not
1248 // the driver that transmits, so it has to follow the RX channel. On RP,
1249 // PLATFORM_DEFAULT resolves to PIO RX whatever the TX driver is -- keying
1250 // off `driver_name` would skip the bound for a UART0 request, which is
1251 // captured by the same pool and hits the same ceiling, while applying a
1252 // PIO-only limit to a PIO TX pointed at some other backend.
1253 const fl::RxBackend capture_backend_for_limit =
1254 rx_channel_to_use ? rx_channel_to_use->backend()
1256 if (capture_backend_for_limit == fl::RxBackend::PLATFORM_DEFAULT ||
1257 capture_backend_for_limit == fl::RxBackend::PIO) {
1258 // Reserve for the gap between arming the capture and the transmitter's
1259 // first edge, which the sampler also spends words on. Measured on an
1260 // RP2350W it sits between 4 us and 64 us: a 63-LED 400 kHz frame passes
1261 // with 64 us of budget to spare and a 64-LED one fails with 4 us. Take
1262 // the upper end -- advertising a maximum that does not work is the
1263 // defect being removed here, so erring long is not symmetric with
1264 // erring short.
1265 constexpr fl::u32 kArmingLeadInNs = 64000;
1266
1267 const fl::u32 bit_period_ns =
1268 static_cast<fl::u32>(resolved_timing.total_period_ns());
1269 const fl::size max_wire_bytes = fl::validation::rpPioMaxWireBytes(
1272 1000000000u / fl::kRpPioRxClockHz,
1273 fl::RxChannelConfig(pin_rx).signal_range_max_ns,
1274 kArmingLeadInNs, bit_period_ns);
1275
1276 for (fl::size i = 0; i < lane_sizes.size(); i++) {
1277 const fl::size leds = static_cast<fl::size>(lane_sizes[i]);
1278 // Same predicate the comparison uses (`legacyLaneUsesRgbw`): an
1279 // RGBW lane is four bytes per LED, so a 100-LED RGBW frame is 400
1280 // wire bytes and does not fit where an RGB one does.
1281 const bool lane_rgbw =
1282 legacy_rgbw ||
1283 (i < legacy_chipsets.size() &&
1284 legacyClocklessChipsetHasAutomaticRgbw(legacy_chipsets[i]));
1285 const fl::size wire_bytes =
1286 rpPioWireFrameBytes(leds, timing_config.encoder, lane_rgbw);
1287 if (wire_bytes > max_wire_bytes) {
1288 response.set("success", false);
1289 response.set("error", "LaneSizeTooLarge");
1290 fl::sstream msg;
1291 msg << "laneSizes[" << i << "] = " << lane_sizes[i] << " puts "
1292 << static_cast<int>(wire_bytes) << " bytes on the wire at "
1293 << timing_name.c_str() << "; PIO RX capture holds "
1294 << static_cast<int>(max_wire_bytes) << " ("
1295 << static_cast<int>(
1296 rpPioMaxLedsForWireBytes(max_wire_bytes,
1297 timing_config.encoder,
1298 lane_rgbw))
1299 << " LEDs)";
1300 response.set("message", msg.str().c_str());
1301 return response;
1302 }
1303 }
1304 }
1305#endif
1306
1307 // Create validation configuration
1308 fl::AutoResearchConfig autoresearch_config(
1309 timing_config.timing,
1310 timing_config.name,
1311 tx_configs,
1312 driver_name.c_str(),
1313 rx_channel_to_use,
1314 mState->rx_buffer,
1315 lane_sizes[0], // base_strip_size (used for logging)
1316 fl::RxDeviceType::RMT, // Default RX device type
1317 timing_config.encoder,
1318 fl::span<const LegacyClocklessChipset>(legacy_chipsets),
1319 legacy_rgbw
1320 );
1321 autoresearch_config.max_power_mw = max_power_mw;
1322 bool legacy_non_ws2812b = false;
1323 for (const auto chipset : legacy_chipsets) {
1324 if (chipset != LegacyClocklessChipset::WS2812B) {
1325 legacy_non_ws2812b = true; // WS2814 and friends emit RGBW
1326 }
1327 }
1328 if (max_power_mw != 0 &&
1329 (lane_sizes.size() != 1 || legacy_rgbw || legacy_non_ws2812b ||
1330 is_spi_chipset_driver ||
1331 fl::ClocklessEncoder::CLOCKLESS_ENCODER_WS2812 != timing_config.encoder)) {
1332 response.set("success", false);
1333 response.set("error", "MaxPowerUnsupportedConfig");
1334 response.set("message",
1335 "maxPowerMw needs one RGB clockless lane (WS2812B for the legacy API)");
1336 return response;
1337 }
1338
1339 // Run test with debug output suppressed
1340 int total_tests = 0;
1341 int passed_tests = 0;
1342 bool passed = false;
1343 uint32_t show_duration_ms = 0;
1344 fl::vector<fl::RunResult> run_results;
1345 WorkerCoreLoad worker_load;
1346 if (worker_core_test && !worker_load.start()) {
1347 response.set("success", false);
1348 response.set("error", "WorkerCoreLoadStartFailed");
1349 return response;
1350 }
1351 fl::json tight_timing_response = fl::json::object();
1352 bool tight_timing_passed = true;
1353
1354 {
1355 // Keep timing-sensitive hardware validation quiet. On Teensy 4,
1356 // Serial-backed FL_WARN output can block long enough to starve
1357 // ObjectFLED's DMA refill path, which is exactly what #3343 is
1358 // trying to prove or eliminate. JSON-RPC responses bypass this guard.
1359 //
1360 // LPUART note: empirically tried both directions (logs disabled vs
1361 // logs enabled during LPUART tests). Logs ENABLED yielded ~0/3
1362 // success (USB-CDC backed up during the 4-pattern loop, RPC
1363 // response never reaches host). Logs DISABLED yielded ~1/3 to
1364 // ~1/5 success. ScopedLogDisable stays in scope for LPUART too.
1365 fl::ScopedLogDisable quiet_logs;
1366
1367 if (is_object_fled_driver) {
1368 fl::objectFledDiagnosticsReset();
1369 fl::objectFledDiagnosticsSetRxPin(pin_rx);
1370 }
1371
1372 if (use_legacy_api) {
1373 // Legacy API path: selected CHIPSET<PIN> template instantiation
1374 for (int iter = 0; iter < iterations; iter++) {
1375 int iter_total = 0, iter_passed = 0;
1376 autoResearchChipsetTimingLegacy(autoresearch_config, iter_total, iter_passed, show_duration_ms, &run_results, frame_count);
1377 total_tests += iter_total;
1378 passed_tests += iter_passed;
1379 }
1380 } else {
1381 // Channel API path: FastLED.add(channel_config)
1382 for (int iter = 0; iter < iterations; iter++) {
1383 int iter_total = 0, iter_passed = 0;
1384 autoResearchChipsetTiming(autoresearch_config, iter_total, iter_passed, show_duration_ms, &run_results, frame_count);
1385 total_tests += iter_total;
1386 passed_tests += iter_passed;
1387 }
1388 }
1389
1390 passed = (total_tests > 0) && (passed_tests == total_tests);
1391 }
1392
1393 if (measure_tight_timing) {
1394 if (use_legacy_api) {
1395 tight_timing_passed = false;
1396 tight_timing_response.set("requested", true);
1397 tight_timing_response.set("supported", false);
1398 tight_timing_response.set("passed", false);
1399 tight_timing_response.set("driver", driver_name.c_str());
1400 tight_timing_response.set("message", "legacy API timing metric is not supported");
1401 } else {
1402 tight_timing_response = measureTightTiming(
1403 driver_name,
1404 timing_config.timing,
1405 tx_configs,
1406 tight_timing_iterations,
1407 tight_timing_max_overhead_us,
1408 tight_timing_passed);
1409 }
1410 bool tight_timing_supported = false;
1411 if (tight_timing_response.contains("supported") &&
1412 tight_timing_response["supported"].is_bool()) {
1413 tight_timing_supported =
1414 tight_timing_response["supported"].as_bool().value();
1415 }
1416 if (tight_timing_supported) {
1417 passed = passed && tight_timing_passed;
1418 }
1419 }
1420
1421 uint32_t duration_ms = millis() - start_ms;
1422 int capture_evidence_bytes = 0;
1423 int capture_evidence_raw_edges = 0;
1424 for (fl::size ri = 0; ri < run_results.size(); ri++) {
1425 const auto& rr = run_results[ri];
1426 if (rr.capturedBytes > 0) {
1427 capture_evidence_bytes += rr.capturedBytes;
1428 }
1429 if (rr.rawEdgesAfterWait > capture_evidence_raw_edges) {
1430 capture_evidence_raw_edges = rr.rawEdgesAfterWait;
1431 }
1432 }
1433
1434 // ========== RESPONSE ==========
1435 const auto heap_after = fl::getFreeHeap();
1436 response.set("heapBeforeInternal", static_cast<int64_t>(heap_before.free_sram));
1437 response.set("heapBeforePsram", static_cast<int64_t>(heap_before.free_psram));
1438 response.set("heapAfterInternal", static_cast<int64_t>(heap_after.free_sram));
1439 response.set("heapAfterPsram", static_cast<int64_t>(heap_after.free_psram));
1440 auto selected_driver = fl::ChannelManager::instance().findDriverByName(driver_name);
1441 if (selected_driver) {
1442 const auto state = selected_driver->poll();
1444 response.set("driverError", state.error.c_str());
1445 passed = false;
1446 }
1447 }
1448 if (worker_core_test) {
1449 worker_load.stop();
1450 if (!selected_driver) {
1451 passed = false;
1452 } else {
1453 const auto worker = selected_driver->workerDiagnostics();
1454 response.set("workerCore", worker.core);
1455 response.set("workerObservedCore", worker.observedCore);
1456 response.set("workerPriority", worker.priority);
1457 response.set("workerSubmittedChunks", static_cast<int64_t>(worker.submittedChunks));
1458 response.set("workerCompletedChunks", static_cast<int64_t>(worker.completedChunks));
1459 response.set("workerTotalChunks", static_cast<int64_t>(worker.totalChunks));
1460 response.set("workerMaxEncodeUs", static_cast<int64_t>(worker.maxEncodeUs));
1461 response.set("workerMaxSubmitUs", static_cast<int64_t>(worker.maxSubmitUs));
1462 response.set("workerStreamError", worker.streamError);
1463 }
1464 response.set("competingTaskPasses", static_cast<int64_t>(worker_load.passes()));
1465 response.set("competingTaskMaxPassUs", static_cast<int64_t>(worker_load.maxPassUs()));
1466 }
1467 response.set("success", true);
1468 response.set("passed", passed);
1469 response.set("totalTests", static_cast<int64_t>(total_tests));
1470 response.set("passedTests", static_cast<int64_t>(passed_tests));
1471 response.set("captureEvidenceExpected", true);
1472 response.set("captureEvidenceBytes",
1473 static_cast<int64_t>(capture_evidence_bytes));
1474 response.set("captureEvidenceRawEdges",
1475 static_cast<int64_t>(capture_evidence_raw_edges));
1476 response.set("duration_ms", static_cast<int64_t>(duration_ms));
1477 response.set("show_duration_ms", static_cast<int64_t>(show_duration_ms));
1478 response.set("driver", driver_name.c_str());
1479 response.set("requestedTxPin", static_cast<int64_t>(pin_tx));
1480 response.set("requestedRxPin", static_cast<int64_t>(pin_rx));
1481 response.set("actualTxPin", static_cast<int64_t>(pin_tx));
1482 response.set("actualRxPin", static_cast<int64_t>(
1483 rx_channel_to_use ? rx_channel_to_use->getPin() : pin_rx));
1484 fl::string capture_backend = rx_channel_to_use
1485 ? rx_channel_to_use->getEngineName()
1486 : fl::string("none");
1487 response.set("captureBackend", capture_backend.c_str());
1488 response.set("laneCount", static_cast<int64_t>(lane_sizes.size()));
1489 fl::json pins_response = fl::json::array();
1490 for (const auto& channel : tx_configs) {
1491 pins_response.push_back(static_cast<int64_t>(channel.getDataPin()));
1492 }
1493 response.set("lanePins", pins_response);
1494#if defined(FL_IS_RP2040) || defined(FL_IS_RP2350)
1495 if (driver_name == "UART0" || driver_name == "UART1") {
1496 auto& uart = driver_name == "UART0"
1497 ? fl::BusTraits<fl::Bus::UART, 0>::instance()
1498 : fl::BusTraits<fl::Bus::UART, 1>::instance();
1499 response.set("rpUartStartAttempted", uart.lastStartAttempted());
1500 response.set("rpUartStartSucceeded", uart.lastStartSucceeded());
1501 response.set("rpUartEncodedSize",
1502 static_cast<int64_t>(uart.lastEncodedSize()));
1503 response.set("rpUartActualBaud",
1504 static_cast<int64_t>(uart.lastActualBaud()));
1505 response.set("rpUartLastError", uart.lastError().c_str());
1506 }
1507 if (driver_name == "PIO0" || driver_name == "PIO1") {
1508 auto& rp_pio = driver_name == "PIO0"
1509 ? fl::BusTraits<fl::Bus::FLEX_IO, 0>::instance()
1510 : fl::BusTraits<fl::Bus::FLEX_IO, 1>::instance();
1511 response.set("rpPioActive", rp_pio.isActive());
1512 response.set("rpPioLastError", rp_pio.lastError().c_str());
1513 response.set("rpPioStartAttempted", rp_pio.lastStartAttempted());
1514 response.set("rpPioStartSucceeded", rp_pio.lastStartSucceeded());
1515 response.set("rpPioWordCount", static_cast<int64_t>(rp_pio.lastWordCount()));
1516 }
1517 #if defined(FL_IS_RP2350)
1518 if (driver_name == "PIO2") {
1519 auto& rp_pio = fl::BusTraits<fl::Bus::FLEX_IO, 2>::instance();
1520 response.set("rpPioActive", rp_pio.isActive());
1521 response.set("rpPioLastError", rp_pio.lastError().c_str());
1522 response.set("rpPioStartAttempted", rp_pio.lastStartAttempted());
1523 response.set("rpPioStartSucceeded", rp_pio.lastStartSucceeded());
1524 response.set("rpPioWordCount", static_cast<int64_t>(rp_pio.lastWordCount()));
1525 }
1526 #endif
1527#endif
1528
1529 fl::json sizes_response = fl::json::array();
1530 for (int size : lane_sizes) {
1531 sizes_response.push_back(static_cast<int64_t>(size));
1532 }
1533 response.set("laneSizes", sizes_response);
1534 response.set("pattern", pattern.c_str());
1535 response.set("useLegacyApi", use_legacy_api);
1536 if (use_legacy_api) {
1537 if (legacy_driver_name != nullptr) {
1538 response.set("legacyDriver", legacy_driver_name);
1539 }
1540 response.set("legacyRgbw", legacy_rgbw);
1541 fl::json legacy_chipsets_response = fl::json::array();
1542 for (LegacyClocklessChipset chipset : legacy_chipsets) {
1543 legacy_chipsets_response.push_back(
1545 }
1546 response.set("legacyChipsets", legacy_chipsets_response);
1547 }
1548 response.set("frameCount", static_cast<int64_t>(frame_count));
1549 response.set("contaminateTxMux", contaminate_tx_mux);
1550 if (contaminate_tx_mux) {
1551 response.set("contaminateTxMuxPin", static_cast<int64_t>(pin_tx));
1552 }
1553 if (measure_tight_timing) {
1554 response.set("tightTiming", tight_timing_response);
1555 }
1556 if (is_object_fled_driver) {
1557 response.set("objectFledDiagnostics",
1558 fl::objectFledDiagnosticsToJson());
1559 response.set("standardGpioPadProbe", standard_gpio_pad_probe);
1560 }
1561#if defined(FL_IS_TEENSY_4X)
1562 // Streaming RX/TX counters (ISR cost, ring overruns/underruns). A handful
1563 // of integers, emitted for every Teensy run so soaks can report them.
1564 {
1565 fl::json ts = fl::FlexPwmRxChannel::streamStatsToJson();
1566 fl::FlexIODiagnostics sd{};
1567 fl::flexio_read_diagnostics(&sd);
1568 ts.set("txUnderruns", static_cast<int64_t>(sd.txUnderruns));
1569 ts.set("txIsrMaxCycles", static_cast<int64_t>(sd.txIsrMaxCycles));
1570 ts.set("txStreamedWords", static_cast<int64_t>(sd.txStreamedWords));
1571 response.set("teensyStream", ts);
1572 }
1573 // FlexPWM RX diagnostics: useful for ANY clockless TX routed through
1574 // pin 22. Skip for LPUART (LPUART has its own status path) AND for
1575 // FLEX_IO (PR #3421 framework-hang investigation found that the
1576 // ~20 fj.set() calls for flexIoDiagnostics below push the heap into
1577 // a state where downstream destructors hang -- emit only for
1578 // OBJECT_FLED where the diagnostics were originally added for
1579 // #3343 / #3410 bring-up).
1580 const bool emit_flex_diagnostics = (driver_name == "OBJECT_FLED");
1581 if (emit_flex_diagnostics) {
1582 response.set("flexPwmRxDiagnostics",
1583 fl::FlexPwmRxChannel::diagnosticsToJson(pin_rx));
1584 }
1585 if (emit_flex_diagnostics) {
1586 // #3410 Round 7: snapshot FlexIO2 register state so we can tell
1587 // whether the peripheral is actually running, what the
1588 // shifter/timer/DMA state is after show(), and whether CTRL,
1589 // SHIFTSDEN, TCD etc match what flexio_show() programmed. Without
1590 // this we are guessing in the dark about why zero_capture happens.
1591 fl::FlexIODiagnostics fd{};
1592 fl::flexio_read_diagnostics(&fd);
1593 fl::json fj = fl::json::object();
1594 fj.set("ctrl", static_cast<int64_t>(fd.ctrl));
1595 fj.set("shiftstat", static_cast<int64_t>(fd.shiftstat));
1596 fj.set("shifterr", static_cast<int64_t>(fd.shifterr));
1597 fj.set("timstat", static_cast<int64_t>(fd.timstat));
1598 fj.set("shiftsden", static_cast<int64_t>(fd.shiftsden));
1599 fj.set("shiftctl0", static_cast<int64_t>(fd.shiftctl0));
1600 fj.set("shiftcfg0", static_cast<int64_t>(fd.shiftcfg0));
1601 fj.set("timctl0", static_cast<int64_t>(fd.timctl0));
1602 fj.set("timcfg0", static_cast<int64_t>(fd.timcfg0));
1603 fj.set("timcmp0", static_cast<int64_t>(fd.timcmp0));
1604 fj.set("ccmCcgr3", static_cast<int64_t>(fd.ccm_ccgr3));
1605 fj.set("ccmCscmr2", static_cast<int64_t>(fd.ccm_cscmr2));
1606 fj.set("ccmCs1cdr", static_cast<int64_t>(fd.ccm_cs1cdr));
1607 fj.set("muxRegValue", static_cast<int64_t>(fd.muxRegValue));
1608 fj.set("padRegValue", static_cast<int64_t>(fd.padRegValue));
1609 fj.set("tcdSaddr", static_cast<int64_t>(fd.tcd_saddr));
1610 fj.set("tcdDaddr", static_cast<int64_t>(fd.tcd_daddr));
1611 fj.set("tcdCiter", static_cast<int64_t>(fd.tcd_citer));
1612 fj.set("tcdBiter", static_cast<int64_t>(fd.tcd_biter));
1613 fj.set("tcdCsr", static_cast<int64_t>(fd.tcd_csr));
1614 fj.set("initialized", fd.initialized);
1615 fj.set("dmaComplete", fd.dmaComplete);
1616 fj.set("txUnderruns", static_cast<int64_t>(fd.txUnderruns));
1617 fj.set("txIsrMaxCycles", static_cast<int64_t>(fd.txIsrMaxCycles));
1618 response.set("flexIoDiagnostics", fj);
1619 }
1620#endif
1621
1622 // Free run_results before building response to reclaim heap
1623 // Only serialize pattern details when tests FAIL (saves heap on passing tests).
1624 // WS2814 legacy runs are the exception: the host requires a size summary
1625 // for every run as proof that 4 bytes/LED (RGBW) went on the wire, so
1626 // passing runs emit just runNumber/totalLeds/totalBytes/passed (#4578).
1627 const bool ws2814_legacy = use_legacy_api && !legacy_chipsets.empty() &&
1628 legacy_chipsets[0] == LegacyClocklessChipset::WS2814;
1629 if (max_power_mw != 0 && !run_results.empty()) {
1630 // Every frame's limiter decision and wire totals, pass or fail, so
1631 // the host can check the policy itself and not only the comparison.
1632 fl::json frames = fl::json::array();
1633 for (fl::size ri = 0; ri < run_results.size(); ri++) {
1634 const auto& rr = run_results[ri];
1635 fl::json f = fl::json::object();
1636 f.set("passed", rr.passed);
1637 f.set("expectedScale", static_cast<int64_t>(rr.expectedScale));
1638 f.set("fullDemandMw", static_cast<int64_t>(rr.fullDemandMw));
1639 f.set("baselineMw", static_cast<int64_t>(rr.baselineMw));
1640 f.set("sumRaw", static_cast<int64_t>(rr.sumRaw));
1641 f.set("sumWire", static_cast<int64_t>(rr.sumWire));
1642 f.set("mismatchedBytes", static_cast<int64_t>(rr.mismatchedBytes));
1643 frames.push_back(f);
1644 }
1645 response.set("maxPowerMw", static_cast<int64_t>(max_power_mw));
1646 response.set("powerFrames", frames);
1647 }
1648 if ((!passed || ws2814_legacy) && !run_results.empty()) {
1649 fl::json patterns = fl::json::array();
1650 for (fl::size ri = 0; ri < run_results.size(); ri++) {
1651 const auto& rr = run_results[ri];
1652 if (rr.passed && !ws2814_legacy) continue; // Skip passing patterns
1653 fl::json pat = fl::json::object();
1654 pat.set("runNumber", static_cast<int64_t>(rr.run_number));
1655 pat.set("totalLeds", static_cast<int64_t>(rr.total_leds));
1656 pat.set("totalBytes", static_cast<int64_t>(rr.totalBytes));
1657 pat.set("passed", rr.passed);
1658 if (rr.passed) {
1659 patterns.push_back(pat);
1660 continue;
1661 }
1662 pat.set("mismatchedLeds", static_cast<int64_t>(rr.mismatches));
1663 pat.set("capturedBytes", static_cast<int64_t>(rr.capturedBytes));
1664 pat.set("captureWaitResult", static_cast<int64_t>(rr.captureWaitResult));
1665 pat.set("rawEdgesAfterWait", static_cast<int64_t>(rr.rawEdgesAfterWait));
1666 pat.set("decodeOk", static_cast<int64_t>(rr.decodeOk));
1667 pat.set("decodeError", static_cast<int64_t>(rr.decodeError));
1668 pat.set("decodeBytes", static_cast<int64_t>(rr.decodeBytes));
1669 pat.set("decodeOutputCapacity",
1670 static_cast<int64_t>(rr.decodeOutputCapacity));
1671 if (rr.rpPioGpioTransitions >= 0) {
1672 pat.set("rpPioGpioTransitions",
1673 static_cast<int64_t>(rr.rpPioGpioTransitions));
1674 }
1675 if (!rr.rxBeginError.empty()) {
1676 pat.set("rxBeginError", rr.rxBeginError.c_str());
1677 }
1678 if (!rr.rawEdgeSample.empty()) {
1679 pat.set("rawEdgeSample", rr.rawEdgeSample.c_str());
1680 }
1681 pat.set("captureFailed", rr.captureFailed);
1682 pat.set("mismatchedBytes", static_cast<int64_t>(rr.mismatchedBytes));
1683 pat.set("lsbOnlyErrors", static_cast<int64_t>(rr.lsbOnlyErrors));
1684
1685 // Serialize first N LED errors (limit to prevent OOM on small MCUs)
1686 constexpr fl::size kMaxSerializedErrors = 5;
1687 if (!rr.errors.empty()) {
1688 fl::json errs = fl::json::array();
1689 const fl::size errLimit = rr.errors.size() < kMaxSerializedErrors
1690 ? rr.errors.size()
1691 : kMaxSerializedErrors;
1692 for (fl::size ei = 0; ei < errLimit; ei++) {
1693 const auto& e = rr.errors[ei];
1694 fl::json err = fl::json::object();
1695 err.set("led", static_cast<int64_t>(e.led_index));
1696 fl::json expected = fl::json::array();
1697 expected.push_back(static_cast<int64_t>(e.expected_r));
1698 expected.push_back(static_cast<int64_t>(e.expected_g));
1699 expected.push_back(static_cast<int64_t>(e.expected_b));
1700 if (e.has_white) {
1701 expected.push_back(
1702 static_cast<int64_t>(e.expected_w));
1703 }
1704 err.set("expected", expected);
1705 fl::json actual = fl::json::array();
1706 actual.push_back(static_cast<int64_t>(e.actual_r));
1707 actual.push_back(static_cast<int64_t>(e.actual_g));
1708 actual.push_back(static_cast<int64_t>(e.actual_b));
1709 if (e.has_white) {
1710 actual.push_back(static_cast<int64_t>(e.actual_w));
1711 }
1712 err.set("actual", actual);
1713 errs.push_back(err);
1714 }
1715 pat.set("errors", errs);
1716 pat.set("totalErrors", static_cast<int64_t>(rr.errors.size()));
1717 }
1718 patterns.push_back(pat);
1719 }
1720 response.set("patterns", patterns);
1721 }
1722 run_results.clear(); // Free memory before serialization
1723
1724 // Return the response — the lambda wrapper will call sendAsyncResponse
1725 return response;
1726}
1727
1728#endif // FL_PLATFORM_HAS_LARGE_MEMORY
CRGB leds[1]
fl::UISlider brightness("Brightness", BRIGHTNESS, 0, 255)
bool autoResearchSetExclusiveDriverByName(const char *name)
AutoResearch-style helper: set an exclusive driver by name.
Full PARLIO encode bench for ESP32-P4 (post-byte-LUT, #2526 landed).
PARLIO ISR-streaming functional validation (#2548 deep-dive follow-up).
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)
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)
Issue #2994 repro: compounded per-sequence timing drift vs 3.10.3.
Wave8 expansion micro-benchmark for #2526.
bool done
TestState state
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
LegacyClocklessChipset
bool legacyClocklessChipsetFromName(const fl::string &name, LegacyClocklessChipset *out)
const char * legacyClocklessChipsetName(LegacyClocklessChipset chipset)
const char * legacyClocklessBoundDriverName()
Name of the driver to which public legacy templates are bound.
bool legacyClocklessChipsetHasAutomaticRgbw(LegacyClocklessChipset chipset)
Rgbw rgbw
int passed_tests
Definition SIMD.ino:75
int total_tests
Definition SIMD.ino:74
fl::net::ble — BLE GATT transport layer for JSON-RPC
SPI encoder configuration for clocked LED chipsets.
FastLED chrono implementation - duration types for time measurements.
fl::json runSingleTestImpl(const fl::json &args)
fl::shared_ptr< AutoResearchState > mState
fl::u8 getBrightness() FL_NO_EXCEPT
Get the current global brightness setting.
Definition FastLED.h:1654
void setBrightness(fl::u8 scale) FL_NO_EXCEPT
Set the global brightness scaling.
Definition FastLED.h:1650
static fl::RxChannelPtr addRx(const fl::RxChannelConfig &config) FL_NO_EXCEPT
Add an RX channel with runtime configuration.
fl::shared_ptr< IChannelDriver > findDriverByName(const fl::string &name) const FL_NO_EXCEPT
Silent counterpart to getDriverByName().
static ChannelManager & instance() FL_NO_EXCEPT
Get the global singleton instance.
const char * c_str() const FL_NO_EXCEPT
size_t size() const FL_NO_EXCEPT
Definition json.h:798
fl::optional< fl::string > as_string() const FL_NO_EXCEPT
Definition json.h:443
fl::optional< i64 > as_int() const FL_NO_EXCEPT
Definition json.h:398
void set(const fl::string &key, const json &value) FL_NO_EXCEPT
Definition json.h:873
fl::optional< bool > as_bool() const FL_NO_EXCEPT
Definition json.h:397
void push_back(const json &value) FL_NO_EXCEPT
Definition json.h:925
bool contains(size_t idx) const FL_NO_EXCEPT
Definition json.h:790
static json object() FL_NO_EXCEPT
Definition json.h:864
static json array() FL_NO_EXCEPT
Definition json.h:860
void reset() FL_NO_EXCEPT
Definition shared_ptr.h:294
string str() const FL_NO_EXCEPT
Definition strstream.h:43
void stop() FL_NO_EXCEPT
Stops the coroutine represented by this handle.
Definition task.cpp.hpp:316
bool is_valid() const FL_NO_EXCEPT
Returns whether this handle refers to a task.
Definition task.cpp.hpp:312
bool isRunning() const FL_NO_EXCEPT
Returns whether the represented coroutine is currently running.
Definition task.cpp.hpp:317
fl::size size() const FL_NO_EXCEPT
bool empty() const FL_NO_EXCEPT
void clear() FL_NO_EXCEPT
Definition vector.h:634
void push_back(const T &value) FL_NO_EXCEPT
Definition vector.h:624
T & back() FL_NO_EXCEPT
Definition vector.h:616
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)
UCS7604 LED chipset encoder implementation.
constexpr EOrder RGB
Definition eorder.h:17
Task executor — runs registered task runners and manages the run loop.
fl::CRGB CRGB
Definition crgb.h:25
Platform-abstracted heap memory query functions.
FastLED's Elegant JSON Library: fl::json
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
shared_ptr< T > make_shared(Args &&... args) FL_NO_EXCEPT
Definition shared_ptr.h:423
void stop() FL_NO_EXCEPT
Stop WiFi entirely (STA and AP).
Definition wifi.cpp.hpp:42
Handle coroutine(const CoroutineConfig &config) FL_NO_EXCEPT
Creates and starts an OS-level coroutine task.
Definition task.cpp.hpp:364
function< void()> func
Function executed by the coroutine, copied at creation time.
Definition task.h:138
u8 priority
Platform task priority relative to the platform idle priority, default 5.
Definition task.h:148
size_t stack_size
Requested stack size in bytes, default 4096.
Definition task.h:144
optional< int > core_id
Optional CPU core affinity, unset by default (no affinity).
Definition task.h:152
string name
Diagnostic name reported by the platform. Defaults to "task".
Definition task.h:140
RxBackend resolveCaptureBackend(RxBackend requested_backend, bool has_explicit_override, bool is_parlio_driver, bool is_esp32_c6) FL_NO_EXCEPT
Select the independent capture backend used by AutoResearch.
Definition validation.h:50
size_t rpPioMaxWireBytes(size_t edge_capacity, size_t dma_tail_words, u32 samples_per_dma_word, u32 sample_period_ns, u32 idle_tail_ns, u32 arming_lead_in_ns, u32 bit_period_ns) FL_NO_EXCEPT
Largest frame, in wire bytes, an RP PIO RX capture can hold.
Definition validation.h:156
ClocklessEncoder
Identifies which encoder to use for clockless chipsets in the Channel API.
@ CLOCKLESS_ENCODER_UCS7604_8BIT
UCS7604 8-bit 800KHz.
@ CLOCKLESS_ENCODER_TM1812_RGBWW
TM1812: two 5-byte RGBWW pixels in each 12-byte IC frame.
@ CLOCKLESS_ENCODER_UCS7604_16BIT
UCS7604 16-bit 800KHz.
@ CLOCKLESS_ENCODER_UCS7604_16BIT_1600
UCS7604 16-bit 1600KHz.
@ CLOCKLESS_ENCODER_WS2812
Default, no preamble (WS2812 and compatible)
@ CLOCKLESS_ENCODER_TM1908
TM1908: command prefix followed by RGB pixels.
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
constexpr size_t kRpPioRxDmaTailWords
Reset-tail words appended to the DMA transfer.
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.
constexpr u32 kRpPioRxSamplesPerDmaWord
Pin samples packed into each 32-bit DMA word.
constexpr ChipsetTimingConfig makeTimingConfig() FL_NO_EXCEPT
Convert compile-time CHIPSET type to runtime timing config.
fl::u32 uint32_t
Definition s16x16x4.h:219
AtomicFake< T > atomic
Definition atomic.h:26
@ memory_order_relaxed
Definition atomic.h:40
@ memory_order_acquire
Definition atomic.h:41
@ memory_order_release
Definition atomic.h:42
size_t ucs7604FrameBytes(size_t num_leds, UCS7604Mode mode, bool is_rgbw) FL_NO_EXCEPT
Total wire bytes of a complete UCS7604 frame.
Definition ucs7604.h:253
fl::u32 millis() FL_NO_EXCEPT
Universal millisecond timer - returns milliseconds since system startup.
fl::u32 micros() FL_NO_EXCEPT
Universal microsecond timer - returns microseconds since system startup.
@ High
At networking priority or above, biased above when supported.
fl::uptr uintptr_t
Definition s16x16x4.h:223
RxBackend
Definition types.h:8
@ I2S_RX
Classic-ESP32 I2S 1-bit oversampling backend — DMA sampling at 16 MHz, capture length limited by RAM ...
Definition types.h:17
@ PIO
RP2040/RP2350 PIO receive backend.
Definition types.h:9
@ PLATFORM_DEFAULT
Use the recommended backend for the active platform (RMT on ESP32; FlexPWM on Teensy 4....
Definition types.h:10
@ RMT
ESP32-only RMT capture backend.
Definition types.h:11
@ 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.
Bus
Portable public bus selector.
Definition bus.h:31
@ FLEX_IO
Definition bus.h:40
@ UART
Definition bus.h:34
HeapInfo getFreeHeap() FL_NO_EXCEPT
Query available heap memory.
Definition heap.cpp.hpp:68
void analogWrite(int pin, u16 val) FL_NO_EXCEPT
Write analog value to pin (PWM)
Definition pin.cpp.hpp:247
Core
Worker task affinity. This does not change peripheral interrupt affinity.
@ Auto
Inherit the engine default, otherwise its legacy policy.
@ Any
Allow the worker to run on any configured RTOS core.
@ CallingCore
Capture the core that creates the worker.
constexpr u32 kRpPioRxClockHz
After synchronizing to the first rising edge the PIO runs one IN PINS instruction per cycle,...
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
InputGamut g
Definition rgbw.h:125
void delayNanoseconds(fl::u32 ns) FL_NO_EXCEPT
Delay for a runtime number of nanoseconds.
Definition delay.cpp.hpp:44
constexpr ClocklessEncoder encoder_for() FL_NO_EXCEPT
Extract the encoder selector from a compile-time TIMING type.
size_t ucs7604BytesPerLed(UCS7604Mode mode, bool is_rgbw) FL_NO_EXCEPT
Wire bytes each LED contributes to a UCS7604 frame.
Definition ucs7604.h:240
@ RMT
RMT-based receiver (ESP32)
Definition rx.h:168
void pinMode(int pin, PinMode mode) FL_NO_EXCEPT
Set pin mode (input, output, pull-up, pull-down)
Definition pin.cpp.hpp:398
void delayMicroseconds(u32 us) FL_NO_EXCEPT
Delay for a given number of microseconds.
unsigned char uint8_t
Definition s16x16x4.h:209
corkscrew_args args
Definition old.h:149
Promise-based fluent API for FastLED - standalone async primitives.
#define FL_NO_EXCEPT
Umbrella header for SIMD subsystem.
@ Black
<div style='background:#000000;width:4em;height:4em;'></div>
Definition crgb.h:517
Configuration for a single LED channel.
Definition config.h:167
constexpr u32 total_period_ns() const FL_NO_EXCEPT
Get total bit period (T1 + T2 + T3)
u32 reset_us
Reset/latch time (microseconds)
Runtime bit-period timing for a clockless chipset.
@ ERROR
Driver encountered an error.
Definition driver.h:174
static SpiEncoder apa102(u32 clock_hz=6000000) FL_NO_EXCEPT
Create APA102 encoder configuration.
Definition spi.h:44