FastLED 3.10.10
Loading...
Searching...
No Matches
AutoResearchPwmDmaClockless.h
Go to the documentation of this file.
1// AutoResearchPwmDmaClockless.h - LPC845 SCT+DMA channels-API engine
2// AutoResearch validation harness (FastLED #3468, #5265).
3//
4// Device-side RPC handlers that exercise the `ChannelEngineLpcSctDma`
5// engine on real LPC845-BRK silicon and measure the wire through a jumper.
6//
7// Gated on `FL_IS_ARM_LPC_845 && FASTLED_LPC_PWM_DMA`. The whole file
8// compiles out on any other build target.
9//
10// Handlers (bound by `autoresearch::pwm_dma_cl::bind(remote)`):
11//
12// `pwmDmaClFrameOnce(led_count, color_rgb, data_pin)`
13// Drive one frame; "ok,started_us,done_us,duration_us". ok is 0 when
14// the frame halted before its last bit.
15//
16// `pwmDmaClFrameBurst(led_count, color_rgb, n_frames, data_pin)`
17// Drive `n_frames` back-to-back, each after the WS2812 reset time;
18// "ok,total_us,fps_x100".
19//
20// `pwmDmaClCaptureSelf(led_count, color_rgb, data_pin, rx_pin, hold_us,
21// step_rgb)`
22// LED i is `(color_rgb + i * step_rgb) & 0xFFFFFF`, so a nonzero step
23// gives every chunk different bytes. Drive one frame and capture every
24// bit's high time on `rx_pin` with
25// `LpcCtimerPulseCapture` (CTIMER0 + DMA). The SCT RX capture can't be
26// used: the transmitter owns the chip's only SCT. `hold_us` > 0
27// busy-waits that long after show() without calling poll(), as
28// FastLED.show() does between frames, so chunk hand-over must come from
29// the DMA interrupt. Bits use WS2812 T0H/T1H with a 1450 ns low phase
30// (see captureTiming()). A rise more than 3 us after the previous one
31// (the line idling mid-frame) stops the capture, so such a frame
32// decodes short. Returns
33// "1,<n>,<byte>...,bits=<b>,t0h=<min>-<max>,t1h=<min>-<max>,gap_guard=<ns>"
34// (ns), for a host-side byte compare.
35//
36// Every handler gives up after a bounded wait instead of spinning on
37// poll() forever, so a stalled engine answers the RPC with a failure.
38//
39// Loopback wiring: one jumper from `data_pin` to `rx_pin`, found by the
40// findConnectedPins scan. `data_pin` carries SCT_OUT0 and `rx_pin` T0_CAP0,
41// both movable SWM functions, so any non-reserved PIO0 pins work.
42
43#pragma once
44
45#include <FastLED.h>
46
47#if defined(FL_IS_ARM_LPC_845) && defined(FASTLED_LPC_PWM_DMA)
48
49#include "fl/channels/data.h"
50#include "fl/channels/bus.h"
54#include "fl/remote/remote.h"
55#include "fl/stl/cstring.h"
56#include "fl/stl/noexcept.h"
57#include "fl/stl/singleton.h"
59#include "fl/stl/sstream.h"
60#include "fl/stl/vector.h"
61#include "fl/system/pin.h"
62#include "fl/system/pin_probe.h"
63#include "platforms/arm/lpc/drivers/sct_dma/channel_engine_lpc_sct_dma.h" // ok platform headers; ok platform specific - this LPC845-only harness tests the concrete SCT+DMA engine type
64// The LPC BusTraits<Bus::BIT_BANG> specialization this file names. It used to
65// arrive only via clockless_channel_lpc.h, which is skipped when another
66// ClocklessController was already picked, leaving the type incomplete.
67#include "platforms/arm/lpc/drivers/sct_dma/bus_traits.h" // ok platform headers; ok platform specific - binds the BIT_BANG bus to the LPC845 SCT+DMA engine under test
68#include "platforms/arm/lpc/drivers/sct_dma/lpc_ctimer_pulse_capture.h" // ok platform headers; ok platform specific - the SCT is the transmitter, so the wire is measured with LPC845 CTIMER0 (no core pulse-capture API exists)
69#include "platforms/arm/lpc/lpc_dma_descriptor_table.h" // ok platform headers; ok platform specific - #5278 fault injection and DMA0 stressor address LPC845 DMA descriptors
70#include "platforms/arm/lpc/lpc_dma_isr.h" // ok platform headers; ok platform specific - FASTLED_LPC_DMA_ISR selects the expected long-frame behaviour (#5278)
71
72namespace autoresearch {
73namespace pwm_dma_cl {
74
75// Captures are capped at 17 LEDs (408 bits): still five chunks of the
76// default 96-bit transmitter chunk, so both descriptor slots are reused on
77// the wire. Not more: the capture buffer is static, and this core's _sbrk
78// lets the heap grow into the stack unchecked. At 20 LEDs the stack and heap
79// were 244 bytes apart, and a 20-LED reply HardFaulted every second call
80// (#5278).
81constexpr int kMaxCaptureLeds = 17;
82
83struct PwmDmaClocklessState {
84 fl::u32 highTicks[kMaxCaptureLeds * 24];
85 fl::u8 decoded[kMaxCaptureLeds * 3];
86};
87
88inline PwmDmaClocklessState& pwmDmaClocklessState() FL_NO_EXCEPT {
90}
91
92// Standard WS2812B timing: T0H = 350 ns, T1H = 800 ns, period 1250 ns.
93inline fl::ChipsetTimingConfig ws2812b_timing() FL_NO_EXCEPT {
94 return fl::ChipsetTimingConfig(/*T1=*/350, /*T2=*/450, /*T3=*/450,
95 /*reset_us=*/50, "WS2812B");
96}
97
98// WS2812B high times with a 1450 ns low phase (period 2250 ns), for the
99// CTIMER capture. The capture copies each bit's CR0 by DMA after the bit's
100// fall and must finish before the next bit's fall. At 1250 ns that window
101// is T3 + T0H = 800 ns (19 ticks at 24 MHz). On the bit whose EV2 makes
102// the TX reload its next descriptor, the TX transfer and descriptor fetch
103// on DMA0 come first and the capture copy misses the window (FastLED
104// #5276). The TX itself is unaffected: on the same bits its writes land
105// in time. A longer low phase gives the copy room while the TX runs the
106// identical path (masks, chunk refills, slot reuse, halt step).
107inline fl::ChipsetTimingConfig captureTiming() FL_NO_EXCEPT {
108 return fl::ChipsetTimingConfig(/*T1=*/350, /*T2=*/450, /*T3=*/1450,
109 /*reset_us=*/50, "WS2812B-long-low");
110}
111
112// Build a `ChannelData` of N LEDs; LED i is `(rgb + i * step) & 0xFFFFFF`
113// (step 0: one solid color). Colors come from the host as 24-bit RGB and
114// are stored GRB (WS2812 wire order).
115inline fl::ChannelDataPtr makeChannelData(
116 int pin, int num_leds, fl::u32 rgb, fl::u32 step,
117 const fl::ChipsetTimingConfig& t = ws2812b_timing()) FL_NO_EXCEPT {
118 fl::vector_psram<fl::u8> encoded(static_cast<fl::size>(num_leds * 3));
119 for (int i = 0; i < num_leds; ++i) {
120 const fl::u32 c = (rgb + static_cast<fl::u32>(i) * step) & 0xFFFFFFu;
121 encoded[i * 3 + 0] = static_cast<fl::u8>((c >> 8) & 0xFF); // G
122 encoded[i * 3 + 1] = static_cast<fl::u8>((c >> 16) & 0xFF); // R
123 encoded[i * 3 + 2] = static_cast<fl::u8>(c & 0xFF); // B
124 }
125 return fl::ChannelData::create(pin, t, fl::move(encoded));
126}
127
128inline fl::ChannelDataPtr makeSolidChannelData(
129 int pin, int num_leds, fl::u32 rgb) FL_NO_EXCEPT {
130 return makeChannelData(pin, num_leds, rgb, 0u);
131}
132
133// READY means the engine is idle, not that the frame went out whole: an
134// early halt (a refill missed its deadline) or a DMA error is READY too.
135inline bool lastFrameComplete(fl::ChannelEngineLpcSctDma& engine) FL_NO_EXCEPT { // ok platform specific - this file tests only the LPC845 SCT+DMA engine; no other driver reports a cut-short frame, so a core API would have one user
136 return engine.transmitter().lastFrameComplete(); // ok platform specific - reads the LPC845 SCT+DMA transmitter's cut-short flag; no core API reports a cut-short frame
137}
138
139// Spin poll() until READY, at most `timeout_us`. False on timeout.
140inline bool waitReady(fl::IChannelDriver& engine, fl::u32 timeout_us) FL_NO_EXCEPT {
141 const fl::u32 t0 = micros();
142 while (engine.poll() != fl::IChannelDriver::DriverState::READY) {
143 if (micros() - t0 > timeout_us) {
144 return false;
145 }
146 }
147 return true;
148}
149
150// Frame air time (1.25 us per bit) plus 20 ms of slack.
151inline fl::u32 frameTimeoutUs(int led_count) FL_NO_EXCEPT {
152 return static_cast<fl::u32>(led_count) * 30u + 20000u;
153}
154
155// A data pin the engine may take over: SCT_OUT0 on a reserved pad (SWD,
156// ISP, console) would cut the link to the host.
157inline bool usablePin(int pin) FL_NO_EXCEPT {
158 return pin >= 0 && pin <= 31 && fl::pinProbeSkipReason(pin) == nullptr;
159}
160
161// Drive one frame through the channels-API engine. Returns
162// "success,started_us,done_us,duration_us" as a CSV string.
163inline fl::string frameOnceHandler(int led_count, fl::u32 rgb, int data_pin) FL_NO_EXCEPT {
164 if (led_count <= 0 || led_count > 300 || !usablePin(data_pin)) {
165 return fl::string("0,0,0,0");
166 }
167 auto& engine = fl::BusTraits<fl::Bus::BIT_BANG>::instance();
168 auto ch = makeSolidChannelData(data_pin, led_count, rgb);
169 if (!engine.canHandle(ch)) {
170 return fl::string("0,0,0,0");
171 }
172
173 const fl::u32 t_start = micros();
174 engine.enqueue(ch);
175 engine.show();
176 const bool ok = waitReady(engine, frameTimeoutUs(led_count)) &&
177 lastFrameComplete(engine);
178 const fl::u32 t_end = micros();
179
180 fl::sstream s;
181 s << (ok ? 1 : 0) << ',' << t_start << ',' << t_end << ',' << (t_end - t_start);
182 return s.str();
183}
184
185// Drive `n_frames` back-to-back. Returns "success,total_us,fps_x100" as CSV.
186inline fl::string frameBurstHandler(int led_count, fl::u32 rgb,
187 int n_frames, int data_pin) FL_NO_EXCEPT {
188 if (led_count <= 0 || led_count > 300 || n_frames <= 0 ||
189 n_frames > 1000 || !usablePin(data_pin)) {
190 return fl::string("0,0,0");
191 }
192 auto& engine = fl::BusTraits<fl::Bus::BIT_BANG>::instance();
193 auto ch = makeSolidChannelData(data_pin, led_count, rgb);
194 if (!engine.canHandle(ch)) {
195 return fl::string("0,0,0");
196 }
197
198 // The strip latches only after the line idles low for reset_us; a
199 // shorter gap would merge two frames, so each frame (the first too, in
200 // case a previous RPC just drove the line) starts that long after the
201 // last one ended.
202 const fl::u32 reset_us = ws2812b_timing().reset_us;
203 // A frame left running by an earlier RPC (one that timed out) must end
204 // first; the first frame then waits the full reset time from there.
205 if (!waitReady(engine, frameTimeoutUs(kMaxCaptureLeds))) {
206 return fl::string("0,0,0");
207 }
208 const fl::u32 t_start = micros();
209 fl::u32 last_end = t_start;
210 for (int i = 0; i < n_frames; ++i) {
211 while (micros() - last_end < reset_us) {
212 }
213 engine.enqueue(ch);
214 engine.show();
215 if (!waitReady(engine, frameTimeoutUs(led_count))) {
216 fl::sstream s;
217 s << "0,stalled_at_frame=" << i;
218 return s.str();
219 }
220 last_end = micros();
221 if (!lastFrameComplete(engine)) {
222 fl::sstream s;
223 s << "0,short_frame=" << i;
224 return s.str();
225 }
226 // Feed the watchdog every N frames so long bursts don't reset us.
227 if ((i & 0x3F) == 0) {
229 }
230 }
231 const fl::u32 t_end = micros();
232 const fl::u32 total_us = t_end - t_start;
233 // fps x 100 to keep two decimals of precision in an integer CSV.
234 const fl::u32 fps_x100 = total_us > 0
235 ? (static_cast<fl::u32>(n_frames) * 100u * 1000000u / total_us)
236 : 0u;
237
238 fl::sstream s;
239 s << 1 << ',' << total_us << ',' << fps_x100;
240 return s.str();
241}
242
243inline fl::u32 ticksToNs(fl::u32 ticks) FL_NO_EXCEPT {
244 return ticks * 1000u / static_cast<fl::u32>(F_CPU / 1000000UL);
245}
246
247// Min-max of captured high times, printed as "<min>-<max>" in ns ("0-0"
248// when empty).
249struct HighRange {
250 fl::u32 lo = 0xFFFFFFFFu;
251 fl::u32 hi = 0;
252 void add(fl::u32 ticks) FL_NO_EXCEPT {
253 lo = ticks < lo ? ticks : lo;
254 hi = ticks > hi ? ticks : hi;
255 }
256};
257
258inline fl::sstream& operator<<(fl::sstream& s, const HighRange& r) FL_NO_EXCEPT {
259 s << (r.hi ? ticksToNs(r.lo) : 0u) << '-' << ticksToNs(r.hi);
260 return s;
261}
262
263// ---------------------------------------------------------------------------
264// #5278 cases: a forced DMA error, and DMA0 contention.
265// ---------------------------------------------------------------------------
266
267// The second chunk's descriptor is the one the transmitter's channel links
268// to. Pointing its destination at GPIO->SET[0], which DMA0 cannot reach
269// (the IOP bus, UM11029 ch. 2), makes the chunk-1 reload raise ERRINT. Must
270// run while chunk 0 plays, i.e. right after show(). False if the frame has
271// no second chunk.
272inline bool corruptSecondChunk() FL_NO_EXCEPT { // ok platform specific - LPC845 DMA0 fault injection for the #5278 error-path case; no core API injects a DMA error
273 volatile fl::lpc::DmaChannelDescriptor* table =
274 reinterpret_cast<volatile fl::lpc::DmaChannelDescriptor*>(DMA0->SRAMBASE); // ok reinterpret cast - DMA descriptor table base
275 const fl::u32 link = table[FASTLED_LPC_PWM_DMA_BASECH].link;
276 if (link == 0u) {
277 return false;
278 }
279 volatile fl::lpc::DmaChannelDescriptor* next =
280 reinterpret_cast<volatile fl::lpc::DmaChannelDescriptor*>(link); // ok reinterpret cast - linked DMA descriptor address
281 next->dst_end = reinterpret_cast<fl::u32>(&GPIO->SET[0]); // ok reinterpret cast - MMIO address the DMA cannot reach
282 return true;
283}
284
285// The contention stressor: a memory-to-memory DMA0 channel (a self-linked
286// 1024-word descriptor between two RAM words) in one of two modes:
287// - unpaced: software-triggered, so it requests all the time. No FastLED
288// driver does this; it is the worst case.
289// - paced: hardware-triggered by SCT DMA request 1 on the transmitter's own
290// T1H event, moving a burst of 2^burst_power words per bit. Every FastLED
291// DMA0 user is peripheral-paced like this, one transfer per request
292// (burst_power 0; UART-DMA requests once per byte, i.e. less often), and
293// colliding on the same event is the worst case for them.
294// Channel 7 is clear of the transmitter (0), the capture (1), the USART
295// requests (2..5) and SPI (4/6).
296constexpr fl::u32 kStressCh = 7u;
297FL_STATIC_ASSERT(kStressCh != FASTLED_LPC_PWM_DMA_BASECH &&
298 kStressCh != FL_LPC_CTIMER_CAPTURE_DMA_CH,
299 "the #5278 stressor channel must differ from the transmitter's and the capture's");
300
301inline volatile fl::lpc::DmaChannelDescriptor& stressLinkDesc() FL_NO_EXCEPT {
302 static volatile fl::lpc::DmaChannelDescriptor d;
303 return d;
304}
305
306inline volatile fl::u32* stressWords() FL_NO_EXCEPT {
307 static volatile fl::u32 w[2];
308 return w;
309}
310
311inline void stressStop() FL_NO_EXCEPT { // ok platform specific - LPC845 DMA0 register sequence (UM11029 16.6.15) for the bench stressor
312 DMA0->COMMON[0].ENABLECLR = (1u << kStressCh);
313 for (fl::u32 i = 0; i < 1000u && (DMA0->COMMON[0].BUSY & (1u << kStressCh)); ++i) {
314 }
315 DMA0->COMMON[0].ABORT = (1u << kStressCh);
316 SCT0->DMAREQ1 = 0u;
317}
318
319// Start the stressor at CHPRIORITY `priority` (0 highest, 7 lowest; the
320// transmitter and the capture run at 0). Paced mode must start after show(),
321// since the transmitter clears SCT DMAREQ1 when it sets up.
322inline void stressStart(fl::u32 priority, bool paced,
323 fl::u32 burst_power) FL_NO_EXCEPT { // ok platform specific - LPC845 DMA0 memory-to-memory stressor for the #5278 contention case
324 fl::lpc::ensureDmaSramBase();
325 // CFGVALID | RELOAD | SWTRIG (unpaced only) | 32-bit, no address
326 // increments, 1024 words.
327 const fl::u32 xfer = (1u << 0) | (1u << 1) | (paced ? 0u : (1u << 2)) |
328 (2u << 8) | (1023u << 16);
329 volatile fl::u32* w = stressWords();
330 volatile fl::lpc::DmaChannelDescriptor& link = stressLinkDesc();
331 link.reserved = xfer;
332 link.src_end = reinterpret_cast<fl::u32>(&w[0]); // ok reinterpret cast - RAM source address
333 link.dst_end = reinterpret_cast<fl::u32>(&w[1]); // ok reinterpret cast - RAM destination address
334 link.link = reinterpret_cast<fl::u32>(&link); // ok reinterpret cast - self-linked descriptor
335 stressStop();
336 volatile fl::lpc::DmaChannelDescriptor* table =
337 reinterpret_cast<volatile fl::lpc::DmaChannelDescriptor*>(DMA0->SRAMBASE); // ok reinterpret cast - DMA descriptor table base
338 table[kStressCh].src_end = link.src_end;
339 table[kStressCh].dst_end = link.dst_end;
340 table[kStressCh].link = link.link;
341 // Paced: SCT_DMA1 trigger (UM11029 Table 288), HWTRIGEN, rising edge,
342 // TRIGBURST of 2^burst_power transfers.
343 INPUTMUX->DMA_ITRIG_INMUX[kStressCh] = paced ? 0x3u : 0xFu;
344 DMA0->CHANNEL[kStressCh].CFG =
345 (paced ? ((1u << 1) | (1u << 4) | (1u << 6) | ((burst_power & 15u) << 8))
346 : 0u) |
347 ((priority & 7u) << 16);
348 if (paced) {
349 SCT0->DMAREQ1 = SCT0->DMAREQ0; // the transmitter's T1H event
350 }
351 DMA0->COMMON[0].SETVALID = (1u << kStressCh);
352 DMA0->COMMON[0].ENABLESET = (1u << kStressCh);
353 DMA0->CHANNEL[kStressCh].XFERCFG = xfer; // SWTRIG starts it
354}
355
356// A rise this long after the previous one ends the capture, so the frame
357// comes up short. Capture bits rise every 2250 ns; some WS2812-class LEDs
358// latch after only ~6 us low, so any stretch mid-frame is a failure.
359constexpr fl::u32 kMaxRiseGapNs = 3000;
360
361// Drive one frame AND measure it on `rx_pin`. Each bit's high time is
362// captured by CTIMER0 + DMA; a high time above the midpoint of T0H and T1H
363// decodes as '1'. A rise more than kMaxRiseGapNs after the previous one
364// stops the capture, so a frame that idles mid-way decodes short. Returns
365// "1,<n>,<byte>...,bits=..,t0h=min-max,t1h=min-max,gap_guard=.." (or
366// "0,<reason>").
367inline fl::string captureFrame(int led_count, fl::u32 rgb, fl::u32 step,
368 int data_pin, int rx_pin, int hold_us,
369 fl::u32 max_gap_ns,
370 const fl::ChipsetTimingConfig& t = captureTiming(),
371 int stress_priority = -1,
372 int stress_paced = 0,
373 bool reload_stats = false) FL_NO_EXCEPT {
374 const fl::u32 t0h = fl::lpc_sct_ticks(t.t1_ns);
375 const fl::u32 t1h = fl::lpc_sct_ticks(t.t1_ns + t.t2_ns);
376 const fl::u32 period = fl::lpc_sct_ticks(t.t1_ns + t.t2_ns + t.t3_ns);
377
378 auto& st = pwmDmaClocklessState();
379 const fl::u32 n_bits = static_cast<fl::u32>(led_count) * 24u;
380 // Sample halfway between the longest high time and the next bit's
381 // rise: CR0 then holds this bit's high time. The capture's DMA copy must
382 // land before the next bit's fall, or it records that bit instead; for
383 // the stressor's RPC (reload_stats) the sample moves to 100 ns after
384 // T1H, so the capture's DMA deadline is within ~150 ns of the
385 // transmitter's (#5278), not ~250 ns tighter.
386 const fl::u32 sample = reload_stats ? t1h + fl::lpc_sct_ticks(100)
387 : (t1h + period) / 2u;
388 // A frame left running by an earlier RPC (one that timed out) must end
389 // before the capture is armed, or its edges count as this frame's bits.
390 auto& engine = fl::BusTraits<fl::Bus::BIT_BANG>::instance();
391 if (!waitReady(engine, frameTimeoutUs(kMaxCaptureLeds))) {
392 return fl::string("0,busy");
393 }
394 fl::LpcCtimerPulseCapture cap;
395 if (!cap.begin(rx_pin, sample, fl::lpc_sct_ticks(max_gap_ns),
396 fl::span<fl::u32>(st.highTicks, n_bits))) {
397 return fl::string("0,capture_begin");
398 }
399
400 auto ch = makeChannelData(data_pin, led_count, rgb, step, t);
401 if (!engine.canHandle(ch)) {
402 cap.end();
403 return fl::string("0,cannot_handle");
404 }
405 if (stress_priority >= 0 && stress_paced == 0) {
406 stressStart(static_cast<fl::u32>(stress_priority), false, 0u);
407 }
408 engine.enqueue(ch);
409 engine.show();
410 if (stress_priority >= 0 && stress_paced > 0) {
411 stressStart(static_cast<fl::u32>(stress_priority), true,
412 static_cast<fl::u32>(stress_paced - 1));
413 }
414 if (hold_us > 0) {
415 delayMicroseconds(static_cast<fl::u32>(hold_us)); // no poll()
416 }
417 const bool sent = waitReady(engine, frameTimeoutUs(led_count));
418 delayMicroseconds(20); // the last bit's MR0 copy lands ~1 us after it
419 if (stress_priority >= 0) {
420 stressStop();
421 }
422 const fl::u32 got = cap.count();
423 cap.end();
424 if (!fl::ChannelEngineLpcSctDma::frameFits(ch->getSize())) {
425 // A FASTLED_LPC_DMA_ISR=0 build drops frames over its limit in
426 // show() (#5278): the engine must go idle at once with nothing on
427 // the wire. A timeout is a stall, not a refusal.
428 if (sent && got == 0u && !lastFrameComplete(engine)) {
429 return fl::string("0,hub_off_refused");
430 }
431 fl::sstream s;
432 s << "0,refusal_leaked,bits=" << got;
433 return s.str();
434 }
435 if (!sent) {
436 fl::sstream s;
437 s << "0,tx_stalled,bits=" << got;
438 return s.str();
439 }
440 if (!lastFrameComplete(engine)) {
441 fl::sstream s;
442 s << "0,tx_short,bits=" << got;
443 return s.str();
444 }
445
446 const fl::u32 threshold = (t0h + t1h) / 2u;
447 // Overall ranges, and separately the bits right after a chunk reload
448 // (bit i with i % CHUNK_BITS == 0, i > 0): their clear mask is the first
449 // transfer of a freshly loaded descriptor, the tightest DMA deadline.
450 HighRange r0, r1, rr0, rr1;
451 fl::memset(st.decoded, 0, sizeof(st.decoded));
452 for (fl::u32 i = 0; i < got; ++i) {
453 const fl::u32 h = st.highTicks[i];
454 const bool reload = i > 0u && (i % FASTLED_LPC_PWM_DMA_CHUNK_BITS) == 0u;
455 if (h > threshold) {
456 st.decoded[i >> 3] |= static_cast<fl::u8>(0x80u >> (i & 7u));
457 r1.add(h);
458 if (reload) rr1.add(h);
459 } else {
460 r0.add(h);
461 if (reload) rr0.add(h);
462 }
463 }
464 const fl::u32 n_bytes = got / 8u;
465 fl::sstream s;
466 if (reload_stats) {
467 // Compact reply for the stressor's RPC: the bytes are compared here,
468 // because a ~250-character reply sent back to back drops replies on
469 // the way to the host. LED i is (rgb + i * step), sent G, R, B.
470 fl::u32 bad = n_bytes == n_bits / 8u ? 0u : 1u;
471 fl::u32 first = 0xFFFFFFFFu, first_exp = 0;
472 for (fl::u32 i = 0; i < n_bytes && i < n_bits / 8u; ++i) {
473 const fl::u32 c = (rgb + (i / 3u) * step) & 0xFFFFFFu;
474 const fl::u32 shift = (i % 3u) == 0u ? 8u : ((i % 3u) == 1u ? 16u : 0u);
475 const fl::u8 want = static_cast<fl::u8>(c >> shift);
476 if (st.decoded[i] != want) {
477 if (bad == 0u) {
478 first = i;
479 first_exp = want;
480 }
481 ++bad;
482 }
483 }
484 s << 1 << ",bytes=" << n_bytes << ",bad=" << bad;
485 if (first != 0xFFFFFFFFu) { // first bad byte: index:got/expected
486 s << ",first=" << first << ':'
487 << static_cast<fl::u32>(st.decoded[first]) << '/' << first_exp;
488 }
489 s << ",bits=" << got
490 << ",t0h=" << r0 << ",t1h=" << r1 << ",reload_t0h=" << rr0
491 << ",reload_t1h=" << rr1;
492 return s.str();
493 }
494 s << 1 << ',' << n_bytes;
495 for (fl::u32 i = 0; i < n_bytes; ++i) {
496 s << ',' << static_cast<fl::u32>(st.decoded[i]);
497 }
498 s << ",bits=" << got;
499 s << ",t0h=" << r0 << ",t1h=" << r1;
500 s << ",gap_guard=" << max_gap_ns;
501 return s.str();
502}
503
504inline fl::string captureSelfHandler(int led_count, fl::u32 rgb,
505 int data_pin, int rx_pin,
506 int hold_us, fl::u32 step) FL_NO_EXCEPT {
507 if (led_count <= 0 || led_count > kMaxCaptureLeds || !usablePin(data_pin) ||
508 !usablePin(rx_pin) || rx_pin == data_pin || hold_us < 0 ||
509 hold_us > 100000) {
510 return fl::string("0,bad_args");
511 }
512 return captureFrame(led_count, rgb, step, data_pin, rx_pin, hold_us,
513 kMaxRiseGapNs);
514}
515
516// #5278: `pwmDmaClCaptureStress` is `pwmDmaClCaptureSelf` with a choice of
517// timing (`real_timing` 1: WS2812 1250 ns bits; 0: the 1450 ns low phase of
518// captureTiming()) and an optional DMA0 stressor running for the whole frame
519// at CHPRIORITY `stress_priority` (-1: none). `paced` 0 is the unpaced
520// stressor; n >= 1 is paced with 2^(n-1) words per bit (see stressStart()).
521inline fl::string captureStressHandler(int led_count, fl::u32 rgb,
522 int data_pin, int rx_pin, fl::u32 step,
523 int real_timing, int stress_priority,
524 int paced) FL_NO_EXCEPT {
525 if (led_count <= 0 || led_count > kMaxCaptureLeds || !usablePin(data_pin) ||
526 !usablePin(rx_pin) || rx_pin == data_pin || stress_priority < -1 ||
527 stress_priority > 7 || paced < 0 || paced > 4) {
528 return fl::string("0,bad_args");
529 }
530 return captureFrame(led_count, rgb, step, data_pin, rx_pin, 0,
531 kMaxRiseGapNs,
532 real_timing ? ws2812b_timing() : captureTiming(),
533 stress_priority, paced, /*reload_stats=*/true);
534}
535
536// #5278: force a DMA error at the first chunk reload (corruptSecondChunk())
537// and check that the frame ends cleanly. `hold_us` > 0 skips poll() that
538// long first, as FastLED.show() does, so only the DMA interrupt can end it.
539// The capture runs to its full kMaxCaptureLeds buffer, so stale bits clocked out
540// after the error are counted. Returns
541// "1,ready=<0|1>,complete=<0|1>,bits=<n>,chunk_bits=<c>,line=<0|1>,hub=<0|1>":
542// a clean failure is ready=1, complete=0, line=0, and bits just past
543// chunk_bits (the error is taken one bit after the reload). Without the DMA
544// ISR hub (hub=0) only poll() stops it, so with hold_us > 0 stale bits run
545// on until the hold ends.
546inline fl::string dmaErrorHandler(int led_count, fl::u32 rgb, int data_pin,
547 int rx_pin, int hold_us) FL_NO_EXCEPT {
548 if (led_count <= 0) {
549 return fl::string("0,bad_args");
550 }
551 const fl::u32 n_bits = static_cast<fl::u32>(led_count) * 24u;
552 if (n_bits <= FASTLED_LPC_PWM_DMA_CHUNK_BITS || led_count > kMaxCaptureLeds ||
553 !usablePin(data_pin) || !usablePin(rx_pin) || rx_pin == data_pin ||
554 hold_us < 0 || hold_us > 100000) {
555 return fl::string("0,bad_args");
556 }
557 const fl::ChipsetTimingConfig t = captureTiming();
558 const fl::u32 t1h = fl::lpc_sct_ticks(t.t1_ns + t.t2_ns);
559 const fl::u32 period = fl::lpc_sct_ticks(t.t1_ns + t.t2_ns + t.t3_ns);
560 auto& engine = fl::BusTraits<fl::Bus::BIT_BANG>::instance();
561 if (!waitReady(engine, frameTimeoutUs(kMaxCaptureLeds))) {
562 return fl::string("0,busy");
563 }
564 auto ch = makeChannelData(data_pin, led_count, rgb, 0u, t);
565 if (!engine.canHandle(ch)) {
566 return fl::string("0,cannot_handle");
567 }
568 // A frame show() would drop leaves no descriptor of its own to corrupt;
569 // the link would be an earlier frame's.
570 if (!fl::ChannelEngineLpcSctDma::frameFits(ch->getSize())) {
571 return fl::string("0,too_long_without_hub");
572 }
573 auto& st = pwmDmaClocklessState();
574 fl::LpcCtimerPulseCapture cap;
575 if (!cap.begin(rx_pin, (t1h + period) / 2u, fl::lpc_sct_ticks(kMaxRiseGapNs),
576 fl::span<fl::u32>(st.highTicks, kMaxCaptureLeds * 24))) {
577 return fl::string("0,capture_begin");
578 }
579 engine.enqueue(ch);
580 engine.show();
581 // Chunk 0 plays for 96 bits (216 us at this timing); the reload that
582 // fails comes after that.
583 if (!corruptSecondChunk()) {
584 cap.end();
585 engine.poll();
586 return fl::string("0,no_second_chunk");
587 }
588 if (hold_us > 0) {
589 delayMicroseconds(static_cast<fl::u32>(hold_us)); // no poll()
590 }
591 const bool ready = waitReady(engine, frameTimeoutUs(led_count));
593 const fl::u32 got = cap.count();
594 cap.end();
596 const bool line_high = fl::digitalRead(rx_pin) == fl::PinValue::High;
597 fl::sstream s;
598 s << 1 << ",ready=" << (ready ? 1 : 0)
599 << ",complete=" << (lastFrameComplete(engine) ? 1 : 0)
600 << ",bits=" << got << ",chunk_bits=" << FASTLED_LPC_PWM_DMA_CHUNK_BITS
601 << ",line=" << (line_high ? 1 : 0) << ",hub=" << FASTLED_LPC_DMA_ISR;
602 return s.str();
603}
604
605// Bind the handlers on the passed-in `Remote`. Call from
606// AutoResearch.ino under `#if defined(FASTLED_LPC_PWM_DMA)`.
607inline void bind(fl::Remote& remote) FL_NO_EXCEPT {
608 remote.bind("pwmDmaClFrameOnce",
609 [](int led_count, fl::u32 rgb, int data_pin) -> fl::string {
610 return frameOnceHandler(led_count, rgb, data_pin);
611 });
612 remote.bind("pwmDmaClFrameBurst",
613 [](int led_count, fl::u32 rgb, int n_frames, int data_pin) -> fl::string {
614 return frameBurstHandler(led_count, rgb, n_frames, data_pin);
615 });
616 remote.bind("pwmDmaClCaptureSelf",
617 [](int led_count, fl::u32 rgb, int data_pin, int rx_pin,
618 int hold_us, fl::u32 step_rgb) -> fl::string {
619 return captureSelfHandler(led_count, rgb, data_pin, rx_pin,
620 hold_us, step_rgb);
621 });
622 remote.bind("pwmDmaClCaptureStress",
623 [](int led_count, fl::u32 rgb, int data_pin, int rx_pin,
624 fl::u32 step_rgb, int real_timing, int stress_priority,
625 int paced) -> fl::string {
626 return captureStressHandler(led_count, rgb, data_pin, rx_pin,
627 step_rgb, real_timing, stress_priority,
628 paced);
629 });
630 remote.bind("pwmDmaClDmaError",
631 [](int led_count, fl::u32 rgb, int data_pin, int rx_pin,
632 int hold_us) -> fl::string {
633 return dmaErrorHandler(led_count, rgb, data_pin, rx_pin, hold_us);
634 });
635}
636
637} // namespace pwm_dma_cl
638} // namespace autoresearch
639
640#endif // FL_IS_ARM_LPC_845 && FASTLED_LPC_PWM_DMA
fl::unique_ptr< fl::Remote > remote
Definition RpcClient.ino:43
Portable compile-time identifiers for LED channel buses.
Per-driver traits keyed on fl::Bus.
Runtime chipset timing configuration for clockless LED drivers.
static ChannelDataPtr create(const ChipsetVariant &chipset, fl::vector_psram< u8 > &&encodedData=fl::vector_psram< u8 >(), ChannelPixelFormat pixelFormat=ChannelPixelFormat::RGB) FL_NO_EXCEPT
Create channel transmission data (modern variant-based API)
Definition data.cpp.hpp:12
static T & instance() FL_NO_EXCEPT
Definition singleton.h:81
static Watchdog & instance() FL_NO_EXCEPT
void feed() FL_NO_EXCEPT
string str() const FL_NO_EXCEPT
Definition strstream.h:43
Channel transmission data - lightweight DTO for driver transmission.
static uint32_t t
Definition Luminova.h:55
constexpr remove_reference< T >::type && move(T &&t) FL_NO_EXCEPT
Definition move.h:30
unsigned char u8
Definition stdint.h:132
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.
ostream & operator<<(ostream &os, const hex_t &) FL_NO_EXCEPT
fl::u32 micros() FL_NO_EXCEPT
Universal microsecond timer - returns microseconds since system startup.
@ High
Logic high (3.3V / 5V, platform-dependent)
Definition pin.h:52
FASTLED_FORCE_INLINE void * memset(void *s, int c, size_t n) FL_NO_EXCEPT
Definition cstring.h:148
constexpr enable_if< is_fixed_point< T >::value, T >::type step(T edge, T x) FL_NO_EXCEPT
float add(float &a, float &b) FL_NO_EXCEPT
const char * pinProbeSkipReason(int pin) FL_NO_EXCEPT
Why a probe must not touch pin at all (no pinMode, read or write), or nullptr when it may.
PinValue digitalRead(int pin) FL_NO_EXCEPT
Read digital value from pin.
Definition pin.cpp.hpp:55
@ Input
Digital input (high impedance)
Definition pin.h:43
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.
Platform-neutral "may a pin probe touch this pin?" API.
#define FL_STATIC_ASSERT(...)
#define FL_NO_EXCEPT
Portable compile-time assertion wrapper.
@ READY
Hardware idle; ready to accept new transmissions.
Definition driver.h:171
Compile-time timing extraction from ChipsetTiming structs.