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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
//! # A driver for the Raspberry Pi Sense HAT
//!
//! The [Sense HAT](https://www.raspberrypi.org/products/sense-hat/) is a
//! sensor board for the Raspberry Pi. It features an LED matrix, a humidity
//! and temperature sensor, a pressure and temperature sensor and a gyroscope.
//!
//! Supported components:
//!
//! * Humidity and Temperature Sensor (an HTS221)
//! * Pressure and Temperature Sensor (a LPS25H)
//! * Gyroscope (an LSM9DS1, requires the RTIMU library)
//!
//! Currently unsupported components:
//!
//! * LED matrix
//! * Joystick

extern crate byteorder;
extern crate i2cdev;
extern crate measurements;

#[cfg(feature = "rtimu")]
extern crate libc;

#[cfg(feature = "led-matrix")]
extern crate sensehat_screen;

mod hts221;
mod lps25h;
mod rh;

pub use measurements::Angle;
pub use measurements::Pressure;
pub use measurements::Temperature;
pub use rh::RelativeHumidity;

use i2cdev::linux::{LinuxI2CDevice, LinuxI2CError};

#[cfg(feature = "rtimu")]
mod lsm9ds1;

#[cfg(not(feature = "rtimu"))]
mod lsm9ds1_dummy;
#[cfg(not(feature = "rtimu"))]
use lsm9ds1_dummy as lsm9ds1;

/// Represents an orientation from the IMU
#[derive(Debug, Copy, Clone)]
pub struct Orientation {
    pub roll: Angle,
    pub pitch: Angle,
    pub yaw: Angle,
}

/// Represents a 3D vector
#[derive(Debug, Copy, Clone)]
pub struct Vector3D {
    pub x: f64,
    pub y: f64,
    pub z: f64,
}

/// Represents an RGB colour
#[cfg(feature = "led-matrix")]
pub use sensehat_screen::color::PixelColor as Colour;

/// A collection of all the data from the IMU
#[derive(Debug, Default)]
struct ImuData {
    timestamp: u64,
    fusion_pose: Option<Orientation>,
    gyro: Option<Vector3D>,
    accel: Option<Vector3D>,
    compass: Option<Vector3D>,
    pressure: Option<f64>,
    temperature: Option<f64>,
    humidity: Option<f64>,
}

/// Represents the Sense HAT itself
pub struct SenseHat<'a> {
    /// LPS25H pressure sensor
    pressure_chip: lps25h::Lps25h<LinuxI2CDevice>,
    /// HTS221 humidity sensor
    humidity_chip: hts221::Hts221<LinuxI2CDevice>,
    /// LSM9DS1 IMU device
    accelerometer_chip: lsm9ds1::Lsm9ds1<'a>,
    /// Cached data
    data: ImuData,
}

/// Errors that this crate can return
#[derive(Debug)]
pub enum SenseHatError {
    NotReady,
    GenericError,
    I2CError(LinuxI2CError),
    LSM9DS1Error(lsm9ds1::Error),
    ScreenError,
    CharacterError(std::string::FromUtf16Error)
}

/// A shortcut for Results that can return `T` or `SenseHatError`
pub type SenseHatResult<T> = Result<T, SenseHatError>;

