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
#![no_std]
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
#![feature(generic_arg_infer)]

pub mod display;
// pub mod drivers;
pub mod interface;

use core::{marker::PhantomData, mem};

use defmt::println;
use display::{DisplayRotation, DisplaySize, FrameBuffer, GrayColorInBits, GrayFrameBuffer};
use drivers::{Driver, GrayScaleDriver, MultiColorDriver};
use embedded_graphics::{
    image::ImageRaw,
    pixelcolor::{BinaryColor, Gray2},
    prelude::{Dimensions, DrawTarget, GrayColor, PixelColor},
    primitives::Rectangle,
    Pixel,
};
use interface::DisplayInterface;
pub use interface::EPDInterface;

pub mod drivers;

pub struct EPD<I: DisplayInterface, S: DisplaySize, D: Driver>
where
    [(); S::N]:,
{
    pub interface: I,
    pub framebuf: FrameBuffer<S>,
    _phantom: PhantomData<(S, D)>,
}

impl<DI: DisplayInterface, S: DisplaySize, D: Driver> EPD<DI, S, D>
where
    [(); S::N]:,
{
    pub fn new(interface: DI) -> Self {
        Self {
            interface,
            framebuf: FrameBuffer::new_inverted(),
            _phantom: PhantomData,
        }
    }

    pub fn init<DELAY>(&mut self, delay: &mut DELAY) -> Result<(), D::Error>
    where
        DELAY: embedded_hal::blocking::delay::DelayUs<u32>,
    {
        D::wake_up(&mut self.interface, delay)?;
        D::set_shape(&mut self.interface, S::WIDTH as _, S::HEIGHT as _)?;
        Ok(())
    }

    pub fn display_frame(&mut self) -> Result<(), D::Error> {
        D::update_frame(&mut self.interface, self.framebuf.as_bytes())?;
        D::turn_on_display(&mut self.interface)
    }

    pub fn sleep<DELAY>(&mut self, delay: &mut DELAY) -> Result<(), D::Error>
    where
        DELAY: embedded_hal::blocking::delay::DelayUs<u32>,
    {
        D::sleep(&mut self.interface, delay)
    }

    pub fn wake_up<DELAY>(&mut self, delay: &mut DELAY) -> Result<(), D::Error>
    where
        DELAY: embedded_hal::blocking::delay::DelayUs<u32>,
    {
        D::wake_up(&mut self.interface, delay)?;
        D::set_shape(&mut self.interface, S::WIDTH as _, S::HEIGHT as _)?;
        Ok(())
    }
}

impl<I: DisplayInterface, S: DisplaySize, D: Driver> Dimensions for EPD<I, S, D>
where
    [(); S::N]:,
{
    fn bounding_box(&self) -> Rectangle {
        self.framebuf.bounding_box()
    }
}

impl<I: DisplayInterface, S: DisplaySize, D: Driver> DrawTarget for EPD<I, S, D>
where
    [(); S::N]:,
{
    type Color = embedded_graphics::pixelcolor::BinaryColor;
    type Error = core::convert::Infallible;

    fn draw_iter<IP>(&mut self, pixels: IP) -> Result<(), Self::Error>
    where
        IP: IntoIterator<Item = embedded_graphics::Pixel<Self::Color>>,
    {
        self.framebuf.draw_iter(pixels)
    }
}

pub struct TriColorEPD<I: DisplayInterface, S: DisplaySize, D: Driver>
where
    [(); S::N]:,
{
    pub interface: I,
    pub framebuf0: FrameBuffer<S>,
    pub framebuf1: FrameBuffer<S>,
    _phantom: PhantomData<(S, D)>,
}

