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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#![no_std]

//! Driver crate for the 3642BS 4 digit 7 segment display
//!
//! [[Datasheet link]](http://www.xlitx.com/datasheet/3641BS.pdf)
//!
//! # How to use
//!
//! Create a new display object by calling [`.new()`](struct.Display.html#method.new) and passing
//! the GPIO pins the display is connected to. It is necessary for your HAL to use [`embedded_hal::digital::v2::OutputPin`](https://docs.rs/embedded-hal/latest/embedded_hal/digital/v2/trait.OutputPin.html)
//!
//! ```
//! let mut display = SevenSeg::new(
//! pins.gpio16.into_push_pull_output(), // Segment A
//! pins.gpio17.into_push_pull_output(), // Segment B
//! pins.gpio18.into_push_pull_output(), // Segment C
//! pins.gpio19.into_push_pull_output(), // Segment D
//! pins.gpio20.into_push_pull_output(), // Segment E
//! pins.gpio21.into_push_pull_output(), // Segment F
//! pins.gpio22.into_push_pull_output(), // Segment G
//!
//! pins.gpio26.into_push_pull_output(), // Dots segment
//!
//! pins.gpio15.into_push_pull_output(), // Digit 0 common anode
//! pins.gpio14.into_push_pull_output(), // Digit 1 common anode
//! pins.gpio13.into_push_pull_output(), // Digit 2 common anode
//! pins.gpio12.into_push_pull_output(), // Digit 3 common anode
//!
//! delay // Your HAL's delay object 
//! );
//! ```
//!
//! Once the display has been defined, the other methods can be called, for example:
//! ```
//! display.clear().unwrap();
//! display.number(1234).unwrap();
//! display.hex(0xAB12).unwrap();
//! ```
//!
//! [`.number()`](struct.Display.html#method.number), [`.hex()`](struct.Display.html#method.hex) and [`.time()`](struct.Display.html#method.time) Will return a [`DisplayErr`](enum.DisplayErr.html) result
//! which can be matched:
//! ```
//! if let Err(err) = display.time(13, 37) {
//!     match err {
//!         DisplayErr::PinFail => info!("Failed to write to a pin!");
//!         DisplayErr::OutOfRange => info!("One of the numbers is too large!")
//!     }
//! }
//! ```
//!
//! You can make your own custom charcaters by specifying which segments should turn on on a
//! bitwise or operation:
//!
//! ```
//! let letter_c = SEG_A | SEG_F | SEG_E | SEG_D;
//! let letter_o = SEG_G | SEG_C | SEG_D | SEG_E;
//! let letter_l = SEG_F | SEG_E | SEG_D;
//! ```
//! (The segment names are indicated on the [datasheet](http://www.xlitx.com/datasheet/3641BS.pdf))
//! 
//! [`.custom()`](struct.Display.html#method.custom) takes an array with 4 values, each corresponding to one digit. The
//! following example demonstrates how to write `CooL` to the display:
//!
//! ```
//! let text_cool = [letter_c, letter_o, letter_o, letter_l];
//! display.custom(text_cool).unwrap();
//! ```

use embedded_hal::digital::v2::OutputPin;
use embedded_hal::blocking::delay::DelayMs;

/// Will turn on the segment A when used in [`.custom()`](struct.Display.html#method.custom). Can be used in combination with other
/// segment constants combining them with the or ( `|` ) operator
pub const SEG_A: u8 = 0b0100_0000;
/// Will turn on the segment B when used in [`.custom()`](struct.Display.html#method.custom). Can be used in combination with other
/// segment constants combining them with the or ( `|` ) operator
pub const SEG_B: u8 = 0b0010_0000;
/// Will turn on the segment C when used in [`.custom()`](struct.Display.html#method.custom). Can be used in combination with other
/// segment constants combining them with the or ( `|` ) operator
pub const SEG_C: u8 = 0b0001_0000;
/// Will turn on the segment D when used in [`.custom()`](struct.Display.html#method.custom). Can be used in combination with other
/// segment constants combining them with the or ( `|` ) operator
pub const SEG_D: u8 = 0b0000_1000;
/// Will turn on the segment E when used in [`.custom()`](struct.Display.html#method.custom). Can be used in combination with other
/// segment constants combining them with the or ( `|` ) operator
pub const SEG_E: u8 = 0b0000_0100;
/// Will turn on the segment F when used in [`.custom()`](struct.Display.html#method.custom). Can be used in combination with other
/// segment constants combining them with the or ( `|` ) operator
pub const SEG_F: u8 = 0b0000_0010;
/// Will turn on the segment G when used in [`.custom()`](struct.Display.html#method.custom). Can be used in combination with other
/// segment constants combining them with the or ( `|` ) operator
pub const SEG_G: u8 = 0b0000_0001;

