FastLED 3.10.10
Loading...
Searching...
No Matches
AutoResearchEsp8266.h
Go to the documentation of this file.
1#pragma once
2//
3// examples/AutoResearch/AutoResearchEsp8266.h
4//
5// ESP8266 driver benches for the low-memory AutoResearch surface.
6//
7// Every bench takes a single `const fl::json&` parameter and reads its fields
8// positionally out of the JSON array the host sends, so
9// `ci.rpc_client.RpcClient.send(name, args=[...])` drives it directly: that
10// client frames one JSON `params` value (params:[args]), and it cannot express a
11// bind of arity 0 or 2+. The `[a, b, c]` lines below are that array.
12//
13// uartWs2812Loopback: [nLeds, rxPin] -> json
14// Encodes a known pattern with the UART WS2812 driver's encoder, streams it
15// out of UART1 (GPIO2) and samples rxPin through GPIO_IN while the hardware
16// shifts it out, so the CPU is free to poll. Needs a jumper GPIO2 -> rxPin:
17// GPIO_IN does not see GPIO2's pad once UART1 owns it (measured: the line
18// reads low whether TX idles high or low). The decoded LED bytes and the
19// measured T0H/T1H/bit-period are returned for the host to judge.
20//
21// uartWs2812Show: [nLeds] -> json
22// Runs the same driver through FastLED.addLeds + FastLED.show().
23//
24// clocklessShow / apa102Show: [nLeds, frames] -> json
25// Run the default bit-banged WS2812 controller (GPIO4) and the APA102
26// controller (data GPIO13, clock GPIO14) through FastLED.show() and report
27// min/max frame time. A frame near twice the floor means the clockless
28// driver aborted and retried after an interrupt overran its timing window.
29//
30// apa102ShowMhz: [nLeds, mhz] -> json (20 frames)
31// APA102 on native HSPI (GPIO13/14) at 6/10/20/40/80 MHz. The driver
32// programs SPI1CLK in init() only, so each rate gets its own controller and
33// the bench re-inits before timing. Reports achievable_hz (decoded from the
34// SPI1CLK the driver just wrote), expected_us from it, and the measured
35// min_us; `success` is the frame time landing in
36// [expected_us, expected_us + 400 us]. The 400 us covers the ~250 us
37// per-show cost plus jitter, so this band only rejects a bus running at half
38// the programmed rate where the wire time is large next to that cost (6 MHz
39// here: 762 us of wire time vs a 781 us bound). At 20 MHz and above the wire
40// time shrinks under the slack and the band cannot see a halved bus -- there
41// `achievable_hz` (read back from SPI1CLK) is the evidence that the divider
42// took effect, not `success`.
43//
44// apa102ShowBitbang: [nLeds, frames] -> json
45// The same chipset on GPIO4/GPIO16, i.e. the generic software SPI fallback,
46// for a same-run comparison against apa102Show. generic_bitbang is false in a
47// FASTLED_ALL_PINS_HARDWARE_SPI build, where that pair resolves to the legacy
48// Arduino-SPI shim and is therefore not a bit-bang baseline.
49//
50// The benches name the HSPI pair as FL_PIN_SPI_DATA_1 / FL_PIN_SPI_CLOCK_1, the
51// same key the native-HSPI specialization uses, so D1/NodeMCU pin orders
52// (7/5) select the same GPIO13/14 pads instead of quietly falling back to the
53// bit-bang. The sense-pin arguments are always raw GPIO numbers.
54//
55// apa102HspiLoopback: [khz, mosiPin, sckPin] -> json
56// Pin-level HSPI check at 25 or 50 kHz. GPIO_IN does not see GPIO13/14 while
57// HSPI owns the pads, so jumper D7 (GPIO13, MOSI) to mosiPin and D5 (GPIO14,
58// SCK) to sckPin (12 and 5 are D6 and D1; both arguments are required). The
59// SCK ISR samples MOSI
60// on every rising edge (mode 0) and the 96 decoded bytes must match. Run
61// wifiOff first: the ISR budget is one SCK period, and MAC interrupts eat it.
62//
63// apa102HspiWatch: [sensePin, nBytes, nField] -> json
64// Starts a 25 kHz HSPI transfer by hand and polls sensePin through GPI for the
65// whole of it, so it counts the edges on the wire without relying on an ISR
66// (the driver's kick() only watches SPIBUSY, which runs for the programmed
67// time whether or not the pad is driven). nField >= 0 re-splits the same
68// total divider across CLKCNT_N/CLKDIV_PRE before the transfer, which is how
69// a zero CLKCNT_L was isolated; -1 runs whatever the driver installed.
70//
71// apa102HspiJumperCheck: [sensePin, txPin] -> json
72// Drives one HSPI output pad (txPin: 13 = MOSI/D7, 14 = SCK/D5) as a plain
73// GPIO and reports whether sensePin both follows the level and counts the
74// edges, which separates a missing jumper from a dead ISR; run it once per
75// signal before the loopback.
76//
77// All three accept sense pins only from 0, 5, 12 and 15 (the rest are the
78// console, the UART bench, the clockless controller's pad, the flash pads, or
79// the HSPI pads pinMode would unmux), and the loopback rejects two equal pins.
80//
81
82#include "platforms/esp/is_esp.h" // ok platform headers // ok platform specific - ESP8266 bench gate
83
84#if defined(FL_IS_ESP8266) // ok platform specific - ESP8266-only bench file
85
86#include "FastLED.h"
88#include "fl/stl/json.h"
89#include "fl/stl/stdint.h"
90#include "fl/stl/string.h"
91#include "fl/wdt/watchdog.h"
92#include "platforms/esp/8266/fastled_esp8266_uart.h" // ok platform headers // ok platform specific - ESP8266 UART driver under test
93
94// IWYU pragma: begin_keep
95#include <esp8266_peri.h> // ok platform specific - GPI, ESP8266_CLOCK for raw loopback sampling
96#include <user_interface.h> // ok platform specific - system_update_cpu_freq, wifi_* for bench setup
97#include "platforms/esp/8266/i2s_ws2812_codec.h" // ok platform headers - codec + samplesToEdges
98#include "platforms/esp/8266/spi_hspi_clock.h" // ok platform headers - HSPI clock divider
99#include <core_esp8266_i2s.h> // ok platform specific - I2S TX/RX registers for the loopback bench
100#include <cont.h> // ok platform specific - cont_get_free_stack (loop-stack headroom)
101// IWYU pragma: end_keep
102
103namespace autoresearch {
104namespace esp8266 {
105
106constexpr int kMaxLoopbackLeds = 10; // 120 UART bytes fit the 128-byte FIFO
107constexpr int kMaxEdges = kMaxLoopbackLeds * 24 * 2 + 4;
108
109// Always inlined: the IRAM capture loop must not call back into flash.
110__attribute__((always_inline)) inline fl::u32 cycles() {
111 fl::u32 c;
112 __asm__ __volatile__("rsr %0,ccount" : "=a"(c)); // ok platform specific - cycle-accurate edge timestamps; no core cycle counter
113 return c;
114}
115
116inline fl::u8 patternByte(int i) {
117 static const fl::u8 kSeed[] = {0x00, 0xFF, 0xAA, 0x55, 0x0F, 0xF0};
118 if (i < static_cast<int>(sizeof(kSeed))) {
119 return kSeed[i];
120 }
121 return static_cast<fl::u8>(i * 37 + 0x5A);
122}
123
124struct EdgeCapture {
125 fl::u32 edges[kMaxEdges];
126 int count;
127 bool firstLevel;
128};
129
130inline EdgeCapture& edgeCapture() {
132}
133
134// Streams `encoded` out of UART1 while timestamping every rxPin edge. Runs
135// from IRAM: from flash, the cold instruction cache on the first call after
136// boot stalled the loop past the first pulses (measured: 4 bits lost).
137// A FIFO write stalls the CPU for ~115 ns. Filling all 120 bytes up front let
138// the UART shift out 11 bits before sampling began, and writing once per
139// sample missed short T0H pulses. So prime two bytes, then write one just
140// after each falling edge, where the line stays low for >= 300 ns. Two edges
141// fall per UART byte, so the FIFO stays ahead of the shifter.
142FL_NO_INLINE static FL_IRAM void captureEdges(
143 const fl::u8* encoded, int nEncoded, fl::u32 mask, fl::u32 idleCycles,
144 EdgeCapture& cap) {
145 bool level = (GPI & mask) != 0; // ok platform specific - raw GPIO sampling / UART1 FIFO feed for the pin-level loopback
146 cap.firstLevel = level;
147 USF(fl::esp8266_uart::kUart) = encoded[0]; // ok platform specific - raw GPIO sampling / UART1 FIFO feed for the pin-level loopback
148 USF(fl::esp8266_uart::kUart) = encoded[1]; // ok platform specific - raw GPIO sampling / UART1 FIFO feed for the pin-level loopback
149 int fed = 2;
150 fl::u32 lastEdge = cycles();
151 while (cap.count < kMaxEdges) {
152 const bool now = (GPI & mask) != 0; // ok platform specific - raw GPIO sampling / UART1 FIFO feed for the pin-level loopback
153 const fl::u32 t = cycles();
154 if (now != level) {
155 cap.edges[cap.count++] = t;
156 level = now;
157 lastEdge = t;
158 if (!now && fed < nEncoded) {
159 USF(fl::esp8266_uart::kUart) = encoded[fed++]; // ok platform specific - raw GPIO sampling / UART1 FIFO feed for the pin-level loopback
160 }
161 } else if (t - lastEdge > idleCycles) {
162 break;
163 }
164 }
165}
166
167inline bool isUsableRxPin(int pin) {
168 // GPIO1/3 carry the RPC console, 6-11 the flash, 2 is the TX under test.
169 return pin == 0 || pin == 4 || pin == 5 || (pin >= 12 && pin <= 15);
170}
171
172inline fl::json uartWs2812Loopback(int nLeds, int rxPin) {
173 if (!isUsableRxPin(rxPin)) {
174 fl::json r = fl::json::object();
175 r.set("success", false);
176 r.set("error", "rxPin must be one of 0,4,5,12,13,14,15");
177 return r;
178 }
179 if (nLeds < 1) nLeds = 1;
180 if (nLeds > kMaxLoopbackLeds) nLeds = kMaxLoopbackLeds;
181 const int nBytes = nLeds * 3;
182
183 fl::u8 encoded[kMaxLoopbackLeds * 12];
184 for (int i = 0; i < nBytes; ++i) {
185 fl::esp8266_uart::encodeByte(patternByte(i), &encoded[i * 4]);
186 }
187
188 pinMode(rxPin, INPUT);
189 fl::esp8266_uart::begin(FASTLED_ESP8266_UART_BAUD);
190 fl::delayMicroseconds(100); // line settles low (latch)
191
192 const fl::u8 prevMhz = system_get_cpu_freq(); // ok platform specific - ESP8266 bring-up bench measures raw SoC behavior; no core API exposes it
193 system_update_cpu_freq(160); // ok platform specific - ESP8266 bring-up bench measures raw SoC behavior; no core API exposes it
194 const fl::u32 cyclesPerUs = 160;
195 const fl::u32 idleCycles = 20 * cyclesPerUs; // 20 us of silence ends it
196
197 EdgeCapture& cap = edgeCapture();
198 cap.count = 0;
199 const fl::u32 mask = 1u << rxPin;
200
201 const fl::u32 savedPs = xt_rsil(15); // ok platform specific - masks all IRQs for cycle-exact sampling
202 captureEdges(encoded, nLeds * 12, mask, idleCycles, cap);
203 xt_wsr_ps(savedPs); // ok platform specific - restores IRQ level from xt_rsil
204 system_update_cpu_freq(prevMhz); // ok platform specific - ESP8266 bring-up bench measures raw SoC behavior; no core API exposes it
205
206 // Pair rising/falling edges into high pulses; classify by width.
207 fl::u32 t0hMin = 0xFFFFFFFF, t0hMax = 0, t1hMin = 0xFFFFFFFF, t1hMax = 0;
208 fl::u32 periodMin = 0xFFFFFFFF, periodMax = 0;
209 const fl::u32 splitCycles = (625 * cyclesPerUs) / 1000; // between 312 and 937 ns
210 fl::u8 decoded[kMaxLoopbackLeds * 3] = {};
211 int bits = 0;
212 const int start = cap.firstLevel ? 1 : 0; // first edge must be rising
213 for (int e = start; e + 1 < cap.count && bits < nBytes * 8; e += 2) {
214 const fl::u32 high = cap.edges[e + 1] - cap.edges[e];
215 const bool one = high > splitCycles;
216 if (one) {
217 decoded[bits / 8] |= static_cast<fl::u8>(0x80 >> (bits % 8));
218 if (high < t1hMin) t1hMin = high;
219 if (high > t1hMax) t1hMax = high;
220 } else {
221 if (high < t0hMin) t0hMin = high;
222 if (high > t0hMax) t0hMax = high;
223 }
224 if (e + 2 < cap.count) {
225 const fl::u32 period = cap.edges[e + 2] - cap.edges[e];
226 if (period < periodMin) periodMin = period;
227 if (period > periodMax) periodMax = period;
228 }
229 ++bits;
230 }
231
232 int byteErrors = 0;
233 int firstBad = -1;
234 for (int i = 0; i < nBytes; ++i) {
235 if (decoded[i] != patternByte(i)) {
236 ++byteErrors;
237 if (firstBad < 0) firstBad = i;
238 }
239 }
240
241 auto ns = [cyclesPerUs](fl::u32 c) -> fl::i64 {
242 return c == 0xFFFFFFFF ? -1 : static_cast<fl::i64>(c) * 1000 / cyclesPerUs;
243 };
244 fl::json r = fl::json::object();
245 r.set("success", bits == nBytes * 8 && byteErrors == 0);
246 r.set("leds", static_cast<fl::i64>(nLeds));
247 r.set("rx_pin", static_cast<fl::i64>(rxPin));
248 r.set("edges", static_cast<fl::i64>(cap.count));
249 r.set("bits", static_cast<fl::i64>(bits));
250 r.set("byte_errors", static_cast<fl::i64>(byteErrors));
251 r.set("first_bad_byte", static_cast<fl::i64>(firstBad));
252 if (firstBad >= 0) {
253 r.set("expected", static_cast<fl::i64>(patternByte(firstBad)));
254 r.set("actual", static_cast<fl::i64>(decoded[firstBad]));
255 }
256 r.set("idle_low_before", !cap.firstLevel);
257 r.set("t0h_ns_min", ns(t0hMin));
258 r.set("t0h_ns_max", ns(t0hMax));
259 r.set("t1h_ns_min", ns(t1hMin));
260 r.set("t1h_ns_max", ns(t1hMax));
261 r.set("period_ns_min", ns(periodMin));
262 r.set("period_ns_max", ns(periodMax));
263 return r;
264}
265
266// Drive the same driver through the public API (FastLED.addLeds + show) so
267// the controller path runs on silicon; the pad capture above checks the
268// waveform that path emits.
269struct ShowState {
270 CRGB leds[64];
271 fl::UARTController_ESP8266<GRB> controller;
272 bool added = false;
273};
274
275inline ShowState& showState() {
277}
278
279inline fl::json uartWs2812Show(int nLeds) {
280 if (nLeds < 1) nLeds = 1;
281 if (nLeds > 64) nLeds = 64;
282 ShowState& st = showState();
283 CRGB* leds = st.leds;
284 if (!st.added) {
285 FastLED.addLeds(&st.controller, leds, 64);
286 st.added = true;
287 }
288 st.controller.setLeds(fl::span<CRGB>(leds, nLeds));
289 for (int i = 0; i < nLeds; ++i) {
290 leds[i] = CRGB(patternByte(i * 3), patternByte(i * 3 + 1), patternByte(i * 3 + 2));
291 }
292 const fl::u32 t0 = micros();
293 st.controller.showLeds(255);
294 const fl::u32 elapsed = micros() - t0;
295 fl::json r = fl::json::object();
296 r.set("success", true);
297 r.set("leds", static_cast<fl::i64>(nLeds));
298 r.set("show_us", static_cast<fl::i64>(elapsed));
299 // 30 us of wire time per LED plus the latch is the floor.
300 r.set("expected_min_us", static_cast<fl::i64>(nLeds * 30 + FASTLED_ESP8266_UART_RESET_US));
301 return r;
302}
303
304constexpr int kClocklessPin = FL_PIN_CLOCKLESS_1;
305// The platform's declared hardware-SPI pair in the active pin order -- the same
306// key the native-HSPI specialization uses -- so the bench cannot silently
307// measure the generic bit-bang under D1/NodeMCU numbering. The *RealPin
308// constants are the fixed GPIO pads behind them, which is what pinMode() and
309// GPI take.
310constexpr int kApaDataPin = FL_PIN_SPI_DATA_1;
311constexpr int kApaClockPin = FL_PIN_SPI_CLOCK_1;
312constexpr int kApaDataRealPin = fl::FastPin<FL_PIN_SPI_DATA_1>::kRealPin;
313constexpr int kApaClockRealPin = fl::FastPin<FL_PIN_SPI_CLOCK_1>::kRealPin;
314
315struct DriverShowState {
316 CRGB leds[64];
317 CLEDController* clockless = nullptr;
318 CLEDController* apa102 = nullptr;
319};
320
321inline DriverShowState& driverShowState() {
323}
324
325// Show one controller for `frames` frames and report frame-time spread.
326//
327// `controller->showLeds()` and not FastLED.show(): each bench times its own
328// driver, so registering several controllers on overlapping pads across a
329// session (apa102ShowMhz adds one per rate, and the bit-bang baseline shares
330// GPIO4 with clocklessShow) cannot make two drivers write the same pin in one
331// frame, and FastLED's global refresh-rate clamp never enters these numbers.
332inline fl::json timeFrames(CLEDController* controller, int nLeds, int frames,
333 fl::i64 floorUs, fl::i64* minUsOut = nullptr) {
334 DriverShowState& st = driverShowState();
335 if (nLeds < 1) nLeds = 1;
336 if (nLeds > 64) nLeds = 64;
337 if (frames < 1) frames = 1;
338 if (frames > 200) frames = 200;
339 controller->setLeds(fl::span<CRGB>(st.leds, nLeds));
340 fl::u32 minUs = 0xFFFFFFFF, maxUs = 0;
341 const fl::u32 frames0 = fl::_frame_cnt, retries0 = fl::_retry_cnt;
342 int truncated = 0; // finished faster than the wire allows: frame dropped
343 int firstTruncated = -1;
344 for (int f = 0; f < frames; ++f) {
345 for (int i = 0; i < nLeds; ++i) {
346 st.leds[i] = CHSV(static_cast<fl::u8>(f * 7 + i * 13), 255, 255);
347 }
348 const fl::u32 t0 = micros();
349 controller->showLeds(255);
350 const fl::u32 us = micros() - t0;
351 if (us < minUs) minUs = us;
352 if (us > maxUs) maxUs = us;
353 if (static_cast<fl::i64>(us) < floorUs) {
354 if (firstTruncated < 0) firstTruncated = f;
355 ++truncated;
356 }
357 }
358 if (minUsOut != nullptr) {
359 *minUsOut = static_cast<fl::i64>(minUs);
360 }
361 fl::json r = fl::json::object();
362 r.set("success", truncated == 0);
363 r.set("truncated", static_cast<fl::i64>(truncated));
364 r.set("first_truncated_frame", static_cast<fl::i64>(firstTruncated));
365 r.set("driver_frames_ok", static_cast<fl::i64>(fl::_frame_cnt - frames0));
366 r.set("driver_retries", static_cast<fl::i64>(fl::_retry_cnt - retries0));
367 r.set("uptime_ms", static_cast<fl::i64>(millis()));
368 r.set("wifi_opmode", static_cast<fl::i64>(wifi_get_opmode())); // ok platform specific - ESP8266 bring-up bench measures raw SoC behavior; no core API exposes it
369 r.set("leds", static_cast<fl::i64>(nLeds));
370 r.set("frames", static_cast<fl::i64>(frames));
371 r.set("min_us", static_cast<fl::i64>(minUs));
372 r.set("max_us", static_cast<fl::i64>(maxUs));
373 r.set("floor_us", floorUs);
374 return r;
375}
376
377inline fl::json clocklessShow(int nLeds, int frames) {
378 DriverShowState& st = driverShowState();
379 if (!st.clockless) {
380 st.clockless = &FastLED.addLeds<WS2812B, kClocklessPin, GRB>(st.leds, 64);
381 }
382 const int n = nLeds < 1 ? 1 : (nLeds > 64 ? 64 : nLeds);
383 return timeFrames(st.clockless, n, frames, static_cast<fl::i64>(n) * 30);
384}
385
386// The chipset's own frame-length formula, so the expectation cannot drift from
387// the length the controller actually emits.
388inline fl::i64 apa102WireBytes(int nLeds) {
389 // APA102Controller is declared at global scope (legacy naming).
390 return static_cast<fl::i64>(
392 static_cast<fl::size>(nLeds)));
393}
394
395// Frame time against the wire time the programmed divider implies. A frame also
396// carries FastLED's fixed per-show cost (~250 us on this board, identical on the
397// bit-bang path) plus up to ~120 us of scheduling jitter, so the pass band is
398// the wire time plus that slack. It is needed because these benches pass
399// floorUs = 0: timeFrames can never see a truncated frame here, so its own
400// `success` is unconditional.
401//
402// 400 us still rejects a bus running at half the programmed rate: at 6 MHz that
403// would take 762 us of wire time, i.e. 1012 us per frame against a 781 us bound.
404// A single divider step (~7% here) is inside this band by construction -- the
405// band exists to catch a rate that never took effect, not to fine-tune it.
406constexpr fl::i64 kApa102FrameSlackUs = 400;
407
408// The divider the driver actually programmed, decoded from SPI1CLK:
409// f_spi = 80 MHz / ((CLKDIV_PRE + 1) * (CLKCNT_N + 1))
410// Reading the register back is deliberate -- mirroring the driver's private
411// clock() arithmetic would keep compiling (and keep reporting) after the driver
412// changed, and expected_us would then describe a divider never programmed.
413inline fl::u32 hspiAppliedHz() {
414 const fl::u32 reg = SPI1CLK; // ok platform specific - reads back the divider ESP8266HSPIOutput::init() just wrote
415 if (reg & fl::esp8266::kHspiEquSysClk) { // ok platform specific - SPI1CLK bit 31; no core API reports the bus clock
416 return fl::esp8266::kHspiSourceHz; // ok platform specific - SPI1's fixed 80 MHz source; no core API exposes it
417 }
418 const fl::u32 pre = ((reg >> 18) & 0x1FFFUL) + 1;
419 const fl::u32 n = ((reg >> 12) & 0x3FUL) + 1;
420 return fl::esp8266::kHspiSourceHz / (pre * n); // ok platform specific - the same fixed-source decode; no core API exposes it
421}
422
423#if defined(FASTLED_ESP8266_RAW_PIN_ORDER) // ok platform specific - the benchmark requires actual GPIO4/16 and no inverse pin mapping API exists
424template <int CLOCK>
425FASTLED_FORCE_INLINE void bitbangFloorBit() {
426 fl::FastPin<4>::hi();
427 fl::FastPin<CLOCK>::hi();
428 fl::FastPin<CLOCK>::lo();
429}
430
431FASTLED_FORCE_INLINE void bitbangFloorPair(volatile fl::u32* port,
432 fl::u32 low, fl::u32 high) {
433 fl::FastPin<4>::fastset(port, low);
434 fl::FastPin<4>::fastset(port, high);
435}
436
437template <int MHZ, int CLOCK>
438inline fl::json bitbangStreamAt(int nBytes, int frames, int mode) {
439 static fl::u8 bytes[512];
440 const int n = nBytes < 1 ? 1 : (nBytes > 512 ? 512 : nBytes);
441 const int count = frames < 1 ? 1 : (frames > 100 ? 100 : frames);
442 for (int i = 0; i < n; ++i) bytes[i] = static_cast<fl::u8>(i * 37 + 11);
443 fl::GenericSoftwareSPIOutput<4, CLOCK, DATA_RATE_MHZ(MHZ)> spi;
444 spi.init();
445 fl::FastPin<CLOCK>::lo();
446 const auto port = fl::FastPin<4>::port();
447 const fl::u32 lowWord = fl::FastPin<4>::hival() & ~fl::FastPin<CLOCK>::mask();
448 const fl::u32 highWord = lowWord | fl::FastPin<CLOCK>::mask();
449 if (mode == 4 && port != fl::FastPin<CLOCK>::port()) {
450 fl::json error = fl::json::object();
451 error.set("success", false);
452 error.set("error", "two-write calibration requires a shared GPIO port");
453 return error;
454 }
455 fl::u32 best = 0xFFFFFFFF;
456 for (int frame = 0; frame < count; ++frame) {
457 __sync_synchronize(); // ok platform specific - begin with an empty Xtensa store buffer
458 const fl::u32 start = cycles();
459 if (mode == 2) {
460 // Calibration: minimum ordered GPIO work, constant data and no
461 // optional pacing. This is a lower bound, not a payload writer.
462 for (int i = 0; i < n; ++i) {
463 bitbangFloorBit<CLOCK>(); bitbangFloorBit<CLOCK>();
464 bitbangFloorBit<CLOCK>(); bitbangFloorBit<CLOCK>();
465 bitbangFloorBit<CLOCK>(); bitbangFloorBit<CLOCK>();
466 bitbangFloorBit<CLOCK>(); bitbangFloorBit<CLOCK>();
467 }
468 } else if (mode == 4) {
469 for (int i = 0; i < n; ++i) {
470 bitbangFloorPair(port, lowWord, highWord); bitbangFloorPair(port, lowWord, highWord);
471 bitbangFloorPair(port, lowWord, highWord); bitbangFloorPair(port, lowWord, highWord);
472 bitbangFloorPair(port, lowWord, highWord); bitbangFloorPair(port, lowWord, highWord);
473 bitbangFloorPair(port, lowWord, highWord); bitbangFloorPair(port, lowWord, highWord);
474 }
475 fl::FastPin<CLOCK>::lo();
476 } else if (mode == 3) {
477 // Isolate the clock register's sustained write latency. Eight
478 // writes per input byte; this mode does not transmit SPI data.
479 for (int i = 0; i < n; ++i) {
480 fl::FastPin<CLOCK>::hi(); fl::FastPin<CLOCK>::hi();
481 fl::FastPin<CLOCK>::hi(); fl::FastPin<CLOCK>::hi();
482 fl::FastPin<CLOCK>::hi(); fl::FastPin<CLOCK>::hi();
483 fl::FastPin<CLOCK>::hi(); fl::FastPin<CLOCK>::hi();
484 }
485 } else if (mode == 1) {
486 for (int i = 0; i < n; ++i) spi.writeByte(bytes[i]);
487 } else {
488 spi.writeBytes(bytes, n);
489 }
490 __sync_synchronize(); // ok platform specific - drain the Xtensa store buffer before stopping the transmit timer
491 const fl::u32 elapsed = cycles() - start;
492 if (elapsed < best) best = elapsed;
493 fl::FastPin<CLOCK>::lo();
494 }
495 const fl::i64 cpuHz = static_cast<fl::i64>(system_get_cpu_freq()) * 1000000; // ok platform specific - convert the actual ESP8266 cycle counter to throughput
496 fl::json r = fl::json::object();
497 r.set("success", true);
498 r.set("bytes", static_cast<fl::i64>(n));
499 r.set("frames", static_cast<fl::i64>(count));
500 r.set("data_pin", static_cast<fl::i64>(4));
501 r.set("clock_pin", static_cast<fl::i64>(CLOCK));
502 r.set("mode", static_cast<fl::i64>(mode));
503 r.set("requested_mhz", static_cast<fl::i64>(MHZ));
504 r.set("cpu_hz", cpuHz);
505 r.set("min_cycles", static_cast<fl::i64>(best));
506 const fl::i64 rate = best ? static_cast<fl::i64>(n) * 8 * cpuHz / best : 0;
507 if (mode == 3) r.set("gpio_writes_per_second", rate);
508 else r.set("bits_per_second", rate);
509 return r;
510}
511
512template <int CLOCK>
513inline fl::json bitbangStreamRate(int nBytes, int frames, int mode, int mhz) {
514 if (mhz == 12) return bitbangStreamAt<12, CLOCK>(nBytes, frames, mode);
515 if (mhz == 40) return bitbangStreamAt<40, CLOCK>(nBytes, frames, mode);
516 return bitbangStreamAt<6, CLOCK>(nBytes, frames, mode);
517}
518
519inline fl::json bitbangStream(int nBytes, int frames, int mode, int mhz, int cpuMhz, int clockPin) {
520 if (clockPin != 14 && clockPin != 16) {
521 fl::json error = fl::json::object();
522 error.set("success", false);
523 error.set("error", "clock pin must be 14 or 16");
524 return error;
525 }
526 const fl::u8 previous = system_get_cpu_freq(); // ok platform specific - compare the RTC-limited writer at both supported ESP8266 CPU frequencies
527 if (cpuMhz == 80 || cpuMhz == 160) {
528 system_update_cpu_freq(cpuMhz); // ok platform specific - temporary benchmark setting, restored before returning
529 }
530 fl::json r;
531 if (clockPin == 14) r = bitbangStreamRate<14>(nBytes, frames, mode, mhz);
532 else r = bitbangStreamRate<16>(nBytes, frames, mode, mhz);
533 system_update_cpu_freq(previous); // ok platform specific - preserve the application's CPU frequency after calibration
534 return r;
535}
536#else
537inline fl::json bitbangStream(int, int, int, int, int, int) {
538 fl::json r = fl::json::object();
539 r.set("success", false);
540 r.set("error", "the bit-bang benchmark requires raw pin order");
541 return r;
542}
543#endif
544
545inline fl::json apa102RateReport(fl::json r, fl::i64 minUs, int nLeds, int mhz,
546 fl::u32 hz) {
547 const fl::i64 bytes = apa102WireBytes(nLeds);
548 const fl::i64 bits = bytes * 8;
549 const fl::i64 expected = hz ? (bits * 1000000 + hz - 1) / static_cast<fl::i64>(hz) : -1;
550 r.set("success", expected > 0 && minUs >= expected &&
551 minUs <= expected + kApa102FrameSlackUs);
552 r.set("mhz", static_cast<fl::i64>(mhz));
553 r.set("requested_hz", static_cast<fl::i64>(mhz) * 1000000);
554 r.set("achievable_hz", static_cast<fl::i64>(hz));
555 r.set("wire_bytes_est", bytes);
556 r.set("expected_us", expected);
557 // The 80 MHz setting is the system-clock bypass, and the bypass is a GPMUX
558 // mux bit as much as SPI1CLK bit 31. Report both, so a hardware-SPI build
559 // at 80 MHz can show the driver paired them and a divider build can show it
560 // did not touch the mux.
561 const fl::u32 reg = SPI1CLK; // ok platform specific - reads back the clock-source selection init() just wrote
562 r.set("reg_equ", static_cast<fl::i64>((reg >> 31) & 1UL));
563 r.set("gpmux_equ", static_cast<fl::i64>((GPMUX >> 9) & 1UL)); // ok platform specific - the bypass mux bit; no core API reports it
564 return r;
565}
566
567// The chipset default: DATA_RATE_MHZ(6) (fl/chipsets/apa102.h).
568inline fl::json apa102Show(int nLeds, int frames) {
569 DriverShowState& st = driverShowState();
570 if (!st.apa102) {
571 st.apa102 = &FastLED.addLeds<APA102, kApaDataPin, kApaClockPin, BGR>(st.leds, 64);
572 }
573 // init() is the only writer of SPI1CLK, and it re-installs the pad mux:
574 // another bench may have left the bus at its own divider or taken the pads
575 // back as plain GPIO, so re-init rather than trust the addLeds-time setup.
576 st.apa102->init();
577 const fl::u32 hz = hspiAppliedHz();
578 const int n = nLeds < 1 ? 1 : (nLeds > 64 ? 64 : nLeds);
579 // Two statements, not one: reading minUs in the same call that fills it in
580 // leaves the order unspecified.
581 fl::i64 minUs = 0;
582 fl::json r = timeFrames(st.apa102, n, frames, 0, &minUs);
583 return apa102RateReport(r, minUs, n, 6, hz);
584}
585
586inline fl::json hspiPinError(const char* what) {
587 fl::json e = fl::json::object();
588 e.set("success", false);
589 e.set("error", what);
590 return e;
591}
592
593// The same chipset on a pin pair HSPI cannot reach: the generic software SPI
594// bit-bang this platform used for every APA102 before the native path. D2/D0,
595// not the loopback sense pins, so a fitted jumper never has two outputs on it.
596//
597// 4/16 are only GPIO4/GPIO16 in raw pin order, and D1/NodeMCU numbering has no
598// FastPin<16> at all, so the baseline is defined for the default order only.
599#if defined(FASTLED_ESP8266_RAW_PIN_ORDER) // ok platform specific - keys 4/16 are GPIO4/16 only in raw order; no API maps a real pad back to a key
600constexpr int kBitbangDataPin = 4;
601constexpr int kBitbangClockPin = 16;
602#endif
603
604inline fl::json apa102ShowBitbang(int nLeds, int frames) {
605#if !defined(FASTLED_ESP8266_RAW_PIN_ORDER) // ok platform specific - those keys exist only in raw order; no core API can express the pair portably
606 (void)nLeds;
607 (void)frames;
608 return hspiPinError("the bit-bang baseline is only defined in raw pin order");
609#else
610 DriverShowState& st = driverShowState();
611 static CLEDController* c = nullptr;
612 if (c == nullptr) {
613 c = &FastLED.addLeds<APA102, kBitbangDataPin, kBitbangClockPin, BGR>(st.leds, 64);
614 }
615 // Another bench may have taken these pads as inputs (uartWs2812Loopback's
616 // rxPin accepts 4), and addLeds() only initialises once.
617 c->init();
618 const int n = nLeds < 1 ? 1 : (nLeds > 64 ? 64 : nLeds);
619 fl::json r = timeFrames(c, n, frames, 0);
620 r.set("data_pin", static_cast<fl::i64>(kBitbangDataPin));
621 r.set("clock_pin", static_cast<fl::i64>(kBitbangClockPin));
622 r.set("wire_bytes_est", apa102WireBytes(n));
623 // This pair is only the generic bit-bang in the default build. Under
624 // FASTLED_ALL_PINS_HARDWARE_SPI every non-HSPI pair goes to the legacy
625 // Arduino-SPI shim, which drives GPIO13/14 -- so there the timing here is
626 // that shim's, not a software bit-bang, and it is not a baseline.
627#if defined(FASTLED_ALL_PINS_HARDWARE_SPI) // ok platform specific - this build resolves the pair to the Arduino-SPI shim; no API reports the backend
628 r.set("generic_bitbang", false);
629#else
630 r.set("generic_bitbang", true);
631#endif
632 return r;
633#endif // FASTLED_ESP8266_RAW_PIN_ORDER
634}
635
636// One APA102 controller per clock rate. SPI1CLK is written by init() alone, so
637// a controller added at a different rate would otherwise keep the previous
638// divider; the bench re-inits to make each rate real.
639template <int MHZ>
640inline CLEDController* apa102At(CRGB* leds) {
641 static CLEDController* c =
642 &FastLED.addLeds<APA102, kApaDataPin, kApaClockPin, BGR, DATA_RATE_MHZ(MHZ)>(leds, 64);
643 return c;
644}
645
646inline fl::json apa102ShowMhz(int nLeds, int frames, int mhz) {
647 DriverShowState& st = driverShowState();
648 CLEDController* c = nullptr;
649 switch (mhz) {
650 case 6: c = apa102At<6>(st.leds); break;
651 case 10: c = apa102At<10>(st.leds); break;
652 case 20: c = apa102At<20>(st.leds); break;
653 case 40: c = apa102At<40>(st.leds); break;
654 case 80: c = apa102At<80>(st.leds); break;
655 default: {
656 fl::json e = fl::json::object();
657 e.set("success", false);
658 e.set("error", "mhz must be 6, 10, 20, 40 or 80");
659 return e;
660 }
661 }
662 const int n = nLeds < 1 ? 1 : (nLeds > 64 ? 64 : nLeds);
663 c->init();
664 // After init(): the divider under test is the one in the register.
665 const fl::u32 hz = hspiAppliedHz();
666 fl::i64 minUs = 0;
667 fl::json r = timeFrames(c, n, frames, 0, &minUs);
668 r = apa102RateReport(r, minUs, n, mhz, hz);
669 r.set("cpu_mhz", static_cast<fl::i64>(system_get_cpu_freq())); // ok platform specific - the bench reports the raw SoC clock; no core API exposes it
670 return r;
671}
672
673// Pin-level HSPI loopback. GPIO_IN does not see GPIO13/14 once HSPI owns the
674// pads, so read MOSI and SCK back through jumpers: SCK (D5, GPIO14) to sckPin
675// and MOSI (D7, GPIO13) to mosiPin. The ISR has to
676// sample the data, because the driver's flush() blocks on the wire. Sense pins
677// are arguments, so a board where those pads are hard to reach can use any two
678// of the pins hspiSensePinOk() allows.
679constexpr int kHspiLoopBytes = 96;
680
681struct HspiLoopbackState {
682 volatile fl::u8 got[kHspiLoopBytes];
683 // Staged here rather than on the handler's stack: this file already split
684 // its bind functions to stay inside 4 KB of loop stack, and the pattern is
685 // fully derivable, so the bytes cost nothing in .bss.
686 fl::u8 tx[kHspiLoopBytes];
687 volatile int bits;
688 volatile int rising;
689 volatile int falling;
690 fl::u32 mosiMask;
691 fl::u32 sckMask;
692};
693
694inline HspiLoopbackState& hspiLoopbackState() {
696}
697
698// The ISR runs on every SCK edge, so it reads a cached pointer rather than
699// paying the singleton lookup, and the accessor must inline so the ISR never
700// fetches from flash mid-transfer.
701__attribute__((always_inline)) inline HspiLoopbackState*& hspiLoopbackActive() {
702 static HspiLoopbackState* s = nullptr;
703 return s;
704}
705
706inline fl::u8 hspiPattern(int i) { return static_cast<fl::u8>(i * 37 + 11); }
707
708// Samples MOSI on every SCK edge and keeps the rising ones (mode 0), so it
709// must stay short: at the bench's clock the ISR gets a few microseconds.
710FL_NO_INLINE static FL_IRAM void hspiSckSample() {
711 HspiLoopbackState& s = *hspiLoopbackActive();
712 const fl::u32 gpi = GPI; // ok platform specific - raw pad sampling for the HSPI pin-level loopback
713 if (gpi & s.sckMask) {
714 ++s.rising;
715 if (s.bits < kHspiLoopBytes * 8) {
716 if (gpi & s.mosiMask) {
717 s.got[s.bits >> 3] |= static_cast<fl::u8>(0x80 >> (s.bits & 7));
718 }
719 ++s.bits;
720 }
721 } else {
722 ++s.falling;
723 }
724}
725
726// The ISR has to finish inside one bit period, so the loopback runs far below
727// the driver's normal clock: at 40 us per bit even the core's generic ISR
728// dispatch has slack.
729template <int KHZ>
730inline fl::json apa102HspiLoopbackAt(int mosiPin, int sckPin) {
731 HspiLoopbackState& s = hspiLoopbackState();
732 hspiLoopbackActive() = &s; // cache for the ISR (constant-initialized static)
733 s.mosiMask = 1u << mosiPin;
734 s.sckMask = 1u << sckPin;
735 s.bits = 0;
736 s.rising = 0;
737 s.falling = 0;
738 for (int i = 0; i < kHspiLoopBytes; ++i) {
739 s.got[i] = 0;
740 s.tx[i] = hspiPattern(i);
741 }
742
743 fl::SPIOutput<kApaDataPin, kApaClockPin, DATA_RATE_KHZ(KHZ)> spi;
744 spi.init();
745 // Snapshot the pad mux the driver just installed. If GPF14 is not the BUS
746 // function, the peripheral shifts the frame internally and nothing reaches
747 // the wire -- which the frame time alone cannot tell you, because the shift
748 // takes exactly as long either way.
749 const fl::u32 gpf13 = GPF13; // ok platform specific - reads back the pad function just installed; no core API reports it
750 const fl::u32 gpf14 = GPF14; // ok platform specific - reads back the pad function just installed; no core API reports it
751 const fl::u32 gpe = GPE; // ok platform specific - reads back the GPIO output enables; no core API reports them
752 pinMode(mosiPin, INPUT);
753 pinMode(sckPin, INPUT);
754 spi.select();
755 const fl::u32 t0 = micros();
756 attachInterrupt(digitalPinToInterrupt(sckPin), hspiSckSample, CHANGE);
757 spi.writeBytes(s.tx, kHspiLoopBytes);
758 const fl::u32 elapsed = micros() - t0;
759 // writeBytes blocks in kick() until SPIBUSY clears, but stay attached
760 // through endTransaction() so no tail edge can be missed.
761 spi.endTransaction();
762 const int risingAfter = s.rising;
763 const int fallingAfter = s.falling;
764 const int bitsAfter = s.bits;
765
766 int badBytes = 0, firstBad = -1;
767 fl::u8 firstBadGot = 0;
768 for (int i = 0; i < kHspiLoopBytes; ++i) {
769 if (s.got[i] != hspiPattern(i)) {
770 if (firstBad < 0) {
771 firstBad = i;
772 // Read now: the probe below drives SCK through this same ISR,
773 // and when the transfer was short it keeps filling got[].
774 firstBadGot = s.got[i];
775 }
776 ++badBytes;
777 }
778 }
779
780 // Was that ISR live for the whole transfer? Drive the SCK pad from the CPU
781 // now, with the same ISR still attached: if these edges are counted but the
782 // transfer's were not, the attach held and the peripheral never drove the
783 // pad -- as opposed to a dead ISR or a missing jumper. Runs after the
784 // measurements so its edges cannot leak into bits/got[].
785 pinMode(kApaClockRealPin, OUTPUT);
786 for (int i = 0; i < 3; ++i) {
787 digitalWrite(kApaClockRealPin, LOW);
789 digitalWrite(kApaClockRealPin, HIGH);
791 }
792 const int probeEdges = s.rising - risingAfter;
793 detachInterrupt(digitalPinToInterrupt(sckPin));
794 spi.stop();
795
796 fl::json r = fl::json::object();
797 r.set("success", bitsAfter == kHspiLoopBytes * 8 && badBytes == 0);
798 r.set("bytes", static_cast<fl::i64>(kHspiLoopBytes));
799 r.set("bits", static_cast<fl::i64>(bitsAfter));
800 r.set("sck_rising_edges", static_cast<fl::i64>(risingAfter));
801 r.set("sck_falling_edges", static_cast<fl::i64>(fallingAfter));
802 // The pad mux the driver installed, and whether the ISR was still live when
803 // the CPU drove the pad: together these separate "no clock reached the pad"
804 // from "no jumper" and from "dead ISR".
805 r.set("gpf13", static_cast<fl::i64>(gpf13));
806 r.set("gpf14", static_cast<fl::i64>(gpf14));
807 r.set("gpe", static_cast<fl::i64>(gpe));
808 r.set("probe_edges", static_cast<fl::i64>(probeEdges));
809 r.set("isr_live_after_transfer", probeEdges == 3);
810 r.set("bad_bytes", static_cast<fl::i64>(badBytes));
811 r.set("first_bad", static_cast<fl::i64>(firstBad));
812 if (firstBad >= 0) {
813 r.set("first_bad_got", static_cast<fl::i64>(firstBadGot));
814 r.set("first_bad_want", static_cast<fl::i64>(hspiPattern(firstBad)));
815 }
816 r.set("khz", static_cast<fl::i64>(KHZ));
817 r.set("elapsed_us", static_cast<fl::i64>(elapsed));
818 // The ISR budget is one SCK period, and the radio's MAC interrupts eat it:
819 // a run with the radio up mis-times edges and reads as a wiring failure.
820 r.set("wifi_opmode", static_cast<fl::i64>(wifi_get_opmode())); // ok platform specific - ESP8266 bring-up bench measures raw SoC behavior; no core API exposes it
821 return r;
822}
823
824#if defined(FASTLED_ESP8266_RAW_PIN_ORDER) // ok platform specific - this loopback verifies actual GPIO4/16, which have no inverse pin-map API
825template <int CLOCK>
826inline fl::json bitbangLoopbackAt(int pattern, int sensePin, int dataSense,
827 int nBytes, int writerMode) {
828 if (sensePin != 0 && sensePin != 5 && sensePin != 12 && sensePin != 15) {
829 return hspiPinError("sense pin must be GPIO0,5,12 or15; connect the selected clock pin to it");
830 }
831 const int n = nBytes < 0 ? 0 : (nBytes > kHspiLoopBytes ? kHspiLoopBytes : nBytes);
832 if (writerMode < 0 || writerMode > 4 || ((writerMode == 2 || writerMode == 3) && n % 3 != 0) || (writerMode == 3 && n > 90) ||
833 (writerMode == 1 && pattern < 0)) {
834 return hspiPinError("pixel counts need whole RGB pixels; start-bit mode allows 30 pixels; repeat mode needs a constant pattern");
835 }
836 fl::GenericSoftwareSPIOutput<4, CLOCK, DATA_RATE_KHZ(50)> spi;
837 spi.init();
838 (fl::pinMode)(sensePin, fl::PinMode::Input);
839 if (dataSense != 4) (fl::pinMode)(dataSense, fl::PinMode::Input);
840 fl::FastPin<CLOCK>::hi();
842 const bool high = (GPI & (1UL << sensePin)) != 0; // ok platform specific - read the physical clock jumper, not the output latch
843 fl::FastPin<CLOCK>::lo();
845 const bool low = (GPI & (1UL << sensePin)) == 0; // ok platform specific - read the physical clock jumper, not the output latch
846 if (!high || !low) return hspiPinError("selected clock jumper does not follow high/low");
847
848 // The remaining fitted jumper checks the final level of an unrelated output.
849 const bool probeUnrelated = sensePin != 12 && sensePin != 13;
850 if (probeUnrelated) {
854 }
855
856 HspiLoopbackState& s = hspiLoopbackState();
857 hspiLoopbackActive() = &s;
858 s.mosiMask = 1UL << dataSense;
859 s.sckMask = 1UL << sensePin;
860 s.bits = s.rising = s.falling = 0;
861 for (int i = 0; i < kHspiLoopBytes; ++i) {
862 s.got[i] = 0;
863 s.tx[i] = pattern < 0 ? hspiPattern(i) : static_cast<fl::u8>(pattern);
864 }
865 CRGB leds[kHspiLoopBytes / 3];
866 for (int i = 0; i < n / 3; ++i) {
867 leds[i] = CRGB(s.tx[i * 3], s.tx[i * 3 + 1], s.tx[i * 3 + 2]);
868 }
869 attachInterrupt(digitalPinToInterrupt(sensePin), hspiSckSample, RISING); // ok platform specific - capture the physical clock edges; no neutral GPIO interrupt API exists
870 const fl::u32 start = micros();
871 if (writerMode == 1) {
872 spi.writeBytesValueRaw(static_cast<fl::u8>(pattern), n);
873 } else if (writerMode == 4) {
874 for (int i = 0; i < n; ++i) spi.writeByte(s.tx[i]);
875 } else if (writerMode >= 2) {
876 PixelController<RGB> pixels(leds, n / 3, ColorAdjustment::noAdjustment(), DISABLE_DITHER);
877 if (writerMode == 3) spi.template writePixels<FLAG_START_BIT, DATA_NOP, RGB>(pixels);
878 else spi.template writePixels<0, DATA_NOP, RGB>(pixels);
879 } else {
880 spi.writeBytes(s.tx, n);
881 }
882 spi.endTransaction();
883 const fl::u32 elapsed = micros() - start;
884 detachInterrupt(digitalPinToInterrupt(sensePin)); // ok platform specific - release the vendor GPIO edge capture installed above
885 const bool clockLow = (GPI & (1UL << sensePin)) == 0; // ok platform specific - verify the physical clock has returned low at API completion
886 const bool unrelatedHigh = !probeUnrelated || (fl::digitalRead)(13) == fl::PinValue::High;
887 if (probeUnrelated) (fl::pinMode)(12, fl::PinMode::Input);
888 const int expectedBits = writerMode == 3 ? (n / 3) * 25 : n * 8;
889 int badBits = 0;
890 for (int bit = 0; bit < expectedBits; ++bit) {
891 bool expected = true;
892 if (writerMode != 3 || bit % 25 != 0) {
893 const int payloadBit = writerMode == 3 ? (bit / 25) * 24 + bit % 25 - 1 : bit;
894 expected = (s.tx[payloadBit / 8] & (0x80 >> (payloadBit % 8))) != 0;
895 }
896 const bool actual = (s.got[bit / 8] & (0x80 >> (bit % 8))) != 0;
897 if (actual != expected) ++badBits;
898 }
899 fl::json r = fl::json::object();
900 r.set("success", s.bits == expectedBits && s.rising == expectedBits && badBits == 0 && clockLow && unrelatedHigh);
901 r.set("bytes", static_cast<fl::i64>(n));
902 r.set("bits", static_cast<fl::i64>(s.bits));
903 r.set("rising_edges", static_cast<fl::i64>(s.rising));
904 r.set("bad_bits", static_cast<fl::i64>(badBits));
905 r.set("clock_low", clockLow);
906 r.set("unrelated_output_final_high", unrelatedHigh);
907 r.set("unrelated_output_tested", probeUnrelated);
908 r.set("writer_mode", static_cast<fl::i64>(writerMode));
909 r.set("elapsed_us", static_cast<fl::i64>(elapsed));
910 r.set("pattern", static_cast<fl::i64>(pattern));
911 r.set("clock_pin", static_cast<fl::i64>(CLOCK));
912 r.set("data_sense_pin", static_cast<fl::i64>(dataSense));
913 r.set("clock_sense_pin", static_cast<fl::i64>(sensePin));
914 r.set("requested_khz", static_cast<fl::i64>(50));
915 return r;
916}
917inline fl::json bitbangLoopback(int pattern, int sensePin, int clockPin, int nBytes, int writerMode) {
918 if (clockPin != 14 && clockPin != 16) return hspiPinError("clock pin must be 14 or 16");
919 if (clockPin == 14) return bitbangLoopbackAt<14>(pattern, sensePin, 2, nBytes, writerMode);
920 return bitbangLoopbackAt<16>(pattern, sensePin, 4, nBytes, writerMode);
921}
922#else
923inline fl::json bitbangLoopback(int, int, int, int, int) {
924 return hspiPinError("the bit-bang loopback requires raw pin order");
925}
926#endif
927
928// A sense pin has to be one of the pins that stay usable while the RPC console
929// and the bus under test are busy: 1 and 3 are UART0 (the console), 2 is the
930// UART bench's TX pad, 4 carries clocklessShow's WS2812 output, 6-11 are the
931// flash pads (pinMode on them resets the board), and 13/14 are the HSPI pads the
932// transfer is driving -- pinMode there would undo the bus mux. GPIO16 is absent from GPI, so it needs GP16I. `other`
933// excludes the pin already used for the other signal, so a self-loop cannot
934// pass with no jumper fitted.
935inline bool hspiSensePinOk(int pin, int other) {
936 const bool usable = pin == 0 || pin == 5 || pin == 12 || pin == 15; // ok platform specific - the ESP8266 pads left usable on a NodeMCU; no core API reports which real pads the active pin order leaves free
937 return usable && pin != other;
938}
939
940// Drives an HSPI output pad as a plain GPIO and both counts interrupts and
941// samples the level on sensePin, so "no jumper fitted" (level never follows, no
942// edges) is told apart from "the HSPI path never drove the pad" (level follows,
943// no edges) and from a dead ISR. Only meaningful with that jumper fitted.
944//
945// txPin is the pad to drive (13 = MOSI/D7, 14 = SCK/D5); sensePin is where the
946// jumper takes it (12 = D6, 5 = D1). Checking both signals separately is what
947// tells a quiet data line from a missing data jumper.
948inline fl::json apa102HspiJumperCheck(int sensePin, int txPin) {
949 if (!hspiSensePinOk(sensePin, -1)) {
950 return hspiPinError("sensePin must be one of 0, 5, 12, 15");
951 }
952 if (txPin != kApaDataRealPin && txPin != kApaClockRealPin) {
953 return hspiPinError("txPin must be 13 (MOSI/D7) or 14 (SCK/D5)");
954 }
955 const int sckPin = sensePin;
956 const int drivePin = txPin;
957 HspiLoopbackState& s = hspiLoopbackState();
958 hspiLoopbackActive() = &s;
959 s.mosiMask = 0; // this check samples SCK only; no stale mask from a loopback
960 s.sckMask = 1u << sckPin;
961 s.bits = 0;
962 s.rising = 0;
963 s.falling = 0;
964 pinMode(sckPin, INPUT);
965 pinMode(drivePin, OUTPUT);
966 // pinMode(OUTPUT) does not clear the output latch, so start from a known
967 // low: a high latch would swallow the first rising edge.
968 digitalWrite(drivePin, LOW);
969 attachInterrupt(digitalPinToInterrupt(sckPin), hspiSckSample, CHANGE);
970 bool seenHigh = false, seenLow = false;
971 for (int i = 0; i < 10; ++i) {
972 digitalWrite(drivePin, HIGH);
974 if (GPI & s.sckMask) { // ok platform specific - raw pad level tells a missing jumper from a dead ISR
975 seenHigh = true;
976 }
977 digitalWrite(drivePin, LOW);
979 if ((GPI & s.sckMask) == 0) { // ok platform specific - raw pad level, as above
980 seenLow = true;
981 }
982 }
983 detachInterrupt(digitalPinToInterrupt(sckPin));
984 // Give the pad back to HSPI, not to the GPIO output register: a later
985 // apa102Show that skipped init() would otherwise clock internally with the
986 // pad held low and still report normal timing.
987 pinMode(drivePin, SPECIAL); // ok platform specific - SPECIAL is the Arduino-core spelling of "restore this pad's BUS function", i.e. give the pad back to HSPI; no core API restores a bus function
988 const bool levelFollows = seenHigh && seenLow;
989 const bool isrCounted = s.rising == 10 && s.falling == 10;
990 fl::json r = fl::json::object();
991 // A floating pin can both follow nothing and (rarely) produce noise edges,
992 // so the level is the authority on whether the jumper is really fitted.
993 r.set("success", levelFollows && isrCounted);
994 r.set("level_follows_tx", levelFollows);
995 r.set("isr_counted_edges", isrCounted);
996 r.set("rising", static_cast<fl::i64>(s.rising));
997 r.set("falling", static_cast<fl::i64>(s.falling));
998 r.set("sense_pin", static_cast<fl::i64>(sensePin));
999 r.set("tx_pin", static_cast<fl::i64>(txPin));
1000 return r;
1001}
1002
1003inline fl::json apa102HspiLoopback(int khz, int mosiPin, int sckPin) {
1004 if (!hspiSensePinOk(mosiPin, sckPin) || !hspiSensePinOk(sckPin, mosiPin)) {
1005 return hspiPinError(
1006 "sense pins must be two different pins from 0, 5, 12, 15");
1007 }
1008 // Rates the driver resolves cleanly with a divider the ISR can keep up
1009 // with: at 25 kHz a bit lasts 40 us, so even the core's generic ISR
1010 // dispatch has room, and the radio must be off (wifiOff) for the rest.
1011 switch (khz) {
1012 case 25: return apa102HspiLoopbackAt<25>(mosiPin, sckPin);
1013 case 50: return apa102HspiLoopbackAt<50>(mosiPin, sckPin);
1014 default: {
1015 fl::json e = fl::json::object();
1016 e.set("success", false);
1017 e.set("error", "khz must be 25 or 50");
1018 return e;
1019 }
1020 }
1021}
1022
1023// Watch the wire from inside the transfer instead of from an ISR.
1024//
1025// kick() only ever looks at SPIBUSY, so on its own it cannot tell a transfer
1026// that drove the pads from one that only shifted internally -- both take the
1027// same time. This stages and starts the transfer by hand and polls the sense
1028// pin in the wait loop, so a count of zero here means the pad really was quiet
1029// (and not merely that no interrupt happened to run).
1030inline fl::json apa102HspiWatch(int sckPin, int nBytes, int nField) {
1031 if (!hspiSensePinOk(sckPin, -1)) {
1032 return hspiPinError("sckPin must be one of 0, 5, 12, 15");
1033 }
1034 const int n = nBytes < 1 ? 1 : (nBytes > 64 ? 64 : nBytes);
1035 fl::SPIOutput<kApaDataPin, kApaClockPin, DATA_RATE_KHZ(25)> spi;
1036 spi.init();
1037 // nField >= 0 re-splits the same total divider across CLKCNT_N and
1038 // CLKDIV_PRE. Before kHspiMinNDivider the driver resolved 25 kHz to
1039 // CLKDIV_PRE = 3201 with CLKCNT_N = CLKCNT_L = 0, and CLKCNT_L is the
1040 // clock's high phase, so the pad had nothing to show; re-splitting the same
1041 // divider with CLKCNT_N = 1 (CLKCNT_L = 1) is how that was confirmed on the
1042 // wire. -1 runs whatever the driver installed, which is what a fixed build
1043 // should be measured with.
1044 const fl::u32 clkBefore = SPI1CLK; // ok platform specific - reads back the divider the driver installed
1045 if (nField >= 0) {
1046 const fl::u32 pre1 = ((clkBefore >> 18) & 0x1FFFUL) + 1;
1047 const fl::u32 n1 = ((clkBefore >> 12) & 0x3FUL) + 1;
1048 const fl::u32 divider = pre1 * n1;
1049 const fl::u32 nNew = (static_cast<fl::u32>(nField) & 0x3FUL) + 1;
1050 const fl::u32 preNew = divider / nNew == 0 ? 1 : divider / nNew;
1051 // Same field layout the driver uses, plus a half-period low phase.
1052 SPI1CLK = ((nNew / 2) & 0x3FUL) | ((nNew - 1) << 12) | ((preNew - 1) << 18); // ok platform specific - rebuilds SPI1CLK by hand; no core API exposes it
1053 }
1054 pinMode(sckPin, INPUT);
1055 const fl::u32 mask = 1u << sckPin;
1056 // Same staging as the driver's flush(): length in SPI1U1, bytes packed
1057 // little-endian into the FIFO words.
1058 const fl::u32 bits = static_cast<fl::u32>(n) * 8 - 1;
1059 const fl::u32 lenMask = (static_cast<fl::u32>(SPIMMOSI) << SPILMOSI) | // ok platform specific - SPI1U field masks/shifts; no core API exposes them
1060 (static_cast<fl::u32>(SPIMMISO) << SPILMISO); // ok platform specific - SPI1U field masks/shifts; no core API exposes them
1061 while (SPI1CMD & SPIBUSY) {} // ok platform specific - waits out a previous transfer; no core API polls SPI1CMD
1062 SPI1U1 = (SPI1U1 & ~lenMask) | (bits << SPILMOSI) | (bits << SPILMISO); // ok platform specific - sets the SPI1 transfer length, as the driver's flush() does
1063 volatile fl::u32* fifo = &SPI1W0; // ok platform specific - SPI1 FIFO staging; no core API exposes it
1064 for (int i = 0; i < (n + 3) / 4; ++i) {
1065 const int b = i * 4;
1066 fl::u32 word = static_cast<fl::u32>(hspiPattern(b));
1067 if (b + 1 < n) word |= static_cast<fl::u32>(hspiPattern(b + 1)) << 8;
1068 if (b + 2 < n) word |= static_cast<fl::u32>(hspiPattern(b + 2)) << 16;
1069 if (b + 3 < n) word |= static_cast<fl::u32>(hspiPattern(b + 3)) << 24;
1070 fifo[i] = word;
1071 }
1072 int transitions = 0, highSamples = 0, samples = 0;
1073 fl::u32 last = GPI & mask; // ok platform specific - raw pad level while the bus runs; no core API reports it
1074 const fl::u32 t0 = micros();
1075 // The same barrier the driver's kick() issues: the SPI1U1 length and FIFO
1076 // writes above must be visible before the peripheral is told to start, or
1077 // the transfer runs with init()'s leftover length and the counts describe
1078 // the wrong frame.
1079 __sync_synchronize();
1080 SPI1CMD |= SPIBUSY; // ok platform specific - starts the hand-staged transfer; no core API starts a raw SPI1 run
1081 while (SPI1CMD & SPIBUSY) { // ok platform specific - polls the bus while sampling the pad; no core API exposes SPI1CMD
1082 const fl::u32 now = GPI & mask; // ok platform specific - raw pad level while the bus runs
1083 ++samples;
1084 if (now != last) {
1085 ++transitions;
1086 last = now;
1087 }
1088 if (now != 0) {
1089 ++highSamples;
1090 }
1091 }
1092 const fl::u32 elapsed = micros() - t0;
1093 spi.stop();
1094
1095 fl::json r = fl::json::object();
1096 r.set("success", transitions > 0);
1097 r.set("khz", static_cast<fl::i64>(25));
1098 r.set("bytes", static_cast<fl::i64>(n));
1099 r.set("bits", static_cast<fl::i64>(n) * 8);
1100 r.set("sck_pin", static_cast<fl::i64>(sckPin));
1101 r.set("transitions", static_cast<fl::i64>(transitions));
1102 r.set("high_samples", static_cast<fl::i64>(highSamples));
1103 r.set("samples", static_cast<fl::i64>(samples));
1104 r.set("elapsed_us", static_cast<fl::i64>(elapsed));
1105 // SPI1CLK: [5:0] CLKCNT_L, [11:6] CLKCNT_H, [17:12] CLKCNT_N, [30:18] PRE.
1106 // Reported after the override, so these are the fields the transfer ran
1107 // with rather than a mirror of what init() left behind.
1108 const fl::u32 clkRan = SPI1CLK; // ok platform specific - reads back the divider the transfer actually ran with
1109 r.set("clk_cnt_l", static_cast<fl::i64>(clkRan & 0x3FUL));
1110 r.set("clk_cnt_h", static_cast<fl::i64>((clkRan >> 6) & 0x3FUL));
1111 r.set("clk_cnt_n", static_cast<fl::i64>((clkRan >> 12) & 0x3FUL));
1112 r.set("clk_pre", static_cast<fl::i64>((clkRan >> 18) & 0x1FFFUL));
1113 r.set("clk_before_pre", static_cast<fl::i64>((clkBefore >> 18) & 0x1FFFUL));
1114 r.set("n_field", static_cast<fl::i64>(nField));
1115 return r;
1116}
1117
1118// Turn the radio off so its MAC NMIs stop preempting bit-banged output.
1119inline fl::json wifiOff() {
1120 wifi_set_opmode_current(NULL_MODE); // ok platform specific - ESP8266 bring-up bench measures raw SoC behavior; no core API exposes it
1121 fl::json r = fl::json::object();
1122 r.set("success", wifi_get_opmode() == NULL_MODE); // ok platform specific - ESP8266 bring-up bench measures raw SoC behavior; no core API exposes it
1123 r.set("wifi_opmode", static_cast<fl::i64>(wifi_get_opmode())); // ok platform specific - ESP8266 bring-up bench measures raw SoC behavior; no core API exposes it
1124 return r;
1125}
1126
1127// UART1 internal loopback (UCLBE): TX feeds the RX FIFO inside the
1128// peripheral, so this proves the encoder, 6N1 framing and 3.2 Mbaud timing
1129// without a jumper. It does not see the GPIO2 pad.
1130inline fl::json uartWs2812InternalLoopback(fl::u32 baud) {
1131 namespace u = fl::esp8266_uart;
1132 u::begin(baud ? baud : FASTLED_ESP8266_UART_BAUD);
1133 // The loopback taps the line after TX inversion and RX inversion does
1134 // not apply to it, so drop TX inversion for the self-test: RX then sees
1135 // ordinary 6N1 frames. The inversion itself is one register bit.
1136 USC0(u::kUart) &= ~(1u << UCTXI); // ok platform specific - UART1 internal-loopback registers; no core API
1137 USC0(u::kUart) |= (1u << UCLBE); // ok platform specific - UART1 internal-loopback registers; no core API
1138 USC0(u::kUart) |= (1u << UCRXRST); // ok platform specific - UART1 internal-loopback registers; no core API
1139 USC0(u::kUart) &= ~(1u << UCRXRST); // ok platform specific - UART1 internal-loopback registers; no core API
1140 const fl::u8 pixel[3] = {0xA5, 0x0F, 0xC3};
1141 fl::u8 sent[12];
1142 for (int i = 0; i < 3; ++i) {
1143 u::encodeByte(pixel[i], &sent[i * 4]);
1144 }
1145 u::write(sent, sizeof(sent));
1146 u::flush();
1147 fl::delayMicroseconds(20 + 9000000 / (baud ? baud : FASTLED_ESP8266_UART_BAUD));
1148 const fl::u32 got = (USS(u::kUart) >> USRXC) & 0xFF; // ok platform specific - UART1 internal-loopback registers; no core API
1149 fl::u32 matched = 0;
1150 fl::json rx = fl::json::array();
1151 for (fl::u32 i = 0; i < got && i < sizeof(sent); ++i) {
1152 const fl::u8 c = static_cast<fl::u8>(USF(u::kUart) & 0x3F); // ok platform specific - UART1 internal-loopback registers; no core API
1153 rx.push_back(static_cast<fl::i64>(c));
1154 if (c == (sent[i] & 0x3F)) {
1155 ++matched;
1156 }
1157 }
1158 USC0(u::kUart) &= ~(1u << UCLBE); // ok platform specific - UART1 internal-loopback registers; no core API
1159 USC0(u::kUart) |= (1u << UCTXI); // ok platform specific - UART1 internal-loopback registers; no core API
1160 fl::json r = fl::json::object();
1161 r.set("sent", static_cast<fl::i64>(sizeof(sent)));
1162 r.set("received", static_cast<fl::i64>(got));
1163 r.set("matched", static_cast<fl::i64>(matched));
1164 r.set("rx", rx);
1165 r.set("success", got == sizeof(sent) && matched == sizeof(sent));
1166 return r;
1167}
1168
1169// Drive GPIO2 as a plain GPIO high then low and read rxPin each time, so a
1170// missing jumper is told apart from a UART1 pin-mux fault. The next UART call
1171// re-runs esp8266_uart::begin(), which hands GPIO2 back to UART1.
1172inline fl::json jumperCheck(int rxPin) {
1173 fl::json r = fl::json::object();
1174 if (!isUsableRxPin(rxPin)) {
1175 r.set("success", false);
1176 r.set("error", "rxPin must be one of 0,4,5,12,13,14,15");
1177 return r;
1178 }
1179 pinMode(rxPin, INPUT);
1180 pinMode(2, OUTPUT);
1181 const fl::u32 mask = 1u << rxPin;
1182 GPOS = 1u << 2; // ok platform specific - plain-GPIO jumper check on raw GPIO registers
1184 const bool seenHigh = (GPI & mask) != 0; // ok platform specific - plain-GPIO jumper check on raw GPIO registers
1185 GPOC = 1u << 2; // ok platform specific - plain-GPIO jumper check on raw GPIO registers
1187 const bool seenLow = (GPI & mask) == 0; // ok platform specific - plain-GPIO jumper check on raw GPIO registers
1188 r.set("rx_pin", static_cast<fl::i64>(rxPin));
1189 r.set("rx_high_when_tx_high", seenHigh);
1190 r.set("rx_low_when_tx_low", seenLow);
1191 r.set("success", seenHigh && seenLow);
1192 return r;
1193}
1194
1195// ESP8266 RPC argument reader. Each bench below is bound with one
1196// `const fl::json&` parameter -- the JSON array the host passes -- instead of
1197// C++ positional parameters, because ci.rpc_client.RpcClient frames every call
1198// as a single `params` value (params:[args]): a raw bind of arity 0 or 2+ is
1199// unreachable through that client. Returns `fallback` for an absent, short, or
1200// non-numeric field.
1201inline int rpcArgInt(const fl::json& args, fl::size index, int fallback) {
1202 if (args.is_array() && index < args.size() && args[index].is_number()) {
1203 const fl::optional<fl::i64> value = args[index].as_int();
1204 if (value.has_value()) {
1205 return static_cast<int>(value.value());
1206 }
1207 }
1208 return fallback;
1209}
1210
1211// Each bind instantiates sizeable temporaries; split the bindings across
1212// non-inlined functions so their frames do not add up on the 4 KB loop
1213// stack (one combined frame overflowed it).
1214FL_NO_INLINE inline void bindEsp8266WatchdogRpcs(fl::Remote& remote) {
1215 // Watchdog bring-up: read why the chip last reset, or stop feeding the
1216 // watchdog (while still yielding) so the user timeout must fire.
1217 remote.bind("resetCause", [](const fl::json& /*args*/) -> fl::json {
1218 auto& wdt = fl::Watchdog::instance();
1219 fl::json r = fl::json::object();
1220 r.set("cause", fl::string(fl::resetCauseName(wdt.lastResetCause())));
1221 r.set("crash_count", static_cast<fl::i64>(wdt.consecutiveCrashCount()));
1222 // Loop-stack headroom (4 KB total); the bind/dispatch path runs close.
1223 r.set("cont_stack_free", static_cast<fl::i64>(cont_get_free_stack(g_pcont))); // ok platform specific - loop-stack headroom diagnostic
1224 return r;
1225 });
1226 remote.bind("watchdogStall", [](const fl::json& args) -> fl::json {
1227 const int ms = rpcArgInt(args, 0, -1);
1228 if (ms < 0) {
1229 fl::json e = fl::json::object();
1230 e.set("error", "ms must be >= 0");
1231 return e;
1232 }
1233 const fl::u32 start = fl::millis();
1234 while (fl::millis() - start < static_cast<fl::u32>(ms)) {
1235 fl::delay(10); // yields, so only fl::Watchdog can fire
1236 }
1237 fl::json r = fl::json::object();
1238 r.set("survived_ms", static_cast<fl::i64>(fl::millis() - start));
1239 return r;
1240 });
1241}
1242
1243FL_NO_INLINE inline void bindEsp8266UartRpcs(fl::Remote& remote) {
1244 // rxPin < 0 runs the jumper-free internal loopback instead, with nLeds
1245 // as the rate in kbaud (0 = the driver's 3.2 Mbaud).
1246 remote.bind("uartWs2812Loopback", [](const fl::json& args) -> fl::json {
1247 const int nLeds = rpcArgInt(args, 0, -1);
1248 const int rxPin = rpcArgInt(args, 1, -1);
1249 if (rxPin < 0) {
1250 // kbaud; 0 = default. USD = ESP8266_CLOCK / baud must stay >= 1.
1251 if (nLeds < 0 || nLeds > 80000) {
1252 fl::json e = fl::json::object();
1253 e.set("error", "kbaud must be in [0, 80000]");
1254 return e;
1255 }
1256 return uartWs2812InternalLoopback(static_cast<fl::u32>(nLeds) * 1000u);
1257 }
1258 // nLeds == 0 checks the jumper itself: GPIO2 as plain GPIO.
1259 if (nLeds == 0) {
1260 return jumperCheck(rxPin);
1261 }
1262 return uartWs2812Loopback(nLeds, rxPin);
1263 });
1264 remote.bind("uartWs2812Show", [](const fl::json& args) -> fl::json {
1265 return uartWs2812Show(rpcArgInt(args, 0, 0));
1266 });
1267}
1268
1269FL_NO_INLINE inline void bindEsp8266DriverRpcs(fl::Remote& remote) {
1270 remote.bind("wifiOff", [](const fl::json& /*args*/) -> fl::json { return wifiOff(); });
1271 remote.bind("clocklessShow", [](const fl::json& args) -> fl::json {
1272 return clocklessShow(rpcArgInt(args, 0, 0), rpcArgInt(args, 1, 1));
1273 });
1274 remote.bind("apa102Show", [](const fl::json& args) -> fl::json {
1275 return apa102Show(rpcArgInt(args, 0, 0), rpcArgInt(args, 1, 1));
1276 });
1277}
1278
1279// Own frame: every bind's temporaries get a stack slot in the caller, and one
1280// more bind in bindEsp8266DriverRpcs overflowed the 4 KB loop stack.
1281FL_NO_INLINE inline void bindEsp8266HspiRpcs(fl::Remote& remote) {
1282 remote.bind("apa102ShowMhz", [](const fl::json& args) -> fl::json {
1283 return apa102ShowMhz(rpcArgInt(args, 0, 0), 20, rpcArgInt(args, 1, 6));
1284 });
1285 remote.bind("apa102HspiLoopback", [](const fl::json& args) -> fl::json {
1286 return apa102HspiLoopback(rpcArgInt(args, 0, 0), rpcArgInt(args, 1, -1),
1287 rpcArgInt(args, 2, -1));
1288 });
1289 remote.bind("apa102HspiJumperCheck", [](const fl::json& args) -> fl::json {
1290 return apa102HspiJumperCheck(rpcArgInt(args, 0, -1), rpcArgInt(args, 1, -1));
1291 });
1292 remote.bind("apa102HspiWatch", [](const fl::json& args) -> fl::json {
1293 return apa102HspiWatch(rpcArgInt(args, 0, -1), rpcArgInt(args, 1, 1),
1294 rpcArgInt(args, 2, -1));
1295 });
1296}
1297
1298// A third frame for the same reason: keep every bind's temporaries in a frame
1299// small enough for the 4 KB loop stack.
1300FL_NO_INLINE inline void bindEsp8266HspiBenchRpcs(fl::Remote& remote) {
1301 remote.bind("bitbangLoopback", [](const fl::json& args) -> fl::json {
1302 return bitbangLoopback(rpcArgInt(args, 0, -1), rpcArgInt(args, 1, 5), rpcArgInt(args, 2, 16),
1303 rpcArgInt(args, 3, 96), rpcArgInt(args, 4, 0));
1304 });
1305 remote.bind("bitbangStream", [](const fl::json& args) -> fl::json {
1306 return bitbangStream(rpcArgInt(args, 0, 512), rpcArgInt(args, 1, 20),
1307 rpcArgInt(args, 2, 0), rpcArgInt(args, 3, 6),
1308 rpcArgInt(args, 4, 0), rpcArgInt(args, 5, 16));
1309 });
1310 remote.bind("apa102ShowBitbang", [](const fl::json& args) -> fl::json {
1311 return apa102ShowBitbang(rpcArgInt(args, 0, 0), rpcArgInt(args, 1, 1));
1312 });
1313}
1314
1315// I2S TX -> RX loopback (#4943 engine + #4945 capture): encode a known pattern
1316// with the I2S codec, stream it out of the I2S peripheral, capture it back
1317// through the I2S RX path, decode, and compare -- all in software on-device.
1318FL_NO_INLINE inline void bindEsp8266I2sRpcs(fl::Remote& remote) {
1319 remote.bind("i2sLoopback", [](int nBytes) -> fl::json {
1320 fl::json r = fl::json::object();
1321 if (nBytes < 1 || nBytes > 300) {
1322 r.set("error", "nBytes must be in [1, 300]");
1323 return r;
1324 }
1325 const int n = nBytes;
1326 static fl::u8 tx[300];
1327 for (int i = 0; i < n; ++i) {
1328 tx[i] = static_cast<fl::u8>(i * 53 + 0x1B);
1329 }
1330 // Encode as the I2S engine does: two 16-bit samples per LED byte.
1331 static fl::u16 samples[600];
1332 for (int i = 0; i < n; ++i) {
1333 fl::esp8266::encodeByte(tx[i], &samples[i * 2]);
1334 }
1335 const int nSamples = n * 2;
1336 // TX + RX on the one I2S peripheral. Only ONE side may drive the clocks
1337 // (driving both from the same peripheral conflicts and yields silence).
1338 (void)i2s_rxtxdrive_begin(true, true, true, false);
1339 i2s_set_rate(fl::esp8266::kI2sSlotHz);
1340 i2s_set_bits(16);
1341 for (int i = 0; i < nSamples; ++i) {
1342 (void)i2s_write_sample_nb(samples[i]);
1343 }
1344 static fl::u16 got[600];
1345 int cap = 0;
1346 const fl::u32 deadline = fl::millis() + 20;
1347 while (cap < nSamples && fl::millis() < deadline) {
1348 if (i2s_rx_available() > 0) {
1349 fl::i16 l = 0, rr = 0;
1350 if (i2s_read_sample(&l, &rr, false)) {
1351 // The core packs (right<<16)|left; the engine's 16-bit sample
1352 // may land in either half depending on the loopback wiring.
1353 fl::u16 s = static_cast<fl::u16>(l);
1354 if (s == 0) {
1355 s = static_cast<fl::u16>(rr);
1356 }
1357 got[cap++] = s;
1358 }
1359 }
1360 }
1361 int firstBad = -1;
1362 for (int i = 0; i < n; ++i) {
1363 if (i * 2 + 1 >= cap) { firstBad = i; break; }
1364 if (fl::esp8266::decodeByte(got[i * 2], got[i * 2 + 1]) != tx[i]) {
1365 firstBad = i;
1366 break;
1367 }
1368 }
1369 r.set("success", firstBad < 0);
1370 r.set("sent", static_cast<fl::i64>(n));
1371 r.set("captured_samples", static_cast<fl::i64>(cap));
1372 r.set("first_bad", static_cast<fl::i64>(firstBad));
1373 r.set("s0", static_cast<fl::i64>(samples[0]));
1374 r.set("g0", static_cast<fl::i64>(got[0]));
1375 r.set("g1", static_cast<fl::i64>(got[1]));
1376 r.set("dec0", static_cast<fl::i64>(fl::esp8266::decodeByte(got[0], got[1])));
1377 return r;
1378 });
1379}
1380
1381// HSPI (SPI1) master loopback (#4942): drive bytes out of MOSI (GPIO13) and
1382// read them back from MISO (GPIO12), which the ESP8266 HSPI does through the
1383// SAME register -- after SPI1CMD/SPIBUSY clears, `SPI1W0 & 0xFF` holds the byte
1384// clocked in on MISO. Jumper D7 (GPIO13) -> D6 (GPIO12) and every byte comes
1385// back. This captures the real hardware SPI output byte-exactly.
1386FL_NO_INLINE inline void bindEsp8266SpiRpcs(fl::Remote& remote) {
1387 remote.bind("spiLoopback", [](int nBytes) -> fl::json {
1388 fl::json r = fl::json::object();
1389 if (nBytes < 1 || nBytes > 64) {
1390 r.set("error", "nBytes must be in [1, 64]");
1391 return r;
1392 }
1393 const int n = nBytes;
1394 // Pads: SPECIAL routes each pad to the SPI1 peripheral function. The
1395 // core's SPI.begin() does exactly this for MISO(12)/MOSI(13)/SCK(14);
1396 // omitting MISO leaves it as a plain GPIO, so the duplex receive reads 0
1397 // even when D7->D6 is wired.
1398 pinMode(12, SPECIAL); // MISO -> SPI1 (data in)
1399 pinMode(13, SPECIAL); // MOSI -> SPI1 (data out)
1400 pinMode(14, SPECIAL); // SCK -> SPI1
1401 while (SPI1CMD & SPIBUSY) {
1402 }
1403 SPI1C = 0;
1404 SPI1C1 = 0;
1405 GPMUX &= ~(1UL << 9);
1406 SPI1CLK = fl::esp8266::hspiClockFor(1000000).reg_value; // 1 MHz
1407 SPI1U = SPIUMOSI | SPIUDUPLEX | SPIUSSE;
1408 SPI1U1 = (7UL << SPILMOSI) | (7UL << SPILMISO);
1409
1410 int firstBad = -1;
1411 fl::u8 lastGot = 0;
1412 for (int i = 0; i < n; ++i) {
1413 const fl::u8 b = static_cast<fl::u8>(i * 37 + 0x1B);
1414 while (SPI1CMD & SPIBUSY) {
1415 }
1416 SPI1W0 = b;
1417 SPI1CMD |= SPIBUSY;
1418 while (SPI1CMD & SPIBUSY) {
1419 }
1420 lastGot = static_cast<fl::u8>(SPI1W0 & 0xFF);
1421 if (lastGot != b && firstBad < 0) {
1422 firstBad = i;
1423 }
1424 }
1425 r.set("success", firstBad < 0);
1426 r.set("sent", static_cast<fl::i64>(n));
1427 r.set("first_bad", static_cast<fl::i64>(firstBad));
1428 r.set("last_got", static_cast<fl::i64>(lastGot));
1429 return r;
1430 });
1431}
1432
1433inline void bindEsp8266Benches(fl::Remote& remote) {
1434 bindEsp8266WatchdogRpcs(remote);
1435 bindEsp8266UartRpcs(remote);
1436 bindEsp8266DriverRpcs(remote);
1437 bindEsp8266HspiRpcs(remote);
1438 bindEsp8266HspiBenchRpcs(remote);
1439 bindEsp8266I2sRpcs(remote);
1440 bindEsp8266SpiRpcs(remote);
1441}
1442
1443} // namespace esp8266
1444} // namespace autoresearch
1445
1446#endif // FL_IS_ESP8266
CRGB leds[1]
FL_DISABLE_WARNING_PUSH FL_DISABLE_WARNING_GLOBAL_CONSTRUCTORS CFastLED FastLED
Global LED strip management instance.
@ APA102
APA102 LED chipset.
Definition FastLED.h:301
CLEDController * controller
fl::unique_ptr< fl::Remote > remote
Definition RpcClient.ino:43
static constexpr size_t calculateBytes(size_t num_leds) FL_NO_EXCEPT
Calculate total byte count for APA102 protocol Used for quad-SPI buffer pre-allocation.
Definition apa102.h:271
::CLEDController & addLeds(::CLEDController *pLed, CRGB *data, int nLedsOrOffset, int nLedsIfOffset=0) FL_NO_EXCEPT
Add a CLEDController instance to the world.
CLEDController & setLeds(CRGB *data, int nLeds) FL_NO_EXCEPT
Set the default array of LEDs to be used by this controller.
VIRTUAL_IF_NOT_AVR void showLeds(fl::u8 brightness) FL_NO_EXCEPT
virtual void init() FL_NO_EXCEPT=0
Initialize the LED controller.
T & value() FL_NO_EXCEPT
Definition optional.h:112
bool has_value() const FL_NO_EXCEPT
Definition optional.h:42
static T & instance() FL_NO_EXCEPT
Definition singleton.h:81
static Watchdog & instance() FL_NO_EXCEPT
void set(const fl::string &key, const json &value) FL_NO_EXCEPT
Definition json.h:873
void push_back(const json &value) FL_NO_EXCEPT
Definition json.h:925
static json object() FL_NO_EXCEPT
Definition json.h:864
static json array() FL_NO_EXCEPT
Definition json.h:860
fl::CLEDController CLEDController
#define DISABLE_DITHER
Disable dithering.
Definition dither_mode.h:14
constexpr EOrder BGR
Definition eorder.h:22
constexpr EOrder GRB
Definition eorder.h:19
static uint32_t t
Definition Luminova.h:55
#define DATA_RATE_KHZ
Definition fastspi.h:96
#define DATA_RATE_MHZ
Definition fastspi.h:95
fl::hsv8 CHSV
Definition chsv.h:11
fl::CRGB CRGB
Definition crgb.h:25
FastLED's Elegant JSON Library: fl::json
unsigned char u8
Definition stdint.h:132
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
u32 _retry_cnt
Frame retry counter for ESP8266 clockless drivers (FASTLED_DEBUG_COUNT_FRAME_RETRIES).
fl::u32 millis() FL_NO_EXCEPT
Universal millisecond timer - returns milliseconds since system startup.
Optional< T > optional
Definition optional.h:16
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
fl::i64 i64
Definition s16x16x4.h:222
u32 _frame_cnt
Frame counter for ESP8266 clockless drivers (FASTLED_DEBUG_COUNT_FRAME_RETRIES).
fl::string_view resetCauseName(ResetCause c) FL_NO_EXCEPT
Return a static-lifetime name for c — zero-cost, no allocation.
Definition watchdog.h:61
void digitalWrite(int pin, PinValue val) FL_NO_EXCEPT
Write digital value to pin.
Definition pin.cpp.hpp:51
PinValue digitalRead(int pin) FL_NO_EXCEPT
Read digital value from pin.
Definition pin.cpp.hpp:55
@ Output
Digital output (push-pull)
Definition pin.h:44
@ Input
Digital input (high impedance)
Definition pin.h:43
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.
corkscrew_args args
Definition old.h:149
#define FASTLED_FORCE_INLINE
#define FL_NO_INLINE
#define FL_IRAM
static ColorAdjustment noAdjustment() FL_NO_EXCEPT
the per-channel scale values premixed with brightness.
Unified cross-platform Watchdog Timer API for FastLED.