embedded_interfaces/registers/spi/
mod.rs

1pub mod codecs;
2
3use crate::TransportError;
4use crate::registers::{ReadableRegister, Register, RegisterCodec, WritableRegister};
5
6/// Represents a trait for SPI codecs. These are responsible to perform
7/// writes and reads to registers, given the register address and
8/// the raw data. Different devices can have different ways to encode
9/// the desired address, R/W bit location, continuous-read mode and more.
10#[maybe_async_cfg::maybe(
11    idents(hal(sync = "embedded_hal", async = "embedded_hal_async")),
12    sync(feature = "sync"),
13    async(feature = "async")
14)]
15#[allow(async_fn_in_trait)]
16pub trait Codec: RegisterCodec {
17    /// Read this register through the given SPI interface
18    async fn read_register<R, I>(interface: &mut I) -> Result<R, TransportError<Self::Error, I::Error>>
19    where
20        R: Register<CodecError = Self::Error> + ReadableRegister,
21        I: hal::spi::r#SpiDevice;
22
23    /// Write this register through the given SPI interface
24    async fn write_register<R, I>(
25        interface: &mut I,
26        register: impl AsRef<R>,
27    ) -> Result<(), TransportError<Self::Error, I::Error>>
28    where
29        R: Register<CodecError = Self::Error> + WritableRegister,
30        I: hal::spi::r#SpiDevice;
31}
32
33#[maybe_async_cfg::maybe(
34    idents(hal(sync = "embedded_hal", async = "embedded_hal_async"), Codec, RegisterInterface),
35    sync(feature = "sync"),
36    async(feature = "async")
37)]
38impl<I> crate::registers::RegisterInterface for crate::spi::SpiDevice<I>
39where
40    I: hal::spi::r#SpiDevice,
41{
42    type BusError = I::Error;
43
44    /// Read this register from this spi device using the codec specified by the register.
45    #[inline]
46    async fn read_register<R>(&mut self) -> Result<R, TransportError<<R as Register>::CodecError, Self::BusError>>
47    where
48        R: ReadableRegister,
49    {
50        <R::SpiCodec as Codec>::read_register::<R, _>(&mut self.interface).await
51    }
52
53    /// Write this register to this spi device using the codec specified by the register.
54    #[inline]
55    async fn write_register<R>(
56        &mut self,
57        register: impl AsRef<R>,
58    ) -> Result<(), TransportError<<R as Register>::CodecError, Self::BusError>>
59    where
60        R: WritableRegister,
61    {
62        <R::SpiCodec as Codec>::write_register(&mut self.interface, register).await
63    }
64}