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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! ST77xx Screen
//!
//! - <https://learn.adafruit.com/adafruit-1-3-and-1-54-240-x-240-wide-angle-tft-lcd-displays>
//!
//! The screen supports multiple physical busses, and this driver is implemented
//! on top of the generic `Bus` interface.
//!
//! Usage
//! -----
//!
//! SPI example
//!
//! ```rust,ignore
//! let tft = components::st77xx::ST77XXComponent::new(mux_alarm,
//!                                                    bus,
//!                                                    Some(&nrf52840::gpio::PORT[GPIO_D3]),
//!                                                    Some(&nrf52840::gpio::PORT[GPIO_D2]),
//!                                                    &capsules::st77xx::ST7735).finalize(
//!     components::st77xx_component_static!(
//!         // bus type
//!         capsules::bus::SpiMasterBus<
//!             'static,
//!             VirtualSpiMasterDevice<'static, nrf52840::spi::SPIM>,
//!         >,
//!         // timer type
//!         nrf52840::rtc::Rtc,
//!         // pin type
//!         nrf52::gpio::GPIOPin<'static>,
//!     ),
//! );
//! ```

use crate::bus::{self, Bus, BusAddr8, DataWidth};
use core::cell::Cell;
use kernel::hil::gpio::Pin;
use kernel::hil::screen::{
    self, ScreenClient, ScreenPixelFormat, ScreenRotation, ScreenSetupClient,
};
use kernel::hil::time::{self, Alarm, ConvertTicks};
use kernel::utilities::cells::{OptionalCell, TakeCell};
use kernel::utilities::leasable_buffer::SubSliceMut;
use kernel::ErrorCode;

pub const BUFFER_SIZE: usize = 24;

#[derive(PartialEq)]
pub struct Command {
    pub id: u8,
    pub parameters: Option<&'static [u8]>,
    pub delay: u8,
}

const NOP: Command = Command {
    id: 0x00,
    parameters: None,
    delay: 0,
};

const SW_RESET: Command = Command {
    id: 0x01,
    parameters: None,
    delay: 150, // 255?
};

const SLEEP_IN: Command = Command {
    id: 0x10,
    parameters: None,
    delay: 10,
};

const SLEEP_OUT: Command = Command {
    id: 0x11,
    parameters: None,
    delay: 255,
};

#[allow(dead_code)]
const PARTIAL_ON: Command = Command {
    id: 0x12,
    parameters: None,
    delay: 0,
};

const INVOFF: Command = Command {
    id: 0x20,
    parameters: None,
    delay: 0,
};

const INVON: Command = Command {
    id: 0x21,
    parameters: None,
    delay: 120,
};

const DISPLAY_OFF: Command = Command {
    id: 0x28,
    parameters: None,
    delay: 100,
};

const DISPLAY_ON: Command = Command {
    id: 0x29,
    parameters: None,
    delay: 100,
};

const WRITE_RAM: Command = Command {
    id: 0x2C,
    parameters: Some(&[]),
    delay: 0,
};

#[allow(dead_code)]
const READ_RAM: Command = Command {
    id: 0x2E,
    parameters: None,
    delay: 0,
};

const CASET: Command = Command {
    id: 0x2A,
    parameters: Some(&[0x00, 0x00, 0x00, 0x00]),
    delay: 0,
};

const RASET: Command = Command {
    id: 0x2B,
    parameters: Some(&[0x00, 0x00, 0x00, 0x00]),
    delay: 0,
};

const NORON: Command = Command {
    id: 0x13,
    parameters: None,
    delay: 10,
};

#[allow(dead_code)]
const IDLE_OFF: Command = Command {
    id: 0x38,
    parameters: None,
    delay: 20,
};

#[allow(dead_code)]
const IDLE_ON: Command = Command {
    id: 0x39,
    parameters: None,
    delay: 0,
};

const COLMOD: Command = Command {
    id: 0x3A,
    parameters: Some(&[0x05]),
    delay: 0,
};

const MADCTL: Command = Command {
    id: 0x36,
    parameters: Some(&[0x00]),
    delay: 0,
};

pub type CommandSequence = &'static [SendCommand];

#[macro_export]
macro_rules! default_parameters_sequence {
    ($($cmd:expr),+) => {
        [$(SendCommand::Default($cmd), )+]
    }
}

