tm1637_embedded_hal/
options.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
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
//! High-level API for display operations.

use crate::{
    exact_size::ExactSizeChainExt, mappings::SegmentBits, maybe_flipped::MaybeFlipped, numbers,
    str::StrParser, tokens::NotFlipped, TM1637,
};

pub mod circles;
mod windows;

mod clock;
mod repeat;
mod scroll;

pub use clock::*;
pub use repeat::*;
pub use scroll::*;

/// High-level API for display operations.
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DisplayOptions<'d, const N: usize, T, CLK, DIO, DELAY, I, M> {
    pub(crate) device: &'d mut TM1637<N, T, CLK, DIO, DELAY>,
    pub(crate) position: usize,
    pub(crate) iter: I,
    pub(crate) _flip: M,
}

impl<'d, 'b, const N: usize, T, CLK, DIO, DELAY, I, M>
    DisplayOptions<'d, N, T, CLK, DIO, DELAY, I, M>
{
    /// Create a new [`DisplayOptions`] instance.
    pub fn new(
        device: &'d mut TM1637<N, T, CLK, DIO, DELAY>,
    ) -> DisplayOptions<'d, N, T, CLK, DIO, DELAY, core::iter::Empty<u8>, NotFlipped> {
        DisplayOptions {
            device,
            position: 0,
            iter: core::iter::empty(),
            _flip: NotFlipped,
        }
    }

    /// Set the position on the display from which to start displaying the bytes.
    pub const fn position(mut self, position: usize) -> Self {
        self.position = position;
        self
    }

    /// Add a slice of bytes.
    pub fn slice(
        self,
        bytes: &'b [u8],
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator + 'b,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator + 'b,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.exact_size_chain(bytes.iter().copied()),
            _flip: self._flip,
        }
    }

    /// Add a string.
    pub fn str(
        self,
        str: &'b str,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator + 'b,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator + 'b,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.exact_size_chain(StrParser::new(str)),
            _flip: self._flip,
        }
    }

    /// Add an iterator of bytes.
    ///
    /// # Example
    ///
    /// Manually map each byte in a slice into a human readable character and set the dot at the 2nd position.
    ///
    /// ```rust
    /// use tm1637_embedded_hal::{mappings::SegmentBits, mock::Noop, str::StrParser, TM1637Builder};
    ///
    /// let mut tm = TM1637Builder::new(Noop, Noop, Noop).build_blocking::<4>();
    ///
    /// tm.options()
    ///     .iter(StrParser::new("HELLO").enumerate().map(move |(i, b)| {
    ///         if i == 1 {
    ///             b | SegmentBits::Dot as u8
    ///         } else {
    ///             b
    ///         }
    ///     }))
    ///     .display()
    ///     .ok();
    ///
    /// // Equivalent to
    ///
    /// tm.options()
    ///    .str("HELLO")
    ///    .dot(1)
    ///    .display()
    ///    .ok();
    /// ```
    pub fn iter<It>(
        self,
        iter: It,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        It: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.exact_size_chain(iter),
            _flip: self._flip,
        }
    }

    /// Prepare to display a digital clock.
    ///
    /// See [`ClockDisplayOptions`].
    pub fn clock(self) -> ClockDisplayOptions<'d, N, T, CLK, DIO, DELAY, I, M> {
        ClockDisplayOptions::new(self)
    }

    /// Use scroll animation options.
    pub fn scroll(self) -> ScrollDisplayOptions<'d, N, T, CLK, DIO, DELAY, I, M> {
        ScrollDisplayOptions::new_with_defaults(self)
    }

    /// Use repeat animation options.
    ///
    /// Display all bytes of the given iterator on the same position.
    ///
    /// See [`RepeatDisplayOptions`].
    pub fn repeat(self) -> RepeatDisplayOptions<'d, N, T, CLK, DIO, DELAY, I, M> {
        RepeatDisplayOptions::new_with_defaults(self)
    }

    /// Add a dynamic dot to the display at the specified position.
    ///
    /// ## Dynamic
    ///
    /// The dot is tied to the byte at the specified position and will move with it.
    pub fn dot(
        self,
        position: usize,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.enumerate().map(move |(i, b)| {
                if i == position {
                    b | SegmentBits::Dot as u8
                } else {
                    b
                }
            }),
            _flip: self._flip,
        }
    }

    /// Remove the dot from the display at the specified position.
    pub fn remove_dot(
        self,
        position: usize,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.enumerate().map(move |(i, b)| {
                if i == position {
                    b & !(SegmentBits::Dot as u8)
                } else {
                    b
                }
            }),
            _flip: self._flip,
        }
    }

    /// Set the dot at the specified position.
    pub fn set_dot(
        self,
        position: usize,
        dot: bool,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.enumerate().map(move |(i, b)| {
                if i == position {
                    if dot {
                        b | SegmentBits::Dot as u8
                    } else {
                        b & !(SegmentBits::Dot as u8)
                    }
                } else {
                    b
                }
            }),
            _flip: self._flip,
        }
    }

    /// Add dots to all positions in the display.
    pub fn dots(
        self,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.map(|b| b | SegmentBits::Dot as u8),
            _flip: self._flip,
        }
    }

    /// Remove dots from all positions in the display.
    pub fn remove_dots(
        self,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.map(|b| b & !(SegmentBits::Dot as u8)),
            _flip: self._flip,
        }
    }

    /// Map the bytes using the provided function.
    ///
    /// # Example
    ///
    /// Manually map each byte in a slice into a human readable character.
    ///
    /// ```rust
    /// use tm1637_embedded_hal::{mappings::from_ascii_byte, mock::Noop, TM1637Builder};
    ///
    /// let mut tm = TM1637Builder::new(Noop, Noop, Noop).build_blocking::<4>();
    ///
    /// tm.options()
    ///     .slice(b"HELLO")
    ///     .map(from_ascii_byte)
    ///     .display()
    ///     .ok();
    ///
    /// // Equivalent** to
    ///
    /// tm.options()
    ///    .str("HELLO")
    ///    .display()
    ///    .ok();
    /// ```
    /// ** The [`DisplayOptions::str`] method uses [`StrParser`] internally.
    pub fn map<F: FnMut(u8) -> u8>(
        self,
        f: F,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.map(f),
            _flip: self._flip,
        }
    }

    /// Flip the display.
    pub fn flip(
        self,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        impl MaybeFlipped<N>,
    >
    where
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M: MaybeFlipped<N>,
    {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter,
            _flip: M::flip(),
        }
    }
}

