use embedded_hal::{delay::DelayNs, i2c::I2c, i2c::ErrorType};
use super::DisplayInterface;
use crate::{command::Page, Error};
pub struct I2cInterface<I2C> {
i2c: I2C,
addr: u8,
}
impl<I2C> I2cInterface<I2C>
where
I2C: I2c,
{
pub fn new(i2c: I2C, addr: u8) -> Self {
Self { i2c, addr }
}
}
impl<I2C> DisplayInterface for I2cInterface<I2C>
where
I2C: I2c + ErrorType,
{
type Error = Error;
fn init(&mut self) -> Result<(), Error> {
Ok(())
}
fn send_commands(&mut self, cmds: &[u8]) -> Result<(), Self::Error> {
let mut writebuf: [u8; 8] = [0; 8];
writebuf[1..=cmds.len()].copy_from_slice(&cmds);
if (cmds.len() == 1) {
log::debug!("send_command : length = {} {:#04x}", cmds.len(), cmds[0]);
} else if (cmds.len() > 1) {
log::debug!("send_command : length = {} {:#04x} {:#04x}", cmds.len(), cmds[0], cmds[1]);
}
Ok(self.i2c
.write(self.addr, &writebuf[..=cmds.len()])?)
}
fn send_data(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
const CHUNKLEN: usize = 128;
const BUFLEN: usize = CHUNKLEN + 1;
if buf.is_empty() {
return Ok(());
}
let mut page = Page::Page0 as u8;
let mut writebuf: [u8; BUFLEN] = [0; BUFLEN];
writebuf[0] = 0x40; log::debug!("send_data buf length is {}", buf.len());
for chunk in buf.chunks(CHUNKLEN) {
writebuf[1..BUFLEN].copy_from_slice(&chunk);
self.i2c
.write(
self.addr,
&[
0x00, page, 0x02, 0x10, ],
)?;
self.i2c.write(self.addr, &writebuf)?;
page += 1;
}
Ok(())
}
}