pub const SEQUENCE_BUFFER_SIZE: usize = 24;

#[derive(Copy, Clone, PartialEq)]
enum Status {
    Idle,
    Init,
    Reset1,
    Reset2,
    Reset3,
    Reset4,
    SendCommand(usize, usize, usize),
    SendCommandSlice(usize),
    SendParametersSlice,
    Delay,
    Error(ErrorCode),
}
#[derive(Copy, Clone, PartialEq)]
pub enum SendCommand {
    Nop,
    Default(&'static Command),
    // first usize is the position in the buffer
    // second usize is the length in the buffer starting from the position
    Position(&'static Command, usize, usize),
    // first usize is the position in the buffer (4 bytes - repeat times, length bytes data)
    // second usize is the length in the buffer
    // third usize is the number of repeats
    Repeat(&'static Command, usize, usize, usize),
    // usize is length
    Slice(&'static Command, usize),
}

pub struct ST77XX<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> {
    bus: &'a B,
    alarm: &'a A,
    dc: Option<&'a P>,
    reset: Option<&'a P>,
    status: Cell<Status>,
    width: Cell<usize>,
    height: Cell<usize>,

    client: OptionalCell<&'a dyn screen::ScreenClient>,
    setup_client: OptionalCell<&'a dyn screen::ScreenSetupClient>,
    setup_command: Cell<bool>,

    sequence_buffer: TakeCell<'static, [SendCommand]>,
    position_in_sequence: Cell<usize>,
    sequence_len: Cell<usize>,
    command: Cell<&'static Command>,
    buffer: TakeCell<'static, [u8]>,

    power_on: Cell<bool>,

    write_buffer: TakeCell<'static, [u8]>,

    current_rotation: Cell<ScreenRotation>,

    screen: &'static ST77XXScreen,
}

impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> ST77XX<'a, A, B, P> {
    pub fn new(
        bus: &'a B,
        alarm: &'a A,
        dc: Option<&'a P>,
        reset: Option<&'a P>,
        buffer: &'static mut [u8],
        sequence_buffer: &'static mut [SendCommand],
        screen: &'static ST77XXScreen,
    ) -> ST77XX<'a, A, B, P> {
        dc.map(|dc| dc.make_output());
        reset.map(|reset| reset.make_output());
        ST77XX {
            alarm,

            dc,
            reset,
            bus,

            status: Cell::new(Status::Idle),
            width: Cell::new(screen.default_width),
            height: Cell::new(screen.default_height),

            client: OptionalCell::empty(),
            setup_client: OptionalCell::empty(),
            setup_command: Cell::new(false),

            sequence_buffer: TakeCell::new(sequence_buffer),
            sequence_len: Cell::new(0),
            position_in_sequence: Cell::new(0),
            command: Cell::new(&NOP),
            buffer: TakeCell::new(buffer),

            power_on: Cell::new(false),

            write_buffer: TakeCell::empty(),

            current_rotation: Cell::new(ScreenRotation::Normal),

            screen,
        }
    }

    fn send_sequence(&self, sequence: CommandSequence) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            let error = self.sequence_buffer.map_or_else(
                || panic!("st77xx: send sequence has no sequence buffer"),
                |sequence_buffer| {
                    if sequence.len() <= sequence_buffer.len() {
                        self.sequence_len.set(sequence.len());
                        for (i, cmd) in sequence.iter().enumerate() {
                            sequence_buffer[i] = *cmd;
                        }
                        Ok(())
                    } else {
                        Err(ErrorCode::NOMEM)
                    }
                },
            );
            if error == Ok(()) {
                self.send_sequence_buffer()
            } else {
                error
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn send_sequence_buffer(&self) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            self.position_in_sequence.set(0);
            // set status to delay so that do_next_op will send the next item in the sequence
            self.status.set(Status::Delay);
            self.do_next_op();
            Ok(())
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn send_command_with_default_parameters(&self, cmd: &'static Command) {
        let mut len = 0;
        self.buffer.map_or_else(
            || panic!("st77xx: send parameters has no buffer"),
            |buffer| {
                // buffer[0] = cmd.id;
                if let Some(parameters) = cmd.parameters {
                    for parameter in parameters.iter() {
                        buffer[len] = *parameter;
                        len += 1;
                    }
                }
            },
        );
        self.send_command(cmd, 0, len, 1);
    }

    fn send_command(&self, cmd: &'static Command, position: usize, len: usize, repeat: usize) {
        self.command.set(cmd);
        self.status.set(Status::SendCommand(position, len, repeat));
        self.dc.map(|dc| dc.clear());
        let _ = self.bus.set_addr(cmd.id.into());
    }

    fn send_command_slice(&self, cmd: &'static Command, len: usize) {
        self.command.set(cmd);
        self.dc.map(|dc| dc.clear());
        self.status.set(Status::SendCommandSlice(len));
        let _ = self.bus.set_addr(cmd.id.into());
    }

    fn send_parameters(&self, position: usize, len: usize, repeat: usize) {
        self.status.set(Status::SendCommand(0, len, repeat - 1));
        if len > 0 {
            self.buffer.take().map_or_else(
                || panic!("st77xx: send parameters has no buffer"),
                |buffer| {
                    // shift parameters
                    if position > 0 {
                        for i in position..len + position {
                            buffer[i - position] = buffer[i];
                        }
                    }
                    self.dc.map(|dc| dc.set());
                    let _ = self.bus.write(DataWidth::Bits8, buffer, len);
                },
            );
        } else {
            self.do_next_op();
        }
    }

    fn send_parameters_slice(&self, len: usize) {
        self.write_buffer.take().map_or_else(
            || panic!("st77xx: no write buffer"),
            |buffer| {
                self.status.set(Status::SendParametersSlice);
                self.dc.map(|dc| dc.set());
                let _ = self.bus.write(DataWidth::Bits16BE, buffer, len / 2);
            },
        );
    }

    fn rotation(&self, rotation: ScreenRotation) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            let rotation_bits = match rotation {
                ScreenRotation::Normal => 0x00,
                ScreenRotation::Rotated90 => 0x60,
                ScreenRotation::Rotated180 => 0xC0,
                ScreenRotation::Rotated270 => 0xA0,
            };
            match rotation {
                ScreenRotation::Normal | ScreenRotation::Rotated180 => {
                    self.width.set(self.screen.default_width);
                    self.height.set(self.screen.default_height);
                }
                ScreenRotation::Rotated90 | ScreenRotation::Rotated270 => {
                    self.width.set(self.screen.default_height);
                    self.height.set(self.screen.default_width);
                }
            };
            self.buffer.map_or_else(
                || panic!("st77xx: set rotation has no buffer"),
                |buffer| {
                    buffer[0] =
                        rotation_bits | MADCTL.parameters.map_or(0, |parameters| parameters[0])
                },
            );
            self.setup_command.set(true);
            self.send_command(&MADCTL, 0, 1, 1);
            self.current_rotation.set(rotation);
            Ok(())
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn display_on(&self) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            if !self.power_on.get() {
                Err(ErrorCode::OFF)
            } else {
                self.setup_command.set(false);
                self.send_command_with_default_parameters(&DISPLAY_ON);
                Ok(())
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn display_off(&self) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            if !self.power_on.get() {
                Err(ErrorCode::OFF)
            } else {
                self.setup_command.set(false);
                self.send_command_with_default_parameters(&DISPLAY_OFF);
                Ok(())
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn display_invert_on(&self) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            if !self.power_on.get() {
                Err(ErrorCode::OFF)
            } else {
                self.setup_command.set(false);
                let cmd = if self.screen.inverted {
                    &INVOFF
                } else {
                    &INVON
                };
                self.send_command_with_default_parameters(cmd);
                Ok(())
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn display_invert_off(&self) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            if !self.power_on.get() {
                Err(ErrorCode::OFF)
            } else {
                self.setup_command.set(false);
                let cmd = if self.screen.inverted {
                    &INVON
                } else {
                    &INVOFF
                };
                self.send_command_with_default_parameters(cmd);
                Ok(())
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn do_next_op(&self) {
        match self.status.get() {
            Status::Delay => {
                let position = self.position_in_sequence.get();

                self.position_in_sequence
                    .set(self.position_in_sequence.get() + 1);
                if position < self.sequence_len.get() {
                    self.sequence_buffer.map_or_else(
                        || panic!("st77xx: do next op has no sequence buffer"),
                        |sequence| {
                            match sequence[position] {
                                SendCommand::Nop => {
                                    self.do_next_op();
                                }
                                SendCommand::Default(cmd) => {
                                    self.send_command_with_default_parameters(cmd);
                                }
                                SendCommand::Position(cmd, position, len) => {
                                    self.send_command(cmd, position, len, 1);
                                }
                                SendCommand::Repeat(cmd, position, len, repeat) => {
                                    self.send_command(cmd, position, len, repeat);
                                }
                                SendCommand::Slice(cmd, len) => {
                                    self.send_command_slice(cmd, len);
                                }
                            };
                        },
                    );
                } else {
                    self.status.set(Status::Idle);
                    if !self.power_on.get() {
                        self.client.map(|client| {
                            self.power_on.set(true);

                            client.screen_is_ready();
                        });
                    } else {
                        if self.setup_command.get() {
                            self.setup_command.set(false);
                            self.setup_client.map(|setup_client| {
                                setup_client.command_complete(Ok(()));
                            });
                        } else {
                            self.client.map(|client| {
                                if self.write_buffer.is_some() {
                                    self.write_buffer.take().map(|buffer| {
                                        let data = SubSliceMut::new(buffer);
                                        client.write_complete(data, Ok(()));
                                    });
                                } else {
                                    client.command_complete(Ok(()));
                                }
                            });
                        }
                    }
                }
            }
            Status::SendCommand(parameters_position, parameters_length, repeat) => {
                if repeat == 0 {
                    self.dc.map(|dc| dc.clear());
                    let mut delay = self.command.get().delay as u32;
                    if delay > 0 {
                        if delay == 255 {
                            delay = 500;
                        }
                        self.set_delay(delay, Status::Delay)
                    } else {
                        self.status.set(Status::Delay);
                        self.do_next_op();
                    }
                } else {
                    self.send_parameters(parameters_position, parameters_length, repeat);
                }
            }
            Status::SendCommandSlice(len) => {
                self.send_parameters_slice(len);
            }
            Status::SendParametersSlice => {
                self.dc.map(|dc| dc.clear());
                let mut delay = self.command.get().delay as u32;
                if delay > 0 {
                    if delay == 255 {
                        delay = 500;
                    }
                    self.set_delay(delay, Status::Delay)
                } else {
                    self.status.set(Status::Delay);
                    self.do_next_op();
                }
            }
            Status::Reset1 => {
                // self.send_command_with_default_parameters(&NOP);
                self.reset.map(|reset| reset.clear());
                self.set_delay(10, Status::Reset2);
            }
            Status::Reset2 => {
                self.reset.map(|reset| reset.set());
                self.set_delay(120, Status::Reset3);
            }
            Status::Reset3 => {
                self.reset.map(|reset| reset.clear());
                self.set_delay(120, Status::Reset4);
            }
            Status::Reset4 => {
                self.reset.map(|reset| reset.set());
                self.set_delay(120, Status::Init);
            }
            Status::Init => {
                self.status.set(Status::Idle);
                let _ = self.send_sequence(self.screen.init_sequence);
            }
            Status::Error(error) => {
                if self.setup_command.get() {
                    self.setup_command.set(false);
                    self.setup_client.map(|setup_client| {
                        setup_client.command_complete(Err(error));
                    });
                } else {
                    self.client.map(|client| {
                        if self.write_buffer.is_some() {
                            self.write_buffer.take().map(|buffer| {
                                let data = SubSliceMut::new(buffer);
                                client.write_complete(data, Err(error));
                            });
                        } else {
                            client.command_complete(Err(error));
                        }
                    });
                }
                self.status.set(Status::Idle);
            }
            _ => {
                panic!("ST77XX status Idle");
            }
        };
    }

    fn set_memory_frame(
        &self,
        position: usize,
        sx: usize,
        sy: usize,
        ex: usize,
        ey: usize,
    ) -> Result<(), ErrorCode> {
        if sx <= self.width.get()
            && sy <= self.height.get()
            && ex <= self.width.get()
            && ey <= self.height.get()
            && sx <= ex
            && sy <= ey
        {
            let (ox, oy) = (self.screen.offset)(self.current_rotation.get());
            if self.status.get() == Status::Idle {
                self.buffer.map_or_else(
                    || panic!("st77xx: set memory frame has no buffer"),
                    |buffer| {
                        // CASET
                        buffer[position] = (((sx + ox) >> 8) & 0xFF) as u8;
                        buffer[position + 1] = ((sx + ox) & 0xFF) as u8;
                        buffer[position + 2] = (((ex + ox) >> 8) & 0xFF) as u8;
                        buffer[position + 3] = ((ex + ox) & 0xFF) as u8;
                        // RASET
                        buffer[position + 4] = (((sy + oy) >> 8) & 0xFF) as u8;
                        buffer[position + 5] = ((sy + oy) & 0xFF) as u8;
                        buffer[position + 6] = (((ey + oy) >> 8) & 0xFF) as u8;
                        buffer[position + 7] = ((ey + oy) & 0xFF) as u8;
                    },
                );
                Ok(())
            } else {
                Err(ErrorCode::BUSY)
            }
        } else {
            Err(ErrorCode::INVAL)
        }
    }

    pub fn init(&self) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            self.status.set(Status::Reset1);
            self.do_next_op();
            Ok(())
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    /// set_delay sets an alarm and saved the next state after that.
    ///
    /// As argument, there are:
    ///  - the duration of the alarm in ms
    ///  - the status of the program after the alarm fires
    ///
    /// Example:
    ///  self.set_delay(10, Status::Idle);
    fn set_delay(&self, timer: u32, next_status: Status) {
        self.status.set(next_status);
        let interval = self.alarm.ticks_from_ms(timer);
        self.alarm.set_alarm(self.alarm.now(), interval);
    }
}

impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> screen::ScreenSetup<'a>
    for ST77XX<'a, A, B, P>
{
    fn set_client(&self, setup_client: &'a dyn ScreenSetupClient) {
        self.setup_client.set(setup_client);
    }

    fn set_resolution(&self, resolution: (usize, usize)) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            if resolution.0 == self.width.get() && resolution.1 == self.height.get() {
                self.setup_client
                    .map(|setup_client| setup_client.command_complete(Ok(())));
                Ok(())
            } else {
                Err(ErrorCode::NOSUPPORT)
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn set_pixel_format(&self, depth: ScreenPixelFormat) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            if depth == ScreenPixelFormat::RGB_565 {
                self.setup_client
                    .map(|setup_client| setup_client.command_complete(Ok(())));
                Ok(())
            } else {
                Err(ErrorCode::INVAL)
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn set_rotation(&self, rotation: ScreenRotation) -> Result<(), ErrorCode> {
        self.rotation(rotation)
    }

    fn get_num_supported_resolutions(&self) -> usize {
        1
    }
    fn get_supported_resolution(&self, index: usize) -> Option<(usize, usize)> {
        match index {
            0 => Some((self.width.get(), self.height.get())),
            _ => None,
        }
    }

    fn get_num_supported_pixel_formats(&self) -> usize {
        1
    }
    fn get_supported_pixel_format(&self, index: usize) -> Option<ScreenPixelFormat> {
        match index {
            0 => Some(ScreenPixelFormat::RGB_565),
            _ => None,
        }
    }
}

impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> screen::Screen<'a> for ST77XX<'a, A, B, P> {
    fn get_resolution(&self) -> (usize, usize) {
        (self.width.get(), self.height.get())
    }

    fn get_pixel_format(&self) -> ScreenPixelFormat {
        ScreenPixelFormat::RGB_565
    }

    fn get_rotation(&self) -> ScreenRotation {
        self.current_rotation.get()
    }

    fn set_write_frame(
        &self,
        x: usize,
        y: usize,
        width: usize,
        height: usize,
    ) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            self.setup_command.set(false);
            let buffer_len = self.buffer.map_or_else(
                || panic!("st77xx: buffer is not available"),
                |buffer| buffer.len() - 1,
            );
            if buffer_len >= 9 {
                // set buffer
                let err = self.set_memory_frame(0, x, y, x + width - 1, y + height - 1);
                if err == Ok(()) {
                    self.sequence_buffer.map_or_else(
                        || panic!("st77xx: set write frame no sequence buffer"),
                        |sequence| {
                            sequence[0] = SendCommand::Position(&CASET, 0, 4);
                            sequence[1] = SendCommand::Position(&RASET, 4, 4);
                            self.sequence_len.set(2);
                        },
                    );
                    let _ = self.send_sequence_buffer();
                }
                err
            } else {
                Err(ErrorCode::NOMEM)
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn write(
        &self,
        mut data: SubSliceMut<'static, u8>,
        continue_write: bool,
    ) -> Result<(), ErrorCode> {
        if self.status.get() == Status::Idle {
            // 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 ).
            // TODO(alevy): replace `chunks_mut` wit `array_chunks` when stable.
            for pair in data.as_slice().chunks_mut(2) {
                pair.swap(0, 1);
            }

            self.setup_command.set(false);
            let len = data.len();
            self.write_buffer.replace(data.take());

            if !continue_write {
                // Writing new data for the first time, make sure to reset
                // the screen buffer location to the beginning.

                let buffer_len = self.buffer.map_or_else(
                    || panic!("st77xx: buffer is not available"),
                    |buffer| buffer.len(),
                );
                if buffer_len > 0 {
                    // set buffer
                    self.sequence_buffer.map_or_else(
                        || panic!("st77xx: write no sequence buffer"),
                        |sequence| {
                            sequence[0] = SendCommand::Slice(&WRITE_RAM, len);
                            self.sequence_len.set(1);
                        },
                    );
                    let _ = self.send_sequence_buffer();
                    Ok(())
                } else {
                    Err(ErrorCode::NOMEM)
                }
            } else {
                // Continuing the previous write.
                self.send_parameters_slice(len);
                Ok(())
            }
        } else {
            Err(ErrorCode::BUSY)
        }
    }

    fn set_client(&self, client: &'a dyn ScreenClient) {
        self.client.set(client);
    }

    fn set_brightness(&self, _brightness: u16) -> Result<(), ErrorCode> {
        Ok(())
    }

    fn set_power(&self, enabled: bool) -> Result<(), ErrorCode> {
        if enabled {
            self.display_on()
        } else {
            self.display_off()
        }
    }

    fn set_invert(&self, enabled: bool) -> Result<(), ErrorCode> {
        if enabled {
            self.display_invert_on()
        } else {
            self.display_invert_off()
        }
    }
}

impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> time::AlarmClient for ST77XX<'a, A, B, P> {
    fn alarm(&self) {
        self.do_next_op();
    }
}

impl<'a, A: Alarm<'a>, B: Bus<'a, BusAddr8>, P: Pin> bus::Client for ST77XX<'a, A, B, P> {
    fn command_complete(
        &self,
        buffer: Option<&'static mut [u8]>,
        _len: usize,
        status: Result<(), ErrorCode>,
    ) {
        if let Some(buffer) = buffer {
            if self.status.get() == Status::SendParametersSlice {
                self.write_buffer.replace(buffer);
            } else {
                self.buffer.replace(buffer);
            }
        }

        if let Err(error) = status {
            self.status.set(Status::Error(error));
        }

        self.do_next_op();
    }
}

/************ ST7735 **************/
#[allow(dead_code)]
const GAMSET: Command = Command {
    id: 0x26,
    // Default parameters: Gama Set
    parameters: Some(&[0]),
    delay: 0,
};

const FRMCTR1: Command = Command {
    id: 0xB1,
    parameters: Some(&[0x01, 0x2C, 0x2D]),
    delay: 0,
};

const FRMCTR2: Command = Command {
    id: 0xB2,
    parameters: Some(&[0x01, 0x2C, 0x2D]),
    delay: 0,
};

const FRMCTR3: Command = Command {
    id: 0xB3,
    parameters: Some(&[0x01, 0x2C, 0x2D, 0x01, 0x2C, 0x2D]),
    delay: 0,
};

const INVCTR: Command = Command {
    id: 0xB4,
    parameters: Some(&[0x07]),
    delay: 0,
};

const PWCTR1: Command = Command {
    id: 0xC0,
    parameters: Some(&[0xA2, 0x02, 0x84]),
    delay: 0,
};

const PWCTR2: Command = Command {
    id: 0xC1,
    parameters: Some(&[0xC5]),
    delay: 0,
};

const PWCTR3: Command = Command {
    id: 0xC2,
    parameters: Some(&[0x0A, 0x00]),
    delay: 0,
};

const PWCTR4: Command = Command {
    id: 0xC3,
    parameters: Some(&[0x8A, 0x2A]),
    delay: 0,
};

const PWCTR5: Command = Command {
    id: 0xC4,
    parameters: Some(&[0x8A, 0xEE]),
    delay: 0,
};

const VMCTR1: Command = Command {
    id: 0xC5,
    parameters: Some(&[0x0E]),
    delay: 0,
};

const GMCTRP1: Command = Command {
    id: 0xE0,
    parameters: Some(&[
        0x02, 0x1c, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2d, 0x29, 0x25, 0x2B, 0x39, 0x00, 0x01, 0x03,
        0x10,
    ]),
    delay: 0,
};

const GMCTRN1: Command = Command {
    id: 0xE1,
    parameters: Some(&[
        0x03, 0x1d, 0x07, 0x06, 0x2E, 0x2C, 0x29, 0x2D, 0x2E, 0x2E, 0x37, 0x3F, 0x00, 0x00, 0x02,
        0x10,
    ]),
    delay: 0,
};

const ST7735_INIT_SEQUENCE: [SendCommand; 20] = crate::default_parameters_sequence!(
    &SW_RESET, &SLEEP_OUT, &FRMCTR1, &FRMCTR2, &FRMCTR3, &INVCTR, &PWCTR1, &PWCTR2, &PWCTR3,
    &PWCTR4, &PWCTR5, &VMCTR1, &INVOFF, &MADCTL, &COLMOD, &CASET, &RASET, &GMCTRP1, &GMCTRN1,
    &NORON
);

/************ ST7789H2 **************/

const PV_GAMMA_CTRL: Command = Command {
    id: 0xE0,
    parameters: Some(&[
        0xD0, 0x08, 0x11, 0x08, 0x0C, 0x15, 0x39, 0x33, 0x50, 0x36, 0x13, 0x14, 0x29, 0x2D,
    ]),
    delay: 0,
};

const NV_GAMMA_CTRL: Command = Command {
    id: 0xE1,
    parameters: Some(&[
        0xD0, 0x08, 0x10, 0x08, 0x06, 0x06, 0x39, 0x44, 0x51, 0x0B, 0x16, 0x14, 0x2F, 0x31,
    ]),
    delay: 0,
};

const PORCH_CTRL: Command = Command {
    id: 0xB2,
    parameters: Some(&[0x0C, 0x0C, 0x00, 0x33, 0x33]),
    delay: 0,
};

const GATE_CTRL: Command = Command {
    id: 0xB7,
    parameters: Some(&[0x35]),
    delay: 0,
};

const LCM_CTRL: Command = Command {
    id: 0xC0,
    parameters: Some(&[0x2C]),
    delay: 0,
};

const VDV_VRH_EN: Command = Command {
    id: 0xC2,
    parameters: Some(&[0x01, 0xC3]),
    delay: 0,
};

const VDV_SET: Command = Command {
    id: 0xC4,
    parameters: Some(&[0x20]),
    delay: 0,
};

const FR_CTRL: Command = Command {
    id: 0xC6,
    parameters: Some(&[0x0F]),
    delay: 0,
};

const VCOM_SET: Command = Command {
    id: 0xBB,
    parameters: Some(&[0x1F]),
    delay: 0,
};

const POWER_CTRL: Command = Command {
    id: 0xD0,
    parameters: Some(&[0xA4, 0xA1]),
    delay: 0,
};

const TEARING_EFFECT: Command = Command {
    id: 0x35,
    parameters: Some(&[0x00]),
    delay: 0,
};

const ST7789H2_INIT_SEQUENCE: [SendCommand; 22] = crate::default_parameters_sequence!(
    &SLEEP_IN,
    &SW_RESET,
    &SLEEP_OUT,
    &NORON,
    &COLMOD,
    &INVON,
    &CASET,
    &RASET,
    &PORCH_CTRL,
    &GATE_CTRL,
    &VCOM_SET,
    &LCM_CTRL,
    &VDV_VRH_EN,
    &VDV_SET,
    &FR_CTRL,
    &POWER_CTRL,
    &PV_GAMMA_CTRL,
    &NV_GAMMA_CTRL,
    &MADCTL,
    &DISPLAY_ON,
    &SLEEP_OUT,
    &TEARING_EFFECT
);

/******** LS016B8UY *********/

const VSYNC_OUTPUT: Command = Command {
    id: 0x35,
    parameters: Some(&[0x00]),
    delay: 0,
};

const NORMAL_DISPLAY: Command = Command {
    id: 0x36,
    parameters: Some(&[0x83]),
    delay: 0,
};

const PANEL_SETTING1: Command = Command {
    id: 0xB0,
    parameters: Some(&[0x01, 0xFE]),
    delay: 0,
};

const PANEL_SETTING2: Command = Command {
    id: 0xB1,
    parameters: Some(&[0xDE, 0x21]),
    delay: 0,
};

const OSCILLATOR: Command = Command {
    id: 0xB3,
    parameters: Some(&[0x02]),
    delay: 0,
};

const PANEL_SETTING_LOCK: Command = Command {
    id: 0xB4,
    parameters: None,
    delay: 0,
};

const PANEL_V_PORCH: Command = Command {
    id: 0xB7,
    parameters: Some(&[0x05, 0x33]),
    delay: 0,
};

const PANEL_IDLE_V_PORCH: Command = Command {
    id: 0xB8,
    parameters: Some(&[0x05, 0x33]),
    delay: 0,
};

const GVDD: Command = Command {
    id: 0xC0,
    parameters: Some(&[0x53]),
    delay: 0,
};

const OPAMP: Command = Command {
    id: 0xC2,
    parameters: Some(&[0x03, 0x12]),
    delay: 0,
};

const RELOAD_MTP_VCOMH: Command = Command {
    id: 0xC5,
    parameters: Some(&[0x00, 0x45]),
    delay: 0,
};

const PANEL_TIMING1: Command = Command {
    id: 0xC8,
    parameters: Some(&[0x04, 0x03]),
    delay: 0,
};

const PANEL_TIMING2: Command = Command {
    id: 0xC9,
    parameters: Some(&[0x5E, 0x08]),
    delay: 0,
};

const PANEL_TIMING3: Command = Command {
    id: 0xCA,
    parameters: Some(&[0x0A, 0x0C, 0x02]),
    delay: 0,
};

const PANEL_TIMING4: Command = Command {
    id: 0xCC,
    parameters: Some(&[0x03, 0x04]),
    delay: 0,
};

const PANEL_POWER: Command = Command {
    id: 0xD0,
    parameters: Some(&[0x0C]),
    delay: 0,
};

const LS0168BUY_TEARING_EFFECT: Command = Command {
    id: 0xDD,
    parameters: Some(&[0x00]),
    delay: 0,
};

const LS016B8UY_INIT_SEQUENCE: [SendCommand; 23] = default_parameters_sequence!(
    &VSYNC_OUTPUT,
    &COLMOD,
    &PANEL_SETTING1,
    &PANEL_SETTING2,
    &PANEL_V_PORCH,
    &PANEL_IDLE_V_PORCH,
    &PANEL_TIMING1,
    &PANEL_TIMING2,
    &PANEL_TIMING3,
    &PANEL_TIMING4,
    &PANEL_POWER,
    &OSCILLATOR,
    &GVDD,
    &RELOAD_MTP_VCOMH,
    &OPAMP,
    &LS0168BUY_TEARING_EFFECT,
    &PANEL_SETTING_LOCK,
    &SLEEP_OUT,
    &NORMAL_DISPLAY,
    &CASET,
    &RASET,
    &DISPLAY_ON,
    &IDLE_OFF
);

pub struct ST77XXScreen {
    init_sequence: &'static [SendCommand],
    default_width: usize,
    default_height: usize,
    inverted: bool,

    /// This function allows the translation of the image
    /// as some screen implementations might have off screen
    /// pixels for some of the rotations
    offset: fn(rotation: ScreenRotation) -> (usize, usize),
}

pub const ST7735: ST77XXScreen = ST77XXScreen {
    init_sequence: &ST7735_INIT_SEQUENCE,
    default_width: 128,
    default_height: 160,
    inverted: false,
    offset: |_| (0, 0),
};

pub const ST7789H2: ST77XXScreen = ST77XXScreen {
    init_sequence: &ST7789H2_INIT_SEQUENCE,
    default_width: 240,
    default_height: 240,
    inverted: true,
    offset: |rotation| match rotation {
        ScreenRotation::Rotated180 => (0, 80),
        ScreenRotation::Rotated270 => (80, 0),
        _ => (0, 0),
    },
};

pub const LS016B8UY: ST77XXScreen = ST77XXScreen {
    init_sequence: &LS016B8UY_INIT_SEQUENCE,
    default_width: 240,
    default_height: 240,
    inverted: false,
    offset: |_| (0, 0),
};