Associated type

This commit is contained in:
Henrik Alsér
2022-07-09 00:00:55 +02:00
parent 15384d27bb
commit d637510b44
8 changed files with 128 additions and 141 deletions

View File

@ -76,54 +76,6 @@ where
}
}
pub struct SpiBusDeviceWithConfig<'a, M: RawMutex, BUS, CS, C> {
bus: &'a Mutex<M, RefCell<BUS>>,
cs: CS,
config: C,
}
impl<'a, M: RawMutex, BUS, CS, C> SpiBusDeviceWithConfig<'a, M, BUS, CS, C> {
pub fn new(bus: &'a Mutex<M, RefCell<BUS>>, cs: CS, config: C) -> Self {
Self { bus, cs, config }
}
}
impl<'a, M: RawMutex, BUS, CS, C> spi::ErrorType for SpiBusDeviceWithConfig<'a, M, BUS, CS, C>
where
BUS: spi::ErrorType,
CS: OutputPin,
{
type Error = SpiBusDeviceError<BUS::Error, CS::Error>;
}
impl<BUS, M, CS, C> SpiDevice for SpiBusDeviceWithConfig<'_, M, BUS, CS, C>
where
M: RawMutex,
BUS: SpiBusFlush + SetConfig<C>,
CS: OutputPin,
{
type Bus = BUS;
fn transaction<R>(&mut self, f: impl FnOnce(&mut Self::Bus) -> Result<R, BUS::Error>) -> Result<R, Self::Error> {
self.bus.lock(|bus| {
let mut bus = bus.borrow_mut();
bus.set_config(&self.config);
self.cs.set_low().map_err(SpiBusDeviceError::Cs)?;
let f_res = f(&mut bus);
// On failure, it's important to still flush and deassert CS.
let flush_res = bus.flush();
let cs_res = self.cs.set_high();
let f_res = f_res.map_err(SpiBusDeviceError::Spi)?;
flush_res.map_err(SpiBusDeviceError::Spi)?;
cs_res.map_err(SpiBusDeviceError::Cs)?;
Ok(f_res)
})
}
}
impl<'d, M, BUS, CS, BusErr, CsErr> embedded_hal_02::blocking::spi::Transfer<u8> for SpiBusDevice<'_, M, BUS, CS>
where
M: RawMutex,
@ -164,3 +116,52 @@ where
})
}
}
pub struct SpiBusDeviceWithConfig<'a, M: RawMutex, BUS: SetConfig, CS> {
bus: &'a Mutex<M, RefCell<BUS>>,
cs: CS,
config: BUS::Config,
}
impl<'a, M: RawMutex, BUS: SetConfig, CS> SpiBusDeviceWithConfig<'a, M, BUS, CS> {
pub fn new(bus: &'a Mutex<M, RefCell<BUS>>, cs: CS, config: BUS::Config) -> Self {
Self { bus, cs, config }
}
}
impl<'a, M, BUS, CS> spi::ErrorType for SpiBusDeviceWithConfig<'a, M, BUS, CS>
where
M: RawMutex,
BUS: spi::ErrorType + SetConfig,
CS: OutputPin,
{
type Error = SpiBusDeviceError<BUS::Error, CS::Error>;
}
impl<BUS, M, CS> SpiDevice for SpiBusDeviceWithConfig<'_, M, BUS, CS>
where
M: RawMutex,
BUS: SpiBusFlush + SetConfig,
CS: OutputPin,
{
type Bus = BUS;
fn transaction<R>(&mut self, f: impl FnOnce(&mut Self::Bus) -> Result<R, BUS::Error>) -> Result<R, Self::Error> {
self.bus.lock(|bus| {
let mut bus = bus.borrow_mut();
bus.set_config(&self.config);
self.cs.set_low().map_err(SpiBusDeviceError::Cs)?;
let f_res = f(&mut bus);
// On failure, it's important to still flush and deassert CS.
let flush_res = bus.flush();
let cs_res = self.cs.set_high();
let f_res = f_res.map_err(SpiBusDeviceError::Spi)?;
flush_res.map_err(SpiBusDeviceError::Spi)?;
cs_res.map_err(SpiBusDeviceError::Cs)?;
Ok(f_res)
})
}
}