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