#[::duplicate::duplicate_item(
    module        async     await               Token                     DelayTrait                             ScrollIter;
    [asynch]      [async]   [await.identity()]  [crate::tokens::Async]    [::embedded_hal_async::delay::DelayNs] [::futures::Stream];
    [blocking]    []        [identity()]        [crate::tokens::Blocking] [::embedded_hal::delay::DelayNs]       [Iterator];
)]
mod module {
    use ::embedded_hal::digital::OutputPin;
    #[allow(unused_imports)]
    use ::futures::StreamExt as _;

    use crate::{
        align::{Align, Aligned},
        maybe_flipped::MaybeFlipped,
        options::DisplayOptions,
        ConditionalInputPin, Error, Identity,
    };

    #[::duplicate::duplicate_item(
        NUM_POS ;
        [4] ;
        [6] ;
    )]
    impl<CLK, DIO, DELAY, ERR, I, M> DisplayOptions<'_, NUM_POS, Token, CLK, DIO, DELAY, I, M>
    where
        CLK: OutputPin<Error = ERR>,
        DIO: OutputPin<Error = ERR> + ConditionalInputPin<ERR>,
        DELAY: DelayTrait,
        I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M: MaybeFlipped<NUM_POS>,
    {
        /// Release the `device` and return the calculated position and bytes.
        pub fn calculate(self) -> (usize, impl Iterator<Item = u8>) {
            let (position, bytes) = M::calculate(self.position, self.iter);

            Align::<NUM_POS>::align(position, bytes)
        }

        /// Display the bytes on a `flipped` or `non-flipped` display.
        pub async fn display(self) -> Result<(), Error<ERR>> {
            let (position, bytes) = M::calculate(self.position, self.iter);

            let (position, bytes) = Align::<NUM_POS>::align(position, bytes);

            self.device.display(position, bytes).await
        }
    }
}

