use crate::{Cat25040Error, Operation, Spi};
use device_driver::{AsyncCommandInterface, AsyncRegisterInterface, CommandInterface, RegisterInterface};
pub struct SpiRegisterInterface<S: Spi> {
spi: S,
}
impl<S: Spi> SpiRegisterInterface<S> {
pub fn new(spi: S) -> Self {
Self { spi }
}
pub fn into_inner(self) -> S {
self.spi
}
pub fn spi_mut(&mut self) -> &mut S {
&mut self.spi
}
}
impl<S: Spi> RegisterInterface for SpiRegisterInterface<S> {
type AddressType = u8;
type Error = Cat25040Error;
fn read_register(
&mut self,
_address: Self::AddressType,
_size_bits: u32,
_data: &mut [u8],
) -> Result<(), Self::Error> {
unimplemented!("Use AsyncRegisterInterface instead for async operations")
}
fn write_register(
&mut self,
_address: Self::AddressType,
_size_bits: u32,
_data: &[u8],
) -> Result<(), Self::Error> {
unimplemented!("Use AsyncRegisterInterface instead for async operations")
}
}
impl<S: Spi> AsyncRegisterInterface for SpiRegisterInterface<S> {
type AddressType = u8;
type Error = Cat25040Error;
async fn read_register(
&mut self,
address: Self::AddressType,
_size_bits: u32,
data: &mut [u8],
) -> Result<(), Self::Error> {
self.spi
.transaction(&mut [Operation::Write(&[address]), Operation::Read(data)])
.await
}
async fn write_register(
&mut self,
address: Self::AddressType,
_size_bits: u32,
data: &[u8],
) -> Result<(), Self::Error> {
let mut buf = [0u8; 9]; buf[0] = address;
let len = 1 + data.len();
buf[1..len].copy_from_slice(data);
self.spi
.transaction(&mut [Operation::Write(&buf[..len])])
.await
}
}
impl<S: Spi> CommandInterface for SpiRegisterInterface<S> {
type AddressType = u8;
type Error = Cat25040Error;
fn dispatch_command(
&mut self,
_address: Self::AddressType,
_size_bits_in: u32,
_input: &[u8],
_size_bits_out: u32,
_output: &mut [u8],
) -> Result<(), Self::Error> {
unimplemented!("Use AsyncCommandInterface instead for async operations")
}
}
impl<S: Spi> AsyncCommandInterface for SpiRegisterInterface<S> {
type AddressType = u8;
type Error = Cat25040Error;
async fn dispatch_command(
&mut self,
address: Self::AddressType,
_size_bits_in: u32,
input: &[u8],
_size_bits_out: u32,
output: &mut [u8],
) -> Result<(), Self::Error> {
if input.is_empty() && output.is_empty() {
self.spi
.transaction(&mut [Operation::Write(&[address])])
.await
} else {
unimplemented!("Commands with input/output not yet supported")
}
}
}