1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use embedded_hal::{i2c as hal_i2c, spi as hal_spi};

/// Blanket trait for types implementing `i2c::I2c
pub trait I2cBus: hal_i2c::I2c {
    type BusError: From<<Self as hal_i2c::ErrorType>::Error>;
}

impl<T, E> I2cBus for T
where
    T: hal_i2c::I2c<Error = E>,
{
    type BusError = E;
}

pub(crate) trait I2cExt {
    type Error;

    fn write_reg<R: Into<u8>>(&mut self, addr: u8, reg: R, value: u8) -> Result<(), Self::Error>;
    fn update_reg<R: Into<u8>>(
        &mut self,
        addr: u8,
        reg: R,
        mask_set: u8,
        mask_clear: u8,
    ) -> Result<(), Self::Error>;
    fn read_reg<R: Into<u8>>(&mut self, addr: u8, reg: R) -> Result<u8, Self::Error>;
}

impl<I2C: I2cBus> I2cExt for I2C {
    type Error = I2C::BusError;

    fn write_reg<R: Into<u8>>(&mut self, addr: u8, reg: R, value: u8) -> Result<(), Self::Error> {
        self.write(addr, &[reg.into(), value])?;
        Ok(())
    }

    fn update_reg<R: Into<u8>>(
        &mut self,
        addr: u8,
        reg: R,
        mask_set: u8,
        mask_clear: u8,
    ) -> Result<(), Self::Error> {
        let reg = reg.into();
        let mut buf = [0x00];
        self.write_read(addr, &[reg], &mut buf)?;
        buf[0] |= mask_set;
        buf[0] &= !mask_clear;
        self.write(addr, &[reg, buf[0]])?;
        Ok(())
    }

    fn read_reg<R: Into<u8>>(&mut self, addr: u8, reg: R) -> Result<u8, Self::Error> {
        let mut buf = [0x00];
        self.write_read(addr, &[reg.into()], &mut buf)?;
        Ok(buf[0])
    }
}

pub trait SpiBus: hal_spi::SpiDevice {
    type BusError: From<<Self as hal_spi::ErrorType>::Error>;
}

impl<T, E> SpiBus for T
where
    T: hal_spi::SpiDevice<Error = E>,
{
    type BusError = E;
}