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
//! # ST7920
//!
//! This is a Rust driver library for LCD displays using the [ST7920] controller.
//!
//! It supports graphics mode of the controller, 128x64 in 1bpp. SPI connection to MCU is supported.
//!
//! The controller supports 1 bit-per-pixel displays, so an off-screen buffer has to be used to provide random access to pixels.
//!
//! Size of the buffer is 1024 bytes.
//!
//! The buffer has to be flushed to update the display after a group of draw calls has been completed.
//! The flush is not part of embedded-graphics API.

#![no_std]
use num_derive::ToPrimitive;
use num_traits::ToPrimitive;

use embedded_hal::delay::DelayNs;
use embedded_hal::digital::OutputPin;
use embedded_hal::spi::SpiDevice;

#[derive(Debug)]
pub enum Error<CommError, PinError> {
    Comm(CommError),
    Pin(PinError),
}

/// ST7920 instructions.
#[derive(ToPrimitive)]
enum Instruction {
    BasicFunction = 0x30,
    ExtendedFunction = 0x34,
    ClearScreen = 0x01,
    EntryMode = 0x06,
    DisplayOnCursorOff = 0x0C,
    GraphicsOn = 0x36,
    SetGraphicsAddress = 0x80,
}

pub const WIDTH: u32 = 128;
pub const HEIGHT: u32 = 64;
const ROW_SIZE: usize = (WIDTH / 8) as usize;
const BUFFER_SIZE: usize = ROW_SIZE * HEIGHT as usize;
const X_ADDR_DIV: u8 = 16;

pub struct ST7920<SPI, RST, CS>
where
    SPI: SpiDevice,
    RST: OutputPin,
    CS: OutputPin,
{
    /// SPI pin
    spi: SPI,

    /// Reset pin.
    rst: RST,

    /// CS pin
    cs: Option<CS>,

    buffer: [u8; BUFFER_SIZE],

    flip: bool,
}

