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
use crate::enums::{JrkG2Command, VarOffset};
use crate::jrk::JrkG2;
use embedded_hal::blocking::i2c;

/// Implement the JrkG2 trait for I2C
pub struct JrkG2I2c<I2c> {
    device: u8,
    i2c: I2c,
}

impl<I2c, I2cError> JrkG2I2c<I2c>
where
    I2c: i2c::Write<Error = I2cError> + i2c::Read<Error = I2cError>,
{
    pub fn new(i2c: I2c) -> Self {
        JrkG2I2c { device: 0x0B, i2c }
    }
    /// The controller have a default 0x0B I2C address, but this can be manually changed in the
    /// configuration utility.
    pub fn set_device(&mut self, device: u8) {
        self.device = device;
    }
}

impl<I2c, I2cError> JrkG2<I2cError> for JrkG2I2c<I2c>
where
    I2c: i2c::Write<Error = I2cError> + i2c::Read<Error = I2cError>,
{
    const HEADER: &'static str = "Reading Jrk state from I2C:\n";

    fn write(&mut self, data: &[u8]) -> Result<(), I2cError> {
        self.i2c.write(self.device, &data)
    }
    fn read(&mut self, cmd: VarOffset) -> Result<u16, I2cError> {
        let mut buf: [u8; 2] = [0, 0];
        self.write(&[JrkG2Command::GetVariable16 as u8 | (cmd as u8 + 1)])?;
        self.i2c.read(self.device, &mut buf)?;
        Ok(buf[0] as u16 + buf[1] as u16 * 256)
    }
}