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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
#![cfg_attr(not(test), no_std)]
#![warn(missing_docs)]

//! IT8951 epaper driver for the waveshare 7.8in display
//! The implementation is based on the IT8951 I80/SPI/I2C programming guide
//! provided by waveshare: https://www.waveshare.com/wiki/7.8inch_e-Paper_HAT

#[macro_use]
extern crate alloc;
use core::marker::PhantomData;

use alloc::string::String;

mod command;
pub mod interface;
pub mod memory_converter_settings;
mod pixel_serializer;
mod register;

use memory_converter_settings::MemoryConverterSetting;
use pixel_serializer::{convert_color_to_pixel_iterator, PixelSerializer};

/// Controller Error
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    /// controller interface error
    Interface(interface::Error),
}
impl From<interface::Error> for Error {
    fn from(e: interface::Error) -> Self {
        Error::Interface(e)
    }
}

/// Device Info Struct
/// Describes the connected display
#[derive(Debug, Clone)]
pub struct DevInfo {
    /// width in pixel of the connected panel
    pub panel_width: u16,
    /// height in pixel of the connected panel
    pub panel_height: u16,
    /// start address of the frame buffer in the controller ram
    pub memory_address: u32,
    /// Controller firmware version
    pub firmware_version: String,
    /// LUT version
    /// The lut describes the waveforms to modify the display content
    /// LUT is specific for every display
    pub lut_version: String,
}

/// Describes a area on the display
#[derive(Debug, PartialEq, Eq)]
pub struct AreaImgInfo {
    /// x position (left to right, 0 is top left corner)
    pub area_x: u16,
    /// y position (top to bottom, 0 is top left corner)
    pub area_y: u16,
    /// width (x-axis)
    pub area_w: u16,
    /// height (y-axis)
    pub area_h: u16,
}

/// See https://www.waveshare.com/w/upload/c/c4/E-paper-mode-declaration.pdf for full description
pub enum WaveformMode {
    /// used for full erase to white, flashy, should be used if framebuffer is not up to date
    Init = 0,
    /// any graytone to black or white, non flashy
    DirectUpdate = 1,
    /// high image quality, all graytones
    GrayscaleClearing16 = 2,
    ///  sparse content on white, eg. text
    GL16 = 3,
    ///  only in combination with with propertary image preprocessing
    GLR16 = 4,
    /// only in combination with with propertary image preprocessing
    GLD16 = 5,
    /// fast, non-flash, from black/white to black/white only
    A2 = 6,
    /// fast, non flash, from any graytone to 1,6,11,16
    DU4 = 7,
}

/// Normal Operation
pub struct Run;
/// The device is either in sleep or standby mode:
/// Sleep: All clocks, pll, osc and the panel are off, but the ram is refreshed
/// Standby: Clocks are gated off, but pll, osc, panel power and ram is active
pub struct PowerDown;
/// Not initalised driver after a power cycle
pub struct Off;

/// IT8951 e paper driver
/// The controller supports multiple interfaces
pub struct IT8951<IT8951Interface, State> {
    interface: IT8951Interface,
    dev_info: Option<DevInfo>,
    marker: core::marker::PhantomData<State>,
}

impl<IT8951Interface: interface::IT8951Interface> IT8951<IT8951Interface, Off> {
    /// Creates a new controller driver object
    /// Call init afterwards to initalize the controller
    pub fn new(interface: IT8951Interface) -> Self {
        IT8951 {
            interface,
            dev_info: None,
            marker: PhantomData {},
        }
    }

    /// Initalize the driver and resets the display
    /// VCOM should be given on your display
    pub fn init(mut self, vcom: u16) -> Result<IT8951<IT8951Interface, Run>, Error> {
        self.interface.reset()?;

        let mut it8951 = IT8951::<IT8951Interface, PowerDown> {
            interface: self.interface,
            dev_info: self.dev_info,
            marker: PhantomData {},
        }
        .sys_run()?;

        let dev_info = it8951.get_system_info()?;

        // Enable Pack Write
        it8951.write_register(register::I80CPCR, 0x0001)?;

        if vcom != it8951.get_vcom()? {
            it8951.set_vcom(vcom)?;
        }

        it8951.dev_info = Some(dev_info);

        it8951.reset()?;

        Ok(it8951)
    }

    /// Create a new Driver for are already active and initalized driver
    /// This can be usefull if the device was still powered on, but the uC restarts.
    /// VCOM should be given on your display
    pub fn attach(interface: IT8951Interface) -> Result<IT8951<IT8951Interface, Run>, Error> {
        let mut it8951 = IT8951 {
            interface,
            dev_info: None,
            marker: PhantomData {},
        }.sys_run()?;
        
        it8951.dev_info = Some(it8951.get_system_info()?);

        Ok(it8951)
    }

}