impl<'a> SenseHat<'a> {
    /// Try and create a new SenseHat object.
    ///
    /// Will open the relevant I2C devices and then attempt to initialise the
    /// chips on the Sense HAT.
    pub fn new() -> SenseHatResult<SenseHat<'a>> {
        Ok(SenseHat {
            humidity_chip: hts221::Hts221::new(LinuxI2CDevice::new("/dev/i2c-1", 0x5f)?)?,
            pressure_chip: lps25h::Lps25h::new(LinuxI2CDevice::new("/dev/i2c-1", 0x5c)?)?,
            accelerometer_chip: lsm9ds1::Lsm9ds1::new()?,
            data: ImuData::default(),
        })
    }

    /// Returns a Temperature reading from the barometer.  It's less accurate
    /// than the barometer (+/- 2 degrees C), but over a wider range.
    pub fn get_temperature_from_pressure(&mut self) -> SenseHatResult<Temperature> {
        let status = self.pressure_chip.status()?;
        if (status & 1) != 0 {
            Ok(Temperature::from_celsius(
                self.pressure_chip.get_temp_celcius()?
            ))
        } else {
            Err(SenseHatError::NotReady)
        }
    }

    /// Returns a Pressure value from the barometer
    pub fn get_pressure(&mut self) -> SenseHatResult<Pressure> {
        let status = self.pressure_chip.status()?;
        if (status & 2) != 0 {
            Ok(Pressure::from_hectopascals(
                self.pressure_chip.get_pressure_hpa()?
            ))
        } else {
            Err(SenseHatError::NotReady)
        }
    }

    /// Returns a Temperature reading from the humidity sensor. It's more
    /// accurate than the barometer (+/- 0.5 degrees C), but over a smaller
    /// range.
    pub fn get_temperature_from_humidity(&mut self) -> SenseHatResult<Temperature> {
        let status = self.humidity_chip.status()?;
        if (status & 1) != 0 {
            let celcius = self.humidity_chip.get_temperature_celcius()?;
            Ok(Temperature::from_celsius(celcius))
        } else {
            Err(SenseHatError::NotReady)
        }
    }

    /// Returns a RelativeHumidity value in percent between 0 and 100
    pub fn get_humidity(&mut self) -> SenseHatResult<RelativeHumidity> {
        let status = self.humidity_chip.status()?;
        if (status & 2) != 0 {
            let percent = self.humidity_chip.get_relative_humidity_percent()?;
            Ok(RelativeHumidity::from_percent(percent))
        } else {
            Err(SenseHatError::NotReady)
        }
    }

    /// Returns a vector representing the current orientation, using all
    /// three sensors.
    pub fn get_orientation(&mut self) -> SenseHatResult<Orientation> {
        self.accelerometer_chip.set_fusion();
        if self.accelerometer_chip.imu_read() {
            self.data = self.accelerometer_chip.get_imu_data()?;
        }
        match self.data.fusion_pose {
            Some(o) => Ok(o),
            None => Err(SenseHatError::NotReady)
        }
    }

    /// Get the compass heading (ignoring gyro and magnetometer)
    pub fn get_compass(&mut self) -> SenseHatResult<Angle> {
        self.accelerometer_chip.set_compass_only();
        if self.accelerometer_chip.imu_read() {
            // Don't cache this data
            let data = self.accelerometer_chip.get_imu_data()?;
            match data.fusion_pose {
                Some(o) => Ok(o.yaw),
                None => Err(SenseHatError::NotReady)
            }
        } else {
            Err(SenseHatError::NotReady)
        }
    }

    /// Returns a vector representing the current orientation using only
    /// the gyroscope.
    pub fn get_gyro(&mut self) -> SenseHatResult<Orientation> {
        self.accelerometer_chip.set_gyro_only();
        if self.accelerometer_chip.imu_read() {
            let data = self.accelerometer_chip.get_imu_data()?;
            match data.fusion_pose {
                Some(o) => Ok(o),
                None => Err(SenseHatError::NotReady)
            }
        } else {
            Err(SenseHatError::NotReady)
        }
    }

    /// Returns a vector representing the current orientation using only
    /// the accelerometer.
    pub fn get_accel(&mut self) -> SenseHatResult<Orientation> {
        self.accelerometer_chip.set_accel_only();
        if self.accelerometer_chip.imu_read() {
            let data = self.accelerometer_chip.get_imu_data()?;
            match data.fusion_pose {
                Some(o) => Ok(o),
                None => Err(SenseHatError::NotReady)
            }
        } else {
            Err(SenseHatError::NotReady)
        }
    }

    /// Returns a vector representing the current acceleration in Gs.
    pub fn get_accel_raw(&mut self) -> SenseHatResult<Vector3D> {
        self.accelerometer_chip.set_accel_only();
        if self.accelerometer_chip.imu_read() {
            self.data = self.accelerometer_chip.get_imu_data()?;
        }
        match self.data.accel {
            Some(a) => Ok(a),
            None => Err(SenseHatError::NotReady)
        }
    }

    /// Displays a scrolling message on the LED matrix.
    ///
    /// Blocks until the entire message has scrolled past.
    #[cfg(feature = "led-matrix")]
    pub fn text(&mut self, message: &str, fg: Colour, bg: Colour) -> SenseHatResult<()> {
        // Connect to our LED Matrix screen.
        let mut screen = sensehat_screen::Screen::open("/dev/fb1").map_err(|_| SenseHatError::ScreenError)?;
        // Get the default `FontCollection`.
        let fonts = sensehat_screen::FontCollection::new();
        // Create a sanitized `FontString`.
        let sanitized = fonts.sanitize_str(message)?;
        // Render the `FontString` as a vector of pixel frames.
        let pixel_frames = sanitized.pixel_frames(fg, bg);
        // Create a `Scroll` from the pixel frame vector.
        let scroll = sensehat_screen::Scroll::new(&pixel_frames);
        // Consume the `FrameSequence` returned by the `left_to_right` method.
        scroll.right_to_left().for_each(|frame| {
            screen.write_frame(&frame.frame_line());
            ::std::thread::sleep(::std::time::Duration::from_millis(100));
        });
        Ok(())
    }

    /// Clears the LED matrix
    #[cfg(feature = "led-matrix")]
    pub fn clear(&mut self) -> SenseHatResult<()> {
        // Connect to our LED Matrix screen.
        let mut screen = sensehat_screen::Screen::open("/dev/fb1").map_err(|_| SenseHatError::ScreenError)?;
        // Send a blank image to clear the screen
        const OFF: [u8; 128] = [0x00; 128];
        screen.write_frame(&sensehat_screen::FrameLine::from_slice(&OFF));
        Ok(())
    }
}

impl From<LinuxI2CError> for SenseHatError {
    fn from(err: LinuxI2CError) -> SenseHatError {
        SenseHatError::I2CError(err)
    }
}

impl From<lsm9ds1::Error> for SenseHatError {
    fn from(err: lsm9ds1::Error) -> SenseHatError {
        SenseHatError::LSM9DS1Error(err)
    }
}

impl From<std::string::FromUtf16Error> for SenseHatError {
    fn from(err: std::string::FromUtf16Error) -> SenseHatError {
        SenseHatError::CharacterError(err)
    }
}


// End of file