-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathlib.rs
374 lines (329 loc) · 11.3 KB
/
lib.rs
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
//! # 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;
extern crate sensehat_screen;
mod rh;
mod hts221;
mod lps25h;
pub use measurements::Temperature;
pub use measurements::Pressure;
pub use measurements::Angle;
pub use rh::RelativeHumidity;
pub use sensehat_screen::{FrameLine, PixelFrame, PixelColor, Rotate, Screen};
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;
pub const LED_HEIGHT: u8 = 8;
pub const LED_WIDTH: u8 = 8;
pub const LED_NUM_PIXELS: usize = LED_HEIGHT as usize * LED_WIDTH as usize;
/// Represents a specific pixel position on the LED
#[derive(Debug, Copy, Clone)]
pub struct PixelPosition {
x: u8,
y: u8
}
/// How to rotate the image on the LED display
#[derive(Debug, Copy, Clone)]
pub enum Rotation {
/// Don't rotate image - top is near GPIO pins
Normal,
/// Rotate image 90 degrees clockwise - top is near USB ports
Clockwise90,
/// Rotate image 180 degrees clockwise - top is near HDMI port
Clockwise180,
/// Rotate image 270 degrees clockwise - top is near micro SD card
Clockwise270
}
/// Represents an orientation from the IMU
#[derive(Debug, Copy, Clone)]
pub struct Orientation {
pub roll: Angle,
pub pitch: Angle,
pub yaw: Angle,
}
/// 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
orientation: Orientation,
/// LED matrix rotation
rotation: Rotation,
/// Current LED contents
image: Image,
/// Handle to the framebuffer
screen: Screen
}
/// Errors that this crate can return
#[derive(Debug)]
pub enum SenseHatError {
NotReady,
GenericError,
PositionOutOfBounds,
I2CError(LinuxI2CError),
LSM9DS1Error(lsm9ds1::Error),
FramebufferError(sensehat_screen::framebuffer::FramebufferError)
}
/// An image on the LED matrix
#[derive(Copy, Clone, Debug)]
pub struct Image(PixelFrame);
/// A shortcut for Results that can return `T` or `SenseHatError`
pub type SenseHatResult<T> = Result<T, SenseHatError>;
/// Draw mode
#[derive(Debug, Copy, Clone)]
pub enum DrawMode {
/// Write this change to the display now
OutputNow,
/// Buffer this change internally
BufferInternally
}
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()?,
orientation: Orientation {
roll: Angle::from_degrees(0.0),
pitch: Angle::from_degrees(0.0),
yaw: Angle::from_degrees(0.0),
},
rotation: Rotation::Normal,
image: Image(PixelFrame::BLUE),
screen: Screen::open("/dev/fb1")?
})
}
/// 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.orientation = self.accelerometer_chip.get_imu_data()?;
}
Ok(self.orientation)
}
/// 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 orientation = self.accelerometer_chip.get_imu_data()?;
Ok(orientation.yaw)
} 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 orientation = self.accelerometer_chip.get_imu_data()?;
Ok(orientation)
} 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 orientation = self.accelerometer_chip.get_imu_data()?;
Ok(orientation)
} else {
Err(SenseHatError::NotReady)
}
}
/// Set the LED matrix rotation
pub fn set_rotation(&mut self, rotation: Rotation, redraw: DrawMode) {
self.rotation = rotation;
self.image.rotate_mut(rotation);
match redraw {
DrawMode::OutputNow => self.redraw(),
_ => {}
}
}
/// Get the current LED matrix rotation
pub fn get_rotation(&self) -> Rotation {
self.rotation
}
/// Set the whole bufferd image.
pub fn set_pixels(&mut self, image: Image) -> SenseHatResult<()> {
self.image = image;
self.redraw();
Ok(())
}
/// Get the whole buffered image.
pub fn get_pixels(&self) -> Image {
return self.image.clone()
}
/// Set the colour of a single pixel.
pub fn set_pixel(&mut self, position: PixelPosition, color: PixelColor, redraw: DrawMode) -> SenseHatResult<()> {
if position.valid() {
self.image.0[position.pixel()] = color;
match redraw {
DrawMode::OutputNow => self.redraw(),
_ => {}
}
Ok(())
} else {
Err(SenseHatError::PositionOutOfBounds)
}
}
/// Get the colour of a single pixel.
pub fn get_pixel(&mut self, position: PixelPosition) -> SenseHatResult<PixelColor> {
if position.valid() {
Ok(self.image.0[position.pixel()])
} else {
Err(SenseHatError::PositionOutOfBounds)
}
}
/// Scroll a message across the screen. Blocks until completion.
pub fn show_message(&mut self, message: &str, speed: f32, text: PixelColor, background: PixelColor) -> SenseHatResult<()> {
println!("Would should show {:?} at {} seconds/frame in {:?}/{:?}", message, speed, text, background);
Ok(())
}
/// Write a single character to the screen
pub fn show_letter(&mut self, letter: char, text: PixelColor, background: PixelColor) -> SenseHatResult<()> {
println!("Would should show {:?} in {:?}/{:?}", letter, text, background);
Ok(())
}
/// Clear the display
pub fn clear(&mut self, color: PixelColor, redraw: DrawMode) -> SenseHatResult<()> {
self.image = Image([color; LED_NUM_PIXELS].into());
match redraw {
DrawMode::OutputNow => self.redraw(),
_ => {}
}
Ok(())
}
pub fn redraw(&mut self) {
let image = self.image.rotate_copy(self.rotation);
let frame = image.0.frame_line();
self.screen.write_frame(&frame);
}
}
impl PixelPosition {
fn valid(&self) -> bool {
(self.x < LED_WIDTH) && (self.y < LED_HEIGHT)
}
fn pixel(&self) -> usize {
usize::from(self.x) + (usize::from(self.y) * usize::from(LED_HEIGHT))
}
}
impl Image {
fn rotate_mut(&mut self, rotation: Rotation) {
match rotation {
Rotation::Normal => {},
Rotation::Clockwise90 => {
self.0.rotate(Rotate::Ccw270);
}
Rotation::Clockwise180 => {
self.0.rotate(Rotate::Ccw180);
}
Rotation::Clockwise270 => {
self.0.rotate(Rotate::Ccw90);
}
}
}
pub fn rotate_copy(&self, rotation: Rotation) -> Image {
let mut im = *self;
im.rotate_mut(rotation);
im
}
}
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<sensehat_screen::framebuffer::FramebufferError> for SenseHatError {
fn from(err: sensehat_screen::framebuffer::FramebufferError) -> SenseHatError {
SenseHatError::FramebufferError(err)
}
}
impl From<[PixelColor; LED_NUM_PIXELS]> for Image {
fn from(array: [PixelColor; 64]) -> Self {
Image(array.into())
}
}
// End of file