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
//! A Rust library for the Raspberry Pi Sense HAT LED Screen
//! ========================================================
//!
//! The [Raspberry Pi Sense HAT](https://www.raspberrypi.org/products/sense-hat/) has an 8×8 RGB LED matrix that provides its own driver for the Linux framebuffer.
//!
//! This library provides a thread-safe, strong-typed, high-level API for the LED matrix, treating
//! it as you would any other screen on a Linux box.
//!
//!
//! # Example
//!
//! The following program shows how to:
//!
//! * Open the framebuffer file-descriptor for the LED matrix screen (`screen`)
//! * Define a pixel color (`red_pixel`)
//! * Define a vector of each pixel color that makes up the screen (`all_64_pixels`)
//! * Turn that vector into a valid screen frame
//! * Show the frame on the screen
//!
//! ```norun
//! extern crate sensehat_screen;
//!
//! use sensehat_screen::{FrameLine, PixelColor, Screen};
//!
//! fn main() {
//!     let mut screen = Screen::open("/dev/fb1").expect("Could not open the framebuffer for the screen");
//!
//!     let red_pixel = PixelColor::new(255, 0, 0); // rgb colors are in the range of 0 <= c < 256.
//!
//!     let all_64_pixels = vec![&red_pixel; 64];   // A single vector of 8 x 8 = 64 pixel colors (rows are grouped by chunks of 8)
//!
//!     let all_red_screen = FrameLine::from_pixels(&all_64_pixels); // a screen frame
//!
//!     screen.write_frame(&all_red_screen); // show the frame on the LED matrix
//! }
//! ```
//!
//!
//! # Features
//!
//! `default`
//! ---------
//! By default, the `linux-framebuffer`, `fonts`, and `serde-support` features are included.
//!
//! `linux-framebuffer`
//! -------------------
//! Use the Linux framebuffer to write to the LED matrix.
//!
//! `fonts`
//! -------
//! A collection of legacy 8x8 fonts, renderable on the LED matrix.
//!
//! `serde-support`
//! ---------------
//! Enables support for serialization/deserialization with `serde`.
//!
#[cfg(feature = "fonts")]
extern crate font8x8;
#[cfg(feature = "linux-framebuffer")]
extern crate framebuffer;
extern crate glob;
#[cfg(feature = "serde-support")]
extern crate serde;
#[cfg(feature = "serde-support")]
#[macro_use]
extern crate serde_derive;

// 8x8 fonts
#[cfg(feature = "fonts")]
mod fonts;

#[cfg(feature = "linux-framebuffer")]
use framebuffer::{Framebuffer, FramebufferError};

#[cfg(feature = "fonts")]
pub use self::fonts::*;

const LED_OFF: PixelColor = PixelColor {
    red: 0,
    green: 0,
    blue: 0,
};

/// A single LED pixel color, with RGB565 rendering.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
pub struct PixelColor {
    red: u8,
    green: u8,
    blue: u8,
}

impl PixelColor {
    /// Create a new LED pixel color.
    pub fn new(red: u8, green: u8, blue: u8) -> Self {
        Self { red, green, blue }
    }

    /// Create a new LED pixel color from a pair of RGB565-encoded bytes.
    pub fn from_rgb565(color: [u8; 2]) -> Self {
        let red = ((color[1] >> 3) & 0x1F) << 3;
        let green = (color[1] & 0b0000_0111) << 5 | (color[0] & 0b1110_0000) >> 3;
        let blue = (color[0] & 0b0001_1111) << 3;
        PixelColor::new(red, green, blue)
    }

    /// Encodes the current LED pixel color into a pair of RGB565-encoded bytes.
    pub fn rgb565(&self) -> [u8; 2] {
        let r = u16::from((self.red >> 3) & 0x1F);
        let g = u16::from((self.green >> 2) & 0x3F);
        let b = u16::from((self.blue >> 3) & 0x1F);
        let rgb = (r << 11) + (g << 5) + b;
        let lsb = (rgb & 0x00FF) as u8;
        let msb = (rgb.swap_bytes() & 0x00FF) as u8;
        [lsb, msb]
    }
}

/// A single frame on the screen.
/// Defaults to an inner capacity for 128 bytes, suitable for the 8x8 pixel screen.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
pub struct FrameLine(Vec<u8>);

impl FrameLine {
    //  Defaults to an empty vector with capacity for 128 bytes.
    fn new() -> Self {
        FrameLine(Vec::with_capacity(128))
    }

    /// Create a new `FrameLine` instance, given a slice of bytes.
    pub fn from_slice(bytes: &[u8]) -> Self {
        FrameLine(bytes.to_vec())
    }

