trellis/
mock.rs

1use super::devices::I2CMasterDevice;
2use std::io::Result;
3
4/// Callback for writes to device.
5/// The first argument is a counter that starts
6/// with 0 and is increment each time the callback
7/// function is called. The counter can be used
8/// to differentiate calls to the function
9/// in tests.
10pub type WriteCb = fn(i32, u8, &[u8]) -> ();
11
12/// A I2CMasterDevice implementation that exists solely for testing.
13/// The MockDevice delegates writes and reades to the supplied
14/// callback functions/data that are used in tests for checking the
15/// correct device communication.
16pub struct MockDevice {
17    write_block_counter: i32,
18    write_block_cb: WriteCb,
19
20    read_block_data: Vec<u8>
21}
22
23impl MockDevice {
24    pub fn new_write_only(write_block_cb: WriteCb) -> MockDevice {
25        return MockDevice::new(write_block_cb, vec![0; 6])
26    }
27
28    pub fn new_read_only(read_block_data: Vec<u8>) -> MockDevice {
29        fn noop(_i:i32, _reg:u8, _vals: &[u8]) {};
30        return MockDevice::new(noop, read_block_data);
31    }
32
33    pub fn new(write_block_cb: WriteCb, read_block_data: Vec<u8>) -> MockDevice {
34        return MockDevice {write_block_cb: write_block_cb,
35                           write_block_counter: 0,
36                           read_block_data: read_block_data};
37    }
38}
39
40impl I2CMasterDevice for MockDevice {
41    fn write_block(&mut self, register: u8, values: &[u8]) -> Result<()> {
42        let cb = self.write_block_cb;
43        cb(self.write_block_counter, register, values);
44        self.write_block_counter += 1;
45        return Ok(());
46    }
47
48    fn read_block(&mut self, _register: u8, _len: u8) -> Result<Vec<u8>> {
49        return Ok(self.read_block_data.clone());
50    }
51}