impl<IT8951Interface: interface::IT8951Interface> IT8951<IT8951Interface, Run> {
    /// Get the Device information
    pub fn get_dev_info(&self) -> DevInfo {
        self.dev_info.clone().unwrap()
    }

    /// Increases the driver strength
    /// Use only if the image is not clear!
    pub fn enhance_driving_capability(&mut self) -> Result<(), Error> {
        self.write_register(0x0038, 0x0602)?;
        Ok(())
    }

    /// initalize the frame buffer and clear the display to white
    pub fn reset(&mut self) -> Result<(), Error> {
        self.clear_frame_buffer(0xF)?;
        self.display(WaveformMode::Init)?;
        Ok(())
    }

    /// set all pixel of the frame buffer to the value of raw_color
    /// raw color must be in range 0..16
    fn clear_frame_buffer(&mut self, raw_color: u16) -> Result<(), Error> {
        let dev_info = self.get_dev_info();
        let width = dev_info.panel_width;
        let height = dev_info.panel_height;
        let mem_addr = dev_info.memory_address;

        let data_entry = raw_color << 12 | raw_color << 8 | raw_color << 4 | raw_color;

        // we need to split the data in multiple transfers to keep the buffer size small
        for w in 0..height {
            self.load_image_area(
                mem_addr,
                MemoryConverterSetting {
                    endianness: memory_converter_settings::MemoryConverterEndianness::LittleEndian,
                    bit_per_pixel:
                        memory_converter_settings::MemoryConverterBitPerPixel::BitsPerPixel4,
                    rotation: memory_converter_settings::MemoryConverterRotation::Rotate0,
                },
                &AreaImgInfo {
                    area_x: 0,
                    area_y: w,
                    area_w: width,
                    area_h: 1,
                },
                &vec![data_entry; width as usize / 4],
            )?;
        }
        Ok(())
    }

    // load image functions ------------------------------------------------------------------------------------------

    /// Loads a full frame into the controller frame buffer using the pixel preprocessor
    /// Warning: For the most usecases, the underlying spi transfer ist not capable to transfer a complete frame
    /// split the frame into multiple areas and use load_image_area instead
    pub fn load_image(
        &mut self,
        target_mem_addr: u32,
        image_settings: MemoryConverterSetting,
        data: &[u16],
    ) -> Result<(), Error> {
        self.set_target_memory_addr(target_mem_addr)?;

        self.interface.write_command(command::IT8951_TCON_LD_IMG)?;
        self.interface.write_data(image_settings.into_arg())?;

        self.interface.write_multi_data(data)?;

        self.interface
            .write_command(command::IT8951_TCON_LD_IMG_END)?;
        Ok(())
    }

    /// Loads pixel data into the controller frame buffer using the pixel preprocessor
    /// Memory Address should be read from the dev_info struct
    /// ImageSettings define the layout of the data buffer
    /// AreaInfo describes the frame buffer area which should be updated
    pub fn load_image_area(
        &mut self,
        target_mem_addr: u32,
        image_settings: MemoryConverterSetting,
        area_info: &AreaImgInfo,
        data: &[u16],
    ) -> Result<(), Error> {
        self.set_target_memory_addr(target_mem_addr)?;

        self.interface.write_command_with_args(
            command::IT8951_TCON_LD_IMG_AREA,
            &[
                image_settings.into_arg(),
                area_info.area_x,
                area_info.area_y,
                area_info.area_w,
                area_info.area_h,
            ],
        )?;

        self.interface.write_multi_data(data)?;

        self.interface
            .write_command(command::IT8951_TCON_LD_IMG_END)?;

        Ok(())
    }

    fn set_target_memory_addr(&mut self, target_mem_addr: u32) -> Result<(), Error> {
        self.write_register(register::LISAR + 2, (target_mem_addr >> 16) as u16)?;
        self.write_register(register::LISAR, target_mem_addr as u16)?;
        Ok(())
    }

    // buffer functions -------------------------------------------------------------------------------------------------

    /// Reads the given memory address from the controller ram into data
    pub fn memory_burst_read(
        &mut self,
        memory_address: u32,
        data: &mut [u16],
    ) -> Result<(), Error> {
        let args = [
            memory_address as u16,
            (memory_address >> 16) as u16,
            data.len() as u16,
            (data.len() >> 16) as u16,
        ];
        self.interface
            .write_command_with_args(command::IT8951_TCON_MEM_BST_RD_T, &args)?;
        self.interface
            .write_command(command::IT8951_TCON_MEM_BST_RD_S)?;

        self.interface.read_multi_data(data)?;

        self.interface
            .write_command(command::IT8951_TCON_MEM_BST_END)?;

        Ok(())
    }

