jrk_g2/
i2c.rs

1use crate::enums::{JrkG2Command, VarOffset};
2use crate::jrk::JrkG2;
3use embedded_hal::blocking::i2c;
4
5/// Implement the `JrkG2` trait for I2C
6pub struct I2c<Bus> {
7    device: u8,
8    i2c: Bus,
9}
10
11impl<Bus, I2cError> I2c<Bus>
12where
13    Bus: i2c::Write<Error = I2cError> + i2c::Read<Error = I2cError>,
14{
15    pub const fn new(i2c: Bus) -> Self {
16        Self { device: 0x0B, i2c }
17    }
18    /// The controller have a default 0x0B I2C address, but this can be manually changed in the
19    /// configuration utility.
20    pub fn set_device(&mut self, device: u8) {
21        self.device = device;
22    }
23}
24
25impl<Bus, I2cError> JrkG2<I2cError> for I2c<Bus>
26where
27    Bus: i2c::Write<Error = I2cError> + i2c::Read<Error = I2cError>,
28{
29    fn write(&mut self, data: &[u8]) -> Result<(), I2cError> {
30        self.i2c.write(self.device, data)
31    }
32    fn read(&mut self, cmd: VarOffset) -> Result<u16, I2cError> {
33        let mut buf: [u8; 2] = [0, 0];
34        self.write(&[JrkG2Command::GetVariable16 as u8 | (cmd as u8 + 1)])?;
35        self.i2c.read(self.device, &mut buf)?;
36        Ok(u16::from_le_bytes(buf))
37    }
38}