    /// Create a new `FrameLine` instance, given a slice of `&PixelColor`.
    pub fn from_pixels(pixels: &[&PixelColor]) -> Self {
        pixels
            .iter()
            .fold(FrameLine::new(), |frame, px| frame.extend(px))
    }

    // Extend the inner vector of bytes by one `PixelColor`. This method
    // consumes the current `FrameLine` instance and returns a new one,
    // useful for using with `Iterator::fold`.
    fn extend(mut self, pixel: &PixelColor) -> Self {
        self.0.extend_from_slice(&pixel.rgb565());
        self
    }

    /// Returns the `FrameLine` as a slice of bytes.
    pub fn as_slice(&self) -> &[u8] {
        self.0.as_slice()
    }
}

impl Default for FrameLine {
    fn default() -> Self {
        FrameLine::new()
    }
}

#[cfg(feature = "linux-framebuffer")]
/// Framebuffered 8x8 LED screen.
#[derive(Debug)]
pub struct Screen {
    framebuffer: Framebuffer,
}

#[cfg(feature = "linux-framebuffer")]
impl Screen {
    /// Open the framebuffer to the screen at the given file-system path.
    pub fn open(path: &str) -> Result<Self, FramebufferError> {
        let framebuffer = Framebuffer::new(path)?;
        Ok(Screen { framebuffer })
    }

    /// Write the contents of a `FrameLine` into the framebuffer. This will
    /// render the frameline on the screen.
    pub fn write_frame(&mut self, frame: &FrameLine) {
        self.framebuffer.write_frame(frame.as_slice());
    }
}

/// Render a font symbol with a `PixelColor` into a `FrameLine`.
#[cfg(feature = "fonts")]
pub fn font_to_frame(symbol: &[u8; 8], color: &PixelColor) -> FrameLine {
    let pixels: Vec<&PixelColor> = symbol.iter().fold(Vec::new(), |mut px, x| {
        for bit in 0..8 {
            match *x & 1 << bit {
                0 => px.push(&LED_OFF),
                _ => px.push(color),
            }
        }
        px
    });
    FrameLine::from_pixels(&pixels)
}

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

    #[test]
    fn color_pixel_encodes_rgb_into_2_bytes_rgb565_with_losses() {
        // black 5-bit, 6-bit, 5-bit resolution
        assert_eq!(
            PixelColor::from_rgb565([0x00, 0x00]),
            PixelColor::new(0x00, 0x00, 0x00)
        );
        // white 5-bit, 6-bit, 5-bit resolution
        assert_eq!(
            PixelColor::from_rgb565([0xFF, 0xFF]),
            PixelColor::new(0xF8, 0xFC, 0xF8)
        );
        // 100% green - 6-bit resolution
        assert_eq!(
            PixelColor::from_rgb565([0xE0, 0x07]),
            PixelColor::new(0x00, 0xFC, 0x00)
        );
    }

    // TODO: x86 linux stores `WORDS` as little-endian, meaning the low-byte is
    // sent before the high-byte. Change dealing with [u8; 2] and replace with a
    // single u16.
    #[test]
    fn color_pixel_converts_rgb_into_2_bytes_rgb565() {
        let white_pixel = PixelColor::new(0xFF, 0xFF, 0xFF);
        assert_eq!(white_pixel.rgb565(), [0xFF, 0xFF]);

        let red_pixel = PixelColor::new(0xFF, 0x00, 0x00);
        assert_eq!(red_pixel.rgb565(), [0x00, 0xF8]);

        let green_pixel = PixelColor::new(0x00, 0xFF, 0x00);
        assert_eq!(green_pixel.rgb565(), [0xE0, 0x07]);

        let blue_pixel = PixelColor::new(0x00, 0x00, 0xFF);
        assert_eq!(blue_pixel.rgb565(), [0x1F, 0x00]);
    }

    #[test]
    fn frame_line_is_created_from_slice_of_bytes() {
        let green: [u8; 8] = [0xE0, 0x07, 0xE0, 0x07, 0xE0, 0x07, 0xE0, 0x07];
        let frame_line = FrameLine::from_slice(&green);
        assert_eq!(frame_line.as_slice(), &green);
    }

    #[test]
    fn frame_line_is_created_from_slice_of_pixel_color_reference() {
        let blue = PixelColor::from_rgb565([0x1F, 0x00]);
        let frame_line = FrameLine::from_pixels(&[&blue, &blue]);
        assert_eq!(frame_line.as_slice(), &[0x1F, 0x00, 0x1F, 0x00]);
    }
}