Skip to main content

trellis/
devices.rs

1extern crate i2cdev;
2
3use self::i2cdev::core::I2CDevice;
4use self::i2cdev::linux::LinuxI2CDevice;
5use self::i2cdev::linux::LinuxI2CError;
6use std::io::Result;
7use std::io;
8use std::result;
9
10/// Host devices that are connected to the Trellis. The Trellis is the slave.
11/// This trate is a small abstraction over the full I2C
12/// since we need only a very small subset.
13/// This trate exists also to make the I2C communciation testable (see also MockDevice
14/// that implements this trait).
15pub trait I2CMasterDevice {
16    fn write_block(&mut self, register: u8, values: &[u8]) -> Result<()>;
17    fn read_block(&mut self, register: u8, len: u8) -> Result<Vec<u8>>;
18}
19
20
21/// A concrete device for using the Trellis
22/// with a Raspberry Pi 2 B+.
23pub struct RaspberryPiBPlus {
24    i2c_device : LinuxI2CDevice,
25}
26
27impl RaspberryPiBPlus {
28    pub fn new() -> RaspberryPiBPlus {
29        let i2cdev = LinuxI2CDevice::new("/dev/i2c-1", 0x70).unwrap();
30        return RaspberryPiBPlus {i2c_device: i2cdev};
31    }
32}
33
34impl I2CMasterDevice for RaspberryPiBPlus {
35    fn write_block(&mut self, register: u8, values: &[u8]) -> Result<()> {
36        let result = self.i2c_device.smbus_process_block(register, values);
37        return convert_to_io_error(result);
38    }
39
40    fn read_block(&mut self, register: u8, len: u8) -> Result<Vec<u8>> {
41        let result = self.i2c_device.smbus_read_i2c_block_data(register, len);
42        return convert_to_io_error(result);
43    }
44}
45
46// END Raspberry Pi B+
47
48fn convert_to_io_error<T>(result: result::Result<T, LinuxI2CError>) -> Result<T> {
49    match result {
50        Ok(o) => Ok(o),
51        Err(e) => Err(io::Error::from(e))
52    }
53}