    /// Writes a buffer of u16 values to the given memory address in the controller ram
    pub fn memory_burst_write(&mut self, memory_address: u32, data: &[u16]) -> Result<(), Error> {
        let args = [
            memory_address as u16,
            (memory_address >> 16) as u16,
            data.len() as u16,
            (data.len() >> 16) as u16,
        ];
        self.interface
            .write_command_with_args(command::IT8951_TCON_MEM_BST_WR, &args)?;

        self.interface.write_multi_data(data)?;

        self.interface
            .write_command(command::IT8951_TCON_MEM_BST_END)?;
        Ok(())
    }

    // display functions ------------------------------------------------------------------------------------------------

    /// Refresh a specific area of the display with the frame buffer content
    /// A usecase specific wafeform must be selected by the user
    pub fn display_area(
        &mut self,
        area_info: &AreaImgInfo,
        mode: WaveformMode,
    ) -> Result<(), Error> {
        self.wait_for_display_ready()?;

        let args = [
            area_info.area_x,
            area_info.area_y,
            area_info.area_w,
            area_info.area_h,
            mode as u16,
        ];

        self.interface
            .write_command_with_args(command::USDEF_I80_CMD_DPY_AREA, &args)?;
        Ok(())
    }

    /// Refresh a specific area of the display from a dedicated frame buffer
    /// A usecase specific wafeform must be selected by the user
    pub fn display_area_buf(
        &mut self,
        area_info: &AreaImgInfo,
        mode: WaveformMode,
        target_mem_addr: u32,
    ) -> Result<(), Error> {
        self.wait_for_display_ready()?;

        let args = [
            area_info.area_x,
            area_info.area_y,
            area_info.area_w,
            area_info.area_h,
            mode as u16,
            target_mem_addr as u16,
            (target_mem_addr >> 16) as u16,
        ];

        self.interface
            .write_command_with_args(command::USDEF_I80_CMD_DPY_BUF_AREA, &args)?;
        Ok(())
    }

    /// Refresh the full E-Ink display with the frame buffer content
    /// A usecase specific wafeform must be selected by the user
    pub fn display(&mut self, mode: WaveformMode) -> Result<(), Error> {
        let dev_info = self.get_dev_info();
        let width = dev_info.panel_width;
        let height = dev_info.panel_height;

        self.display_area(
            &AreaImgInfo {
                area_x: 0,
                area_y: 0,
                area_w: width,
                area_h: height,
            },
            mode,
        )?;
        Ok(())
    }

    // misc  ------------------------------------------------------------------------------------------------

    fn wait_for_display_ready(&mut self) -> Result<(), Error> {
        while Ok(0) != self.read_register(register::LUTAFSR) {}
        Ok(())
    }

    /// Activate sleep power mode
    /// All clocks, pll, osc and the panel are off, but the ram is refreshed
    pub fn sleep(mut self) -> Result<IT8951<IT8951Interface, PowerDown>, Error> {
        self.interface.write_command(command::IT8951_TCON_SLEEP)?;
        Ok(IT8951 {
            interface: self.interface,
            dev_info: self.dev_info,
            marker: PhantomData {},
        })
    }

    /// Activate standby power mode
    /// Clocks are gated off, but pll, osc, panel power and ram is active
    pub fn standby(mut self) -> Result<IT8951<IT8951Interface, PowerDown>, Error> {
        self.interface.write_command(command::IT8951_TCON_STANDBY)?;
        Ok(IT8951 {
            interface: self.interface,
            dev_info: self.dev_info,
            marker: PhantomData {},
        })
    }

    fn get_system_info(&mut self) -> Result<DevInfo, Error> {
        self.interface
            .write_command(command::USDEF_I80_CMD_GET_DEV_INFO)?;

        self.interface.wait_while_busy()?;

        // 40 bytes payload
        let mut buf = [0x0000; 20];
        self.interface.read_multi_data(&mut buf)?;

        Ok(DevInfo {
            panel_width: buf[0],
            panel_height: buf[1],
            memory_address: ((buf[3] as u32) << 16) | (buf[2] as u32),
            firmware_version: self.buf_to_string(&buf[4..12]),
            lut_version: self.buf_to_string(&buf[12..20]),
        })
    }

