embedded_interfaces/registers/i2c/
mod.rs

1pub mod codecs;
2
3use crate::TransportError;
4use crate::registers::{ReadableRegister, Register, RegisterCodec, WritableRegister};
5
6/// Represents a trait for I2C 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, address size, continuous-read mode and more.
10#[maybe_async_cfg::maybe(
11    idents(hal(sync = "embedded_hal", async = "embedded_hal_async"), I2cBoundBus),
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 I2C interface.
18    async fn read_register<R, I, A>(
19        bound_bus: &mut crate::i2c::I2cBoundBus<I, A>,
20    ) -> Result<R, TransportError<Self::Error, I::Error>>
21    where
22        R: Register<CodecError = Self::Error> + ReadableRegister,
23        I: hal::i2c::I2c<A> + hal::i2c::ErrorType,
24        A: hal::i2c::AddressMode + Copy + core::fmt::Debug;
25
26    /// Write this register through the given I2C interface.
27    async fn write_register<R, I, A>(
28        bound_bus: &mut crate::i2c::I2cBoundBus<I, A>,
29        register: impl AsRef<R>,
30    ) -> Result<(), TransportError<Self::Error, I::Error>>
31    where
32        R: Register<CodecError = Self::Error> + WritableRegister,
33        I: hal::i2c::I2c<A> + hal::i2c::ErrorType,
34        A: hal::i2c::AddressMode + Copy + core::fmt::Debug;
35}
36
37#[maybe_async_cfg::maybe(
38    idents(hal(sync = "embedded_hal", async = "embedded_hal_async"), Codec, RegisterInterface),
39    sync(feature = "sync"),
40    async(feature = "async")
41)]
42impl<I, A> crate::registers::RegisterInterface for crate::i2c::I2cDevice<I, A>
43where
44    I: hal::i2c::I2c<A> + hal::i2c::ErrorType,
45    A: hal::i2c::AddressMode + Copy + core::fmt::Debug,
46{
47    type BusError = I::Error;
48
49    /// Read this register from this spi device using the codec specified by the register.
50    #[inline]
51    async fn read_register<R>(&mut self) -> Result<R, TransportError<<R as Register>::CodecError, Self::BusError>>
52    where
53        R: ReadableRegister,
54    {
55        <R::I2cCodec as Codec>::read_register::<R, _, A>(&mut self.bound_bus).await
56    }
57
58    /// Write this register to this i2c device using the codec specified by the register.
59    #[inline]
60    async fn write_register<R>(
61        &mut self,
62        register: impl AsRef<R>,
63    ) -> Result<(), TransportError<<R as Register>::CodecError, Self::BusError>>
64    where
65        R: WritableRegister,
66    {
67        <R::I2cCodec as Codec>::write_register(&mut self.bound_bus, register).await
68    }
69}