/// Will turn on the two dots when used in [`.custom()`](struct.Display.html#method.custom). Can be used in combination with other
/// segment constants combining them with the or ( `|` ) operator. Note that only one of the common
/// anodes connects to the two dots.
pub const SEG_SD: u8 = 0b1000_0000;

const MIN_DEC: i32 = -1999;
const MAX_DEC: i32 = 9999;
const MIN_HEX: i32 = -0x1FFF;
const MAX_HEX: i32 = 0xFFFF;
const MIN_TIME: u8 = 0;
const MAX_TIME: u8 = 99;

/// Error type returned by the [`.number()`](struct.Display.html#method.number), [`.hex()`](struct.Display.html#method.hex) and [`.time()`](struct.Display.html#method.time) methods
#[derive(Debug)]
pub enum DisplayErr {
    /// Will be returned if `.custom()` fails to set any pin state
    PinFail,
    /// Will be returned if the value passed is not within the accepted range
    OutOfRange,
}

const fn get_digit(digit: u16) -> u8 {
    match digit {
        0 => 0b0111_1110,
        1 => 0b0011_0000,
        2 => 0b0110_1101,
        3 => 0b0111_1001,
        4 => 0b0011_0011,
        5 => 0b0101_1011,
        6 => 0b0101_1111,
        7 => 0b0111_0000,
        8 => 0b0111_1111,
        9 => 0b0111_1011,
        10 => 0b0111_0111,
        11 => 0b0001_1111,
        12 => 0b0100_1110,
        13 => 0b0011_1101,
        14 => 0b0100_1111,
        15 => 0b0100_0111,
        _ => 0b0000_0000,
    }
}

/// To use the display you'll need to pass the microcontroller's pins and the delay object in your
/// HAL.
///
/// The example uses pins 12-26, but any GPIO pin can be used for any of the fields.
/// ```
/// let mut display = SevenSeg::new(
///     pins.gpio16.into_push_pull_output(), // Segment A
///     pins.gpio17.into_push_pull_output(), // Segment B
///     pins.gpio18.into_push_pull_output(), // Segment C
///     pins.gpio19.into_push_pull_output(), // Segment D
///     pins.gpio20.into_push_pull_output(), // Segment E
///     pins.gpio21.into_push_pull_output(), // Segment F
///     pins.gpio22.into_push_pull_output(), // Segment G
///
///     pins.gpio26.into_push_pull_output(), // Dots segment
///
///     pins.gpio15.into_push_pull_output(), // Digit 0 common anode
///     pins.gpio14.into_push_pull_output(), // Digit 1 common anode
///     pins.gpio13.into_push_pull_output(), // Digit 2 common anode
///     pins.gpio12.into_push_pull_output(), // Digit 3 common anode
///
///     delay,
///     );
/// ```
pub struct Display<A, B, C, D, E, F, G, SD, D1, D2, D3, D4, DL> {
    seg_a: A,
    seg_b: B,
    seg_c: C,
    seg_d: D,
    seg_e: E,
    seg_f: F,
    seg_g: G,

    seg_dots: SD,

    dig_1: D1,
    dig_2: D2,
    dig_3: D3,
    dig_4: D4,

    delay: DL,
}

