FastLED 3.10.10
Loading...
Searching...
No Matches
AutoResearchRemotePinMethods.cpp
Go to the documentation of this file.
1// Pin configuration RPC bindings: get/set TX/RX/pair, GPIO connectivity
2// probe, jumper-finder, debug-log toggle, help. GPIO is the implementation;
3// the RPC API is "pins" (the user-facing concept).
4// Extracted from AutoResearchRemote.cpp as part of #3132 / meta #3127.
5
7#if FL_PLATFORM_HAS_LARGE_MEMORY
8
9// Legacy debug macros (no-ops, kept for debugTest RPC function)
10#define DEBUG_PRINT(x) do {} while(0)
11#define DEBUG_PRINTLN(x) do {} while(0)
12
13#include "AutoResearchRemote.h"
14#include "AutoResearchBle.h"
15#include "AutoResearchNet.h"
16#include "AutoResearchOta.h"
18#include "fl/system/heap.h"
19#include "Common.h"
20#include "AutoResearchTest.h"
21#include "AutoResearchHelpers.h"
23#include "fl/stl/sstream.h"
24#include "fl/stl/unique_ptr.h"
25#include "fl/stl/optional.h"
26#include "fl/stl/json.h"
27#include "fl/task/task.h"
28#include "fl/task/executor.h"
30#include "fl/stl/atomic.h"
31#include "fl/task/promise.h"
32#include "fl/math/simd.h"
33#include "AutoResearchSimd.h"
39#include "fl/chipsets/spi.h"
40#include "fl/channels/config.h"
41#include <Arduino.h>
42
43#include "fl/net/ble.h"
44
45#include "fl/codec/h264.h"
46#include "fl/codec/mp4_parser.h"
47#include "fl/stl/cstdio.h"
49#include "fl/fx/frame.h"
50
51namespace {
52
53struct HelpEntry {
54 const char* name;
55 const char* phase;
56 const char* args;
57 const char* returns;
58 const char* description;
59};
60
61void streamHelpEntry(fl::JsonStreamWriter& writer, const HelpEntry& entry) {
62 writer.beginObject();
63 writer.member("name", entry.name);
64 writer.member("phase", entry.phase);
65 writer.member("args", entry.args);
66 writer.member("returns", entry.returns);
67 writer.member("description", entry.description);
68 writer.endObject();
69}
70
71static const HelpEntry kHelpEntries[] = {
72#if defined(FL_AUTORESEARCH_MEMORY_BENCH)
73#if FL_AUTORESEARCH_MEMORY_BENCH == 3
74 {"memoryBench", "Memory", "[{chipset:apa102|sk9822, pixels:1000, frames:20}]", "{success, heapBefore, heapAfterRegister, heapSteady, frames, wireMismatches, frameUs}", "Native SPI2 full-frame loopback to SPI3; run --spi-streaming. Reset before each chipset."},
75#else
76 {"memoryBench", "Memory", "[{pin:4}] (optional)", "{success, heapBefore, heapAfterRegister, heapSteady, driverCount, actualDriverName}", "Cold typed/runtime binding: 32 red WS2812 pixels on the selected pin for 20 frames; run --driver-binding typed or runtime."},
77#endif
78#endif
79 {"rpc.discover", "JSON-RPC", "[]", "{schema:[[name, ...], ...]}", "Discover the registered JSON-RPC method schema"},
80 {"start", "Phase 1: Basic Control", "[]", "void", "Trigger test matrix execution"},
81 {"status", "Phase 1: Basic Control", "[]", "{ready, platform, rpcReady, ledRxAvailable, pinTx, pinRx}", "Query RPC, platform, and LED RX readiness"},
82 {"drivers", "Phase 1: Basic Control", "[]", "[{name, priority, enabled}, ...]", "List available drivers"},
83 {"getConfig", "Phase 2: Configuration", "[]", "{drivers, laneRange, stripSizes, totalTestCases}", "Query current test matrix configuration"},
84 {"setDrivers", "Phase 2: Configuration", "[driver1, driver2, ...]", "{success, driversSet, testCases}", "Configure enabled drivers"},
85 {"setLaneRange", "Phase 2: Configuration", "[minLanes, maxLanes]", "{success, minLanes, maxLanes, testCases}", "Configure lane range (1-16)"},
86 {"setStripSizes", "Phase 2: Configuration", "[size] or [shortSize, longSize]", "{success, stripSizesSet, testCases}", "Configure strip sizes"},
87 {"runTestCase", "Phase 3: Selective Execution", "[testCaseIndex]", "{success, testCaseIndex, result}", "Run single test case by index"},
88 {"runDriver", "Phase 3: Selective Execution", "[driverName]", "{success, driver, testsRun, results}", "Run all tests for specific driver"},
89 {"runSingleTest", "Phase 3: Selective Execution", "{driver, laneSizes, lanePins?:GPIO[], workerCore?:string(auto|0|1|any|calling), useLegacyApi?:bool}", "{success, passed, totalTests, passedTests, lanePins, workerCore?, workerObservedCore?, workerPriority?, workerSubmittedChunks?, workerCompletedChunks?, workerTotalChunks?, workerMaxEncodeUs?, workerMaxSubmitUs?, workerStreamError?, competingTaskPasses?, competingTaskMaxPassUs?, heapBeforeInternal, heapBeforePsram, heapAfterInternal, heapAfterPsram, driverError?}", "Run lane-0 byte loopback; optional LCD worker affinity validation under Core-0 load (#5001)"},
90 {"runAll", "Phase 3: Selective Execution", "[]", "{success, totalCases, passedCases, skippedCases, results}", "Run full test matrix with JSON results"},
91 {"getResults", "Phase 3: Selective Execution", "[]", "[{driver, lanes, stripSize, ...}, ...]", "Return all test results"},
92 {"getResult", "Phase 3: Selective Execution", "[testCaseIndex]", "{driver, lanes, stripSize, ...}", "Return specific test case result"},
93 {"perfProbeBitBangCost", "Phase 2: Performance", "[{iterations, ns, pin}]", "{success, nop_us_per_iter, delay_us_per_iter, delay_hz_us_per_iter, write_byte_us_per_iter, clock_query_us, predicted_bit_overhead_us}", "Attribute the BIT_BANG per-bit overhead across delay vs pin-write calls (FastLED#4203)"},
94#if FL_COLOR_PIPELINE_SHARED
95 {"mixedPowerShowPerf", "Phase 2: Performance", "[{pixels, frames, budget_mw}] (optional; max 128 pixels/channel)", "{success, on_median_us, off_median_us, on_plan_modeled_mw, off_plan_modeled_mw, on_plan_flux_q16, off_plan_flux_q16, on_fnv1a, off_fnv1a}", "Benchmark mixed RGB/RGBW/RGBWW power planning plus encode through FastLED.show(), excluding physical wire time; resets power settings to unlimited (#4499)"},
96#endif
97 {"reset", "Phase 4: Utility", "[]", "{success, message, testCasesCleared}", "Reset test state without device reboot"},
98 {"halt", "Phase 4: Utility", "[]", "{success, message}", "Trigger sketch halt"},
99 {"ping", "Phase 4: Utility", "[]", "{success, message, timestamp, uptimeMs, lastResetCause, lastResetWasWatchdog, frameCounter}", "Health check with timestamp and reset evidence"},
100 {"debugTest", "Phase 4: Utility", "object", "{success, received}", "Echo an exact nested JSON payload"},
101 {"testNoSerial", "Phase 4: Utility", "[]", "{success, message, serial_safe}", "Verify RPC execution without device-side serial logging"},
102 {"testRpConcurrency", "Phase 4: Utility", "[]", "{success, supported, backend, core1Ready, core1Done, recursiveMutexReady, generation, expected, actual}", "Exercise mutex and semaphore synchronization across both RP physical cores"},
103 {"testRpPioContention", "Phase 4: Utility", "[]", "{success, numPios, pin, baselineFreeSms, control:{proxyValid, freeDuring, claimedOne, freeAfter, released}, contention:{starvedSms, freeAfterStarve, proxyValid, claimsIntact, noTheft, survivedShow, freeAfter}, noLeak}", "FastLED#1471 repro: claim every PIO state machine the way Adafruit TinyUSB does, then build a clockless controller and verify FastLED declines cleanly instead of stealing a state machine from the other library."},
104 {"testRpPioParallelResources", "Phase 4: Utility", "[{pinA, pinB, numLeds, iterations}] (all optional)", "{success, pinA, pinB, baseline, busiestInFlight, released, framesSampled, samplesTaken, pio0HeldOne, pio1HeldOne, bothHeldAtOnce, noOverClaim, observedInFlight, collisionFree, showsCompleted, noResidueBetweenFrames, noLeak}", "FastLED#3899: drive PIO0 and PIO1 simultaneously and assert at the SDK-claim level that neither engine over-claims mid-flight, both give everything back between frames, and nothing is left claimed on teardown. Whether the two are ever in flight at the same instant is reported as a diagnostic, not asserted."},
105 {"getPins", "Phase 5: Pin Configuration", "[]", "{txPin, rxPin, defaults: {txPin, rxPin}, platform}", "Query current and default pin configuration"},
106 {"setTxPin", "Phase 5: Pin Configuration", "[pin]", "{success, txPin, previousTxPin, testCases}", "Set TX pin (regenerates test cases)"},
107 {"setRxPin", "Phase 5: Pin Configuration", "[pin]", "{success, rxPin, previousRxPin, rxChannelRecreated}", "Set RX pin (recreates RX channel)"},
108 {"setPins", "Phase 5: Pin Configuration", "[{txPin, rxPin}] or [txPin, rxPin]", "{success, txPin, rxPin, rxChannelRecreated, testCases}", "Set both TX and RX pins atomically"},
109 {"findConnectedPins", "Phase 5: Pin Configuration", "[{startPin, endPin, autoApply}] (all optional)", "{success, found, txPin, rxPin, autoApplied, testedPairs}", "Probe adjacent pin pairs to find jumper wire connection"},
110 {"help", "Phase 4: Utility", "[]", "[{name, phase, args, returns, description}, ...]", "List all RPC functions with descriptions"},
111 {"testSimd", "Phase 4: Utility", "[]", "{success, passed, totalTests, passedTests, failedTests, failures:[string]}", "Run comprehensive SIMD test suite (85 tests)"},
112 {"testSimdBenchmark", "Phase 4: Utility", "[{iterations}] (optional, default 10000)", "{success, iterations, float_us, s16x16_us, simd_us}", "Benchmark multiply speed: float vs s16x16 vs s16x16x4 SIMD"},
113 {"animartrixPerlinBench", "Phase 4: Utility", "[{iterations}] (optional, default 100, max 10000)", "{success, iterations, pnoise_calls_per_iter, pnoise_float_us, pnoise_i16_us, speedup_x1000}", "Animartrix-representative Perlin noise bench: scalar float pnoise vs s16x16 fixed-point pnoise2d (16x16 grid per iter, mirrors a real frame). Answers: how much does fixed-point beat float for Animartrix's hot path on this hardware?"},
114 {"wave8ExpandBenchmark", "Phase 4: Utility", "[{iterations}] (optional, default 30000, max 200000)", "{success, iterations, expand_nibble_us, expand_byte_us, expand_batched_us, transpose16_nibble_us, transpose16_byte_us, sink}", "Bench PARLIO Wave8 expansion (#2526): nibble vs byte vs batched LUT, plus full per-byte-position cost (expansion + 16-lane transpose)"},
115 {"ieee754CodecTest", "Phase 4: Utility", "[]", "{success, tests_run, tests_failed, first_failure, expected_bits, actual_bits}", "On-device verification of the integer-only IEEE 754 decimal codec (#3039): parse, format, round-trip, overflow/underflow, and NaN rejection without strtof/libm."},
116 {"mp3CodecTest", "Phase 4: Utility", "[]", "{success, streams_run, streams_failed, first_failure, expected_fnv1a, actual_fnv1a, expected_samples, actual_samples, decode_micros, scratch_bytes, shared_decoder_matched, samples_decoded, frames_decoded, combined_fnv1a}", "Bit-exact on-device check of the fixed-point MP3 decoder against host-computed FNV-1a checksums, over a Layer I and a Layer III stream, decoded both with a fresh decoder each and with one decoder shared across layers (FastLED#4116 scratch union)."},
117 {"parlioEncodeBenchmark", "Phase 4: Utility", "[{iterations}] (optional, default 12000, max 200000)", "{success, iters, lanes, leds_per_lane, scratchPsramOk, outputPsramOk, perpos_ss_us, perpos_sp_us, perpos_ps_us, perpos_pp_us, frame_ss_us, frame_sp_us, frame_ps_us, frame_pp_us, sink}", "Bench full PARLIO encode hot loop (16-lane gather + BF1 pipe4 direct encode) with SRAM and optional PSRAM placements; answers PSRAM hypothesis + ISR-streaming feasibility"},
118 {"timingDriftTest", "Phase 4: Utility", "[{pin, numLeds, iterations}] (all optional; default pin=4, numLeds=35, iterations=10)", "{success, pin, num_leds, iterations, cpu_mhz, show_count, show_min_us, show_max_us, show_total_us, iter_ms:[...]}", "Issue #2994 repro for compounded per-sequence timing drift on master vs 3.10.3. Replays the reporter's WS2812B-ring + millisDelay-gated fade sketch and returns per-sequence wall time (theoretical 2495 ms; on 3.10.3 rock-steady, on master 2563-2752)."},
119 {"parlioStreamValidate", "Phase 4: Utility", "[{baseTxPin, txPins, numLanes, numLeds, iterations, timeoutMs}] (all optional; txPins overrides contiguous baseTxPin)", "{success, completed, baseTxPin, txPins, lanes, leds_per_lane, iterations, perIterUs:[...], steadyAvgUs, failedIter, underrunCount, txDoneCount, workerIsrCount, ringError, hardwareIdle}", "Functional test of the PARLIO ISR-chunked streaming engine (#2548). Drives N back-to-back FastLED.show() calls through the production engine (which uses BF1+pipe4 on 16-lane Wave8 since #2559) and verifies all complete within timeout. Catches hangs/stalls."},
120 {"flexioRxBenchmark", "Phase 4: Utility", "[{frequency_hz=1000, duration_ms=100, tx_pin=3, rx_pin=4}] (all optional)", "{success, frequency_hz, duration_ms, tx_pin, rx_pin, edges_captured, periods, period_mean_ns, period_sigma_ns, period_min_ns, period_max_ns}", "Square-wave validation for the FlexIO RX backend (Teensy 4.x only, FastLED#2764 Phase 2). Drives tx_pin via analogWriteFrequency at 50%% duty, captures via RxBackend::FLEXIO on rx_pin, reports per-period statistics."},
121 {"dualSpiHostLoopback", "Phase 4: Utility", "[{activeHost:2|3, dummyFirst:false|true}]", "{success, activeHost, dummyFirst, verifiedLeds, wireMismatches, rawEdges}", "On ESP32 boards with two SPI hosts, register one APA102 output on each host and verify eight LED frames from GPIO 1 to GPIO 2. Reset between calls."},
122 {"softSpiClockLoopback", "Phase 4: Utility", "[]", "{success, primed, rawEdges, highAvgNs, lowAvgNs, highMinNs, lowMinNs, periodNs, measuredKhz, requestedKhz}", "Build with FASTLED_FORCE_SOFTWARE_SPI and jumper GPIO 0 to GPIO 1. Drives SPIOutput at 250 kHz with its clock on GPIO 0 and measures the clock from RX edges (#5124). Reset between calls."},
123 {"staticInitTest", "Phase 4: Utility", "[]", "{success, constructorEntered, constructions, contenders, completed, overlapped, workersSuspended}", "ESP32: two FreeRTOS tasks contend on one slow function-local static. Sample a blocked contender during construction and require quiescent workers before teardown. Exactly one construction must run. No wiring required; reboot the board before repeating (#4994). The reset RPC does not clear this state."},
124 {"flexioObjectFledTest", "Phase 4: Utility", "[{test_case=0..4, tx_pin=3, rx_pin=4, capture_ms=50}] (all optional)", "{success, test_case, tx_pin, rx_pin, num_leds, expected_bytes, decoded_bytes, matched, mismatched, edges_captured}", "End-to-end ObjectFLED TX -> FlexIO RX loopback verification (Teensy 4.x only, FastLED#2764 Phase 3). Drives WS2812 patterns through Bus::FLEX_IO slot 0, captures via RxBackend::FLEXIO, decodes the bit stream, and reports byte-level match counts. Five fixed test patterns: 0=red, 1=RGB triple, 2=all zeros, 3=all ones, 4=100-LED alternating."},
125};
126
127static const fl::size kHelpEntryCount = sizeof(kHelpEntries) / sizeof(kHelpEntries[0]);
128
129} // namespace
130
131
133 // Register "setDebug" function - enable/disable runtime debug logging
134 remote.bind("setDebug", [this](const fl::json& args) -> fl::json {
135 fl::json response = fl::json::object();
136
137 // Validate args: expects [enabled: bool]
138 if (!args.is_array() || args.size() != 1) {
139 response.set("success", false);
140 response.set("error", "InvalidArgs");
141 response.set("message", "Expected [enabled: bool]");
142 return response;
143 }
144
145 if (!args[0].is_bool()) {
146 response.set("success", false);
147 response.set("error", "InvalidType");
148 response.set("message", "Argument must be boolean");
149 return response;
150 }
151
152 bool enabled = args[0].as_bool().value();
153 mState->debug_enabled = enabled;
154 fl::setLogLevel(static_cast<fl::u8>(
157
158 response.set("success", true);
159 response.set("debug_enabled", enabled);
160 response.set("message", enabled ? "Debug logging enabled" : "Debug logging disabled");
161
162 return response;
163 });
164
165 // Register "testGpioConnection" function - test if TX and RX pins are electrically connected
166 // This is a pre-test to diagnose hardware connection issues before running validation
167 remote.bind("testGpioConnection", [](const fl::json& args) -> fl::json {
168 fl::json response = fl::json::object();
169
170 // Validate args: expects [txPin, rxPin]
171 if (!args.is_array() || args.size() != 2) {
172 response.set("error", "InvalidArgs");
173 response.set("message", "Expected [txPin, rxPin]");
174 return response;
175 }
176
177 if (!args[0].is_int() || !args[1].is_int()) {
178 response.set("error", "InvalidPinType");
179 response.set("message", "Pin numbers must be integers");
180 return response;
181 }
182
183 int tx_pin = static_cast<int>(args[0].as_int().value());
184 int rx_pin = static_cast<int>(args[1].as_int().value());
185
186 // Test 1: TX drives LOW, RX has pullup → RX should read LOW if connected
187 pinMode(tx_pin, OUTPUT);
188 // Same-pin RMT loopback needs the output to remain enabled. Turning
189 // that same pin into an input would only measure its pullup.
190 if (rx_pin != tx_pin) {
191 pinMode(rx_pin, INPUT_PULLUP);
192 }
193 digitalWrite(tx_pin, LOW);
194 delay(5); // Allow signal to settle
195 int rx_when_tx_low = digitalRead(rx_pin);
196
197 // Test 2: TX drives HIGH → RX should read HIGH if connected
198 digitalWrite(tx_pin, HIGH);
199 delay(5); // Allow signal to settle
200 int rx_when_tx_high = digitalRead(rx_pin);
201
202 // Restore pins to safe state
203 pinMode(tx_pin, INPUT);
204 pinMode(rx_pin, INPUT);
205
206 // Analyze results
207 bool connected = (rx_when_tx_low == LOW) && (rx_when_tx_high == HIGH);
208
209 response.set("txPin", static_cast<int64_t>(tx_pin));
210 response.set("rxPin", static_cast<int64_t>(rx_pin));
211 response.set("rxWhenTxLow", rx_when_tx_low == LOW ? "LOW" : "HIGH");
212 response.set("rxWhenTxHigh", rx_when_tx_high == HIGH ? "HIGH" : "LOW");
213 response.set("connected", connected);
214
215 if (connected) {
216 response.set("success", true);
217 response.set("message", "GPIO pins are connected");
218 } else {
219 response.set("success", false);
220 if (rx_when_tx_low == HIGH && rx_when_tx_high == HIGH) {
221 response.set("message", "RX pin stuck HIGH - no connection detected (check jumper wire)");
222 } else if (rx_when_tx_low == LOW && rx_when_tx_high == LOW) {
223 response.set("message", "RX pin stuck LOW - possible short to ground");
224 } else {
225 response.set("message", "Unexpected GPIO behavior - check wiring");
226 }
227 }
228
229 return response;
230 });
231
232 // ========================================================================
233 // Pin Configuration RPC Functions (Dynamic TX/RX Pin Support)
234 // ========================================================================
235
236 // Register "getPins" function - query current and default pin configuration
237 remote.bind("getPins", [this](const fl::json& args) -> fl::json {
238 fl::json response = fl::json::object();
239 response.set("success", true);
240 response.set("txPin", static_cast<int64_t>(mState->pin_tx));
241 response.set("rxPin", static_cast<int64_t>(mState->pin_rx));
242
243 fl::json defaults = fl::json::object();
244 defaults.set("txPin", static_cast<int64_t>(mState->default_pin_tx));
245 defaults.set("rxPin", static_cast<int64_t>(mState->default_pin_rx));
246 response.set("defaults", defaults);
247
248 // Use the shared chipName() so this agrees with `status`. The
249 // hand-rolled chain here only knew four ESP32 variants and reported
250 // "unknown" for every other target, so an RP2350W answered
251 // getPins -> platform "unknown"
252 // status -> platform "Raspberry Pi Pico 2 W (RP2350)"
253 // on the same firmware (FastLED#3899, whose closeout requires exact
254 // recorded identities). chipName() covers stub, the ESP32 family,
255 // Teensy 4.x and both RP2350 variants.
256 response.set("platform", autoresearch::chipName());
257
258 return response;
259 });
260
261 // Register "setTxPin" function - set TX pin (regenerates test cases)
262 remote.bind("setTxPin", [this](const fl::json& args) -> fl::json {
263 fl::json response = fl::json::object();
264
265 if (!args.is_array() || args.size() != 1 || !args[0].is_int()) {
266 response.set("error", "InvalidArgs");
267 response.set("message", "Expected [pin: int]");
268 return response;
269 }
270
271 int new_pin = static_cast<int>(args[0].as_int().value());
272
273 // Validate pin range (ESP32 GPIO range)
274 if (new_pin < 0 || new_pin > 48) {
275 response.set("error", "InvalidPin");
276 response.set("message", "Pin must be 0-48");
277 return response;
278 }
279
280 int old_pin = mState->pin_tx;
281 if (new_pin != old_pin) {
282 mState->invalidateLedRxValidation();
283 }
284 mState->pin_tx = new_pin;
285
286 response.set("success", true);
287 response.set("txPin", static_cast<int64_t>(new_pin));
288 response.set("previousTxPin", static_cast<int64_t>(old_pin));
289 return response;
290 });
291
292 // Register "setRxPin" function - set RX pin (recreates RX channel)
293 remote.bind("setRxPin", [this](const fl::json& args) -> fl::json {
294 fl::json response = fl::json::object();
295
296 if (!args.is_array() || args.size() != 1 || !args[0].is_int()) {
297 response.set("error", "InvalidArgs");
298 response.set("message", "Expected [pin: int]");
299 return response;
300 }
301
302 int new_pin = static_cast<int>(args[0].as_int().value());
303
304 // Validate pin range (ESP32 GPIO range)
305 if (new_pin < 0 || new_pin > 48) {
306 response.set("error", "InvalidPin");
307 response.set("message", "Pin must be 0-48");
308 return response;
309 }
310
311 int old_pin = mState->pin_rx;
312 bool pin_changed = (new_pin != old_pin);
313 bool rx_recreated = false;
314
315 if (pin_changed) {
316 fl::shared_ptr<fl::RxChannel> replacement_rx;
317 if (mState->rx_factory) {
318 replacement_rx = mState->rx_factory(new_pin);
319 }
320 if (!replacement_rx) {
321 response.set("error", "RxChannelCreationFailed");
322 response.set("message", "Failed to create RX channel on new pin");
323 response.set("pinRx", static_cast<int64_t>(new_pin));
324 return response;
325 }
326
327 mState->invalidateLedRxValidation();
328 mState->pin_rx = new_pin;
329 mState->rx_channel = replacement_rx;
330 rx_recreated = true;
331 }
332
333 response.set("success", true);
334 response.set("rxPin", static_cast<int64_t>(new_pin));
335 response.set("previousRxPin", static_cast<int64_t>(old_pin));
336 response.set("rxChannelRecreated", rx_recreated);
337 return response;
338 });
339
340 // Register "setPins" function - set both TX and RX pins atomically
341 remote.bind("setPins", [this](const fl::json& args) -> fl::json {
342 fl::json response = fl::json::object();
343
344 // Accept either {txPin, rxPin} object or [txPin, rxPin] array
345 int new_tx_pin = -1;
346 int new_rx_pin = -1;
347
348 if (args.is_array() && args.size() == 1 && args[0].is_object()) {
349 // Object form: [{txPin: int, rxPin: int}]
350 fl::json config = args[0];
351 if (config.contains("txPin") && config["txPin"].is_int()) {
352 new_tx_pin = static_cast<int>(config["txPin"].as_int().value());
353 }
354 if (config.contains("rxPin") && config["rxPin"].is_int()) {
355 new_rx_pin = static_cast<int>(config["rxPin"].as_int().value());
356 }
357 } else if (args.is_array() && args.size() == 2) {
358 // Array form: [txPin, rxPin]
359 if (args[0].is_int()) {
360 new_tx_pin = static_cast<int>(args[0].as_int().value());
361 }
362 if (args[1].is_int()) {
363 new_rx_pin = static_cast<int>(args[1].as_int().value());
364 }
365 } else {
366 response.set("error", "InvalidArgs");
367 response.set("message", "Expected [{txPin, rxPin}] or [txPin, rxPin]");
368 return response;
369 }
370
371 // Validate pin ranges
372 if (new_tx_pin < 0 || new_tx_pin > 48) {
373 response.set("error", "InvalidTxPin");
374 response.set("message", "TX pin must be 0-48");
375 return response;
376 }
377 if (new_rx_pin < 0 || new_rx_pin > 48) {
378 response.set("error", "InvalidRxPin");
379 response.set("message", "RX pin must be 0-48");
380 return response;
381 }
382
383 int old_tx_pin = mState->pin_tx;
384 int old_rx_pin = mState->pin_rx;
385 bool tx_pin_changed = (new_tx_pin != old_tx_pin);
386 bool rx_pin_changed = (new_rx_pin != old_rx_pin);
387 bool rx_recreated = false;
388
389 fl::shared_ptr<fl::RxChannel> replacement_rx;
390 if (rx_pin_changed) {
391 if (mState->rx_factory) {
392 replacement_rx = mState->rx_factory(new_rx_pin);
393 }
394 if (!replacement_rx) {
395 response.set("error", "RxChannelCreationFailed");
396 response.set("message", "Failed to create RX channel - previous pins preserved");
397 response.set("pinRx", static_cast<int64_t>(new_rx_pin));
398 return response;
399 }
400 }
401
402 // Commit pins, validation, and channel as one state transition only
403 // after any replacement channel has been created successfully.
404 if (tx_pin_changed || rx_pin_changed) {
405 mState->invalidateLedRxValidation();
406 }
407 mState->pin_tx = new_tx_pin;
408 mState->pin_rx = new_rx_pin;
409 if (rx_pin_changed) {
410 mState->rx_channel = replacement_rx;
411 rx_recreated = true;
412 }
413
414 response.set("success", true);
415 response.set("txPin", static_cast<int64_t>(new_tx_pin));
416 response.set("rxPin", static_cast<int64_t>(new_rx_pin));
417 response.set("previousTxPin", static_cast<int64_t>(old_tx_pin));
418 response.set("previousRxPin", static_cast<int64_t>(old_rx_pin));
419 response.set("rxChannelRecreated", rx_recreated);
420 return response;
421 });
422
423 // Register "findConnectedPins" function - probe adjacent pin pairs to find a jumper wire connection
424 // This allows automatic discovery of TX/RX pin pair without requiring user to specify them
425 remote.bind("findConnectedPins", [this](const fl::json& args) -> fl::json {
427 });
428
429 // Register "help" function - list all RPC functions with descriptions
430 remote.bindStreaming("help", [](fl::JsonStreamWriter& writer, const fl::json& args, const fl::json& requestId) {
431 (void)args;
432 (void)requestId;
433
434 writer.beginObject();
435 writer.member("success", true);
436 writer.member("totalFunctions", static_cast<fl::i64>(kHelpEntryCount));
437 writer.key("functions");
438 writer.beginArray();
439 for (fl::size i = 0; i < kHelpEntryCount; ++i) {
440 streamHelpEntry(writer, kHelpEntries[i]);
441 }
442 writer.endArray();
443 writer.endObject();
444 });
445}
446
447#endif // FL_PLATFORM_HAS_LARGE_MEMORY
fl::UIDescription description("Demo of the Animatrix effects. @author of fx is StefanPetrick")
Full PARLIO encode bench for ESP32-P4 (post-byte-LUT, #2526 landed).
PARLIO ISR-streaming functional validation (#2548 deep-dive follow-up).
Issue #2994 repro: compounded per-sequence timing drift vs 3.10.3.
Wave8 expansion micro-benchmark for #2526.
int requestId
fl::unique_ptr< fl::Remote > remote
Definition RpcClient.ino:43
fl::net::ble — BLE GATT transport layer for JSON-RPC
SPI encoder configuration for clocked LED chipsets.
fl::shared_ptr< AutoResearchState > mState
fl::json findConnectedPinsImpl(const fl::json &args)
void bindPinMethods(fl::Remote &remote)
void beginObject() FL_NO_EXCEPT
void key(const char *k) FL_NO_EXCEPT
void member(const char *k, const char *s) FL_NO_EXCEPT
JSON-RPC server with scheduling support.
Definition remote.h:42
fl::optional< i64 > as_int() const FL_NO_EXCEPT
Definition json.h:398
void set(const fl::string &key, const json &value) FL_NO_EXCEPT
Definition json.h:873
bool contains(size_t idx) const FL_NO_EXCEPT
Definition json.h:790
static json object() FL_NO_EXCEPT
Definition json.h:864
Task executor — runs registered task runners and manages the run loop.
Platform-abstracted heap memory query functions.
FastLED's Elegant JSON Library: fl::json
constexpr const char * chipName()
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
void setLogLevel(u8 level) FL_NO_EXCEPT
Set the global log level.
@ FL_LOG_LEVEL_DEBUG
All logging including debug (default)
Definition cstdio.h:42
@ FL_LOG_LEVEL_NONE
No logging (completely silent)
Definition cstdio.h:38
fl::i64 i64
Definition s16x16x4.h:222
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
void pinMode(int pin, PinMode mode) FL_NO_EXCEPT
Set pin mode (input, output, pull-up, pull-down)
Definition pin.cpp.hpp:398
corkscrew_args args
Definition old.h:149
Promise-based fluent API for FastLED - standalone async primitives.
Umbrella header for SIMD subsystem.