Skip to main content

capsules_extra/
st77xx.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! ST77xx Screen
6//!
7//! - <https://learn.adafruit.com/adafruit-1-3-and-1-54-240-x-240-wide-angle-tft-lcd-displays>
8//!
9//! The screen supports multiple physical busses, and this driver is implemented
10//! on top of the generic `Bus` interface.
11//!
12//! Usage
13//! -----
14//!
15//! SPI example
16//!
17//! ```rust,ignore
18//! let tft = components::st77xx::ST77XXComponent::new(mux_alarm,
19//!                                                    bus,
20//!                                                    Some(&nrf52840::gpio::PORT[GPIO_D3]),
21//!                                                    Some(&nrf52840::gpio::PORT[GPIO_D2]),
22//!                                                    &capsules::st77xx::ST7735).finalize(
23//!     components::st77xx_component_static!(
24//!         // bus type
25//!         capsules::bus::SpiMasterBus<
26//!             'static,
27//!             VirtualSpiMasterDevice<'static, nrf52840::spi::SPIM>,
28//!         >,
29//!         // timer type
30//!         nrf52840::rtc::Rtc,
31//!         // pin type
32//!         nrf52::gpio::GPIOPin<'static>,
33//!     ),
34//! );
35//! ```
36
37use crate::bus::{self, Bus, BusAddr8, DataWidth};
38use core::cell::Cell;
39use kernel::ErrorCode;
40use kernel::hil::gpio::Pin;
41use kernel::hil::screen::{
42    self, ScreenClient, ScreenPixelFormat, ScreenRotation, ScreenSetupClient,
43};
44use kernel::hil::time::{self, Alarm, ConvertTicks};
45use kernel::utilities::cells::{OptionalCell, TakeCell};
46use kernel::utilities::leasable_buffer::SubSliceMut;
47
48pub const BUFFER_SIZE: usize = 24;
49
50#[derive(PartialEq)]
51pub struct Command {
52    pub id: u8,
53    pub parameters: Option<&'static [u8]>,
54    pub delay: u8,
55}
56
57const NOP: Command = Command {
58    id: 0x00,
59    parameters: None,
60    delay: 0,
61};
62
63const SW_RESET: Command = Command {
64    id: 0x01,
65    parameters: None,
66    delay: 150, // 255?
67};
68
69const SLEEP_IN: Command = Command {
70    id: 0x10,
71    parameters: None,
72    delay: 10,
73};
74
75const SLEEP_OUT: Command = Command {
76    id: 0x11,
77    parameters: None,
78    delay: 255,
79};
80
81#[allow(dead_code)]
82const PARTIAL_ON: Command = Command {
83    id: 0x12,
84    parameters: None,
85    delay: 0,
86};
87
88const INVOFF: Command = Command {
89    id: 0x20,
90    parameters: None,
91    delay: 0,
92};
93
94const INVON: Command = Command {
95    id: 0x21,
96    parameters: None,
97    delay: 120,
98};
99
100const DISPLAY_OFF: Command = Command {
101    id: 0x28,
102    parameters: None,
103    delay: 100,
104};
105
106const DISPLAY_ON: Command = Command {
107    id: 0x29,
108    parameters: None,
109    delay: 100,
110};
111
112const WRITE_RAM: Command = Command {
113    id: 0x2C,
114    parameters: Some(&[]),
115    delay: 0,
116};
117
118#[allow(dead_code)]
119const READ_RAM: Command = Command {
120    id: 0x2E,
121    parameters: None,
122    delay: 0,
123};
124
125const CASET: Command = Command {
126    id: 0x2A,
127    parameters: Some(&[0x00, 0x00, 0x00, 0x00]),
128    delay: 0,
129};
130
131const RASET: Command = Command {
132    id: 0x2B,
133    parameters: Some(&[0x00, 0x00, 0x00, 0x00]),
134    delay: 0,
135};
136
137const NORON: Command = Command {
138    id: 0x13,
139    parameters: None,
140    delay: 10,
141};
142
143#[allow(dead_code)]
144const IDLE_OFF: Command = Command {
145    id: 0x38,
146    parameters: None,
147    delay: 20,
148};
149
150#[allow(dead_code)]
151const IDLE_ON: Command = Command {
152    id: 0x39,
153    parameters: None,
154    delay: 0,
155};
156
157const COLMOD: Command = Command {
158    id: 0x3A,
159    parameters: Some(&[0x05]),
160    delay: 0,
161};
162
163const MADCTL: Command = Command {
164    id: 0x36,
165    parameters: Some(&[0x00]),
166    delay: 0,
167};
168
169pub type CommandSequence = &'static [SendCommand];
170
171#[macro_export]
172macro_rules! default_parameters_sequence {
173    ($($cmd:expr),+) => {
174        [$(SendCommand::Default($cmd), )+]
175    }
176}
177
178pub const SEQUENCE_BUFFER_SIZE: usize = 24;
179
180#[derive(Copy, Clone, PartialEq)]
181enum Status {
182    Idle,
183    Init,
184    Reset1,
185    Reset2,
186    Reset3,
187    Reset4,
188    SendCommand(usize, usize, usize),
189    SendCommandSlice(usize),
190    SendParametersSlice,
191    Delay,
192    Error(ErrorCode),
193}
194#[derive(Copy, Clone, PartialEq)]
195pub enum SendCommand {
196    Nop,
197    Default(&'static Command),
198    // first usize is the position in the buffer
199    // second usize is the length in the buffer starting from the position
200    Position(&'static Command, usize, usize),
201    // first usize is the position in the buffer (4 bytes - repeat times, length bytes data)
202    // second usize is the length in the buffer
203    // third usize is the number of repeats
204    Repeat(&'static Command, usize, usize, usize),
205    // usize is length
206    Slice(&'static Command, usize),
207}
208
209pub struct ST77XX<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> {
210    bus: &'a B,
211    alarm: &'a A,
212    dc: Option<&'a P>,
213    reset: Option<&'a P>,
214    status: Cell<Status>,
215    width: Cell<usize>,
216    height: Cell<usize>,
217
218    client: OptionalCell<&'a dyn screen::ScreenClient>,
219    setup_client: OptionalCell<&'a dyn screen::ScreenSetupClient>,
220    setup_command: Cell<bool>,
221
222    sequence_buffer: TakeCell<'static, [SendCommand]>,
223    position_in_sequence: Cell<usize>,
224    sequence_len: Cell<usize>,
225    command: Cell<&'static Command>,
226    buffer: TakeCell<'static, [u8]>,
227
228    power_on: Cell<bool>,
229
230    write_buffer: TakeCell<'static, [u8]>,
231
232    current_rotation: Cell<ScreenRotation>,
233
234    screen: &'static ST77XXScreen,
235}
236
237impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> ST77XX<'a, A, B, P> {
238    pub fn new(
239        bus: &'a B,
240        alarm: &'a A,
241        dc: Option<&'a P>,
242        reset: Option<&'a P>,
243        buffer: &'static mut [u8],
244        sequence_buffer: &'static mut [SendCommand],
245        screen: &'static ST77XXScreen,
246    ) -> ST77XX<'a, A, B, P> {
247        dc.map(|dc| dc.make_output());
248        reset.map(|reset| reset.make_output());
249        ST77XX {
250            alarm,
251
252            dc,
253            reset,
254            bus,
255
256            status: Cell::new(Status::Idle),
257            width: Cell::new(screen.default_width),
258            height: Cell::new(screen.default_height),
259
260            client: OptionalCell::empty(),
261            setup_client: OptionalCell::empty(),
262            setup_command: Cell::new(false),
263
264            sequence_buffer: TakeCell::new(sequence_buffer),
265            sequence_len: Cell::new(0),
266            position_in_sequence: Cell::new(0),
267            command: Cell::new(&NOP),
268            buffer: TakeCell::new(buffer),
269
270            power_on: Cell::new(false),
271
272            write_buffer: TakeCell::empty(),
273
274            current_rotation: Cell::new(ScreenRotation::Normal),
275
276            screen,
277        }
278    }
279
280    fn send_sequence(&self, sequence: CommandSequence) -> Result<(), ErrorCode> {
281        if self.status.get() == Status::Idle {
282            let error = self.sequence_buffer.map_or_else(
283                || panic!("st77xx: send sequence has no sequence buffer"),
284                |sequence_buffer| {
285                    if sequence.len() <= sequence_buffer.len() {
286                        self.sequence_len.set(sequence.len());
287                        for (i, cmd) in sequence.iter().enumerate() {
288                            sequence_buffer[i] = *cmd;
289                        }
290                        Ok(())
291                    } else {
292                        Err(ErrorCode::NOMEM)
293                    }
294                },
295            );
296            if error == Ok(()) {
297                self.send_sequence_buffer()
298            } else {
299                error
300            }
301        } else {
302            Err(ErrorCode::BUSY)
303        }
304    }
305
306    fn send_sequence_buffer(&self) -> Result<(), ErrorCode> {
307        if self.status.get() == Status::Idle {
308            self.position_in_sequence.set(0);
309            // set status to delay so that do_next_op will send the next item in the sequence
310            self.status.set(Status::Delay);
311            self.do_next_op();
312            Ok(())
313        } else {
314            Err(ErrorCode::BUSY)
315        }
316    }
317
318    fn send_command_with_default_parameters(&self, cmd: &'static Command) {
319        let mut len = 0;
320        self.buffer.map_or_else(
321            || panic!("st77xx: send parameters has no buffer"),
322            |buffer| {
323                // buffer[0] = cmd.id;
324                if let Some(parameters) = cmd.parameters {
325                    for parameter in parameters.iter() {
326                        buffer[len] = *parameter;
327                        len += 1;
328                    }
329                }
330            },
331        );
332        self.send_command(cmd, 0, len, 1);
333    }
334
335    fn send_command(&self, cmd: &'static Command, position: usize, len: usize, repeat: usize) {
336        self.command.set(cmd);
337        self.status.set(Status::SendCommand(position, len, repeat));
338        self.dc.map(|dc| dc.clear());
339        let _ = self.bus.set_addr(cmd.id.into());
340    }
341
342    fn send_command_slice(&self, cmd: &'static Command, len: usize) {
343        self.command.set(cmd);
344        self.dc.map(|dc| dc.clear());
345        self.status.set(Status::SendCommandSlice(len));
346        let _ = self.bus.set_addr(cmd.id.into());
347    }
348
349    fn send_parameters(&self, position: usize, len: usize, repeat: usize) {
350        self.status.set(Status::SendCommand(0, len, repeat - 1));
351        if len > 0 {
352            self.buffer.take().map_or_else(
353                || panic!("st77xx: send parameters has no buffer"),
354                |buffer| {
355                    // shift parameters
356                    if position > 0 {
357                        for i in position..len + position {
358                            buffer[i - position] = buffer[i];
359                        }
360                    }
361                    self.dc.map(|dc| dc.set());
362                    match self.bus.write(DataWidth::Bits8, buffer, len) {
363                        Ok(()) => (),
364                        Err((e, buf)) => {
365                            self.buffer.replace(buf);
366                            self.status.set(Status::Error(e));
367                            self.do_next_op();
368                        }
369                    }
370                },
371            );
372        } else {
373            self.do_next_op();
374        }
375    }
376
377    fn send_parameters_slice(&self, len: usize) {
378        self.write_buffer.take().map_or_else(
379            || panic!("st77xx: no write buffer"),
380            |buffer| {
381                self.status.set(Status::SendParametersSlice);
382                self.dc.map(|dc| dc.set());
383                match self.bus.write(DataWidth::Bits16BE, buffer, len / 2) {
384                    Ok(()) => (),
385                    Err((e, buf)) => {
386                        self.write_buffer.replace(buf);
387                        self.status.set(Status::Error(e));
388                        self.do_next_op();
389                    }
390                }
391            },
392        );
393    }
394
395    fn rotation(&self, rotation: ScreenRotation) -> Result<(), ErrorCode> {
396        if self.status.get() == Status::Idle {
397            let rotation_bits = match rotation {
398                ScreenRotation::Normal => 0x00,
399                ScreenRotation::Rotated90 => 0x60,
400                ScreenRotation::Rotated180 => 0xC0,
401                ScreenRotation::Rotated270 => 0xA0,
402            };
403            match rotation {
404                ScreenRotation::Normal | ScreenRotation::Rotated180 => {
405                    self.width.set(self.screen.default_width);
406                    self.height.set(self.screen.default_height);
407                }
408                ScreenRotation::Rotated90 | ScreenRotation::Rotated270 => {
409                    self.width.set(self.screen.default_height);
410                    self.height.set(self.screen.default_width);
411                }
412            }
413            self.buffer.map_or_else(
414                || panic!("st77xx: set rotation has no buffer"),
415                |buffer| {
416                    buffer[0] =
417                        rotation_bits | MADCTL.parameters.map_or(0, |parameters| parameters[0])
418                },
419            );
420            self.setup_command.set(true);
421            self.send_command(&MADCTL, 0, 1, 1);
422            self.current_rotation.set(rotation);
423            Ok(())
424        } else {
425            Err(ErrorCode::BUSY)
426        }
427    }
428
429    fn display_on(&self) -> Result<(), ErrorCode> {
430        if self.status.get() == Status::Idle {
431            if !self.power_on.get() {
432                Err(ErrorCode::OFF)
433            } else {
434                self.setup_command.set(false);
435                self.send_command_with_default_parameters(&DISPLAY_ON);
436                Ok(())
437            }
438        } else {
439            Err(ErrorCode::BUSY)
440        }
441    }
442
443    fn display_off(&self) -> Result<(), ErrorCode> {
444        if self.status.get() == Status::Idle {
445            if !self.power_on.get() {
446                Err(ErrorCode::OFF)
447            } else {
448                self.setup_command.set(false);
449                self.send_command_with_default_parameters(&DISPLAY_OFF);
450                Ok(())
451            }
452        } else {
453            Err(ErrorCode::BUSY)
454        }
455    }
456
457    fn display_invert_on(&self) -> Result<(), ErrorCode> {
458        if self.status.get() == Status::Idle {
459            if !self.power_on.get() {
460                Err(ErrorCode::OFF)
461            } else {
462                self.setup_command.set(false);
463                let cmd = if self.screen.inverted {
464                    &INVOFF
465                } else {
466                    &INVON
467                };
468                self.send_command_with_default_parameters(cmd);
469                Ok(())
470            }
471        } else {
472            Err(ErrorCode::BUSY)
473        }
474    }
475
476    fn display_invert_off(&self) -> Result<(), ErrorCode> {
477        if self.status.get() == Status::Idle {
478            if !self.power_on.get() {
479                Err(ErrorCode::OFF)
480            } else {
481                self.setup_command.set(false);
482                let cmd = if self.screen.inverted {
483                    &INVON
484                } else {
485                    &INVOFF
486                };
487                self.send_command_with_default_parameters(cmd);
488                Ok(())
489            }
490        } else {
491            Err(ErrorCode::BUSY)
492        }
493    }
494
495    fn do_next_op(&self) {
496        match self.status.get() {
497            Status::Delay => {
498                let position = self.position_in_sequence.get();
499
500                self.position_in_sequence
501                    .set(self.position_in_sequence.get() + 1);
502                if position < self.sequence_len.get() {
503                    self.sequence_buffer.map_or_else(
504                        || panic!("st77xx: do next op has no sequence buffer"),
505                        |sequence| match sequence[position] {
506                            SendCommand::Nop => self.do_next_op(),
507                            SendCommand::Default(cmd) => {
508                                self.send_command_with_default_parameters(cmd)
509                            }
510                            SendCommand::Position(cmd, position, len) => {
511                                self.send_command(cmd, position, len, 1)
512                            }
513                            SendCommand::Repeat(cmd, position, len, repeat) => {
514                                self.send_command(cmd, position, len, repeat)
515                            }
516                            SendCommand::Slice(cmd, len) => self.send_command_slice(cmd, len),
517                        },
518                    );
519                } else {
520                    self.status.set(Status::Idle);
521                    if !self.power_on.get() {
522                        self.client.map(|client| {
523                            self.power_on.set(true);
524
525                            client.screen_is_ready()
526                        });
527                    } else {
528                        if self.setup_command.get() {
529                            self.setup_command.set(false);
530                            self.setup_client
531                                .map(|setup_client| setup_client.command_complete(Ok(())));
532                        } else {
533                            self.client.map(|client| {
534                                if self.write_buffer.is_some() {
535                                    self.write_buffer.take().map(|buffer| {
536                                        let data = SubSliceMut::new(buffer);
537                                        client.write_complete(data, Ok(()))
538                                    });
539                                } else {
540                                    client.command_complete(Ok(()))
541                                }
542                            });
543                        }
544                    }
545                }
546            }
547            Status::SendCommand(parameters_position, parameters_length, repeat) => {
548                if repeat == 0 {
549                    self.dc.map(|dc| dc.clear());
550                    let mut delay = self.command.get().delay as u32;
551                    if delay > 0 {
552                        if delay == 255 {
553                            delay = 500;
554                        }
555                        self.set_delay(delay, Status::Delay)
556                    } else {
557                        self.status.set(Status::Delay);
558                        self.do_next_op();
559                    }
560                } else {
561                    self.send_parameters(parameters_position, parameters_length, repeat);
562                }
563            }
564            Status::SendCommandSlice(len) => {
565                self.send_parameters_slice(len);
566            }
567            Status::SendParametersSlice => {
568                self.dc.map(|dc| dc.clear());
569                let mut delay = self.command.get().delay as u32;
570                if delay > 0 {
571                    if delay == 255 {
572                        delay = 500;
573                    }
574                    self.set_delay(delay, Status::Delay)
575                } else {
576                    self.status.set(Status::Delay);
577                    self.do_next_op();
578                }
579            }
580            Status::Reset1 => {
581                // self.send_command_with_default_parameters(&NOP);
582                self.reset.map(|reset| reset.clear());
583                self.set_delay(10, Status::Reset2);
584            }
585            Status::Reset2 => {
586                self.reset.map(|reset| reset.set());
587                self.set_delay(120, Status::Reset3);
588            }
589            Status::Reset3 => {
590                self.reset.map(|reset| reset.clear());
591                self.set_delay(120, Status::Reset4);
592            }
593            Status::Reset4 => {
594                self.reset.map(|reset| reset.set());
595                self.set_delay(120, Status::Init);
596            }
597            Status::Init => {
598                self.status.set(Status::Idle);
599                let _ = self.send_sequence(self.screen.init_sequence);
600            }
601            Status::Error(error) => {
602                self.status.set(Status::Idle);
603                if self.setup_command.get() {
604                    self.setup_command.set(false);
605                    self.setup_client.map(|setup_client| {
606                        setup_client.command_complete(Err(error));
607                    });
608                } else {
609                    self.client.map(|client| {
610                        if self.write_buffer.is_some() {
611                            self.write_buffer.take().map(|buffer| {
612                                let data = SubSliceMut::new(buffer);
613                                client.write_complete(data, Err(error));
614                            });
615                        } else {
616                            client.command_complete(Err(error));
617                        }
618                    });
619                }
620            }
621            _ => {
622                panic!("ST77XX status Idle");
623            }
624        }
625    }
626
627    fn set_memory_frame(
628        &self,
629        position: usize,
630        sx: usize,
631        sy: usize,
632        ex: usize,
633        ey: usize,
634    ) -> Result<(), ErrorCode> {
635        if sx <= self.width.get()
636            && sy <= self.height.get()
637            && ex <= self.width.get()
638            && ey <= self.height.get()
639            && sx <= ex
640            && sy <= ey
641        {
642            let (ox, oy) = (self.screen.offset)(self.current_rotation.get());
643            if self.status.get() == Status::Idle {
644                self.buffer.map_or_else(
645                    || panic!("st77xx: set memory frame has no buffer"),
646                    |buffer| {
647                        // CASET
648                        buffer[position] = (((sx + ox) >> 8) & 0xFF) as u8;
649                        buffer[position + 1] = ((sx + ox) & 0xFF) as u8;
650                        buffer[position + 2] = (((ex + ox) >> 8) & 0xFF) as u8;
651                        buffer[position + 3] = ((ex + ox) & 0xFF) as u8;
652                        // RASET
653                        buffer[position + 4] = (((sy + oy) >> 8) & 0xFF) as u8;
654                        buffer[position + 5] = ((sy + oy) & 0xFF) as u8;
655                        buffer[position + 6] = (((ey + oy) >> 8) & 0xFF) as u8;
656                        buffer[position + 7] = ((ey + oy) & 0xFF) as u8;
657                    },
658                );
659                Ok(())
660            } else {
661                Err(ErrorCode::BUSY)
662            }
663        } else {
664            Err(ErrorCode::INVAL)
665        }
666    }
667
668    pub fn init(&self) -> Result<(), ErrorCode> {
669        if self.status.get() == Status::Idle {
670            self.status.set(Status::Reset1);
671            self.do_next_op();
672            Ok(())
673        } else {
674            Err(ErrorCode::BUSY)
675        }
676    }
677
678    /// set_delay sets an alarm and saved the next state after that.
679    ///
680    /// As argument, there are:
681    ///  - the duration of the alarm in ms
682    ///  - the status of the program after the alarm fires
683    ///
684    /// Example:
685    ///  self.set_delay(10, Status::Idle);
686    fn set_delay(&self, timer: u32, next_status: Status) {
687        self.status.set(next_status);
688        let interval = self.alarm.ticks_from_ms(timer);
689        self.alarm.set_alarm(self.alarm.now(), interval);
690    }
691}
692
693impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> screen::ScreenSetup<'a>
694    for ST77XX<'a, A, B, P>
695{
696    fn set_client(&self, setup_client: &'a dyn ScreenSetupClient) {
697        self.setup_client.set(setup_client);
698    }
699
700    fn set_resolution(&self, resolution: (usize, usize)) -> Result<(), ErrorCode> {
701        if self.status.get() == Status::Idle {
702            if resolution.0 == self.width.get() && resolution.1 == self.height.get() {
703                self.setup_client
704                    .map(|setup_client| setup_client.command_complete(Ok(())));
705                Ok(())
706            } else {
707                Err(ErrorCode::NOSUPPORT)
708            }
709        } else {
710            Err(ErrorCode::BUSY)
711        }
712    }
713
714    fn set_pixel_format(&self, depth: ScreenPixelFormat) -> Result<(), ErrorCode> {
715        if self.status.get() == Status::Idle {
716            if depth == ScreenPixelFormat::RGB_565 {
717                self.setup_client
718                    .map(|setup_client| setup_client.command_complete(Ok(())));
719                Ok(())
720            } else {
721                Err(ErrorCode::INVAL)
722            }
723        } else {
724            Err(ErrorCode::BUSY)
725        }
726    }
727
728    fn set_rotation(&self, rotation: ScreenRotation) -> Result<(), ErrorCode> {
729        self.rotation(rotation)
730    }
731
732    fn get_num_supported_resolutions(&self) -> usize {
733        1
734    }
735    fn get_supported_resolution(&self, index: usize) -> Option<(usize, usize)> {
736        match index {
737            0 => Some((self.width.get(), self.height.get())),
738            _ => None,
739        }
740    }
741
742    fn get_num_supported_pixel_formats(&self) -> usize {
743        1
744    }
745    fn get_supported_pixel_format(&self, index: usize) -> Option<ScreenPixelFormat> {
746        match index {
747            0 => Some(ScreenPixelFormat::RGB_565),
748            _ => None,
749        }
750    }
751}
752
753impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> screen::Screen<'a> for ST77XX<'a, A, B, P> {
754    fn get_resolution(&self) -> (usize, usize) {
755        (self.width.get(), self.height.get())
756    }
757
758    fn get_pixel_format(&self) -> ScreenPixelFormat {
759        ScreenPixelFormat::RGB_565
760    }
761
762    fn get_rotation(&self) -> ScreenRotation {
763        self.current_rotation.get()
764    }
765
766    fn set_write_frame(
767        &self,
768        x: usize,
769        y: usize,
770        width: usize,
771        height: usize,
772    ) -> Result<(), ErrorCode> {
773        if self.status.get() == Status::Idle {
774            self.setup_command.set(false);
775            let buffer_len = self.buffer.map_or_else(
776                || panic!("st77xx: buffer is not available"),
777                |buffer| buffer.len() - 1,
778            );
779            if buffer_len >= 9 {
780                // set buffer
781                let err = self.set_memory_frame(0, x, y, x + width - 1, y + height - 1);
782                if err == Ok(()) {
783                    self.sequence_buffer.map_or_else(
784                        || panic!("st77xx: set write frame no sequence buffer"),
785                        |sequence| {
786                            sequence[0] = SendCommand::Position(&CASET, 0, 4);
787                            sequence[1] = SendCommand::Position(&RASET, 4, 4);
788                            self.sequence_len.set(2);
789                        },
790                    );
791                    let _ = self.send_sequence_buffer();
792                }
793                err
794            } else {
795                Err(ErrorCode::NOMEM)
796            }
797        } else {
798            Err(ErrorCode::BUSY)
799        }
800    }
801
802    fn write(
803        &self,
804        mut data: SubSliceMut<'static, u8>,
805        continue_write: bool,
806    ) -> Result<(), ErrorCode> {
807        if self.status.get() == Status::Idle {
808            // Data is provided as RGB565 ( RRRRR GGG | GGG BBBBB ), but the device expects it to come over the bus in little endian, so ( GGG BBBBB | RRRRR GGG ).
809            // TODO(alevy): replace `chunks_mut` wit `array_chunks` when stable.
810            for pair in data.as_mut_slice().chunks_mut(2) {
811                pair.swap(0, 1);
812            }
813
814            self.setup_command.set(false);
815            let len = data.len();
816            self.write_buffer.replace(data.take());
817
818            if !continue_write {
819                // Writing new data for the first time, make sure to reset
820                // the screen buffer location to the beginning.
821
822                let buffer_len = self.buffer.map_or_else(
823                    || panic!("st77xx: buffer is not available"),
824                    |buffer| buffer.len(),
825                );
826                if buffer_len > 0 {
827                    // set buffer
828                    self.sequence_buffer.map_or_else(
829                        || panic!("st77xx: write no sequence buffer"),
830                        |sequence| {
831                            sequence[0] = SendCommand::Slice(&WRITE_RAM, len);
832                            self.sequence_len.set(1);
833                        },
834                    );
835                    let _ = self.send_sequence_buffer();
836                    Ok(())
837                } else {
838                    Err(ErrorCode::NOMEM)
839                }
840            } else {
841                // Continuing the previous write.
842                self.send_parameters_slice(len);
843                Ok(())
844            }
845        } else {
846            Err(ErrorCode::BUSY)
847        }
848    }
849
850    fn set_client(&self, client: &'a dyn ScreenClient) {
851        self.client.set(client);
852    }
853
854    fn set_brightness(&self, _brightness: u16) -> Result<(), ErrorCode> {
855        Ok(())
856    }
857
858    fn set_power(&self, enabled: bool) -> Result<(), ErrorCode> {
859        if enabled {
860            self.display_on()
861        } else {
862            self.display_off()
863        }
864    }
865
866    fn set_invert(&self, enabled: bool) -> Result<(), ErrorCode> {
867        if enabled {
868            self.display_invert_on()
869        } else {
870            self.display_invert_off()
871        }
872    }
873}
874
875impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> time::AlarmClient for ST77XX<'a, A, B, P> {
876    fn alarm(&self) {
877        self.do_next_op();
878    }
879}
880
881impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> bus::Client for ST77XX<'a, A, B, P> {
882    fn command_complete(
883        &self,
884        buffer: Option<&'static mut [u8]>,
885        _len: usize,
886        status: Result<(), ErrorCode>,
887    ) {
888        if let Some(buffer) = buffer {
889            if self.status.get() == Status::SendParametersSlice {
890                self.write_buffer.replace(buffer);
891            } else {
892                self.buffer.replace(buffer);
893            }
894        }
895
896        if let Err(error) = status {
897            self.status.set(Status::Error(error));
898        }
899
900        self.do_next_op();
901    }
902}
903
904/************ ST7735 **************/
905#[allow(dead_code)]
906const GAMSET: Command = Command {
907    id: 0x26,
908    // Default parameters: Gama Set
909    parameters: Some(&[0]),
910    delay: 0,
911};
912
913const FRMCTR1: Command = Command {
914    id: 0xB1,
915    parameters: Some(&[0x01, 0x2C, 0x2D]),
916    delay: 0,
917};
918
919const FRMCTR2: Command = Command {
920    id: 0xB2,
921    parameters: Some(&[0x01, 0x2C, 0x2D]),
922    delay: 0,
923};
924
925const FRMCTR3: Command = Command {
926    id: 0xB3,
927    parameters: Some(&[0x01, 0x2C, 0x2D, 0x01, 0x2C, 0x2D]),
928    delay: 0,
929};
930
931const INVCTR: Command = Command {
932    id: 0xB4,
933    parameters: Some(&[0x07]),
934    delay: 0,
935};
936
937const PWCTR1: Command = Command {
938    id: 0xC0,
939    parameters: Some(&[0xA2, 0x02, 0x84]),
940    delay: 0,
941};
942
943const PWCTR2: Command = Command {
944    id: 0xC1,
945    parameters: Some(&[0xC5]),
946    delay: 0,
947};
948
949const PWCTR3: Command = Command {
950    id: 0xC2,
951    parameters: Some(&[0x0A, 0x00]),
952    delay: 0,
953};
954
955const PWCTR4: Command = Command {
956    id: 0xC3,
957    parameters: Some(&[0x8A, 0x2A]),
958    delay: 0,
959};
960
961const PWCTR5: Command = Command {
962    id: 0xC4,
963    parameters: Some(&[0x8A, 0xEE]),
964    delay: 0,
965};
966
967const VMCTR1: Command = Command {
968    id: 0xC5,
969    parameters: Some(&[0x0E]),
970    delay: 0,
971};
972
973const GMCTRP1: Command = Command {
974    id: 0xE0,
975    parameters: Some(&[
976        0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2B, 0x39, 0x00, 0x01, 0x03,
977        0x10,
978    ]),
979    delay: 0,
980};
981
982const GMCTRN1: Command = Command {
983    id: 0xE1,
984    parameters: Some(&[
985        0x03, 0x1d, 0x07, 0x06, 0x2E, 0x2C, 0x29, 0x2D, 0x2E, 0x2E, 0x37, 0x3F, 0x00, 0x00, 0x02,
986        0x10,
987    ]),
988    delay: 0,
989};
990
991const ST7735_INIT_SEQUENCE: [SendCommand; 20] = crate::default_parameters_sequence!(
992    &SW_RESET, &SLEEP_OUT, &FRMCTR1, &FRMCTR2, &FRMCTR3, &INVCTR, &PWCTR1, &PWCTR2, &PWCTR3,
993    &PWCTR4, &PWCTR5, &VMCTR1, &INVOFF, &MADCTL, &COLMOD, &CASET, &RASET, &GMCTRP1, &GMCTRN1,
994    &NORON
995);
996
997/************ ST7789H2 **************/
998
999const PV_GAMMA_CTRL: Command = Command {
1000    id: 0xE0,
1001    parameters: Some(&[
1002        0xD0, 0x08, 0x11, 0x08, 0x0C, 0x15, 0x39, 0x33, 0x50, 0x36, 0x13, 0x14, 0x29, 0x2D,
1003    ]),
1004    delay: 0,
1005};
1006
1007const NV_GAMMA_CTRL: Command = Command {
1008    id: 0xE1,
1009    parameters: Some(&[
1010        0xD0, 0x08, 0x10, 0x08, 0x06, 0x06, 0x39, 0x44, 0x51, 0x0B, 0x16, 0x14, 0x2F, 0x31,
1011    ]),
1012    delay: 0,
1013};
1014
1015const PORCH_CTRL: Command = Command {
1016    id: 0xB2,
1017    parameters: Some(&[0x0C, 0x0C, 0x00, 0x33, 0x33]),
1018    delay: 0,
1019};
1020
1021const GATE_CTRL: Command = Command {
1022    id: 0xB7,
1023    parameters: Some(&[0x35]),
1024    delay: 0,
1025};
1026
1027const LCM_CTRL: Command = Command {
1028    id: 0xC0,
1029    parameters: Some(&[0x2C]),
1030    delay: 0,
1031};
1032
1033const VDV_VRH_EN: Command = Command {
1034    id: 0xC2,
1035    parameters: Some(&[0x01, 0xC3]),
1036    delay: 0,
1037};
1038
1039const VDV_SET: Command = Command {
1040    id: 0xC4,
1041    parameters: Some(&[0x20]),
1042    delay: 0,
1043};
1044
1045const FR_CTRL: Command = Command {
1046    id: 0xC6,
1047    parameters: Some(&[0x0F]),
1048    delay: 0,
1049};
1050
1051const VCOM_SET: Command = Command {
1052    id: 0xBB,
1053    parameters: Some(&[0x1F]),
1054    delay: 0,
1055};
1056
1057const POWER_CTRL: Command = Command {
1058    id: 0xD0,
1059    parameters: Some(&[0xA4, 0xA1]),
1060    delay: 0,
1061};
1062
1063const TEARING_EFFECT: Command = Command {
1064    id: 0x35,
1065    parameters: Some(&[0x00]),
1066    delay: 0,
1067};
1068
1069const ST7789H2_INIT_SEQUENCE: [SendCommand; 22] = crate::default_parameters_sequence!(
1070    &SLEEP_IN,
1071    &SW_RESET,
1072    &SLEEP_OUT,
1073    &NORON,
1074    &COLMOD,
1075    &INVON,
1076    &CASET,
1077    &RASET,
1078    &PORCH_CTRL,
1079    &GATE_CTRL,
1080    &VCOM_SET,
1081    &LCM_CTRL,
1082    &VDV_VRH_EN,
1083    &VDV_SET,
1084    &FR_CTRL,
1085    &POWER_CTRL,
1086    &PV_GAMMA_CTRL,
1087    &NV_GAMMA_CTRL,
1088    &MADCTL,
1089    &DISPLAY_ON,
1090    &SLEEP_OUT,
1091    &TEARING_EFFECT
1092);
1093
1094/******** LS016B8UY *********/
1095
1096const VSYNC_OUTPUT: Command = Command {
1097    id: 0x35,
1098    parameters: Some(&[0x00]),
1099    delay: 0,
1100};
1101
1102const NORMAL_DISPLAY: Command = Command {
1103    id: 0x36,
1104    parameters: Some(&[0x83]),
1105    delay: 0,
1106};
1107
1108const PANEL_SETTING1: Command = Command {
1109    id: 0xB0,
1110    parameters: Some(&[0x01, 0xFE]),
1111    delay: 0,
1112};
1113
1114const PANEL_SETTING2: Command = Command {
1115    id: 0xB1,
1116    parameters: Some(&[0xDE, 0x21]),
1117    delay: 0,
1118};
1119
1120const OSCILLATOR: Command = Command {
1121    id: 0xB3,
1122    parameters: Some(&[0x02]),
1123    delay: 0,
1124};
1125
1126const PANEL_SETTING_LOCK: Command = Command {
1127    id: 0xB4,
1128    parameters: None,
1129    delay: 0,
1130};
1131
1132const PANEL_V_PORCH: Command = Command {
1133    id: 0xB7,
1134    parameters: Some(&[0x05, 0x33]),
1135    delay: 0,
1136};
1137
1138const PANEL_IDLE_V_PORCH: Command = Command {
1139    id: 0xB8,
1140    parameters: Some(&[0x05, 0x33]),
1141    delay: 0,
1142};
1143
1144const GVDD: Command = Command {
1145    id: 0xC0,
1146    parameters: Some(&[0x53]),
1147    delay: 0,
1148};
1149
1150const OPAMP: Command = Command {
1151    id: 0xC2,
1152    parameters: Some(&[0x03, 0x12]),
1153    delay: 0,
1154};
1155
1156const RELOAD_MTP_VCOMH: Command = Command {
1157    id: 0xC5,
1158    parameters: Some(&[0x00, 0x45]),
1159    delay: 0,
1160};
1161
1162const PANEL_TIMING1: Command = Command {
1163    id: 0xC8,
1164    parameters: Some(&[0x04, 0x03]),
1165    delay: 0,
1166};
1167
1168const PANEL_TIMING2: Command = Command {
1169    id: 0xC9,
1170    parameters: Some(&[0x5E, 0x08]),
1171    delay: 0,
1172};
1173
1174const PANEL_TIMING3: Command = Command {
1175    id: 0xCA,
1176    parameters: Some(&[0x0A, 0x0C, 0x02]),
1177    delay: 0,
1178};
1179
1180const PANEL_TIMING4: Command = Command {
1181    id: 0xCC,
1182    parameters: Some(&[0x03, 0x04]),
1183    delay: 0,
1184};
1185
1186const PANEL_POWER: Command = Command {
1187    id: 0xD0,
1188    parameters: Some(&[0x0C]),
1189    delay: 0,
1190};
1191
1192const LS0168BUY_TEARING_EFFECT: Command = Command {
1193    id: 0xDD,
1194    parameters: Some(&[0x00]),
1195    delay: 0,
1196};
1197
1198const LS016B8UY_INIT_SEQUENCE: [SendCommand; 23] = default_parameters_sequence!(
1199    &VSYNC_OUTPUT,
1200    &COLMOD,
1201    &PANEL_SETTING1,
1202    &PANEL_SETTING2,
1203    &PANEL_V_PORCH,
1204    &PANEL_IDLE_V_PORCH,
1205    &PANEL_TIMING1,
1206    &PANEL_TIMING2,
1207    &PANEL_TIMING3,
1208    &PANEL_TIMING4,
1209    &PANEL_POWER,
1210    &OSCILLATOR,
1211    &GVDD,
1212    &RELOAD_MTP_VCOMH,
1213    &OPAMP,
1214    &LS0168BUY_TEARING_EFFECT,
1215    &PANEL_SETTING_LOCK,
1216    &SLEEP_OUT,
1217    &NORMAL_DISPLAY,
1218    &CASET,
1219    &RASET,
1220    &DISPLAY_ON,
1221    &IDLE_OFF
1222);
1223
1224pub struct ST77XXScreen {
1225    init_sequence: &'static [SendCommand],
1226    default_width: usize,
1227    default_height: usize,
1228    inverted: bool,
1229
1230    /// This function allows the translation of the image
1231    /// as some screen implementations might have off screen
1232    /// pixels for some of the rotations
1233    offset: fn(rotation: ScreenRotation) -> (usize, usize),
1234}
1235
1236impl ST77XXScreen {
1237    pub const fn new(
1238        init_sequence: &'static [SendCommand],
1239        default_width: usize,
1240        default_height: usize,
1241        inverted: bool,
1242        offset: fn(rotation: ScreenRotation) -> (usize, usize),
1243    ) -> Self {
1244        Self {
1245            init_sequence,
1246            default_width,
1247            default_height,
1248            inverted,
1249            offset,
1250        }
1251    }
1252}
1253
1254pub const ST7735: ST77XXScreen = ST77XXScreen {
1255    init_sequence: &ST7735_INIT_SEQUENCE,
1256    default_width: 128,
1257    default_height: 160,
1258    inverted: false,
1259    offset: |_| (0, 0),
1260};
1261
1262pub const ST7789H2: ST77XXScreen = ST77XXScreen {
1263    init_sequence: &ST7789H2_INIT_SEQUENCE,
1264    default_width: 240,
1265    default_height: 240,
1266    inverted: true,
1267    offset: |rotation| match rotation {
1268        ScreenRotation::Rotated180 => (0, 80),
1269        ScreenRotation::Rotated270 => (80, 0),
1270        _ => (0, 0),
1271    },
1272};
1273
1274pub const LS016B8UY: ST77XXScreen = ST77XXScreen {
1275    init_sequence: &LS016B8UY_INIT_SEQUENCE,
1276    default_width: 240,
1277    default_height: 240,
1278    inverted: false,
1279    offset: |_| (0, 0),
1280};