    fn buf_to_string(&self, buf: &[u16]) -> String {
        buf.iter()
            .filter(|&&raw| raw != 0x0000)
            .fold(String::new(), |mut res, &raw| {
                if let Some(c) = char::from_u32((raw & 0xFF) as u32) {
                    res.push(c);
                }
                if let Some(c) = char::from_u32((raw >> 8) as u32) {
                    res.push(c);
                }
                res
            })
    }

    fn get_vcom(&mut self) -> Result<u16, Error> {
        self.interface.write_command(command::USDEF_I80_CMD_VCOM)?;
        self.interface.write_data(0x0000)?;
        let vcom = self.interface.read_data()?;
        Ok(vcom)
    }

    fn set_vcom(&mut self, vcom: u16) -> Result<(), Error> {
        self.interface.write_command(command::USDEF_I80_CMD_VCOM)?;
        self.interface.write_data(0x0001)?;
        self.interface.write_data(vcom)?;
        Ok(())
    }

    fn read_register(&mut self, reg: u16) -> Result<u16, Error> {
        self.interface.write_command(command::IT8951_TCON_REG_RD)?;
        self.interface.write_data(reg)?;
        let data = self.interface.read_data()?;
        Ok(data)
    }

    fn write_register(&mut self, reg: u16, data: u16) -> Result<(), Error> {
        self.interface.write_command(command::IT8951_TCON_REG_WR)?;
        self.interface.write_data(reg)?;
        self.interface.write_data(data)?;
        Ok(())
    }
}

impl<IT8951Interface: interface::IT8951Interface> IT8951<IT8951Interface, PowerDown> {
    /// Activate active power mode
    /// This is the normal operation power mode
    pub fn sys_run(mut self) -> Result<IT8951<IT8951Interface, Run>, Error> {
        self.interface.write_command(command::IT8951_TCON_SYS_RUN)?;
        Ok(IT8951 {
            interface: self.interface,
            dev_info: self.dev_info,
            marker: PhantomData {},
        })
    }
}

// --------------------------- embedded graphics support --------------------------------------

use embedded_graphics::{pixelcolor::Gray4, prelude::*, primitives::Rectangle};

impl<IT8951Interface: interface::IT8951Interface> DrawTarget for IT8951<IT8951Interface, Run> {
    type Color = Gray4;

    type Error = Error;

    fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
        let raw_color = color.luma() as u16;
        self.clear_frame_buffer(raw_color)
    }

    fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Self::Color>,
    {
        let iter = convert_color_to_pixel_iterator(*area, self.bounding_box(), colors.into_iter());

        let pixel = PixelSerializer::new(area.intersection(&self.bounding_box()), iter);

        for (area_img_info, buffer) in pixel {
            let dev_info = self.get_dev_info();
            self.load_image_area(
                dev_info.memory_address,
                MemoryConverterSetting {
                    endianness: memory_converter_settings::MemoryConverterEndianness::LittleEndian,
                    bit_per_pixel:
                        memory_converter_settings::MemoryConverterBitPerPixel::BitsPerPixel4,
                    rotation: memory_converter_settings::MemoryConverterRotation::Rotate0,
                },
                &area_img_info,
                &buffer,
            )?;
        }
        Ok(())
    }

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = embedded_graphics::Pixel<Self::Color>>,
    {
        let dev_info = self.get_dev_info();
        let width = dev_info.panel_width as i32;
        let height = dev_info.panel_height as i32;
        for Pixel(coord, color) in pixels.into_iter() {
            if (coord.x >= 0 && coord.x < width) || (coord.y >= 0 || coord.y < height) {
                let data: u16 = (color.luma() as u16) << ((coord.x % 4) * 4);

                self.load_image_area(
                    dev_info.memory_address,
                    MemoryConverterSetting {
                        endianness:
                            memory_converter_settings::MemoryConverterEndianness::LittleEndian,
                        bit_per_pixel:
                            memory_converter_settings::MemoryConverterBitPerPixel::BitsPerPixel4,
                        rotation: memory_converter_settings::MemoryConverterRotation::Rotate0,
                    },
                    &AreaImgInfo {
                        area_x: coord.x as u16,
                        area_y: coord.y as u16,
                        area_w: 1,
                        area_h: 1,
                    },
                    &[data],
                )?;
            }
        }
        Ok(())
    }
}

impl<IT8951Interface: interface::IT8951Interface> OriginDimensions
    for IT8951<IT8951Interface, Run>
{
    fn size(&self) -> Size {
        let dev_info = self.dev_info.as_ref().unwrap();
        Size::new(dev_info.panel_width as u32, dev_info.panel_height as u32)
    }
}