FastLED 3.10.10
Loading...
Searching...
No Matches
spi_channel_adapter.cpp.hpp
Go to the documentation of this file.
1
3
5#include "fl/log/log.h"
6#include "fl/stl/cstring.h" // For memcpy
7#include "fl/channels/config.h" // For SpiChipsetConfig
8// IWYU pragma: begin_keep
9#include "platforms/shared/spi_hw_1.h" // For SpiHw1::Config // ok platform headers
10#include "fl/stl/noexcept.h"
11// IWYU pragma: end_keep
12
13namespace fl {
14
15// Static factory method (multi-controller version)
18 fl::vector<int> priorities,
20 const char* adapterName
22 // Validation
23 if (hwControllers.empty()) {
24 FL_WARN("SpiChannelEngineAdapter::create: No controllers provided");
25 return nullptr;
26 }
27
28 if (hwControllers.size() != priorities.size() || hwControllers.size() != names.size()) {
29 FL_WARN("SpiChannelEngineAdapter::create: Size mismatch in arguments");
30 return nullptr;
31 }
32
33 if (!adapterName || adapterName[0] == '\0') {
34 FL_WARN("SpiChannelEngineAdapter::create: Empty adapter name");
35 return nullptr;
36 }
37
38 // Create adapter
39 auto adapter = fl::make_shared<SpiChannelEngineAdapter>(adapterName);
40
41 // Register all controllers
42 for (size_t i = 0; i < hwControllers.size(); i++) {
43 if (!hwControllers[i]) {
44 FL_WARN("SpiChannelEngineAdapter: Null controller at index " << i);
45 continue;
46 }
47
48 adapter->mControllers.emplace_back(hwControllers[i], priorities[i], names[i]);
49
50 FL_DBG("SpiChannelEngineAdapter: Registered controller '" << names[i] << "' (priority " << priorities[i] << ", lanes: " << (static_cast<int>(hwControllers[i]->getLaneCount())) << ")");
51 }
52
53 if (adapter->mControllers.empty()) {
54 FL_WARN("SpiChannelEngineAdapter: No valid controllers registered");
55 return nullptr;
56 }
57
58 for (auto& ctrl : adapter->mControllers) {
59 ctrl.controller->setStreamCompletionCallback(&streamCompletionThunk, adapter.get());
60 }
61
62 return adapter;
63}
64
66 FL_NO_EXCEPT : mName(name)
67{
68 // Controllers added via create() factory method
69}
70
72 FL_DBG("SpiChannelEngineAdapter: Destructor for '" << mName << "'");
73
74 // Clear any enqueued channels that were never transmitted
75 // This prevents infinite loop in poll() which returns DRAINING if enqueued channels exist
76 mEnqueuedChannels.clear();
77
78 // Poll until READY to ensure cleanup of any in-flight transmissions
79 while (poll() != DriverState::READY) {
80 // Busy-wait for transmission completion
81 // This is acceptable in destructor context
82 }
83
84 // Shutdown all initialized controllers
85 for (auto& ctrl : mControllers) {
86 if (ctrl.controller && ctrl.controller->isInitialized()) {
87 ctrl.controller->end();
88 }
89 if (ctrl.controller) ctrl.controller->setStreamCompletionCallback(nullptr, nullptr);
90 }
91}
92
94 int maxPriority = -1;
95 for (const auto& ctrl : mControllers) {
96 if (ctrl.priority > maxPriority) {
97 maxPriority = ctrl.priority;
98 }
99 }
100 return maxPriority;
101}
102
104 // Check if clock pin already assigned
105 for (const auto& assignment : mClockPinAssignments) {
106 if (assignment.clockPin == clockPin && assignment.requestedBus == requestedBus) {
107 return assignment.controllerIndex;
108 }
109 }
110
111 // Find highest priority available controller
112 int bestIndex = -1;
113 int bestPriority = -1;
114
115 for (size_t i = 0; i < mControllers.size(); i++) {
116 if (requestedBus != Esp32SpiBus::AUTO &&
117 mControllers[i].controller->getBusId() != static_cast<int>(requestedBus)) {
118 continue;
119 }
120 if (requestedBus == Esp32SpiBus::AUTO &&
122 continue;
123 }
124
125 if (mControllers[i].priority > bestPriority) {
126 bestIndex = i;
127 bestPriority = mControllers[i].priority;
128 }
129 }
130
131 // Record assignment
132 if (bestIndex >= 0) {
133 mClockPinAssignments.push_back({clockPin, requestedBus, static_cast<size_t>(bestIndex)});
134 }
135
136 return bestIndex;
137}
138
140 const ControllerInfo& ctrl, int clockPin) const FL_NO_EXCEPT {
141
142 // Uninitialized controllers can handle any pin
143 if (!ctrl.isInitialized) {
144 return true;
145 }
146
147 // Check if already handling this pin
148 for (int assignedPin : ctrl.assignedClockPins) {
149 if (assignedPin == clockPin) {
150 return true;
151 }
152 }
153
154 // ESP32 constraint: cannot re-initialize with different pins
155 return false;
156}
157
159 ControllerInfo& ctrl, int clockPin, int dataPin, u32 clockSpeedHz) FL_NO_EXCEPT {
160
161 if (ctrl.isInitialized) {
162 if (!ctrl.assignedClockPins.empty() &&
163 ctrl.assignedClockPins[0] == clockPin &&
164 ctrl.configuredDataPin == dataPin &&
165 ctrl.configuredClockSpeedHz == clockSpeedHz) {
166 return true;
167 }
168 ctrl.controller->end();
169 ctrl.isInitialized = false;
170 ctrl.assignedClockPins.clear();
171 }
172
173 // Initialize controller based on lane count
174 u8 lanes = ctrl.controller->getLaneCount();
175
176 if (lanes == 1) {
177 SpiHw1::Config config;
178 config.bus_num = static_cast<fl::u8>(ctrl.controller->getBusId());
179 config.clock_pin = clockPin;
180 config.data_pin = dataPin;
181 config.clock_speed_hz = clockSpeedHz;
182 config.max_transfer_sz = 65536;
183
184 if (!ctrl.controller->begin(&config)) {
185 FL_WARN("SpiChannelEngineAdapter: Failed to initialize " << ctrl.name);
186 return false;
187 }
188 } else {
189 // TODO: Multi-lane initialization (SpiHw2/4/8/16)
190 FL_WARN("SpiChannelEngineAdapter: Multi-lane init not yet implemented");
191 return false;
192 }
193
194 ctrl.isInitialized = true;
195 ctrl.configuredDataPin = dataPin;
196 ctrl.configuredClockSpeedHz = clockSpeedHz;
197 ctrl.assignedClockPins.push_back(clockPin);
198
199 FL_DBG("SpiChannelEngineAdapter: Initialized " << ctrl.name << " with clock pin " << clockPin);
200
201 return true;
202}
203
204bool SpiChannelEngineAdapter::canHandle(const ChannelDataPtr& data) const FL_NO_EXCEPT {
205 if (!data) {
206 return false;
207 }
208
209 // ⚠️ CRITICAL: Accept ONLY true SPI chipsets (APA102, SK9822, HD108)
210 // Reject clockless chipsets (WS2812, SK6812) - those use ChannelEngineSpi or RMT
211 //
212 // This is the opposite of ChannelEngineSpi::canHandle(), which should be:
213 // return !data->isSpi(); // Accept clockless, reject true SPI
214 //
215 // Correct routing:
216 // APA102 → SpiChannelEngineAdapter (this adapter)
217 // WS2812 → ChannelEngineSpi (clockless-over-SPI) OR RMT/PARLIO
218 return data->isSpi();
219}
220
221void SpiChannelEngineAdapter::enqueue(ChannelDataPtr channelData) FL_NO_EXCEPT {
222 if (!channelData) {
223 FL_WARN("SpiChannelEngineAdapter: Null channel data passed to enqueue()");
224 return;
225 }
226
227 // Validate that we can handle this data
228 if (!canHandle(channelData)) {
229 FL_WARN("SpiChannelEngineAdapter: Cannot handle non-SPI channel data (chipset mismatch)");
230 return;
231 }
232
233 mEnqueuedChannels.push_back(channelData);
234 FL_DBG("SpiChannelEngineAdapter: Enqueued channel (total: " << mEnqueuedChannels.size() << ")");
235}
236
238 if (mStreamingFrame) {
239 // Preserve the active frame and its source owners if called early.
240 if (advanceStreaming() == DriverState::BUSY) return;
241 }
242 if (mEnqueuedChannels.empty()) {
243 return;
244 }
245
246 FL_DBG("SpiChannelEngineAdapter: show() called with " << mEnqueuedChannels.size() << " channels");
247
248 // Move enqueued channels to transmitting list
250 mEnqueuedChannels.clear();
251
252 for (const auto& ctrl : mControllers) {
253 if (ctrl.controller->supportsStreaming()) {
254 mStreamingFrame = true;
257 return;
258 }
259 }
260
261 // Group adjacent channels with identical SPI bus configuration.
263
264 FL_DBG("SpiChannelEngineAdapter: Grouped into " << groups.size() << " SPI configuration groups");
265
266 // Transmit each group sequentially
267 for (size_t i = 0; i < groups.size(); i++) {
268 const ClockPinGroup& group = groups[i];
269
270 FL_DBG("SpiChannelEngineAdapter: Transmitting group with clock pin " << group.clockPin << " (" << group.channels.size() << " channels)");
271
272 if (!transmitBatch(group.channels)) {
273 FL_WARN("SpiChannelEngineAdapter: Failed to transmit batch for clock pin " << group.clockPin);
274 // Continue with other groups rather than aborting entirely
275 }
276 }
277
278 FL_DBG("SpiChannelEngineAdapter: show() complete");
279}
280
282 if (mStreamingFrame) return advanceStreaming();
283 // Check if ANY controller is busy
284 bool anyBusy = false;
285 for (const auto& ctrl : mControllers) {
286 if (ctrl.controller && ctrl.controller->isBusy()) {
287 anyBusy = true;
288 break;
289 }
290 }
291
292 if (anyBusy) {
293 return DriverState::BUSY;
294 }
295
296 // All controllers idle - release transmitting channels
297 if (!mTransmittingChannels.empty()) {
298 FL_DBG("SpiChannelEngineAdapter: Releasing " << mTransmittingChannels.size() << " completed channels");
299
300 for (const auto& channel : mTransmittingChannels) {
301 if (channel) {
302 channel->setInUse(false);
303 }
304 }
305 mTransmittingChannels.clear();
306 }
307
308 // Check for draining state
309 if (!mEnqueuedChannels.empty()) {
310 return DriverState::DRAINING;
311 }
312
313 return DriverState::READY;
314}
315
319
323
325 for (const auto& ctrl : mControllers) {
326 if (ctrl.controller->isBusy()) return DriverState::BUSY;
327 }
328
329 if (mNextStreamingChannel != 0) {
330 const auto& previous = mTransmittingChannels[mNextStreamingChannel - 1];
331 if (previous) previous->setInUse(false);
332 }
333
335 const size_t index = mNextStreamingChannel++;
336 const auto& channel = mTransmittingChannels[index];
337 if (!channel) continue;
339 // Report a dropped frame even with normal errors-only logging.
340 // Keep the established READY-after-failure semantics: a sticky
341 // ERROR would prevent onBeginFrame() from reaching the next retry.
342 FL_ERROR("SpiChannelEngineAdapter: SPI frame submission failed on pin "
343 << channel->getPin() << " (" << channel->getData().size() << " bytes)");
344 channel->setInUse(false);
345 continue;
346 }
347 for (const auto& ctrl : mControllers) {
348 if (ctrl.controller->isBusy()) return DriverState::BUSY;
349 }
350 channel->setInUse(false);
351 }
352
353 mTransmittingChannels.clear();
354 mStreamingFrame = false;
356 return mEnqueuedChannels.empty() ? DriverState::READY : DriverState::DRAINING;
357}
358
361) FL_NO_EXCEPT {
363
364 for (const auto& channel : channels) {
365 if (!channel) {
366 continue;
367 }
368
369 // Extract clock pin from chipset configuration
370 const auto& chipset = channel->getChipset();
371 if (!chipset.is<SpiChipsetConfig>()) {
372 FL_WARN("SpiChannelEngineAdapter: Non-SPI chipset in groupByClockPin");
373 continue;
374 }
375
376 const SpiChipsetConfig& spiConfig = chipset.get<SpiChipsetConfig>();
377 int clockPin = spiConfig.clockPin;
378 int dataPin = channel->getPin();
379 u32 clockSpeedHz = spiConfig.timing.clock_hz;
380
381 // Preserve enqueue order when the same host alternates configurations.
382 if (!groups.empty()) {
383 ClockPinGroup& last = groups.back();
384 if (last.clockPin == clockPin && last.dataPin == dataPin &&
385 last.clockSpeedHz == clockSpeedHz &&
386 last.requestedBus == spiConfig.spiBus) {
387 last.channels.push_back(channel);
388 continue;
389 }
390 }
391
392 ClockPinGroup newGroup;
393 newGroup.clockPin = clockPin;
394 newGroup.dataPin = dataPin;
395 newGroup.clockSpeedHz = clockSpeedHz;
396 newGroup.requestedBus = spiConfig.spiBus;
397 newGroup.channels.push_back(channel);
398 groups.push_back(newGroup);
399 }
400
401 return groups;
402}
403
405 if (channels.empty()) {
406 return true;
407 }
408
409 // Extract clock pin and data pin from first channel (all same in batch)
410 const auto& chipset = channels[0]->getChipset();
411 if (!chipset.is<SpiChipsetConfig>()) {
412 FL_WARN("SpiChannelEngineAdapter: Non-SPI chipset in transmitBatch");
413 return false;
414 }
415
416 const SpiChipsetConfig& spiConfig = chipset.get<SpiChipsetConfig>();
417 int clockPin = spiConfig.clockPin;
418 int dataPin = channels[0]->getPin(); // MOSI pin from channel config
419
420 // Select controller for this clock pin
421 int controllerIndex = selectControllerForClockPin(clockPin, spiConfig.spiBus);
422 if (controllerIndex < 0) {
423 FL_WARN("SpiChannelEngineAdapter: No available controller for clock pin " << clockPin);
424 return false;
425 }
426
427 ControllerInfo& ctrl = mControllers[controllerIndex];
428
429 // Initialize controller if needed
430 if (!initializeControllerIfNeeded(ctrl, clockPin, dataPin,
431 spiConfig.timing.clock_hz)) {
432 return false;
433 }
434
435 // Transmit using selected controller
436 for (const auto& channel : channels) {
437 if (!channel) {
438 continue;
439 }
440
441 // Mark channel as in use
442 channel->setInUse(true);
443
444 // Get encoded data
445 const auto& data = channel->getData();
446 if (data.empty()) {
447 FL_WARN("SpiChannelEngineAdapter: Empty channel data");
448 channel->setInUse(false);
449 continue;
450 }
451
452 FL_DBG("SpiChannelEngineAdapter: Transmitting channel via " << ctrl.name << " (pin " << channel->getPin() << ", " << data.size() << " bytes)");
453
454 if (ctrl.controller->supportsStreaming()) {
455 // The backend retains or copies encoded bytes until completion.
456 // advanceStreaming() submits one channel at a time, preserving
457 // pin/rate changes and enqueue order without blocking show().
458 if (!ctrl.controller->transmitStream(channel)) {
459 channel->setInUse(false);
460 return false;
461 }
462 return true;
463 }
464
465 // Acquire DMA buffer
466 DMABuffer dmaBuffer = ctrl.controller->acquireDMABuffer(data.size());
467 if (!dmaBuffer.ok()) {
468 FL_WARN("SpiChannelEngineAdapter: Failed to acquire DMA buffer (error " << (static_cast<int>(dmaBuffer.error())) << ")");
469 channel->setInUse(false);
470 return false;
471 }
472
473 // Copy data to DMA buffer
474 fl::span<u8> buffer = dmaBuffer.data();
475 if (buffer.size() < data.size()) {
476 FL_WARN("SpiChannelEngineAdapter: DMA buffer too small (" << buffer.size() << " < " << data.size() << ")");
477 channel->setInUse(false);
478 return false;
479 }
480
481 fl::memcpy(buffer.data(), data.data(), data.size());
482
483 // Transmit (async mode for non-blocking operation)
484 if (!ctrl.controller->transmit(TransmitMode::ASYNC)) {
485 FL_WARN("SpiChannelEngineAdapter: Transmission failed");
486 channel->setInUse(false);
487 return false;
488 }
489
490 FL_DBG("SpiChannelEngineAdapter: Transmission queued successfully");
491 }
492
493 // Wait for transmission to complete (synchronous for now)
494 // TODO: Make fully async by returning BUSY state and polling in poll()
495 if (!ctrl.controller->waitComplete(1000)) { // 1 second timeout
496 FL_WARN("SpiChannelEngineAdapter: Transmission timeout");
497 return false;
498 }
499
500 FL_DBG("SpiChannelEngineAdapter: Batch transmission complete");
501 return true;
502}
503
504} // namespace fl
CLEDController * controller
bool transmitBatch(fl::span< const ChannelDataPtr > channels) FL_NO_EXCEPT
Transmit a batch of channels sharing one SPI configuration.
fl::vector< ClockPinGroup > groupByClockPin(fl::span< const ChannelDataPtr > channels) FL_NO_EXCEPT
Group adjacent channels with matching pins, host, and clock rate.
DriverState advanceStreaming() FL_NO_EXCEPT
Advance ordered streaming channels after the preceding source is reaped.
void enqueue(ChannelDataPtr channelData) FL_NO_EXCEPT override
Enqueue channel data for transmission.
fl::string mName
Engine name for debugging.
int getPriority() const FL_NO_EXCEPT
Get maximum priority among all controllers.
void show() FL_NO_EXCEPT override
Trigger transmission of enqueued data.
static void streamCompletionThunk(void *context) FL_NO_EXCEPT
bool canHandle(const ChannelDataPtr &data) const FL_NO_EXCEPT override
Check if adapter can handle channel data.
fl::vector< ControllerInfo > mControllers
All managed controllers.
static fl::shared_ptr< SpiChannelEngineAdapter > create(fl::vector< fl::shared_ptr< SpiHwBase > > hwControllers, fl::vector< int > priorities, fl::vector< const char * > names, const char *adapterName) FL_NO_EXCEPT
Create unified adapter managing multiple controllers.
PollNeededCallbackSlot mPollNeededCallback
bool initializeControllerIfNeeded(ControllerInfo &ctrl, int clockPin, int dataPin, u32 clockSpeedHz) FL_NO_EXCEPT
Initialize controller if needed for this clock pin.
int selectControllerForClockPin(int clockPin, Esp32SpiBus requestedBus) FL_NO_EXCEPT
Select best controller for a given clock pin.
SpiChannelEngineAdapter(const char *name) FL_NO_EXCEPT
Private constructor - use create() factory method.
bool canControllerHandleClockPin(const ControllerInfo &ctrl, int clockPin) const FL_NO_EXCEPT
Check if controller can handle this clock pin.
DriverState poll() FL_NO_EXCEPT override
Query driver state and perform maintenance.
~SpiChannelEngineAdapter() FL_NO_EXCEPT override
Destructor.
void setPollNeededCallback(PollNeededCallback callback) FL_NO_EXCEPT override
Install the manager-owned poll-needed callback for ISR wakeups.
fl::vector< ChannelDataPtr > mEnqueuedChannels
Channels waiting for show()
fl::vector< ClockPinAssignment > mClockPinAssignments
Clock pin → controller mapping.
fl::vector< ChannelDataPtr > mTransmittingChannels
Channels currently transmitting.
Channels sharing one SPI bus configuration.
fl::size size() const FL_NO_EXCEPT
const T * data() const FL_NO_EXCEPT
Definition span.h:486
constexpr fl::size size() const FL_NO_EXCEPT
Definition span.h:483
fl::size size() const FL_NO_EXCEPT
bool empty() const FL_NO_EXCEPT
void push_back(const T &value) FL_NO_EXCEPT
Definition vector.h:624
T & back() FL_NO_EXCEPT
Definition vector.h:616
#define FL_WARN(...)
Definition log.h:437
#define FL_DBG
Definition log.h:553
#define FL_ERROR(...)
Definition log.h:373
Centralized logging categories for FastLED hardware interfaces and subsystems.
shared_ptr< T > make_shared(Args &&... args) FL_NO_EXCEPT
Definition shared_ptr.h:423
constexpr remove_reference< T >::type && move(T &&t) FL_NO_EXCEPT
Definition s16x16x4.h:30
unsigned char u8
Definition s16x16x4.h:132
unsigned char u8
Definition stdint.h:132
Esp32SpiBus
ESP-IDF SPI host selection for an individual clocked LED controller.
Definition spi_bus.h:18
u8 u8 fract8 blur_amount FL_NO_EXCEPT
Definition blur.h:186
FASTLED_FORCE_INLINE void * memcpy(void *dest, const void *src, size_t n) FL_NO_EXCEPT
Definition cstring.h:136
Base definition for an LED controller.
Adapter that wraps HW SPI controllers for ChannelManager.
Driver state with optional error message.
Definition driver.h:169
ISR-safe callback handle invoked when the manager should poll again.
Definition driver.h:62
fl::shared_ptr< SpiHwBase > controller
Hardware instance.
fl::string name
Name (e.g., "SPI2", "SPI3", "I2S0")
Information about a registered SPI hardware controller.
SpiEncoder timing
SPI encoder configuration.
Definition config.h:106
Esp32SpiBus spiBus
ESP-IDF host override, or AUTO.
Definition config.h:107
int clockPin
GPIO clock pin (SCK)
Definition config.h:105
SPI chipset configuration (data + clock pins)
Definition config.h:103
u32 clock_hz
SPI clock frequency in Hz (e.g., 6000000 for 6MHz)
Definition spi.h:40