#[::duplicate::duplicate_item(
    function    type_   link;
    [u8]        [u8]    ["[`u8`](crate::numbers::u8)"];
    [u8_2]      [u8]    ["[`u8_2`](crate::numbers::u8_2)"];
    [r_u8_2]    [u8]    ["[`r_u8_2`](crate::numbers::r_u8_2)"];
    [u16_3]     [u16]   ["[`u16_3`](crate::numbers::u16_3)"];
    [r_u16_3]   [u16]   ["[`r_u16_3`](crate::numbers::r_u16_3)"];
    [u16_4]     [u16]   ["[`u16_4`](crate::numbers::u16_4)"];
    [r_u16_4]   [u16]   ["[`r_u16_4`](crate::numbers::r_u16_4)"];
    [u32_5]     [u32]   ["[`u32_5`](crate::numbers::u32_5)"];
    [r_u32_5]   [u32]   ["[`r_u32_5`](crate::numbers::r_u32_5)"];
    [u32_6]     [u32]   ["[`u32_6`](crate::numbers::u32_6)"];
    [r_u32_6]   [u32]   ["[`r_u32_6`](crate::numbers::r_u32_6)"];
    [i8_2]      [i8]    ["[`i8_2`](crate::numbers::i8_2)"];
    [i16_3]     [i16]   ["[`i16_3`](crate::numbers::i16_3)"];
    [r_i16_3]   [i16]   ["[`r_i16_3`](crate::numbers::r_i16_3)"];
    [i16_4]     [i16]   ["[`i16_4`](crate::numbers::i16_4)"];
    [r_i16_4]   [i16]   ["[`r_i16_4`](crate::numbers::r_i16_4)"];
    [i32_5]     [i32]   ["[`i32_5`](crate::numbers::i32_5)"];
    [r_i32_5]   [i32]   ["[`r_i32_5`](crate::numbers::r_i32_5)"];
    [i32_6]     [i32]   ["[`i32_6`](crate::numbers::i32_6)"];
    [r_i32_6]   [i32]   ["[`r_i32_6`](crate::numbers::r_i32_6)"];
)]
impl<'d, const N: usize, T, CLK, DIO, DELAY, I, M> DisplayOptions<'d, N, T, CLK, DIO, DELAY, I, M>
where
    I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
{
    #[doc = "See "]
    #[doc = link]
    pub fn function(
        self,
        n: type_,
    ) -> DisplayOptions<
        'd,
        N,
        T,
        CLK,
        DIO,
        DELAY,
        impl DoubleEndedIterator<Item = u8> + ExactSizeIterator,
        M,
    > {
        DisplayOptions {
            device: self.device,
            position: self.position,
            iter: self.iter.exact_size_chain(numbers::function(n).into_iter()),
            _flip: self._flip,
        }
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::vec;
    use std::vec::Vec;

    use crate::{mappings::str_from_byte, mock::Noop, TM1637Builder};

    #[test]
    fn dot_is_dynamically_tied_to_byte() {
        let mut tm = TM1637Builder::new(Noop, Noop, Noop).build_blocking::<4>();

        let (_, iter) = tm.options().str("HELLO").dot(1).dot(3).calculate();
        let collected = iter.map(str_from_byte).collect::<Vec<_>>();

        assert_eq!(vec!["H", "E.", "L", "L."], collected);

        let (_, iter) = tm.options().str("HELLO").dot(1).dot(3).flip().calculate();
        let collected = iter.map(str_from_byte).collect::<Vec<_>>();

        assert_eq!(vec!["7.", "7", "3.", "H"], collected);
    }
}