impl<SPI, RST, CS, PinError, SPIError> ST7920<SPI, RST, CS>
where
    SPI: SpiDevice<Error = SPIError>,
    RST: OutputPin<Error = PinError>,
    CS: OutputPin<Error = PinError>,
{
    /// Create a new [`ST7920<SPI, RST, CS>`] driver instance that uses SPI connection.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use st7920::ST7920;
    ///
    /// let result = ST7920::new(spi, GPIO::new(pins.p01), None, false);
    /// assert_eq!(result, );
    /// ```
    pub fn new(spi: SPI, rst: RST, cs: Option<CS>, flip: bool) -> Self {
        let buffer = [0; BUFFER_SIZE];

        ST7920 {
            spi,
            rst,
            cs,
            buffer,
            flip,
        }
    }

    fn enable_cs<Delay: DelayNs>(
        &mut self,
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        if let Some(cs) = self.cs.as_mut() {
            cs.set_high().map_err(Error::Pin)?;
            delay.delay_us(1);
        }
        Ok(())
    }

    fn disable_cs<Delay: DelayNs>(
        &mut self,
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        if let Some(cs) = self.cs.as_mut() {
            delay.delay_us(1);
            cs.set_low().map_err(Error::Pin)?;
        }
        Ok(())
    }

    #[inline]
    fn do_init<Delay: DelayNs>(
        &mut self,
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        self.hard_reset(delay)?;
        self.write_command(Instruction::BasicFunction)?;
        delay.delay_us(200);
        self.write_command(Instruction::DisplayOnCursorOff)?;
        delay.delay_us(100);
        self.write_command(Instruction::ClearScreen)?;
        delay.delay_ms(10);
        self.write_command(Instruction::EntryMode)?;
        delay.delay_us(100);
        self.write_command(Instruction::ExtendedFunction)?;
        delay.delay_ms(10);
        self.write_command(Instruction::GraphicsOn)?;
        delay.delay_ms(100);
        Ok(())
    }

    /// Initialize the display controller
    pub fn init<Delay: DelayNs>(
        &mut self,
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        self.enable_cs(delay)?;
        let result = self.do_init(delay);
        self.disable_cs(delay)?;
        result
    }

    fn hard_reset<Delay: DelayNs>(
        &mut self,
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        self.rst.set_low().map_err(Error::Pin)?;
        delay.delay_ms(40);
        self.rst.set_high().map_err(Error::Pin)?;
        delay.delay_ms(40);
        Ok(())
    }

    fn write_command(&mut self, command: Instruction) -> Result<(), Error<SPIError, PinError>> {
        self.write_command_param(command, 0)
    }

    fn write_command_param(
        &mut self,
        command: Instruction,
        param: u8,
    ) -> Result<(), Error<SPIError, PinError>> {
        let command_param = command.to_u8().unwrap() | param;
        let cmd: u8 = 0xF8;

        self.spi
            .write(&[cmd, command_param & 0xF0, (command_param << 4) & 0xF0])
            .map_err(Error::Comm)?;

        Ok(())
    }

    fn write_data(&mut self, data: u8) -> Result<(), Error<SPIError, PinError>> {
        self.spi
            .write(&[0xFA, data & 0xF0, (data << 4) & 0xF0])
            .map_err(Error::Comm)?;
        Ok(())
    }

    fn set_address(&mut self, x: u8, y: u8) -> Result<(), Error<SPIError, PinError>> {
        const HALF_HEIGHT: u8 = HEIGHT as u8 / 2;

        self.write_command_param(
            Instruction::SetGraphicsAddress,
            if y < HALF_HEIGHT { y } else { y - HALF_HEIGHT },
        )?;
        self.write_command_param(
            Instruction::SetGraphicsAddress,
            if y < HALF_HEIGHT {
                x / X_ADDR_DIV
            } else {
                x / X_ADDR_DIV + (WIDTH as u8 / X_ADDR_DIV)
            },
        )?;

        Ok(())
    }

    /// Modify the raw buffer. 1 byte (u8) = 8 pixels
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let mut st7920 = st7920::ST7920(...);
    /// // add crazy pattern
    /// st7920.modify_buffer(|x, y, v| {
    ///     if x % 2 == y % 2 {
    ///         v | 0b10101010
    ///     } else {
    ///         v
    ///     }
    /// });
    /// st7920.flush();
    /// ```
    pub fn modify_buffer(&mut self, f: fn(x: u8, y: u8, v: u8) -> u8) {
        for i in 0..BUFFER_SIZE {
            let row = i / ROW_SIZE;
            let column = i - (row * ROW_SIZE);
            self.buffer[i] = f(column as u8, row as u8, self.buffer[i]);
        }
    }

    /// clears the buffer but don't update the display
    pub fn clear_buffer(&mut self) {
        for i in 0..BUFFER_SIZE {
            self.buffer[i] = 0;
        }
    }

    /// Clear whole display area and clears the buffer
    pub fn clear<Delay: DelayNs>(
        &mut self,
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        self.clear_buffer();
        self.flush(delay)?;
        Ok(())
    }

    /// Clear a buffer region.
    ///
    /// If the region is completely off screen,
    /// nothing will be done and Ok()) will be returned.
    /// If the given width or height are too big,
    /// width and height will be trimmed to the screen dimensions.
    pub fn clear_buffer_region(
        &mut self,
        x: u8,
        mut y: u8,
        mut w: u8,
        mut h: u8,
    ) -> Result<(), Error<SPIError, PinError>> {
        // Top-left is on screen and region has a width/height?
        if x < WIDTH as u8 && y < HEIGHT as u8 && w > 0 && h > 0 {
            // Limit width and height to right and bottom edge.
            if x.saturating_add(w) > WIDTH as u8 {
                w = WIDTH as u8 - x;
            }
            if y.saturating_add(h) > HEIGHT as u8 {
                h = HEIGHT as u8 - y;
            }

            let mut adj_x = x;
            if self.flip {
                y = HEIGHT as u8 - (y + h);
                adj_x = WIDTH as u8 - (x + w);
            }

            let start = adj_x / 8;
            let mut right = adj_x + w;
            let end = (right / 8) + 1;

            let start_gap = adj_x % 8;

            right = end * 8;

            let end_gap = 8 - (right % 8);

            let mut row_start = y as usize * ROW_SIZE;
            for _ in y..y + h {
                for x in start..end {
                    let mut mask = 0xFF_u8;
                    if x == start {
                        mask = 0xFF_u8 >> start_gap;
                    }
                    if x == end {
                        mask &= 0xFF_u8 >> end_gap;
                    }

                    let pos = row_start + x as usize;
                    self.buffer[pos] &= !mask;
                }

                row_start += ROW_SIZE;
            }
        }
        Ok(())
    }

    /// Draw pixel
    ///
    /// Doesn't draw anything, if the x or y coordinates are off canvas.
    ///
    /// Supported values are 0 and (not 0)
    #[inline]
    pub fn set_pixel(&mut self, x: u8, y: u8, val: u8) {
        if x < WIDTH as u8 && y < HEIGHT as u8 {
            self.set_pixel_unchecked(x, y, val);
        }
    }

    /// Draw pixel without canvas bounds checking.
    ///
    /// Supported values are 0 and (not 0)
    ///
    /// # Panics
    ///
    /// May panic or draw to undefined pixels, if x or y coordinates are off canvas.
    #[inline]
    pub fn set_pixel_unchecked(&mut self, mut x: u8, mut y: u8, val: u8) {
        if self.flip {
            y = (HEIGHT - 1) as u8 - y;
            x = (WIDTH - 1) as u8 - x;
        }
        let idx = y as usize * ROW_SIZE + x as usize / 8;
        let x_mask = 0x80 >> (x % 8);
        if val != 0 {
            self.buffer[idx] |= x_mask;
        } else {
            self.buffer[idx] &= !x_mask;
        }
    }

    #[inline]
    fn do_flush(&mut self) -> Result<(), Error<SPIError, PinError>> {
        for y in 0..HEIGHT as u8 / 2 {
            self.set_address(0, y)?;

            let mut row_start = y as usize * ROW_SIZE;
            for x in 0..ROW_SIZE {
                self.write_data(self.buffer[row_start + x])?;
            }
            row_start += (HEIGHT as usize / 2) * ROW_SIZE;
            for x in 0..ROW_SIZE {
                self.write_data(self.buffer[row_start + x])?;
            }
        }
        Ok(())
    }

    /// Flush buffer to update entire display
    pub fn flush<Delay: DelayNs>(
        &mut self,
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        self.enable_cs(delay)?;
        let result = self.do_flush();
        self.disable_cs(delay)?;
        result
    }

    #[inline]
    fn do_flush_region(
        &mut self,
        x: u8,
        mut y: u8,
        w: u8,
        h: u8,
    ) -> Result<(), Error<SPIError, PinError>> {
        let mut adj_x = x;
        if self.flip {
            y = HEIGHT as u8 - (y + h);
            adj_x = WIDTH as u8 - (x + w);
        }

        let mut left = adj_x - adj_x % X_ADDR_DIV;
        let mut right = (adj_x + w) - 1;
        right -= right % X_ADDR_DIV;
        right += X_ADDR_DIV;

        if left > adj_x {
            left -= X_ADDR_DIV; //make sure rightmost pixels are covered
        }

        let mut row_start = y as usize * ROW_SIZE;
        self.set_address(adj_x, y)?;
        for y in y..(y + h) {
            self.set_address(adj_x, y)?;

            for x in left / 8..right / 8 {
                self.write_data(self.buffer[row_start + x as usize])?;
            }

            row_start += ROW_SIZE;
        }
        Ok(())
    }

    /// Flush buffer to update region of the display
    ///
    /// If the region is completely off screen,
    /// nothing will be done and Ok()) will be returned.
    /// If the given width or height are too big,
    /// width and height will be trimmed to the screen dimensions.
    pub fn flush_region<Delay: DelayNs>(
        &mut self,
        x: u8,
        y: u8,
        mut w: u8,
        mut h: u8,
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        // Top-left is on screen and region has a width/height?
        if x < WIDTH as u8 && y < HEIGHT as u8 && w > 0 && h > 0 {
            // Limit width and height to right and bottom edge.
            if x.saturating_add(w) > WIDTH as u8 {
                w = WIDTH as u8 - x;
            }
            if y.saturating_add(h) > HEIGHT as u8 {
                h = HEIGHT as u8 - y;
            }

            self.enable_cs(delay)?;
            let result = self.do_flush_region(x, y, w, h);
            self.disable_cs(delay)?;
            result
        } else {
            Ok(())
        }
    }
}

