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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! # Rust support for the Raspberry Pi Sense HAT.
//!
//! The [Raspberry Pi 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, a joystick and a
//! gyroscope. See <https://www.raspberrypi.org/products/sense-hat/> for
//! details on the Sense HAT.
//!
//! See <https://github.com/RPi-Distro/python-sense-hat> for the official
//! Python driver. This one tries to follow the same API as the Python
//! version.
//!
//! See <https://github.com/thejpster/pi-workshop-rs/> for some workshop
//! materials which use this driver.
//!
//! ## Supported components:
//!
//! * Humidity and Temperature Sensor (an HTS221)
//! * Pressure and Temperature Sensor (a LPS25H)
//! * Gyroscope (an LSM9DS1, requires the RTIMU library)
//! * LED matrix (partial support for scrolling text only)
//!
//! ## Currently unsupported components:
//!
//! * Joystick
//!
//! ## Example use
//!
//! ```
//! use sensehat::{Colour, SenseHat};
//! if let Ok(mut hat) = SenseHat::new() {
//!     println!("{:?}", hat.get_pressure());
//!     hat.text("Hi!", Colour::RED, Colour::WHITE).unwrap();
//! }
//! ```

extern crate byteorder;
extern crate i2cdev;
extern crate measurements;
#[cfg(feature = "led-matrix")]
extern crate tint;

#[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;

#[cfg(feature = "led-matrix")]
use sensehat_screen::color::PixelColor;

/// 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")]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Colour(PixelColor);

/// A measure of frames per second.
#[cfg(feature = "led-matrix")]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Fps(pub u8);

/// 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 accelerometer 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.
    ///
    /// The `interval` can be a `std::time::Duration` or an `Fps` (frames per
    /// second).
    ///
    /// The `fg` and `bg` values set the foreground and background colours.
    /// You can either specify:
    /// * a constant colour like `Colour::WHITE`,
    /// * a string from the [W3C basic keywords](https://www.w3.org/TR/css-color-3/#html4) like `"white"` or `"purple"`, or
    /// * an RGB 8-bit triple like `(0, 0xFF, 0)`.
    #[cfg(feature = "led-matrix")]
    pub fn show_message<INT, FG, BG>(&mut self, message: &str, interval: INT, fg: FG, bg: BG) -> SenseHatResult<()>
    where
        INT: Into<::std::time::Duration>,
        FG: Into<Colour>,
        BG: Into<Colour>,
    {
        // Calculate our waiting time for each frame
        let wait_time = interval.into();
        // 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.into().0, bg.into().0);
        // Create a `Scroll` from the pixel frame vector.
        let scroll = sensehat_screen::Scroll::new(&pixel_frames);
        // Consume the `FrameSequence` returned by the `right_to_left` method.
        scroll.right_to_left().for_each(|frame| {
            screen.write_frame(&frame.frame_line());
            ::std::thread::sleep(wait_time);
        });
        Ok(())

    }

    /// Displays a scrolling message on the LED matrix. Blocks until the
    /// entire message has scrolled past. Scrolls at a fixed 10 frames per
    /// second.
    ///
    /// The `fg` and `bg` values set the foreground and background colours.
    /// You can either specify:
    /// * a constant colour like `Colour::WHITE`,
    /// * a string from the [W3C basic keywords](https://www.w3.org/TR/css-color-3/#html4) like `"white"` or `"purple"`, or
    /// * an RGB 8-bit triple like `(0, 0xFF, 0)`.
    #[cfg(feature = "led-matrix")]
    pub fn text<FG, BG>(&mut self, message: &str, fg: FG, bg: BG) -> SenseHatResult<()>
    where
        FG: Into<Colour>,
        BG: Into<Colour>,
    {
        self.show_message(message, ::std::time::Duration::from_millis(100), fg, bg)
    }

    /// 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)
    }
}

#[cfg(feature = "led-matrix")]
impl<'a> Into<Colour> for &'a str {
    fn into(self) -> Colour {
        let rgb = tint::Color::name(self).unwrap();
        Colour(rgb.to_rgb255().into())
    }
}

#[cfg(feature = "led-matrix")]
impl<'a> Into<Colour> for (u8, u8, u8) {
    fn into(self) -> Colour {
        Colour(self.into())
    }
}

#[cfg(feature = "led-matrix")]
impl<'a> Into<::std::time::Duration> for Fps {
    fn into(self) -> ::std::time::Duration {
        ::std::time::Duration::new(0, 1_000_000_000 / self.0 as u32)
    }
}

#[cfg(feature = "led-matrix")]
impl Colour {
    pub const WHITE: Colour = Colour(PixelColor::WHITE);
    pub const RED: Colour = Colour(PixelColor::RED);
    pub const GREEN: Colour = Colour(PixelColor::GREEN);
    pub const BLUE: Colour = Colour(PixelColor::BLUE);
    pub const BLACK: Colour = Colour(PixelColor::BLACK);
    pub const YELLOW: Colour = Colour(PixelColor::YELLOW);
    pub const MAGENTA: Colour = Colour(PixelColor::MAGENTA);
    pub const CYAN: Colour = Colour(PixelColor::CYAN);
}

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

    #[cfg(feature = "led-matrix")]
    #[test]
    fn check_colours_string() {
        let colour_str: Colour = "red".into();
        let colour_const: Colour = Colour::RED;
        assert_eq!(colour_str, colour_const);
    }

    #[cfg(feature = "led-matrix")]
    #[test]
    fn check_colours_tuple() {
        let colour_tuple: Colour = (0xFF, 0, 0).into();
        let colour_const: Colour = Colour::RED;
        assert_eq!(colour_tuple, colour_const);
    }
}

// End of file