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
/* sevenseg.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! A seven-segment display graphics primitive

// Imports ===================================================================
use core::cell::RefCell;
use avr_oxide::util::datatypes::{BitField, BitFieldAccess, BitIndex};
use avrox_display::gfx::{Renderable, RenderPlane, XCoord, Point, YCoord, Area};
use avrox_display::{GfxError, GfxResult};
use avrox_display::gfx::dynamic::{OptionalDisplayAs};
use avr_oxide::OxideResult::{Err,Ok};

// Declarations ==============================================================
/// A seven-segment display primitive, that is able to render any of the
/// hex digits from 0 to F.
///
/// This simple primitive allows us to render basic messages on a display
/// without the overhead of needing fonts/bitmaps loaded.  Useful in a
/// low-memory device.
#[derive(Clone,Copy)]
pub struct SevenSegmentHexDigit<PIX>
where
  PIX: Clone
{
  value: Option<u8>,
  on_colour: PIX,
  off_colour: PIX
}

pub struct SevenSegmentDisplay<const DIGITS: usize,const RADIX: u8,PIX,VALUE>
where
  PIX: Clone,
  VALUE: OptionalDisplayAs<u32> + Clone
{
  value: VALUE,
  digit_renderer: RefCell<SevenSegmentHexDigit<PIX>>
}

// The segments to enable/disable for each character we are able to
// display.  We can display any of the hex digits from 0 to F
//
//   aaaaa
//  f     b
//  f     b
//   ggggg
//  e     c
//  e     c
//   ddddd  dp
//
static SEGMENT_MAP : [BitField; 16] = [
  BitField::with_initial(0b00111111), // 0
  BitField::with_initial(0b00000110), // 1
  BitField::with_initial(0b01011011), // 2
  BitField::with_initial(0b01001111), // 3
  BitField::with_initial(0b01100110), // 4
  BitField::with_initial(0b01101101), // 5
  BitField::with_initial(0b01111101), // 6
  BitField::with_initial(0b00000111), // 7
  BitField::with_initial(0b01111111), // 8
  BitField::with_initial(0b01101111), // 9
  BitField::with_initial(0b01011111), // a
  BitField::with_initial(0b01111100), // b
  BitField::with_initial(0b00111001), // c
  BitField::with_initial(0b01011110), // d
  BitField::with_initial(0b01111001), // e
  BitField::with_initial(0b01110001), // f
];
const SEG_A  : BitIndex = BitIndex::bit_c(0);
const SEG_B  : BitIndex = BitIndex::bit_c(1);
const SEG_C  : BitIndex = BitIndex::bit_c(2);
const SEG_D  : BitIndex = BitIndex::bit_c(3);
const SEG_E  : BitIndex = BitIndex::bit_c(4);
const SEG_F  : BitIndex = BitIndex::bit_c(5);
const SEG_G  : BitIndex = BitIndex::bit_c(6);
const SEG_DP : BitIndex = BitIndex::bit_c(7);


// Code ======================================================================
impl<PIX: Clone> SevenSegmentHexDigit<PIX> {
  pub const WIDTH:  XCoord = 6;
  pub const HEIGHT: YCoord = 7;

  pub fn new(on_colour: PIX, off_colour: PIX) -> Self {
    SevenSegmentHexDigit {
      value: None,
      on_colour: on_colour,
      off_colour: off_colour
    }
  }

  pub fn new_digit(on_colour: PIX, off_colour: PIX, digit: u8) -> Self {
    SevenSegmentHexDigit {
      value: Some(digit & 0x0f),
      on_colour: on_colour,
      off_colour: off_colour
    }
  }

  pub fn get_digit(&self) -> Option<u8> {
    self.value
  }
  pub fn set_digit(&mut self, digit: u8){
    self.value = Some(digit & 0x0f)
  }
  pub fn set_digit_o(&mut self, digit: Option<u8>){
    self.value = digit
  }
  pub fn clr_digit(&mut self){
    self.value = None
  }

  /// Determine which segment a given pixel falls on
  const fn segment_for_pixel(coord: Point) -> Option<BitIndex> {
    match ( coord.1, coord.0 ) { // Note - back to front, the match is more readable if row-by-row
      (6, 5) => Some(SEG_DP), // The decimal point

      (0, 1) |
      (0, 2) |
      (0, 3) => Some(SEG_A),

      (3, 0) | // We extend F down into G's row
      (1, 0) |
      (2, 0) => Some(SEG_F),

      (1, 4) |
      (2, 4) => Some(SEG_B),

      (3, 1) |
      (3, 2) |
      (3, 3) => Some(SEG_G),

      (4, 0) |
      (5, 0) => Some(SEG_E),

      (3, 4) | // We extend C up into G's row
      (4, 4) |
      (5, 4) => Some(SEG_C),

      (6, 1) |
      (6, 2) |
      (6, 3) => Some(SEG_D),

      _ => None // Everything else is unknown/background
    }
  }
}

impl<PIX> Renderable for SevenSegmentHexDigit<PIX>
where
  PIX: Clone
{
  type PIXEL = PIX;

  fn get_pixel_at<P: RenderPlane>(&self, coord: Point) -> GfxResult<Self::PIXEL> {
    match (self.value, Self::segment_for_pixel(coord)) {
      (None,Some(_segment)) => Ok(self.off_colour.clone()),
      (Some(digit),Some(segment)) => {
        if SEGMENT_MAP[digit as usize].is_set(segment) {
          Ok(self.on_colour.clone())
        } else {
          Ok(self.off_colour.clone())
        }
      },
      _ => Err(GfxError::OutOfBounds)
    }
  }

  fn get_dimensions<P: RenderPlane>(&self) -> GfxResult<(XCoord, YCoord)> {
    Ok((Self::WIDTH, Self::HEIGHT))
  }
}

impl<const DIGITS: usize,const RADIX: u8,PIX,VALUE> SevenSegmentDisplay<DIGITS,RADIX,PIX,VALUE>
where
  PIX: Clone,
  VALUE: OptionalDisplayAs<u32> + Clone
{
  pub const WIDTH:  XCoord = SevenSegmentHexDigit::<PIX>::WIDTH * DIGITS as u16;
  pub const HEIGHT: XCoord = SevenSegmentHexDigit::<PIX>::HEIGHT;
  pub const CHAR_WIDTH:  XCoord = SevenSegmentHexDigit::<PIX>::WIDTH;
  pub const CHAR_HEIGHT: XCoord = SevenSegmentHexDigit::<PIX>::HEIGHT;


  pub fn new(on_colour: PIX, off_colour: PIX, value: VALUE) -> Self {
    SevenSegmentDisplay {
      value: value,
      digit_renderer: RefCell::new(SevenSegmentHexDigit::new(on_colour,off_colour))
    }
  }

  pub fn set_value(&mut self, value: VALUE){
    self.value = value
  }
}

impl<const DIGITS: usize,const RADIX: u8,PIX,VALUE> Renderable for SevenSegmentDisplay<DIGITS,RADIX,PIX,VALUE>
where
  PIX: Clone,
  VALUE: OptionalDisplayAs<u32> + Clone
{
  type PIXEL = PIX;

  fn get_pixel_at<P: RenderPlane>(&self, coord: Point) -> GfxResult<Self::PIXEL> {
    let mut renderer = self.digit_renderer.borrow_mut();

    if self.value.is_displayed() {
      // Which digit is this coord?
      let digit_pos = (coord.0 / Self::CHAR_WIDTH) as usize;
      if digit_pos < DIGITS {
        let digit_lsf_pos = DIGITS - digit_pos - 1; // Count from least-significant

        let value : u32 = self.value.display_value();

        let scale = (RADIX as u32).pow(digit_lsf_pos as u32);
        let digit = (if scale > 0 { value / scale } else { value }) % RADIX as u32;

        renderer.set_digit((digit as u8) & 0x0f);
        renderer.get_pixel_at::<P>(Point(coord.0 % Self::CHAR_WIDTH, coord.1))
      } else {
        Err(GfxError::OutOfBounds)
      }
    } else {
      Err(GfxError::OutOfBounds)
    }
  }

  fn get_dimensions<P: RenderPlane>(&self) -> GfxResult<(XCoord, YCoord)> {
    Ok((Self::CHAR_WIDTH * DIGITS as XCoord, Self::CHAR_HEIGHT))
  }

  fn has_changes<P: RenderPlane>(&self) -> bool {
    self.value.is_mutable()
  }

  fn get_change_area<P: RenderPlane>(&self) -> GfxResult<Option<Area>> {
    #[cfg(test)]
    println!("SevenSegmentDisplay get_change_area");

    if self.value.is_mutable() {
      #[cfg(test)]
      println!("Volatile value");

      let dims = self.get_dimensions::<P>()?;

      #[cfg(test)]
      println!("  SSD Dims = {:?}", dims);

      Ok(Some(Area {
        tl: Point(0,0),
        w: dims.0,
        h: dims.1
      }))
    } else {
      #[cfg(test)]
      println!("Non-Volatile value");

      Ok(None)
    }
  }
}



// Tests =====================================================================
#[cfg(test)]
mod tests {
  use core::cell::RefCell;
  use avrox_display::gfx::fills::SolidFill;
  use avrox_display::gfx::pixels::Monochromatic;
  use avrox_display::gfx::primitives::{Overlay, Rectangle};
  use avrox_display::gfx::sevenseg::{SevenSegmentDisplay, SevenSegmentHexDigit};
  use avrox_display::gfx::test::MonochromeTestRenderer;

  #[test]
  fn test_7seg_digit() {
    let renderer = MonochromeTestRenderer::new();

    for d in 0x00u8..=0x0fu8 {
      let scene =
        Overlay::new(
          SevenSegmentHexDigit::new_digit(Monochromatic::WHITE,
                                          Monochromatic::BLACK,
                                          d),
          SolidFill::new(Monochromatic::BLACK));

      renderer.render_scene(&scene);
    }
  }

  #[test]
  fn test_7seg_display() {
    let renderer = MonochromeTestRenderer::new();

    let mut display = SevenSegmentDisplay::<6,10,_,_>::new(Monochromatic::WHITE, Monochromatic::BLACK, Some(1234u32));
    let scene = Overlay::new(
      display,
      SolidFill::new(Monochromatic::BLACK));

    renderer.render_scene(&scene);

    let mut display = SevenSegmentDisplay::<6,16,_,_>::new(Monochromatic::WHITE, Monochromatic::BLACK, Some(1234u32));
    let scene = Overlay::new(
      display,
      SolidFill::new(Monochromatic::BLACK));

    renderer.render_scene(&scene);

    let mut display = SevenSegmentDisplay::<6,2,_,_>::new(Monochromatic::WHITE, Monochromatic::BLACK, Some(1234u32));
    let scene = Overlay::new(
      display,
      SolidFill::new(Monochromatic::BLACK));

    renderer.render_scene(&scene);
  }

  #[test]
  fn test_7seg_dynamic_data() {
    let renderer = MonochromeTestRenderer::new();

    let value = RefCell::new(Some(123u32));

    let display = SevenSegmentDisplay::<8,10,_,_>::new(Monochromatic::WHITE, Monochromatic::BLACK, &value);
    let scene = Overlay::new(
      display,
      SolidFill::new(Monochromatic::BLACK));

    renderer.render_scene(&scene);

    *value.borrow_mut() = Some(80081355);

    renderer.render_scene(&scene);

    *value.borrow_mut() = None;

    renderer.render_scene(&scene);
  }
}