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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
extern crate embedded_hal as hal;

use std::io::{self, Read};

const WRITE_BUF_SIZE: usize = 64;

#[derive(Debug)]
pub enum MockError {
    Io(io::Error),
}

impl From<io::Error> for MockError {
    fn from(e: io::Error) -> Self {
        MockError::Io(e)
    }
}

pub struct I2cMock<'a> {
    data: &'a [u8],
    address: Option<u8>,
    buf: [u8; WRITE_BUF_SIZE],
    buf_bytes_written: usize,
}

impl<'a> I2cMock<'a> {
    pub fn new() -> Self {
        I2cMock {
            data: &[],
            address: None,
            buf: [0; WRITE_BUF_SIZE],
            buf_bytes_written: 0,
        }
    }

    /// Set data that will be read by `read()`.
    pub fn set_read_data(&mut self, data: &'a [u8]) {
        self.data = data;
    }

    /// Return the data that was written by the last write command.
    pub fn get_write_data(&self) -> &[u8] {
        &self.buf[0..self.buf_bytes_written]
    }

    /// Return the address that was used by the last read or write command.
    pub fn get_last_address(&self) -> Option<u8> {
        self.address
    }
}

impl<'a> hal::blocking::i2c::Read for I2cMock<'a> {
    type Error = MockError;

    fn read(&mut self, address: u8, mut buffer: &mut [u8]) -> Result<(), Self::Error> {
        self.address = Some(address);
        self.data.read(&mut buffer)?;
        Ok(())
    }
}

impl<'a> hal::blocking::i2c::Write for I2cMock<'a> {
    type Error = MockError;

    fn write(&mut self, address: u8, bytes: &[u8]) -> Result<(), Self::Error> {
        if bytes.len() > WRITE_BUF_SIZE {
            panic!("Write buffer is too small for this number of bytes ({} > {})",
                   bytes.len(), WRITE_BUF_SIZE);
        }
        self.address = Some(address);
        self.buf[0..bytes.len()].copy_from_slice(bytes);
        self.buf_bytes_written = bytes.len();
        Ok(())
    }
}

impl<'a> hal::blocking::i2c::WriteRead for I2cMock<'a> {
    type Error = MockError;

    fn write_read(
        &mut self,
        address: u8,
        bytes: &[u8],
        mut buffer: &mut [u8],
    ) -> Result<(), Self::Error> {
        if bytes.len() > WRITE_BUF_SIZE {
            panic!("Write buffer is too small for this number of bytes ({} > {})",
                   bytes.len(), WRITE_BUF_SIZE);
        }
        self.address = Some(address);
        self.data.read(&mut buffer)?;
        self.buf[0..bytes.len()].copy_from_slice(bytes);
        self.buf_bytes_written = bytes.len();
        Ok(())
    }
}

pub struct DelayMockNoop;

macro_rules! impl_delay_us {
    ($type:ty) => {
        impl hal::blocking::delay::DelayUs<$type> for DelayMockNoop {
            /// A no-op delay implementation.
            fn delay_us(&mut self, _n: $type) { }
        }
    }
}

impl_delay_us!(u8);
impl_delay_us!(u16);
impl_delay_us!(u32);
impl_delay_us!(u64);

macro_rules! impl_delay_ms {
    ($type:ty) => {
        impl hal::blocking::delay::DelayMs<$type> for DelayMockNoop {
            /// A no-op delay implementation.
            fn delay_ms(&mut self, _n: $type) { }
        }
    }
}

impl_delay_ms!(u8);
impl_delay_ms!(u16);
impl_delay_ms!(u32);
impl_delay_ms!(u64);

#[cfg(test)]
mod tests {
    use super::*;

    use hal::blocking::i2c::{Read, Write, WriteRead};

    #[test]
    fn i2c_read_no_data_set() {
        let mut i2c = I2cMock::new();
        let mut buf = [0; 3];
        i2c.read(0, &mut buf).unwrap();
        assert_eq!(buf, [0; 3]);
    }

    #[test]
    fn i2c_read_some_data_set() {
        let mut i2c = I2cMock::new();
        let mut buf = [0; 3];
        i2c.set_read_data(&[1, 2]);
        i2c.read(0, &mut buf).unwrap();
        assert_eq!(buf, [1, 2, 0]);
    }

    #[test]
    fn i2c_read_too_much_data_set() {
        let mut i2c = I2cMock::new();
        let mut buf = [0; 3];
        i2c.set_read_data(&[1, 2, 3, 4]);
        i2c.read(0, &mut buf).unwrap();
        assert_eq!(buf, [1, 2, 3]);
    }

    #[test]
    fn i2c_write_data() {
        let mut i2c = I2cMock::new();
        let buf = [1, 2, 4];
        assert_eq!(i2c.get_last_address(), None);
        i2c.write(42, &buf[..]).unwrap();
        assert_eq!(i2c.get_last_address(), Some(42));
        assert_eq!(i2c.get_write_data(), &[1, 2, 4]);
        i2c.write(23, &buf[1..2]).unwrap();
        assert_eq!(i2c.get_last_address(), Some(23));
        assert_eq!(i2c.get_write_data(), &[2]);
    }

    #[test]
    #[should_panic]
    fn i2c_write_data_too_much() {
        let mut i2c = I2cMock::new();
        let buf = [0; 65];
        i2c.write(42, &buf[..]).unwrap();
    }

    #[test]
    fn i2c_read_write_data() {
        let mut i2c = I2cMock::new();
        let buf = [1, 2, 4];
        let mut buf2 = [0; 3];
        assert_eq!(i2c.get_last_address(), None);
        i2c.write_read(42, &buf[..], &mut buf2).unwrap();
        assert_eq!(i2c.get_last_address(), Some(42));
        assert_eq!(i2c.get_write_data(), &[1, 2, 4]);
    }
}