use hal;
use super::DisplayInterface;
use crate::{command::Page, Error};
pub struct I2cInterface<I2C> {
i2c: I2C,
addr: u8,
}
impl<I2C> I2cInterface<I2C>
where
I2C: hal::blocking::i2c::Write,
{
pub fn new(i2c: I2C, addr: u8) -> Self {
Self { i2c, addr }
}
}
impl<I2C, CommE> DisplayInterface for I2cInterface<I2C>
where
I2C: hal::blocking::i2c::Write<Error = CommE>,
{
type Error = Error<CommE, ()>;
fn init(&mut self) -> Result<(), Self::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);
self.i2c
.write(self.addr, &writebuf[..=cmds.len()])
.map_err(Error::Comm)
}
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;
for chunk in buf.chunks(CHUNKLEN) {
writebuf[1..BUFLEN].copy_from_slice(&chunk);
self.i2c
.write(
self.addr,
&[
0x00, page, 0x02, 0x10, ],
)
.map_err(Error::Comm)?;
self.i2c.write(self.addr, &writebuf).map_err(Error::Comm)?;
page += 1;
}
Ok(())
}
}