| 51 | /// @tparam SPI_INDEX SPI peripheral index (0, 1, or 2) |
| 52 | template<u8 DATA_PIN, u8 CLOCK_PIN, u32 SPI_CLOCK_RATE, SPIClass & SPIObject, int SPI_INDEX> |
| 53 | class SPIDeviceProxy { |
| 54 | private: |
| 55 | SPIBusHandle mHandle; // Handle from SPIBusManager |
| 56 | SPIBusManager* mBusManager; // Pointer to global bus manager |
| 57 | fl::unique_ptr<Teensy4HardwareSPIOutput<DATA_PIN, CLOCK_PIN, SPI_CLOCK_RATE, SPIObject, SPI_INDEX>> mSingleSPI; |
| 58 | fl::vector<u8> mWriteBuffer; // Buffered writes (for Dual/Quad-SPI) |
| 59 | bool mInitialized; // Whether init() was called |
| 60 | bool mBusInitialized; // Whether bus manager has been initialized |
| 61 | bool mInTransaction; // Whether select() was called |
| 62 | |
| 63 | public: |
| 64 | /// Constructor - just stores pins, actual setup happens in init() |
| 65 | SPIDeviceProxy() |
| 66 | : mHandle() |
| 67 | , mBusManager(nullptr) |
| 68 | , mInitialized(false) |
| 69 | , mBusInitialized(false) |
| 70 | , mInTransaction(false) |
| 71 | { |
| 72 | } |
| 73 | |
| 74 | /// Destructor - cleanup owned resources and unregister from bus manager |
| 75 | ~SPIDeviceProxy() { |
| 76 | // Unregister from bus manager (releases Dual/Quad-SPI if last device) |
| 77 | if (mBusManager && mHandle.is_valid) { |
| 78 | mBusManager->unregisterDevice(mHandle); |
| 79 | mHandle = SPIBusHandle(); // Invalidate handle |
| 80 | } |
| 81 | |
| 82 | mSingleSPI.reset(); |
| 83 | } |
| 84 | |
| 85 | /// Initialize SPI device and register with bus manager |
| 86 | /// Called by LED controller's init() method |
| 87 | void init() FL_NOEXCEPT { |
| 88 | if (mInitialized) { |
| 89 | return; // Already initialized |
| 90 | } |
| 91 | |
| 92 | // Get global bus manager |
| 93 | mBusManager = &getSPIBusManager(); |
| 94 | |
| 95 | // Register with bus manager |
| 96 | // NOTE: Bus manager will determine if we use Single/Dual/Quad SPI |
| 97 | // based on how many devices share our clock pin |
| 98 | mHandle = mBusManager->registerDevice(CLOCK_PIN, DATA_PIN, SPI_CLOCK_RATE, this); |
| 99 | |
| 100 | if (!mHandle.is_valid) { |
| 101 | FL_LOG_SPI("SPIDeviceProxy: Failed to register with bus manager (pin " |
| 102 | << static_cast<int>(CLOCK_PIN) << ":" << static_cast<int>(DATA_PIN) << ")"); |
| 103 | return; |
| 104 | } |
| 105 | |
| 106 | // IMPORTANT: DO NOT initialize bus manager here! |
| 107 | // We defer initialization until the first transmit() call (lazy initialization). |
| 108 | // This allows all devices on the same clock pin to register before the bus |
| 109 | // decides whether to use Single-SPI, Dual-SPI, or Quad-SPI mode. |
| 110 | // If we initialize here, the first device gets SINGLE_SPI mode before other |
nothing calls this directly
no test coverage detected