1use core::cell::Cell;
18use kernel::ErrorCode;
19use kernel::hil;
20use kernel::utilities::cells::{MapCell, OptionalCell, TakeCell};
21use kernel::utilities::leasable_buffer::SubSliceMut;
22
23pub const BUFFER_SIZE: usize = 1032;
24
25const CONTROLLER_WIDTH: usize = 128;
27const CONTROLLER_HEIGHT: usize = 64;
29
30pub trait Variant {
32 const HAS_CHARGE_PUMP: bool;
34
35 const INIT_COMMANDS: &'static [Command];
38}
39
40pub enum Ssd1306 {}
42
43impl Variant for Ssd1306 {
44 const HAS_CHARGE_PUMP: bool = true;
45 const INIT_COMMANDS: &'static [Command] = &[
46 Command::SetPrechargePeriod {
47 phase1: 0x1,
48 phase2: 0xf,
49 },
50 Command::SetVcomDeselect { level: 2 },
51 ];
52}
53
54pub type Ssd1315 = Ssd1306;
56
57pub enum Ssd1309 {}
64
65impl Variant for Ssd1309 {
66 const HAS_CHARGE_PUMP: bool = false;
67 const INIT_COMMANDS: &'static [Command] = &[];
68}
69
70#[derive(Clone, Copy)]
76pub struct PanelConfig {
77 pub segment_remap: bool,
81 pub com_scan_decrement: bool,
85 pub com_pins_alternative: bool,
91 pub com_left_right_remap: bool,
95}
96
97impl Default for PanelConfig {
98 fn default() -> Self {
100 PanelConfig {
101 segment_remap: true,
102 com_scan_decrement: true,
103 com_pins_alternative: true,
104 com_left_right_remap: false,
105 }
106 }
107}
108
109#[derive(Clone, Copy, PartialEq)]
111pub enum DataKind {
112 Command,
113 Data,
114}
115
116pub trait Transport<'a> {
118 fn set_client(&self, client: &'a dyn TransportClient);
119
120 fn send(
126 &self,
127 kind: DataKind,
128 buffer: &'static mut [u8],
129 len: usize,
130 ) -> Result<(), (ErrorCode, &'static mut [u8])>;
131}
132
133pub trait TransportClient {
134 fn send_done(&self, buffer: &'static mut [u8], result: Result<(), ErrorCode>);
135}
136
137pub struct I2CTransport<'a, I: hil::i2c::I2CDevice<'a>> {
142 i2c: &'a I,
143 client: OptionalCell<&'a dyn TransportClient>,
144}
145
146impl<'a, I: hil::i2c::I2CDevice<'a>> I2CTransport<'a, I> {
147 pub fn new(i2c: &'a I) -> Self {
148 Self {
149 i2c,
150 client: OptionalCell::empty(),
151 }
152 }
153}
154
155impl<'a, I: hil::i2c::I2CDevice<'a>> Transport<'a> for I2CTransport<'a, I> {
156 fn set_client(&self, client: &'a dyn TransportClient) {
157 self.client.set(client);
158 }
159
160 fn send(
161 &self,
162 kind: DataKind,
163 buffer: &'static mut [u8],
164 len: usize,
165 ) -> Result<(), (ErrorCode, &'static mut [u8])> {
166 buffer[0] = match kind {
167 DataKind::Command => 0, DataKind::Data => 0x40, };
170
171 self.i2c.enable();
172 self.i2c.write(buffer, len).map_err(|(e, buf)| {
173 self.i2c.disable();
174 (e.into(), buf)
175 })
176 }
177}
178
179impl<'a, I: hil::i2c::I2CDevice<'a>> hil::i2c::I2CClient for I2CTransport<'a, I> {
180 fn command_complete(&self, buffer: &'static mut [u8], status: Result<(), hil::i2c::Error>) {
181 self.i2c.disable();
182 self.client
183 .map(|client| client.send_done(buffer, status.map_err(Into::into)));
184 }
185}
186
187pub struct SpiTransport<'a, S: hil::spi::SpiMaster<'a>, P: hil::gpio::Output> {
194 spi: &'a S,
195 dc: &'a P,
196 client: OptionalCell<&'a dyn TransportClient>,
197}
198
199impl<'a, S: hil::spi::SpiMaster<'a>, P: hil::gpio::Output> SpiTransport<'a, S, P> {
200 pub fn new(spi: &'a S, dc: &'a P) -> Self {
201 Self {
202 spi,
203 dc,
204 client: OptionalCell::empty(),
205 }
206 }
207}
208
209impl<'a, S: hil::spi::SpiMaster<'a>, P: hil::gpio::Output> Transport<'a>
210 for SpiTransport<'a, S, P>
211{
212 fn set_client(&self, client: &'a dyn TransportClient) {
213 self.client.set(client);
214 }
215
216 fn send(
217 &self,
218 kind: DataKind,
219 buffer: &'static mut [u8],
220 len: usize,
221 ) -> Result<(), (ErrorCode, &'static mut [u8])> {
222 match kind {
223 DataKind::Command => self.dc.clear(),
224 DataKind::Data => self.dc.set(),
225 }
226
227 let mut buf_slice = SubSliceMut::new(buffer);
228 buf_slice.slice(1..len);
229 self.spi
230 .read_write_bytes(buf_slice, None)
231 .map_err(|(e, buf_slice, _)| (e, buf_slice.take()))
232 }
233}
234
235impl<'a, S: hil::spi::SpiMaster<'a>, P: hil::gpio::Output> hil::spi::SpiMasterClient
236 for SpiTransport<'a, S, P>
237{
238 fn read_write_done(
239 &self,
240 write_buffer: SubSliceMut<'static, u8>,
241 _read_buffer: Option<SubSliceMut<'static, u8>>,
242 status: Result<usize, ErrorCode>,
243 ) {
244 self.client
245 .map(|client| client.send_done(write_buffer.take(), status.map(|_| ())));
246 }
247}
248
249#[derive(Copy, Clone, PartialEq)]
250#[repr(usize)]
251pub enum Command {
252 SetChargePump { enable: bool },
255
256 SetContrast { contrast: u8 },
260 EntireDisplayOn { ignore_ram: bool },
262 SetDisplayInvert { inverse: bool },
264 SetDisplayOnOff { on: bool },
266
267 ContinuousHorizontalScroll {
270 left: bool,
271 page_start: u8,
272 interval: u8,
273 page_end: u8,
274 },
275 ContinuousVerticalHorizontalScroll {
278 left: bool,
279 page_start: u8,
280 interval: u8,
281 page_end: u8,
282 vertical_offset: u8,
283 },
284 DeactivateScroll = 0x2e,
286 ActivateScroll = 0x2f,
288 SetVerticalScrollArea { rows_fixed: u8, rows_scroll: u8 },
292
293 SetLowerColumnStartAddress { address: u8 },
300 SetHigherColumnStartAddress { address: u8 },
306 SetMemoryAddressingMode { mode: u8 },
308 SetColumnAddress { column_start: u8, column_end: u8 },
310 SetPageAddress { page_start: u8, page_end: u8 },
312 SetPageStartAddress { address: u8 },
315
316 SetDisplayStartLine { line: u8 },
320 SetSegmentRemap { reverse: bool },
322 SetMultiplexRatio { ratio: u8 },
324 SetComScanDirection { decrement: bool },
326 SetDisplayOffset { vertical_shift: u8 } = 0xd3,
328 SetComPins { alternative: bool, enable_com: bool },
330
331 SetDisplayClockDivide {
334 divide_ratio: u8,
335 oscillator_frequency: u8,
336 },
337 SetPrechargePeriod { phase1: u8, phase2: u8 },
339 SetVcomDeselect { level: u8 },
341}
342
343impl Command {
344 pub fn encode(self, buffer: &mut SubSliceMut<'static, u8>) {
345 let take = match self {
346 Self::SetChargePump { enable } => {
347 buffer[0] = 0x8D;
348 buffer[1] = 0x10 | ((enable as u8) << 2);
349 2
350 }
351 Self::SetContrast { contrast } => {
352 buffer[0] = 0x81;
353 buffer[1] = contrast;
354 2
355 }
356 Self::EntireDisplayOn { ignore_ram } => {
357 buffer[0] = 0xa4 | (ignore_ram as u8);
358 1
359 }
360 Self::SetDisplayInvert { inverse } => {
361 buffer[0] = 0xa6 | (inverse as u8);
362 1
363 }
364 Self::SetDisplayOnOff { on } => {
365 buffer[0] = 0xae | (on as u8);
366 1
367 }
368 Self::ContinuousHorizontalScroll {
369 left,
370 page_start,
371 interval,
372 page_end,
373 } => {
374 buffer[0] = 0x26 | (left as u8);
375 buffer[1] = 0;
376 buffer[2] = page_start;
377 buffer[3] = interval;
378 buffer[4] = page_end;
379 buffer[5] = 0;
380 buffer[6] = 0xff;
381 7
382 }
383 Self::ContinuousVerticalHorizontalScroll {
384 left,
385 page_start,
386 interval,
387 page_end,
388 vertical_offset,
389 } => {
390 buffer[0] = 0x29 | (left as u8);
391 buffer[1] = 0;
392 buffer[2] = page_start;
393 buffer[3] = interval;
394 buffer[4] = page_end;
395 buffer[5] = vertical_offset;
396 6
397 }
398 Self::DeactivateScroll => {
399 buffer[0] = 0x2e;
400 1
401 }
402 Self::ActivateScroll => {
403 buffer[0] = 0x2f;
404 1
405 }
406 Self::SetVerticalScrollArea {
407 rows_fixed,
408 rows_scroll,
409 } => {
410 buffer[0] = 0xa3;
411 buffer[1] = rows_fixed;
412 buffer[2] = rows_scroll;
413 3
414 }
415 Self::SetLowerColumnStartAddress { address } => {
416 buffer[0] = 0x00 | (address & 0xF);
417 1
418 }
419 Self::SetHigherColumnStartAddress { address } => {
420 buffer[0] = 0x10 | ((address >> 4) & 0xF);
421 1
422 }
423 Self::SetMemoryAddressingMode { mode } => {
424 buffer[0] = 0x20;
425 buffer[1] = mode;
426 2
427 }
428 Self::SetColumnAddress {
429 column_start,
430 column_end,
431 } => {
432 buffer[0] = 0x21;
433 buffer[1] = column_start;
434 buffer[2] = column_end;
435 3
436 }
437 Self::SetPageAddress {
438 page_start,
439 page_end,
440 } => {
441 buffer[0] = 0x22;
442 buffer[1] = page_start;
443 buffer[2] = page_end;
444 3
445 }
446 Self::SetPageStartAddress { address } => {
447 buffer[0] = 0xb0 | (address & 0x7);
448 1
449 }
450 Self::SetDisplayStartLine { line } => {
451 buffer[0] = 0x40 | (line & 0x3F);
452 1
453 }
454 Self::SetSegmentRemap { reverse } => {
455 buffer[0] = 0xa0 | (reverse as u8);
456 1
457 }
458 Self::SetMultiplexRatio { ratio } => {
459 buffer[0] = 0xa8;
460 buffer[1] = ratio;
461 2
462 }
463 Self::SetComScanDirection { decrement } => {
464 buffer[0] = 0xc0 | ((decrement as u8) << 3);
465 1
466 }
467 Self::SetDisplayOffset { vertical_shift } => {
468 buffer[0] = 0xd3;
469 buffer[1] = vertical_shift;
470 2
471 }
472 Self::SetComPins {
473 alternative,
474 enable_com,
475 } => {
476 buffer[0] = 0xda;
477 buffer[1] = ((alternative as u8) << 4) | ((enable_com as u8) << 5) | 0x2;
478 2
479 }
480 Self::SetDisplayClockDivide {
481 divide_ratio,
482 oscillator_frequency,
483 } => {
484 buffer[0] = 0xd5;
485 buffer[1] = ((oscillator_frequency & 0xF) << 4) | (divide_ratio & 0xf);
486 2
487 }
488 Self::SetPrechargePeriod { phase1, phase2 } => {
489 buffer[0] = 0xd9;
490 buffer[1] = ((phase2 & 0xF) << 4) | (phase1 & 0xf);
491 2
492 }
493 Self::SetVcomDeselect { level } => {
494 buffer[0] = 0xdb;
495 buffer[1] = (level & 0xF) << 4;
496 2
497 }
498 };
499
500 buffer.slice(take..);
503 }
504}
505
506#[derive(Clone, Copy, PartialEq)]
508enum State {
509 Idle,
510 Init,
511 SimpleCommand,
512 Write,
513}
514
515pub struct Ssd13xx<
516 'a,
517 V: Variant,
518 T: Transport<'a>,
519 const WIDTH: usize = CONTROLLER_WIDTH,
520 const HEIGHT: usize = CONTROLLER_HEIGHT,
521> {
522 transport: &'a T,
523 state: Cell<State>,
524 client: OptionalCell<&'a dyn hil::screen::ScreenClient>,
525 setup_client: OptionalCell<&'a dyn hil::screen::ScreenSetupClient>,
526 buffer: TakeCell<'static, [u8]>,
527 write_buffer: MapCell<SubSliceMut<'static, u8>>,
528 enable_charge_pump: bool,
529 panel: PanelConfig,
530 _variant: core::marker::PhantomData<V>,
531}
532
533impl<'a, V: Variant, T: Transport<'a>, const WIDTH: usize, const HEIGHT: usize>
534 Ssd13xx<'a, V, T, WIDTH, HEIGHT>
535{
536 const COLUMN_OFFSET: usize = (CONTROLLER_WIDTH - WIDTH) / 2;
538
539 const VALID_RESOLUTION: () = assert!(
541 WIDTH > 0
542 && WIDTH <= CONTROLLER_WIDTH
543 && HEIGHT > 0
544 && HEIGHT <= CONTROLLER_HEIGHT
545 && HEIGHT.is_multiple_of(8)
546 );
547
548 pub fn new(
552 transport: &'a T,
553 buffer: &'static mut [u8],
554 enable_charge_pump: bool,
555 panel: PanelConfig,
556 ) -> Self {
557 let () = Self::VALID_RESOLUTION;
558
559 Ssd13xx {
560 transport,
561 state: Cell::new(State::Idle),
562 client: OptionalCell::empty(),
563 setup_client: OptionalCell::empty(),
564 buffer: TakeCell::new(buffer),
565 write_buffer: MapCell::empty(),
566 enable_charge_pump,
567 panel,
568 _variant: core::marker::PhantomData,
569 }
570 }
571
572 pub fn init_screen(&self) {
573 let commands = [
574 Command::SetDisplayOnOff { on: false },
575 Command::SetDisplayClockDivide {
576 divide_ratio: 0,
577 oscillator_frequency: 0x8,
578 },
579 Command::SetMultiplexRatio {
580 ratio: HEIGHT as u8 - 1,
581 },
582 Command::SetDisplayOffset { vertical_shift: 0 },
583 Command::SetDisplayStartLine { line: 0 },
584 Command::SetMemoryAddressingMode { mode: 0 }, Command::SetSegmentRemap {
586 reverse: self.panel.segment_remap,
587 },
588 Command::SetComScanDirection {
589 decrement: self.panel.com_scan_decrement,
590 },
591 Command::SetComPins {
592 alternative: self.panel.com_pins_alternative,
593 enable_com: self.panel.com_left_right_remap,
594 },
595 Command::SetContrast { contrast: 0xcf },
596 Command::EntireDisplayOn { ignore_ram: false },
597 Command::SetDisplayInvert { inverse: false },
598 Command::DeactivateScroll,
599 ];
600 let charge_pump = Command::SetChargePump {
601 enable: self.enable_charge_pump,
602 };
603
604 let sequence = commands
605 .iter()
606 .chain(V::HAS_CHARGE_PUMP.then_some(&charge_pump))
607 .chain(V::INIT_COMMANDS)
608 .chain(&[Command::SetDisplayOnOff { on: true }]);
609
610 match self.send_sequence(sequence) {
611 Ok(()) => {
612 self.state.set(State::Init);
613 }
614 Err(_e) => {}
615 }
616 }
617
618 fn send_sequence<'c>(
619 &self,
620 sequence: impl IntoIterator<Item = &'c Command>,
621 ) -> Result<(), ErrorCode> {
622 if self.state.get() == State::Idle {
623 self.buffer.take().map_or(Err(ErrorCode::NOMEM), |buffer| {
624 let mut buf_slice = SubSliceMut::new(buffer);
625
626 buf_slice.slice(1..);
629
630 for cmd in sequence {
631 cmd.encode(&mut buf_slice);
632 }
633
634 let remaining_len = buf_slice.len();
637 buf_slice.reset();
638 let tx_len = buf_slice.len() - remaining_len;
639
640 match self
641 .transport
642 .send(DataKind::Command, buf_slice.take(), tx_len)
643 {
644 Ok(()) => Ok(()),
645 Err((e, buf)) => {
646 self.buffer.replace(buf);
647 Err(e)
648 }
649 }
650 })
651 } else {
652 Err(ErrorCode::BUSY)
653 }
654 }
655}
656
657impl<'a, V: Variant, T: Transport<'a>, const WIDTH: usize, const HEIGHT: usize>
658 hil::screen::ScreenSetup<'a> for Ssd13xx<'a, V, T, WIDTH, HEIGHT>
659{
660 fn set_client(&self, client: &'a dyn hil::screen::ScreenSetupClient) {
661 self.setup_client.set(client);
662 }
663
664 fn set_resolution(&self, _resolution: (usize, usize)) -> Result<(), ErrorCode> {
665 Err(ErrorCode::NOSUPPORT)
666 }
667
668 fn set_pixel_format(&self, _depth: hil::screen::ScreenPixelFormat) -> Result<(), ErrorCode> {
669 Err(ErrorCode::NOSUPPORT)
670 }
671
672 fn set_rotation(&self, _rotation: hil::screen::ScreenRotation) -> Result<(), ErrorCode> {
673 Err(ErrorCode::NOSUPPORT)
674 }
675
676 fn get_num_supported_resolutions(&self) -> usize {
677 1
678 }
679
680 fn get_supported_resolution(&self, index: usize) -> Option<(usize, usize)> {
681 match index {
682 0 => Some((WIDTH, HEIGHT)),
683 _ => None,
684 }
685 }
686
687 fn get_num_supported_pixel_formats(&self) -> usize {
688 1
689 }
690
691 fn get_supported_pixel_format(&self, index: usize) -> Option<hil::screen::ScreenPixelFormat> {
692 match index {
693 0 => Some(hil::screen::ScreenPixelFormat::Mono_8BitPage),
694 _ => None,
695 }
696 }
697}
698
699impl<'a, V: Variant, T: Transport<'a>, const WIDTH: usize, const HEIGHT: usize>
700 hil::screen::Screen<'a> for Ssd13xx<'a, V, T, WIDTH, HEIGHT>
701{
702 fn set_client(&self, client: &'a dyn hil::screen::ScreenClient) {
703 self.client.set(client);
704 }
705
706 fn get_resolution(&self) -> (usize, usize) {
707 (WIDTH, HEIGHT)
708 }
709
710 fn get_pixel_format(&self) -> hil::screen::ScreenPixelFormat {
711 hil::screen::ScreenPixelFormat::Mono_8BitPage
712 }
713
714 fn get_rotation(&self) -> hil::screen::ScreenRotation {
715 hil::screen::ScreenRotation::Normal
716 }
717
718 fn set_write_frame(
719 &self,
720 x: usize,
721 y: usize,
722 width: usize,
723 height: usize,
724 ) -> Result<(), ErrorCode> {
725 let commands = [
726 Command::SetPageAddress {
727 page_start: (y / 8) as u8,
728 page_end: ((y / 8) + (height / 8) - 1) as u8,
729 },
730 Command::SetColumnAddress {
731 column_start: (Self::COLUMN_OFFSET + x) as u8,
732 column_end: (Self::COLUMN_OFFSET + x + width - 1) as u8,
733 },
734 ];
735 match self.send_sequence(&commands) {
736 Ok(()) => {
737 self.state.set(State::SimpleCommand);
738 Ok(())
739 }
740 Err(e) => Err(e),
741 }
742 }
743
744 fn write(&self, data: SubSliceMut<'static, u8>, _continue: bool) -> Result<(), ErrorCode> {
745 self.buffer.take().map_or(Err(ErrorCode::NOMEM), |buffer| {
746 let mut buf_slice = SubSliceMut::new(buffer);
747
748 buf_slice.slice(1..);
751
752 let copy_len = core::cmp::min(buf_slice.len(), data.len());
754
755 for i in 0..copy_len {
756 buf_slice[i] = data[i];
757 }
758
759 let tx_len = copy_len + 1;
760
761 match self
762 .transport
763 .send(DataKind::Data, buf_slice.take(), tx_len)
764 {
765 Ok(()) => {
766 self.state.set(State::Write);
767 self.write_buffer.replace(data);
768 Ok(())
769 }
770 Err((e, buf)) => {
771 self.buffer.replace(buf);
772 Err(e)
773 }
774 }
775 })
776 }
777
778 fn set_brightness(&self, brightness: u16) -> Result<(), ErrorCode> {
779 let commands = [Command::SetContrast {
780 contrast: (brightness >> 8) as u8,
781 }];
782 match self.send_sequence(&commands) {
783 Ok(()) => {
784 self.state.set(State::SimpleCommand);
785 Ok(())
786 }
787 Err(e) => Err(e),
788 }
789 }
790
791 fn set_power(&self, enabled: bool) -> Result<(), ErrorCode> {
792 let commands = [Command::SetDisplayOnOff { on: enabled }];
793 match self.send_sequence(&commands) {
794 Ok(()) => {
795 self.state.set(State::SimpleCommand);
796 Ok(())
797 }
798 Err(e) => Err(e),
799 }
800 }
801
802 fn set_invert(&self, enabled: bool) -> Result<(), ErrorCode> {
803 let commands = [Command::SetDisplayInvert { inverse: enabled }];
804 match self.send_sequence(&commands) {
805 Ok(()) => {
806 self.state.set(State::SimpleCommand);
807 Ok(())
808 }
809 Err(e) => Err(e),
810 }
811 }
812}
813
814impl<'a, V: Variant, T: Transport<'a>, const WIDTH: usize, const HEIGHT: usize> TransportClient
815 for Ssd13xx<'a, V, T, WIDTH, HEIGHT>
816{
817 fn send_done(&self, buffer: &'static mut [u8], result: Result<(), ErrorCode>) {
818 self.buffer.replace(buffer);
819
820 match self.state.get() {
821 State::Init => {
822 self.state.set(State::Idle);
823 self.client.map(|client| client.screen_is_ready());
824 }
825
826 State::SimpleCommand => {
827 self.state.set(State::Idle);
828 self.client.map(|client| client.command_complete(result));
829 }
830
831 State::Write => {
832 self.state.set(State::Idle);
833 self.write_buffer.take().map(|buf| {
834 self.client.map(|client| client.write_complete(buf, result));
835 });
836 }
837 _ => {}
838 }
839 }
840}