impl<DI: DisplayInterface, S: DisplaySize, D: MultiColorDriver> TriColorEPD<DI, S, D>
where
    [(); S::N]:,
{
    pub fn new(interface: DI) -> Self {
        Self {
            interface,
            framebuf0: FrameBuffer::new_inverted(),
            framebuf1: FrameBuffer::new(),
            _phantom: PhantomData,
        }
    }

    pub fn init<DELAY>(&mut self, delay: &mut DELAY) -> Result<(), D::Error>
    where
        DELAY: embedded_hal::blocking::delay::DelayUs<u32>,
    {
        D::wake_up(&mut self.interface, delay)?;

        D::set_shape(&mut self.interface, S::WIDTH as _, S::HEIGHT as _)?;

        Ok(())
    }

    pub fn display_frame(&mut self) -> Result<(), D::Error> {
        D::update_channel_frame(&mut self.interface, 0, self.framebuf0.as_bytes())?;
        D::update_channel_frame(&mut self.interface, 1, self.framebuf1.as_bytes())?;
        D::turn_on_display(&mut self.interface)
    }

    pub fn sleep<DELAY>(&mut self, delay: &mut DELAY) -> Result<(), D::Error>
    where
        DELAY: embedded_hal::blocking::delay::DelayUs<u32>,
    {
        D::sleep(&mut self.interface, delay)
    }

    pub fn wake_up<DELAY>(&mut self, delay: &mut DELAY) -> Result<(), D::Error>
    where
        DELAY: embedded_hal::blocking::delay::DelayUs<u32>,
    {
        D::wake_up(&mut self.interface, delay)?;
        D::set_shape(&mut self.interface, S::WIDTH as _, S::HEIGHT as _)?;
        Ok(())
    }
}