impl<A, B, C, D, E, F, G, SD, D1, D2, D3, D4, DL> Display<A, B, C, D, E, F, G, SD, D1, D2, D3, D4, DL>
where
    A: OutputPin,
    B: OutputPin,
    C: OutputPin,
    D: OutputPin,
    E: OutputPin,
    F: OutputPin,
    G: OutputPin,

    SD: OutputPin,

    D1: OutputPin,
    D2: OutputPin,
    D3: OutputPin,
    D4: OutputPin,

    DL: DelayMs<u8>,
    
    core::convert::Infallible: core::convert::From<<A as OutputPin>::Error>

    + core::convert::From<<B as OutputPin>::Error>
    + core::convert::From<<C as OutputPin>::Error>
    + core::convert::From<<D as OutputPin>::Error>
    + core::convert::From<<E as OutputPin>::Error>
    + core::convert::From<<F as OutputPin>::Error>
    + core::convert::From<<G as OutputPin>::Error>

    + core::convert::From<<SD as OutputPin>::Error>

    + core::convert::From<<D1 as OutputPin>::Error>
    + core::convert::From<<D2 as OutputPin>::Error>
    + core::convert::From<<D3 as OutputPin>::Error>
    + core::convert::From<<D4 as OutputPin>::Error>,
{
    /// Creates a new display object from the pins you pass it.
    /// Order: A, B, C, D, E, F, G, SD, D1, D2, D3, D4.
    /// `D1, D2, D3 and D4` are the common anodes.
    /// ```text
    ///   _______
    /// /-\__A__/-\
    /// | |     | |
    /// |F|     |B|
    /// | |     | |
    /// \ /-----\ /
    /// / \__G__/ \
    /// | |     | |
    /// |E|     |C|
    /// | |_____| |
    /// \_/__D__\_/ __
    ///            |SD|
    ///             --
    /// ```
    pub const fn new(
        seg_a: A,
        seg_b: B,
        seg_c: C,
        seg_d: D,
        seg_e: E,
        seg_f: F,
        seg_g: G,
        seg_dots: SD,
        dig_1: D1,
        dig_2: D2,
        dig_3: D3,
        dig_4: D4,
        delay: DL,
    ) -> Self {
        Self {
            seg_a,
            seg_b,
            seg_c,
            seg_d,
            seg_e,
            seg_f,
            seg_g,

            seg_dots,

            dig_1,
            dig_2,
            dig_3,
            dig_4,

            delay,
        }
    }

    /// Pulls the common anodes low, turning off the display.
    ///
    /// # Errors
    ///
    /// Will return an error if it fails to set the pins low.
    pub fn clear(&mut self) -> Result<(), core::convert::Infallible> {
        self.dig_1.set_low()?;
        self.dig_2.set_low()?;
        self.dig_3.set_low()?;
        self.dig_4.set_low()?;
        Ok(())
    }

    /// You can make your own custom charcaters by writing which segments should turn on:
    /// ```
    /// let letter_a: u8 = SEG_A | SEG_B | SEG_C | SEG_E | SEG_F | SEG_G
    /// ```
    ///
    /// The .custom() function modifies the 4 digits, so you'll have to pass an array with the
    /// value for the four digits.
    /// ```
    /// let custom_msg: [u8; 4] = [0, 0, 0, letter_a];
    /// display.custom(custom_msg);
    /// ```
    ///
    /// # Errors
    ///
    /// Will return an error if it fails to set the state of any of the pins
    pub fn custom(&mut self, digits: [u8; 4]) -> Result<(), core::convert::Infallible> {
        for (digit, segments) in (0_u8..).zip(digits.into_iter()) {
            match digit {
                0 => {
                    self.dig_1.set_high()?;
                    self.dig_2.set_low()?;
                    self.dig_3.set_low()?;
                    self.dig_4.set_low()?;
                }

                1 => {
                    self.dig_1.set_low()?;
                    self.dig_2.set_high()?;
                    self.dig_3.set_low()?;
                    self.dig_4.set_low()?;
                }

                2 => {
                    self.dig_1.set_low()?;
                    self.dig_2.set_low()?;
                    self.dig_3.set_high()?;
                    self.dig_4.set_low()?;
                }

                3 => {

                    self.dig_1.set_low()?;
                    self.dig_2.set_low()?;
                    self.dig_3.set_low()?;
                    self.dig_4.set_high()?;
                }

                _ => (),
            }

            if segments & SEG_A == SEG_A {
                self.seg_a.set_low()?;
            } else {
                self.seg_a.set_high()?;
            }

            if segments & SEG_B == SEG_B {
                self.seg_b.set_low()?;
            } else {
                self.seg_b.set_high()?;
            }

            if segments & SEG_C == SEG_C {
                self.seg_c.set_low()?;
            } else {
                self.seg_c.set_high()?;
            }

            if segments & SEG_D == SEG_D {
                self.seg_d.set_low()?;
            } else {
                self.seg_d.set_high()?;
            }

            if segments & SEG_E == SEG_E {
                self.seg_e.set_low()?;
            } else {
                self.seg_e.set_high()?;
            }

            if segments & SEG_F == SEG_F {
                self.seg_f.set_low()?;
            } else {
                self.seg_f.set_high()?;
            }

            if segments & SEG_G == SEG_G {
                self.seg_g.set_low()?;
            } else {
                self.seg_g.set_high()?;
            }

            if segments & SEG_SD == SEG_SD {
                self.seg_dots.set_low()?;
            } else {
                self.seg_dots.set_high()?;
            }

            self.delay.delay_ms(1);
        }
        Ok(())
    }
    
    /// Displays a 4 digit number between -1999 and 9999. 
    ///
    /// # Errors
    ///
    /// Will return an error if the number is not in the range or if the .custom() call inside
    /// returns an error.
    pub fn number(&mut self, number: i32) -> Result<(), DisplayErr> {
        if !(MIN_DEC..=MAX_DEC).contains(&number) {
            return Err(DisplayErr::OutOfRange);
        }

        let mut sign: bool = false;
        let abs_number: u16 = if number >= 0 {
            number as u16
        } else {
            sign = true;
            -number as u16
        };

        let numbers: [u16; 4] = [
            abs_number / 1000,
            (abs_number / 100) % 10,
            (abs_number / 10) % 10,
            abs_number % 10,
        ];
        let mut segments: [u8; 4] = [0; 4];

        for i in 0..=3 {
            segments[i] = match numbers[i] {
                0 => match i {
                    1 => {
                        if abs_number > 999 {
                            get_digit(0)
                        } else {
                            get_digit(16)
                        }
                    }
                    2 => {
                        if abs_number > 99 {
                            get_digit(0)
                        } else {
                            get_digit(16)
                        }
                    }
                    3 => get_digit(0),
                    _ => get_digit(16),
                },
                n => get_digit(n)
            }
        }

        if sign {
            segments[0] |= SEG_G;
        }


        if self.custom(segments).is_err() {
            return Err(DisplayErr::PinFail);
        }

        Ok(())
    }

    /// Displays a hex value between -0x1FFF and 0xFFFF. 
    ///
    /// # Errors
    ///
    /// Will return an error if the value is not in the range or if the .custom() call inside
    /// returns an error
    pub fn hex(&mut self, number: i32) -> Result<(), DisplayErr> {
        if !(MIN_HEX..=MAX_HEX).contains(&number) {
            return Err(DisplayErr::OutOfRange);
        }

        let mut sign: bool = false;
        let abs_number: u16 = if number >= 0 {
            number as u16
        } else {
            sign = true;
            -number as u16
        };

        let numbers: [u16; 4] = [
            abs_number / 4096,
            (abs_number / 256) % 16,
            (abs_number / 16) % 16,
            abs_number % 16,
        ];
        let mut segments: [u8; 4] = [0; 4];

        for i in 0..=3 {
            segments[i] = match numbers[i] {
                0 => match i {
                    1 => {
                        if abs_number > 999 {
                            get_digit(0)
                        } else {
                            get_digit(16)
                        }
                    }
                    2 => {
                        if abs_number > 99 {
                            get_digit(0)
                        } else {
                            get_digit(16)
                        }
                    }
                    3 => get_digit(0),
                    _ => get_digit(16),
                },
                n => get_digit(n)
            }
        }

        if sign {
            segments[0] |= SEG_G;
        }

        if self.custom(segments).is_err() {
            return Err(DisplayErr::PinFail);
        }
        Ok(())
    }

    /// Displays a time value, blinks every second.
    ///
    /// # Errors
    ///
    /// Will return an error if either of the numbers is bigger than 99 or if the .custom() call
    /// inside returns an error
    pub fn time(&mut self, left: u8, right: u8, seconds: u8) -> Result<(), DisplayErr> {
        if !(MIN_TIME..=MAX_TIME).contains(&left) || !(0..=99).contains(&right) {
            return Err(DisplayErr::OutOfRange);
        }

        let mut segments: [u8; 4] = [0; 4];
        let numbers: [u8; 4] = [left / 10, left % 10, right / 10, right % 10];

        for i in 0..=3 {
            segments[i] = get_digit(numbers[i].into())
        }

        if seconds % 2 == 0 {
            segments[1] |= SEG_SD;
        }

        if self.custom(segments).is_err() {
            return Err(DisplayErr::PinFail);
        }
        Ok(())
    }
}