Skip to main content

capsules_extra/
ssd13xx.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 2023.
4
5//! SSD1306/SSD1309/SSD1315 OLED Screen
6//!
7//! The SSD1306, SSD1309, and SSD1315 share their command set and 128x64 display
8//! RAM. The exact chip is selected through the [`Variant`] generic type
9//! parameter ([`Ssd1306`], [`Ssd1309`], or [`Ssd1315`]). Select the panel
10//! resolution with the `WIDTH` and `HEIGHT` const generics (128x64 by default).
11//! Panels narrower than 128 columns are assumed to be centered in the
12//! controller's columns.
13//!
14//! Both controllers can be attached over I2C ([`I2CTransport`]) or 4-wire SPI
15//! with a data/command pin ([`SpiTransport`]).
16
17use 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
25/// Number of columns in the controller's display RAM.
26const CONTROLLER_WIDTH: usize = 128;
27/// Number of rows (COM lines) of the controller.
28const CONTROLLER_HEIGHT: usize = 64;
29
30/// Settings that differ between the controllers this driver supports.
31pub trait Variant {
32    /// Whether the controller has an internal charge pump (command `0x8D`).
33    const HAS_CHARGE_PUMP: bool;
34
35    /// Controller-specific commands sent during initialization, before the
36    /// display is turned on.
37    const INIT_COMMANDS: &'static [Command];
38}
39
40/// The SSD1306 controller.
41pub 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
54/// The SSD1315 controller, which is compatible with the SSD1306.
55pub type Ssd1315 = Ssd1306;
56
57/// The SSD1309 controller.
58///
59/// The SSD1309 has no charge pump (the panel voltage is supplied externally)
60/// and encodes the VCOMH deselect level differently from the SSD1306. It keeps
61/// its reset defaults for the pre-charge period (`0x22`) and VCOMH level
62/// (`0x34`, ~0.78 x VCC).
63pub enum Ssd1309 {}
64
65impl Variant for Ssd1309 {
66    const HAS_CHARGE_PUMP: bool = false;
67    const INIT_COMMANDS: &'static [Command] = &[];
68}
69
70/// How the panel is wired to the controller's segment (column) and COM (row)
71/// lines. This depends on the display module, and decides the orientation of
72/// the image.
73///
74/// The fields are named after the controller commands they configure.
75#[derive(Clone, Copy)]
76pub struct PanelConfig {
77    /// Set Segment Re-map (`0xA0`/`0xA1`).
78    ///
79    /// `true` maps column 0 to SEG127, mirroring the image horizontally.
80    pub segment_remap: bool,
81    /// Set COM Output Scan Direction (`0xC0`/`0xC8`).
82    ///
83    /// `true` scans from COM[N-1] to COM0, mirroring the image vertically.
84    pub com_scan_decrement: bool,
85    /// Set COM Pins Hardware Configuration (`0xDA`).
86    ///
87    /// `true` means alternative (interleaved) instead of sequential COM pin
88    /// configuration. Panels with 64 rows typically use the alternative
89    /// configuration, panels with 32 rows the sequential one.
90    pub com_pins_alternative: bool,
91    /// Set COM Pins Hardware Configuration (`0xDA`).
92    ///
93    /// `true` means enabling COM left/right remap.
94    pub com_left_right_remap: bool,
95}
96
97impl Default for PanelConfig {
98    /// The configuration of common 128x64 modules.
99    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/// Whether bytes sent to the controller are commands or display data.
110#[derive(Clone, Copy, PartialEq)]
111pub enum DataKind {
112    Command,
113    Data,
114}
115
116/// Bus that connects the controller.
117pub trait Transport<'a> {
118    fn set_client(&self, client: &'a dyn TransportClient);
119
120    /// Send `buffer[1..len]` to the controller as `kind` bytes.
121    ///
122    /// `buffer[0]` is reserved for the transport (e.g. the I2C control byte).
123    /// On success, [`TransportClient::send_done`] returns the buffer. `len`
124    /// includes this byte.
125    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
137/// I2C transport for SSD13xx screens.
138///
139/// Each transfer starts with a control byte that marks the following bytes as
140/// commands or data.
141pub 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, // Co = 0, D/C̅ = 0
168            DataKind::Data => 0x40, // Co = 0, D/C̅ = 1
169        };
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
187/// 4-wire SPI transport: the D/C̅ pin marks the transferred bytes as commands
188/// (low) or data (high).
189///
190/// The transport uses the SPI controller directly, so the controller cannot
191/// be shared with other devices. Its chip select, clock rate, and mode must be
192/// configured before use (SPI mode 0).
193pub 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    // Charge Pump Commands
253    /// Charge Pump Setting.
254    SetChargePump { enable: bool },
255
256    // Fundamental Commands
257    /// SetContrastControl. Double byte command to select 1 out of 256 contrast
258    /// steps. Contrast increases as the value increases.
259    SetContrast { contrast: u8 },
260    /// Entire Display On.
261    EntireDisplayOn { ignore_ram: bool },
262    /// Set Normal Display.
263    SetDisplayInvert { inverse: bool },
264    /// Set Display Off.
265    SetDisplayOnOff { on: bool },
266
267    // Scrolling Commands
268    /// Continuous Horizontal Scroll. Right or Left Horizontal Scroll.
269    ContinuousHorizontalScroll {
270        left: bool,
271        page_start: u8,
272        interval: u8,
273        page_end: u8,
274    },
275    /// Continuous Vertical and Horizontal Scroll. Vertical and Right Horizontal
276    /// Scroll.
277    ContinuousVerticalHorizontalScroll {
278        left: bool,
279        page_start: u8,
280        interval: u8,
281        page_end: u8,
282        vertical_offset: u8,
283    },
284    /// Deactivate Scroll. Stop scrolling that is configured by scroll commands.
285    DeactivateScroll = 0x2e,
286    /// Activate Scroll. Start scrolling that is configured by scroll commands.
287    ActivateScroll = 0x2f,
288    /// Set Vertical Scroll Area. Set number of rows in top fixed area. The
289    /// number of rows in top fixed area is referenced to the top of the GDDRAM
290    /// (i.e. row 0).
291    SetVerticalScrollArea { rows_fixed: u8, rows_scroll: u8 },
292
293    // Addressing Setting Commands
294    /// Set Lower Column Start Address for Page Addressing Mode.
295    ///
296    /// Set the lower nibble of the column start address register for Page
297    /// Addressing Mode using `X[3:0]` as data bits. The initial display line
298    /// register is reset to 0000b after RESET.
299    SetLowerColumnStartAddress { address: u8 },
300    /// Set Higher Column Start Address for Page Addressing Mode.
301    ///
302    /// Set the higher nibble of the column start address register for Page
303    /// Addressing Mode using `X[3:0]` as data bits. The initial display line
304    /// register is reset to 0000b after RESET.
305    SetHigherColumnStartAddress { address: u8 },
306    /// Set Memory Addressing Mode.
307    SetMemoryAddressingMode { mode: u8 },
308    /// Set Column Address. Setup column start and end address.
309    SetColumnAddress { column_start: u8, column_end: u8 },
310    /// Set Page Address. Setup page start and end address.
311    SetPageAddress { page_start: u8, page_end: u8 },
312    /// Set Page Start Address for Page Addressing Mode. Set GDDRAM Page Start
313    /// Address (PAGE0~PAGE7) for Page Addressing Mode using `X[2:0]`.
314    SetPageStartAddress { address: u8 },
315
316    // Hardware Configuration Commands
317    /// Set Display Start Line. Set display RAM display start line register from
318    /// 0-63 using `X[5:0]`.
319    SetDisplayStartLine { line: u8 },
320    /// Set Segment Remap.
321    SetSegmentRemap { reverse: bool },
322    /// Set Multiplex Ratio.
323    SetMultiplexRatio { ratio: u8 },
324    /// Set COM Output Scan Direction.
325    SetComScanDirection { decrement: bool },
326    /// Set Display Offset. Set vertical shift by COM from 0-63.
327    SetDisplayOffset { vertical_shift: u8 } = 0xd3,
328    /// Set COM Pins Hardware Configuration
329    SetComPins { alternative: bool, enable_com: bool },
330
331    // Timing & Driving Scheme Setting Commands.
332    /// Set Display Clock Divide Ratio/Oscillator Frequency.
333    SetDisplayClockDivide {
334        divide_ratio: u8,
335        oscillator_frequency: u8,
336    },
337    /// Set Pre-charge Period.
338    SetPrechargePeriod { phase1: u8, phase2: u8 },
339    /// Set VCOMH Deselect Level.
340    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        // Move the available region of the buffer to what is remaining after
501        // this command was encoded.
502        buffer.slice(take..);
503    }
504}
505
506// #[derive(Copy, Clone, PartialEq)]
507#[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    /// Column of the controller's display RAM where the panel starts.
537    const COLUMN_OFFSET: usize = (CONTROLLER_WIDTH - WIDTH) / 2;
538
539    /// Rejects unsupported resolutions at compile time.
540    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    /// Create the screen driver.
549    ///
550    /// `enable_charge_pump` is ignored for controllers without a charge pump.
551    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 }, //horizontal
585            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                // Move the window of the subslice after the header byte
627                // reserved for the transport.
628                buf_slice.slice(1..);
629
630                for cmd in sequence {
631                    cmd.encode(&mut buf_slice);
632                }
633
634                // We need the amount of data that has been sliced away
635                // at the start of the subslice.
636                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            // Move the window of the subslice after the header byte reserved
749            // for the transport.
750            buf_slice.slice(1..);
751
752            // Figure out how much we can send.
753            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}