cleans up lifetimes and ownership
This commit is contained in:
@@ -1,15 +1,30 @@
|
||||
use std::fmt::{Debug, Formatter};
|
||||
use std::time::Instant;
|
||||
use anyhow::{bail, Result};
|
||||
use embedded_hal::i2c::I2c;
|
||||
use log::{info, trace};
|
||||
use crate::hardware::error::I2cError;
|
||||
|
||||
pub struct Mcp23017<I2C> {
|
||||
pub trait Mcp23017 {
|
||||
fn init(&mut self) -> Result<()>;
|
||||
fn set_pin(&mut self, pin: u8, value: bool) -> Result<()>;
|
||||
fn flush(&mut self) -> Result<()>;
|
||||
}
|
||||
|
||||
pub struct Mcp23017Driver<I2C> {
|
||||
i2c: I2C,
|
||||
address: u8,
|
||||
bank: [u8; 2],
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
impl<I2C> Mcp23017<I2C>
|
||||
impl<I2C> Debug for Mcp23017Driver<I2C> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Mcp23017Driver {{ address: {} }}", self.address)
|
||||
}
|
||||
}
|
||||
|
||||
impl<I2C> Mcp23017Driver<I2C>
|
||||
where
|
||||
I2C: I2c,
|
||||
I2C::Error : Send,
|
||||
@@ -17,6 +32,7 @@ where
|
||||
I2C::Error : 'static
|
||||
{
|
||||
pub fn new(i2c: I2C, address: u8) -> Self {
|
||||
trace!("Mcp23017Driver::new(i2c, address: {address:07b})");
|
||||
Self {
|
||||
i2c,
|
||||
address,
|
||||
@@ -24,12 +40,27 @@ where
|
||||
dirty: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<I2C> Mcp23017 for Mcp23017Driver<I2C>
|
||||
where
|
||||
I2C: I2c,
|
||||
I2C::Error : Send,
|
||||
I2C::Error : Sync,
|
||||
I2C::Error : 'static
|
||||
{
|
||||
fn init(&mut self) -> Result<()> {
|
||||
trace!("Mcp23017Driver::init(self: {self:?})");
|
||||
// Set each pin as an output (Addresses 0x00 & 0x01)
|
||||
let data: [u8; _] = [0x00, 0x00, 0x00];
|
||||
self.i2c.write(self.address, &data).map_err(I2cError)?;
|
||||
|
||||
pub fn init(&self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_pin(&mut self, pin: u8, value: bool) -> Result<()> {
|
||||
fn set_pin(&mut self, pin: u8, value: bool) -> Result<()> {
|
||||
trace!("Mcp23017Driver::set_pin(self: {self:?}, pin: {pin}, value: {value})");
|
||||
let (pin_bank, dirty_flag, pin_index) = match pin {
|
||||
0..8 => {
|
||||
(&mut self.bank[0], &mut self.dirty, pin as u32)
|
||||
@@ -53,9 +84,11 @@ where
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn flush(&mut self) -> Result<()> {
|
||||
fn flush(&mut self) -> Result<()> {
|
||||
trace!("Mcp23017Driver::flush(self: {self:?})");
|
||||
if self.dirty {
|
||||
let data: [u8; _] = [0x12, self.bank[0], self.bank[1]];
|
||||
// This blocks while writing
|
||||
self.i2c.write(self.address, &data).map_err(I2cError)?;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
Reference in New Issue
Block a user