#[cfg(feature = "graphics")]
use embedded_graphics::{
    self, draw_target::DrawTarget, geometry::Point, pixelcolor::BinaryColor, prelude::*,
};

#[cfg(feature = "graphics")]
impl<SPI, CS, RST, PinError, SPIError> OriginDimensions for ST7920<SPI, CS, RST>
where
    SPI: SpiDevice<Error = SPIError>,
    RST: OutputPin<Error = PinError>,
    CS: OutputPin<Error = PinError>,
{
    fn size(&self) -> Size {
        Size {
            width: WIDTH,
            height: HEIGHT,
        }
    }
}

#[cfg(feature = "graphics")]
impl<SPI, CS, RST, PinError, SPIError> DrawTarget for ST7920<SPI, CS, RST>
where
    SPI: SpiDevice<Error = SPIError>,
    RST: OutputPin<Error = PinError>,
    CS: OutputPin<Error = PinError>,
{
    type Error = core::convert::Infallible;
    type Color = BinaryColor;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        for p in pixels {
            let Pixel(coord, color) = p;

            #[cfg(not(feature = "graphics-unchecked"))]
            let in_bounds =
                coord.x >= 0 && coord.x < WIDTH as i32 && coord.y >= 0 && coord.y < HEIGHT as i32;
            #[cfg(feature = "graphics-unchecked")]
            let in_bounds = true;

            if in_bounds {
                let x = coord.x as u8;
                let y = coord.y as u8;
                let c = match color {
                    BinaryColor::Off => 0,
                    BinaryColor::On => 1,
                };
                self.set_pixel_unchecked(x, y, c);
            }
        }

        Ok(())
    }
}

