embassy_embedded_hal/shared_bus/asynch/
spi.rs1use embassy_hal_internal::drop::OnDrop;
29use embassy_sync::blocking_mutex::raw::RawMutex;
30use embassy_sync::mutex::Mutex;
31use embedded_hal_1::digital::OutputPin;
32use embedded_hal_1::spi::Operation;
33use embedded_hal_async::spi;
34
35use crate::shared_bus::SpiDeviceError;
36use crate::SetConfig;
37
38pub struct SpiDevice<'a, M: RawMutex, BUS, CS> {
40    bus: &'a Mutex<M, BUS>,
41    cs: CS,
42}
43
44impl<'a, M: RawMutex, BUS, CS> SpiDevice<'a, M, BUS, CS> {
45    pub fn new(bus: &'a Mutex<M, BUS>, cs: CS) -> Self {
47        Self { bus, cs }
48    }
49}
50
51impl<'a, M: RawMutex, BUS, CS> spi::ErrorType for SpiDevice<'a, M, BUS, CS>
52where
53    BUS: spi::ErrorType,
54    CS: OutputPin,
55{
56    type Error = SpiDeviceError<BUS::Error, CS::Error>;
57}
58
59impl<M, BUS, CS, Word> spi::SpiDevice<Word> for SpiDevice<'_, M, BUS, CS>
60where
61    M: RawMutex,
62    BUS: spi::SpiBus<Word>,
63    CS: OutputPin,
64    Word: Copy + 'static,
65{
66    async fn transaction(&mut self, operations: &mut [spi::Operation<'_, Word>]) -> Result<(), Self::Error> {
67        if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) {
68            return Err(SpiDeviceError::DelayNotSupported);
69        }
70
71        let mut bus = self.bus.lock().await;
72        self.cs.set_low().map_err(SpiDeviceError::Cs)?;
73
74        let cs_drop = OnDrop::new(|| {
75            let _ = self.cs.set_high();
80        });
81
82        let op_res = 'ops: {
83            for op in operations {
84                let res = match op {
85                    Operation::Read(buf) => bus.read(buf).await,
86                    Operation::Write(buf) => bus.write(buf).await,
87                    Operation::Transfer(read, write) => bus.transfer(read, write).await,
88                    Operation::TransferInPlace(buf) => bus.transfer_in_place(buf).await,
89                    #[cfg(not(feature = "time"))]
90                    Operation::DelayNs(_) => unreachable!(),
91                    #[cfg(feature = "time")]
92                    Operation::DelayNs(ns) => match bus.flush().await {
93                        Err(e) => Err(e),
94                        Ok(()) => {
95                            embassy_time::Timer::after_nanos(*ns as _).await;
96                            Ok(())
97                        }
98                    },
99                };
100                if let Err(e) = res {
101                    break 'ops Err(e);
102                }
103            }
104            Ok(())
105        };
106
107        let flush_res = bus.flush().await;
109
110        cs_drop.defuse();
113        let cs_res = self.cs.set_high();
114
115        let op_res = op_res.map_err(SpiDeviceError::Spi)?;
116        flush_res.map_err(SpiDeviceError::Spi)?;
117        cs_res.map_err(SpiDeviceError::Cs)?;
118
119        Ok(op_res)
120    }
121}
122
123pub struct SpiDeviceWithConfig<'a, M: RawMutex, BUS: SetConfig, CS> {
129    bus: &'a Mutex<M, BUS>,
130    cs: CS,
131    config: BUS::Config,
132}
133
134impl<'a, M: RawMutex, BUS: SetConfig, CS> SpiDeviceWithConfig<'a, M, BUS, CS> {
135    pub fn new(bus: &'a Mutex<M, BUS>, cs: CS, config: BUS::Config) -> Self {
137        Self { bus, cs, config }
138    }
139
140    pub fn set_config(&mut self, config: BUS::Config) {
142        self.config = config;
143    }
144}
145
146impl<'a, M, BUS, CS> spi::ErrorType for SpiDeviceWithConfig<'a, M, BUS, CS>
147where
148    BUS: spi::ErrorType + SetConfig,
149    CS: OutputPin,
150    M: RawMutex,
151{
152    type Error = SpiDeviceError<BUS::Error, CS::Error>;
153}
154
155impl<M, BUS, CS, Word> spi::SpiDevice<Word> for SpiDeviceWithConfig<'_, M, BUS, CS>
156where
157    M: RawMutex,
158    BUS: spi::SpiBus<Word> + SetConfig,
159    CS: OutputPin,
160    Word: Copy + 'static,
161{
162    async fn transaction(&mut self, operations: &mut [spi::Operation<'_, Word>]) -> Result<(), Self::Error> {
163        if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) {
164            return Err(SpiDeviceError::DelayNotSupported);
165        }
166
167        let mut bus = self.bus.lock().await;
168        bus.set_config(&self.config).map_err(|_| SpiDeviceError::Config)?;
169        self.cs.set_low().map_err(SpiDeviceError::Cs)?;
170
171        let cs_drop = OnDrop::new(|| {
172            let _ = self.cs.set_high();
174        });
175
176        let op_res = 'ops: {
177            for op in operations {
178                let res = match op {
179                    Operation::Read(buf) => bus.read(buf).await,
180                    Operation::Write(buf) => bus.write(buf).await,
181                    Operation::Transfer(read, write) => bus.transfer(read, write).await,
182                    Operation::TransferInPlace(buf) => bus.transfer_in_place(buf).await,
183                    #[cfg(not(feature = "time"))]
184                    Operation::DelayNs(_) => unreachable!(),
185                    #[cfg(feature = "time")]
186                    Operation::DelayNs(ns) => match bus.flush().await {
187                        Err(e) => Err(e),
188                        Ok(()) => {
189                            embassy_time::Timer::after_nanos(*ns as _).await;
190                            Ok(())
191                        }
192                    },
193                };
194                if let Err(e) = res {
195                    break 'ops Err(e);
196                }
197            }
198            Ok(())
199        };
200
201        let flush_res = bus.flush().await;
203        cs_drop.defuse();
204        let cs_res = self.cs.set_high();
205
206        let op_res = op_res.map_err(SpiDeviceError::Spi)?;
207        flush_res.map_err(SpiDeviceError::Spi)?;
208        cs_res.map_err(SpiDeviceError::Cs)?;
209
210        Ok(op_res)
211    }
212}