use core::time::Duration;
use embedded_graphics::{
pixelcolor::BinaryColor,
prelude::{Point, Size},
primitives::Rectangle,
};
use embedded_hal::{
digital::{OutputPin, PinState},
spi::{Phase, Polarity},
};
use embedded_hal_async::delay::DelayNs;
use crate::{
buffer::{binary_buffer_length, split_low_and_high, BinaryBuffer, BufferView},
hw::{BusyHw, DcHw, DelayHw, ErrorHw, ResetHw, SpiHw},
log::{debug, debug_assert},
DisplayPartial, DisplaySimple, Displayable, Reset, Sleep, Wake,
};
const LUT_FULL_UPDATE: [u8; 30] = [
0x50, 0xAA, 0x55, 0xAA, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
const LUT_PARTIAL_UPDATE: [u8; 30] = [
0x10, 0x18, 0x18, 0x08, 0x18, 0x18, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x13, 0x14, 0x44, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshMode {
Full,
Partial,
PartialBlackBypass,
PartialWhiteBypass,
}
impl RefreshMode {
pub fn lut(&self) -> &[u8; 30] {
match self {
RefreshMode::Full => &LUT_FULL_UPDATE,
_ => &LUT_PARTIAL_UPDATE,
}
}
}
pub const DISPLAY_HEIGHT: u16 = 296;
pub const DISPLAY_WIDTH: u16 = 128;
pub const RECOMMENDED_MIN_FULL_REFRESH_INTERVAL: Duration = Duration::from_secs(180);
pub const RECOMMENDED_MAX_FULL_REFRESH_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
pub const RECOMMENDED_SPI_HZ: u32 = 4_000_000; pub const RECOMMENDED_SPI_PHASE: Phase = Phase::CaptureOnFirstTransition;
pub const RECOMMENDED_SPI_POLARITY: Polarity = Polarity::IdleLow;
pub const DEFAULT_BUSY_WHEN: PinState = PinState::High;
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
DriverOutputControl = 0x01,
BoosterSoftStartControl = 0x0C,
DeepSleepMode = 0x10,
DataEntryModeSetting = 0x11,
SwReset = 0x12,
TemperatureSensorControl = 0x1A,
MasterActivation = 0x20,
DisplayUpdateControl1 = 0x21,
DisplayUpdateControl2 = 0x22,
WriteRam = 0x24,
WriteOldRam = 0x26,
WriteVcom = 0x2C,
WriteLut = 0x32,
SetDummyLinePeriod = 0x3A,
SetGateLineWidth = 0x3B,
BorderWaveformControl = 0x3C,
SetRamXStartEnd = 0x44,
SetRamYStartEnd = 0x45,
SetRamX = 0x4E,
SetRamY = 0x4F,
Noop = 0xFF,
}
impl Command {
fn register(&self) -> u8 {
*self as u8
}
}
pub const BINARY_BUFFER_LENGTH: usize =
binary_buffer_length(Size::new(DISPLAY_WIDTH as u32, DISPLAY_HEIGHT as u32));
pub type Epd2In9Buffer =
BinaryBuffer<{ binary_buffer_length(Size::new(DISPLAY_WIDTH as u32, DISPLAY_HEIGHT as u32)) }>;
pub fn new_buffer() -> Epd2In9Buffer {
Epd2In9Buffer::new(Size::new(DISPLAY_WIDTH as u32, DISPLAY_HEIGHT as u32))
}
const DRIVER_OUTPUT_INIT_DATA: [u8; 3] = [0x27, 0x01, 0x00];
const BOOSTER_SOFT_START_INIT_DATA: [u8; 3] = [0xD7, 0xD6, 0x9D];
trait StateInternal {}
#[allow(private_bounds)]
pub trait State: StateInternal {}
pub trait StateAwake: State {}
macro_rules! impl_base_state {
($state:ident) => {
impl StateInternal for $state {}
impl State for $state {}
};
}
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StateUninitialized();
impl_base_state!(StateUninitialized);
impl StateAwake for StateUninitialized {}
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StateReady {
mode: RefreshMode,
}
impl_base_state!(StateReady);
impl StateAwake for StateReady {}
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StateAsleep<W: StateAwake> {
wake_state: W,
}
impl<W: StateAwake> StateInternal for StateAsleep<W> {}
impl<W: StateAwake> State for StateAsleep<W> {}
pub struct Epd2In9<HW, STATE> {
hw: HW,
state: STATE,
}
impl<HW> Epd2In9<HW, StateUninitialized>
where
HW: DcHw + ResetHw + BusyHw + DelayHw + ErrorHw + SpiHw,
HW::Error: From<<HW::Dc as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Reset as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
{
pub fn new(hw: HW) -> Self {
Epd2In9 {
hw,
state: StateUninitialized(),
}
}
}
impl<HW, STATE> Epd2In9<HW, STATE>
where
HW: DcHw + ResetHw + BusyHw + DelayHw + ErrorHw + SpiHw,
STATE: StateAwake,
HW::Error: From<<HW::Dc as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Reset as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
{
pub async fn init(
mut self,
spi: &mut HW::Spi,
mode: RefreshMode,
) -> Result<Epd2In9<HW, StateReady>, HW::Error> {
debug!("Initialising display");
self = self.reset().await?;
self.send(spi, Command::SwReset, &[]).await?;
self.send(spi, Command::DriverOutputControl, &DRIVER_OUTPUT_INIT_DATA)
.await?;
self.send(
spi,
Command::BoosterSoftStartControl,
&BOOSTER_SOFT_START_INIT_DATA,
)
.await?;
self.send(spi, Command::DataEntryModeSetting, &[0b11])
.await?;
self.send(spi, Command::WriteVcom, &[0xA8]).await?;
self.send(spi, Command::SetDummyLinePeriod, &[0x1A]).await?;
self.send(spi, Command::SetGateLineWidth, &[0x08]).await?;
let mut epd = Epd2In9 {
hw: self.hw,
state: StateReady { mode },
};
epd.set_refresh_mode_impl(spi, mode).await?;
Ok(epd)
}
}
impl<HW, STATE> Epd2In9<HW, STATE>
where
HW: DcHw + BusyHw + ErrorHw + SpiHw,
STATE: StateAwake,
HW::Error: From<<HW::Dc as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
{
pub async fn set_border(
&mut self,
spi: &mut HW::Spi,
color: BinaryColor,
) -> Result<(), HW::Error> {
let border_setting: u8 = match color {
BinaryColor::Off => 0x00,
BinaryColor::On => 0x01,
};
self.send(spi, Command::BorderWaveformControl, &[border_setting])
.await
}
pub async fn send(
&mut self,
spi: &mut HW::Spi,
command: Command,
data: &[u8],
) -> Result<(), HW::Error> {
use crate::hw::CommandDataSend;
self.hw.send(spi, command.register(), data).await
}
}
impl<HW> Epd2In9<HW, StateReady>
where
HW: DcHw + BusyHw + DelayHw + ErrorHw + SpiHw,
HW::Error: From<<HW::Dc as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
{
pub async fn set_refresh_mode(
&mut self,
spi: &mut HW::Spi,
mode: RefreshMode,
) -> Result<(), HW::Error> {
if self.state.mode == mode {
Ok(())
} else {
debug!("Changing refresh mode to {:?}", mode);
self.set_refresh_mode_impl(spi, mode).await?;
Ok(())
}
}
pub async fn set_window(
&mut self,
spi: &mut HW::Spi,
shape: Rectangle,
) -> Result<(), HW::Error> {
let x_start = shape.top_left.x;
let x_end = x_start + shape.size.width as i32 - 1;
debug_assert!(
x_start % 8 == 0 && x_end % 8 == 7,
"window's top_left.x and width must be 8-bit aligned"
);
let x_start_byte = ((x_start >> 3) & 0xFF) as u8;
let x_end_byte = ((x_end >> 3) & 0xFF) as u8;
self.send(spi, Command::SetRamXStartEnd, &[x_start_byte, x_end_byte])
.await?;
let (y_start_low, y_start_high) = split_low_and_high(shape.top_left.y as u16);
let (y_end_low, y_end_high) =
split_low_and_high((shape.top_left.y + shape.size.height as i32 - 1) as u16);
self.send(
spi,
Command::SetRamYStartEnd,
&[y_start_low, y_start_high, y_end_low, y_end_high],
)
.await?;
Ok(())
}
pub async fn set_cursor(
&mut self,
spi: &mut HW::Spi,
position: Point,
) -> Result<(), HW::Error> {
debug_assert_eq!(position.x % 8, 0, "position.x must be 8-bit aligned");
self.send(spi, Command::SetRamX, &[(position.x >> 3) as u8])
.await?;
let (y_low, y_high) = split_low_and_high(position.y as u16);
self.send(spi, Command::SetRamY, &[y_low, y_high]).await?;
Ok(())
}
async fn set_refresh_mode_impl(
&mut self,
spi: &mut HW::Spi,
mode: RefreshMode,
) -> Result<(), HW::Error> {
self.send(spi, Command::WriteLut, mode.lut()).await?;
self.state.mode = mode;
match mode {
RefreshMode::Partial => {
self.send(spi, Command::DisplayUpdateControl1, &[0x00])
.await
}
RefreshMode::PartialBlackBypass => {
self.send(spi, Command::DisplayUpdateControl1, &[0x90])
.await
}
RefreshMode::PartialWhiteBypass => {
self.send(spi, Command::DisplayUpdateControl1, &[0x80])
.await
}
_ => Ok(()),
}
}
}
impl<HW> Displayable<HW::Spi, HW::Error> for Epd2In9<HW, StateReady>
where
HW: DcHw + BusyHw + DelayHw + ErrorHw + SpiHw,
HW::Error: From<<HW::Dc as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
{
async fn update_display(&mut self, spi: &mut HW::Spi) -> Result<(), HW::Error> {
debug!("Updating display");
self.send(spi, Command::DisplayUpdateControl2, &[0xC4])
.await?;
self.send(spi, Command::MasterActivation, &[]).await?;
self.send(spi, Command::Noop, &[]).await?;
Ok(())
}
}
impl<HW> DisplaySimple<1, 1, HW::Spi, HW::Error> for Epd2In9<HW, StateReady>
where
HW: DcHw + BusyHw + DelayHw + ErrorHw + SpiHw,
HW::Error: From<<HW::Dc as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
{
async fn display_framebuffer(
&mut self,
spi: &mut HW::Spi,
buf: &dyn BufferView<1, 1>,
) -> Result<(), HW::Error> {
self.write_framebuffer(spi, buf).await?;
self.update_display(spi).await
}
async fn write_framebuffer(
&mut self,
spi: &mut HW::Spi,
buf: &dyn BufferView<1, 1>,
) -> Result<(), HW::Error> {
let buffer_bounds = buf.window();
self.set_window(spi, buffer_bounds).await?;
self.set_cursor(spi, buffer_bounds.top_left).await?;
self.send(spi, Command::WriteRam, buf.data()[0]).await
}
}
impl<HW> DisplayPartial<1, 1, HW::Spi, HW::Error> for Epd2In9<HW, StateReady>
where
HW: DcHw + BusyHw + DelayHw + ErrorHw + SpiHw,
HW::Error: From<<HW::Dc as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
{
async fn write_base_framebuffer(
&mut self,
spi: &mut HW::Spi,
buf: &dyn BufferView<1, 1>,
) -> Result<(), HW::Error> {
let buffer_bounds = buf.window();
self.set_window(spi, buffer_bounds).await?;
self.set_cursor(spi, buffer_bounds.top_left).await?;
self.send(spi, Command::WriteOldRam, buf.data()[0]).await
}
}
async fn reset_impl<HW>(hw: &mut HW) -> Result<(), HW::Error>
where
HW: ResetHw + DelayHw + ErrorHw,
HW::Error: From<<HW::Reset as embedded_hal::digital::ErrorType>::Error>,
{
debug!("Resetting EPD");
hw.reset().set_low()?;
hw.delay().delay_ms(10).await;
hw.reset().set_high()?;
hw.delay().delay_ms(10).await;
Ok(())
}
impl<HW, STATE> Reset<HW::Error> for Epd2In9<HW, STATE>
where
HW: ResetHw + DelayHw + ErrorHw,
HW::Error: From<<HW::Reset as embedded_hal::digital::ErrorType>::Error>,
STATE: StateAwake,
{
type DisplayOut = Epd2In9<HW, STATE>;
async fn reset(mut self) -> Result<Self::DisplayOut, HW::Error> {
reset_impl(&mut self.hw).await?;
Ok(self)
}
}
impl<HW, W> Reset<HW::Error> for Epd2In9<HW, StateAsleep<W>>
where
HW: ResetHw + DelayHw + ErrorHw,
HW::Error: From<<HW::Reset as embedded_hal::digital::ErrorType>::Error>,
W: StateAwake,
{
type DisplayOut = Epd2In9<HW, W>;
async fn reset(mut self) -> Result<Self::DisplayOut, HW::Error> {
reset_impl(&mut self.hw).await?;
Ok(Epd2In9 {
hw: self.hw,
state: self.state.wake_state,
})
}
}
impl<HW, STATE> Sleep<HW::Spi, HW::Error> for Epd2In9<HW, STATE>
where
HW: DcHw + BusyHw + ErrorHw + SpiHw,
HW::Error: From<<HW::Dc as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
STATE: StateAwake,
{
type DisplayOut = Epd2In9<HW, StateAsleep<STATE>>;
async fn sleep(mut self, spi: &mut HW::Spi) -> Result<Self::DisplayOut, HW::Error>
where {
debug!("Sleeping EPD");
self.send(spi, Command::DeepSleepMode, &[0x01]).await?;
Ok(Epd2In9 {
hw: self.hw,
state: StateAsleep {
wake_state: self.state,
},
})
}
}
impl<HW, W> Wake<HW::Spi, HW::Error> for Epd2In9<HW, StateAsleep<W>>
where
HW: ResetHw + BusyHw + DelayHw + ErrorHw + SpiHw,
HW::Error: From<<HW::Reset as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Busy as embedded_hal::digital::ErrorType>::Error>
+ From<<HW::Spi as embedded_hal_async::spi::ErrorType>::Error>,
W: StateAwake,
{
type DisplayOut = Epd2In9<HW, W>;
async fn wake(self, _spi: &mut HW::Spi) -> Result<Self::DisplayOut, HW::Error> {
debug!("Waking EPD");
self.reset().await
}
}