#[cfg(feature = "graphics")]
impl<SPI, RST, CS, PinError, SPIError> ST7920<SPI, RST, CS>
where
    SPI: SpiDevice<Error = SPIError>,
    RST: OutputPin<Error = PinError>,
    CS: OutputPin<Error = PinError>,
{
    pub fn flush_region_graphics<Delay: DelayNs>(
        &mut self,
        region: (Point, Size),
        delay: &mut Delay,
    ) -> Result<(), Error<SPIError, PinError>> {
        let mut width: u32 = region.1.width;
        let mut height: u32 = region.1.height;
        let mut x: i32 = region.0.x;
        let mut y: i32 = region.0.y;
        // Trim negative x position to zero. Reduce width accordingly.
        if x < 0 {
            width = width.saturating_sub((-x) as u32);
            x = 0;
        }
        // Trim negative y position to zero. Reduce height accordingly.
        if y < 0 {
            height = height.saturating_sub((-y) as u32);
            y = 0;
        }
        // Trim x, y, width and height to u8 range.
        x = x.min(u8::MAX as i32);
        y = y.min(u8::MAX as i32);
        width = width.min(u8::MAX as u32);
        height = height.min(u8::MAX as u32);
        self.flush_region(x as u8, y as u8, width as u8, height as u8, delay)
    }
}