impl<I: DisplayInterface, S: DisplaySize, D: Driver> Dimensions for TriColorEPD<I, S, D>
where
    [(); S::N]:,
{
    fn bounding_box(&self) -> Rectangle {
        self.framebuf0.bounding_box()
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum TriColor {
    White,
    Black,
    Red, // or yellow?
}
/// The `Raw` can be is set to `()` because `EpdColor` doesn't need to be
/// converted to raw data for the display and isn't stored in images.
impl PixelColor for TriColor {
    type Raw = ();
}

impl<I: DisplayInterface, SIZE: DisplaySize, D: Driver> DrawTarget for TriColorEPD<I, SIZE, D>
where
    [(); SIZE::N]:,
{
    type Color = TriColor;
    type Error = core::convert::Infallible;

    fn draw_iter<IP>(&mut self, pixels: IP) -> Result<(), Self::Error>
    where
        IP: IntoIterator<Item = embedded_graphics::Pixel<Self::Color>>,
    {
        for Pixel(point, color) in pixels.into_iter() {
            match color {
                TriColor::White => {
                    self.framebuf0.draw_iter([Pixel(point, BinaryColor::On)])?;
                    self.framebuf1.draw_iter([Pixel(point, BinaryColor::Off)])?;
                }
                TriColor::Black => {
                    self.framebuf0.draw_iter([Pixel(point, BinaryColor::Off)])?;
                    self.framebuf1.draw_iter([Pixel(point, BinaryColor::Off)])?;
                }
                TriColor::Red => {
                    self.framebuf0.draw_iter([Pixel(point, BinaryColor::On)])?;
                    self.framebuf1.draw_iter([Pixel(point, BinaryColor::On)])?;
                }
            }
        }
        Ok(())
    }
}

pub struct GrayScaleEPD<C, I: DisplayInterface, SIZE: DisplaySize, D: GrayScaleDriver<C>>
where
    C: GrayColor + GrayColorInBits + PixelColor + From<<C as PixelColor>::Raw>,
    [(); SIZE::N]:,
    [(); C::BITS_PER_PIXEL]:,
    [(); SIZE::N * C::BITS_PER_PIXEL]:,
{
    pub interface: I,
    pub framebuf: GrayFrameBuffer<SIZE, C>,
    _phantom: PhantomData<D>,
}

impl<'a, C, I: DisplayInterface, SIZE: DisplaySize, D: GrayScaleDriver<C>>
    GrayScaleEPD<C, I, SIZE, D>
where
    C: GrayColor + GrayColorInBits + PixelColor + From<<C as PixelColor>::Raw>,
    [(); SIZE::N]:,
    [(); C::BITS_PER_PIXEL]:,
    [(); SIZE::N * C::BITS_PER_PIXEL]:,
{
    pub fn new(interface: I) -> Self {
        Self {
            interface,
            framebuf: GrayFrameBuffer::new(),
            _phantom: PhantomData,
        }
    }

    pub fn init<DELAY>(&mut self, delay: &mut DELAY) -> Result<(), D::Error>
    where
        DELAY: embedded_hal::blocking::delay::DelayUs<u32>,
    {
        D::wake_up(&mut self.interface, delay)?;
        D::set_shape(&mut self.interface, SIZE::WIDTH as _, SIZE::HEIGHT as _)?;

        Ok(())
    }

    pub fn set_rotation(&mut self, rotation: i32) {
        self.framebuf.set_rotation(rotation);
    }

    pub fn display_frame(&mut self) -> Result<(), D::Error> {
        D::setup_gray_scale(&mut self.interface)?;

        let width_in_byte = SIZE::WIDTH / 8 + (SIZE::WIDTH % 8 != 0) as usize;

        for i in (0..C::MAX_VALUE + 1).rev() {

            defmt::debug!("display layer {}", i);
            let mut tmp = [0xffu8; SIZE::N];
            // extract gray channel and fill in the tmp buffer
            for y in 0..SIZE::HEIGHT {
                for x in 0..SIZE::WIDTH {
                    let byte_offset = y * width_in_byte + x / 8;
                    let bit_offset = 7 - x % 8;

                    let pixel = self.framebuf.get_pixel_in_raw_pos(x, y);

                    let val = pixel.luma(); // 0, 1, 2, 3
                    // defmt::info!("x {} y {}  val {}", x, y, val);

                    if val == 7 {
                       // defmt::info!("layer 7");
                    }
                    if val < i {
                        tmp[byte_offset] &= !(1 << bit_offset);
                        //tmp[byte_offset] |= (1 << bit_offset);
                    }
                }
            }
            println!("frame {}", tmp.iter().filter(|&&x| x != 0xff).count());
            D::update_frame(&mut self.interface, &tmp)?;
            D::turn_on_display(&mut self.interface)?;
        }

        Ok(())
    }

    pub fn sleep<DELAY>(&mut self, delay: &mut DELAY) -> Result<(), D::Error>
    where
        DELAY: embedded_hal::blocking::delay::DelayUs<u32>,
    {
        D::sleep(&mut self.interface, delay)
    }

    pub fn clear_display(&mut self, color: BinaryColor) -> Result<(), D::Error> {
        D::restore_normal_mode(&mut self.interface)?;

        self.framebuf.fill(color);

        D::update_frame(&mut self.interface, self.framebuf.as_bytes())?;
        D::turn_on_display(&mut self.interface)?;
        Ok(())
    }
}

impl<C, DI: DisplayInterface, S: DisplaySize, D: GrayScaleDriver<C>> DrawTarget
    for GrayScaleEPD<C, DI, S, D>
where
    [(); S::N]:,
    [(); C::BITS_PER_PIXEL]:,
    [(); S::N * C::BITS_PER_PIXEL]:,

    C: GrayColor + GrayColorInBits + PixelColor + From<<C as PixelColor>::Raw>,
{
    type Color = C;
    type Error = core::convert::Infallible;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        for Pixel(point, color) in pixels.into_iter() {
            self.framebuf.set_pixel(point.x as _, point.y as _, color);
        }
        Ok(())
    }
}

impl<C, DI: DisplayInterface, S: DisplaySize, D: GrayScaleDriver<C>> Dimensions
    for GrayScaleEPD<C, DI, S, D>
where
    [(); S::N]:,
    [(); C::BITS_PER_PIXEL]:,
    [(); S::N * C::BITS_PER_PIXEL]:,

    C: GrayColor + GrayColorInBits + PixelColor + From<<C as PixelColor>::Raw>,
{
    fn bounding_box(&self) -> Rectangle {
        self.framebuf.bounding_box()
    }
}