extern crate alloc;
use alloc::rc::Rc;
use core::cell::RefCell;
use embedded_hal::delay::DelayNs;
use embedded_hal::digital::OutputPin;
use embedded_hal::spi::{ErrorType, Operation, SpiBus, SpiDevice};
use super::DeviceError;
use crate::spi::shared::transaction;
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
pub struct RcDevice<Bus, Cs, Delay> {
bus: Rc<RefCell<Bus>>,
cs: Cs,
delay: Delay,
}
impl<Bus, Cs, Delay> RcDevice<Bus, Cs, Delay> {
#[inline]
pub fn new(bus: Rc<RefCell<Bus>>, mut cs: Cs, delay: Delay) -> Result<Self, Cs::Error>
where
Cs: OutputPin,
{
cs.set_high()?;
Ok(Self { bus, cs, delay })
}
}
impl<Bus, Cs> RcDevice<Bus, Cs, super::NoDelay> {
#[inline]
pub fn new_no_delay(bus: Rc<RefCell<Bus>>, mut cs: Cs) -> Result<Self, Cs::Error>
where
Cs: OutputPin,
{
cs.set_high()?;
Ok(Self {
bus,
cs,
delay: super::NoDelay,
})
}
}
impl<Bus, Cs, Delay> ErrorType for RcDevice<Bus, Cs, Delay>
where
Bus: ErrorType,
Cs: OutputPin,
{
type Error = DeviceError<Bus::Error, Cs::Error>;
}
impl<Word, Bus, Cs, Delay> SpiDevice<Word> for RcDevice<Bus, Cs, Delay>
where
Word: Copy + 'static,
Bus: SpiBus<Word>,
Cs: OutputPin,
Delay: DelayNs,
{
#[inline]
fn transaction(&mut self, operations: &mut [Operation<'_, Word>]) -> Result<(), Self::Error> {
let bus = &mut *self.bus.borrow_mut();
transaction(operations, bus, &mut self.delay, &mut self.cs)
}
}