Initialize the SPI hardware.
44 {
46 return fl::task::Error("Device not initialized");
47 }
48
49 if (
pImpl->initialized) {
50
52 }
53
54
55 if (
pImpl->config.spi_mode > 3) {
56 FL_WARN(
"SPI Device: Invalid SPI mode " <<
pImpl->config.spi_mode <<
" (must be 0-3)");
57 return fl::task::Error("Invalid SPI mode");
58 }
59
60
61
62 if (
pImpl->config.spi_mode != 0) {
63 FL_WARN(
"SPI Device: SPI mode " <<
pImpl->config.spi_mode <<
" requested but hardware layer only supports mode 0 - ignoring");
64 }
65
66
67 SPIBusManager& mgr = getSPIBusManager();
68 int data_pin =
pImpl->config.data_pins.empty() ? -1 :
pImpl->config.data_pins[0];
69 pImpl->bus_handle = mgr.registerDevice(
70 pImpl->config.clock_pin,
71 data_pin,
72 pImpl->config.clock_speed_hz,
73 this
74 );
75
76 if (!
pImpl->bus_handle.is_valid) {
77 FL_WARN(
"SPI Device: Failed to register with bus manager");
78 return fl::task::Error("Failed to register with bus manager");
79 }
80
81
82 if (!mgr.initialize()) {
83 FL_WARN(
"SPI Device: Bus initialization failed");
84 return fl::task::Error("Bus initialization failed");
85 }
86
87
88 const SPIBusInfo* bus_info = mgr.getBusInfo(
pImpl->bus_handle.bus_id);
89 if (bus_info && bus_info->bus_type == SPIBusType::SINGLE_SPI && !bus_info->hw_controller) {
90
91 const fl::vector<fl::shared_ptr<SpiHw1>>& controllers = SpiHw1::getAll();
92 if (controllers.
empty()) {
93 FL_WARN(
"SPI Device: No SpiHw1 controllers available on this platform");
94 return fl::task::Error("No SpiHw1 controllers available");
95 }
96
97
98 fl::shared_ptr<SpiHw1> hw = controllers[0];
99
100 SpiHw1::Config hw_config;
101 hw_config.clock_pin =
pImpl->config.clock_pin;
102 hw_config.data_pin =
pImpl->config.data_pins.empty() ? -1 :
pImpl->config.data_pins[0];
103 hw_config.clock_speed_hz =
pImpl->config.clock_speed_hz;
104 hw_config.bus_num = 0;
105
106 if (!hw->begin(hw_config)) {
107 FL_WARN(
"SPI Device: Failed to initialize SpiHw1 controller");
108 return fl::task::Error("Failed to initialize SpiHw1");
109 }
110
111 pImpl->hw_backend = hw;
112 pImpl->owns_backend =
false;
113 FL_LOG_SPI(
"SPI Device: Created SpiHw1 controller for SINGLE_SPI mode");
114 } else {
115
116 pImpl->hw_backend = bus_info ? bus_info->hw_controller :
nullptr;
117 pImpl->owns_backend =
false;
118 }
119
120 pImpl->initialized =
true;
121 FL_LOG_SPI(
"SPI Device: Initialized successfully");
123}
fl::unique_ptr< Impl > pImpl
bool empty() const FL_NO_EXCEPT
#define FL_LOG_SPI(...)
Serial Peripheral Interface (SPI) logging Logs SPI configuration, initialization, and transfers.
constexpr nullopt_t nullopt