This commit is contained in:
2025-09-20 10:38:15 -07:00
parent 8e6ed92eea
commit 6d3fbb926e
13 changed files with 72 additions and 70 deletions

View File

@@ -42,8 +42,12 @@ trait DataReadAccess {
pub trait DataReader { pub trait DataReader {
fn reset(&mut self); fn reset(&mut self);
fn read_be<T>(&mut self) -> Option<T> where T: ReadableDataType; fn read_be<T>(&mut self) -> Option<T>
fn read_le<T>(&mut self) -> Option<T> where T: ReadableDataType; where
T: ReadableDataType;
fn read_le<T>(&mut self) -> Option<T>
where
T: ReadableDataType;
fn read(&mut self, bytes: usize) -> Option<&[u8]>; fn read(&mut self, bytes: usize) -> Option<&[u8]>;
} }
@@ -56,7 +60,7 @@ impl<'a> DataViewReader<'a> {
pub fn new(data: &'a [u8]) -> Self { pub fn new(data: &'a [u8]) -> Self {
Self { Self {
data, data,
position: 0usize position: 0usize,
} }
} }
} }
@@ -91,7 +95,7 @@ impl<const LENGTH: usize> DataBufferReader<LENGTH> {
pub fn get_buffer(&mut self) -> &mut [u8] { pub fn get_buffer(&mut self) -> &mut [u8] {
&mut self.data &mut self.data
} }
pub fn get_write_buffer(&mut self, length: usize) -> &mut [u8] { pub fn get_write_buffer(&mut self, length: usize) -> &mut [u8] {
self.reset(); self.reset();
&mut self.data[..length] &mut self.data[..length]
@@ -119,7 +123,8 @@ impl<U: DataReadAccess> DataReader for U {
fn read_be<T>(&mut self) -> Option<T> fn read_be<T>(&mut self) -> Option<T>
where where
T: ReadableDataType { T: ReadableDataType,
{
let position = self.get_position(); let position = self.get_position();
if self.get_data().len() < position + T::BYTES { if self.get_data().len() < position + T::BYTES {
return None; return None;
@@ -133,7 +138,8 @@ impl<U: DataReadAccess> DataReader for U {
fn read_le<T>(&mut self) -> Option<T> fn read_le<T>(&mut self) -> Option<T>
where where
T: ReadableDataType { T: ReadableDataType,
{
let position = self.get_position(); let position = self.get_position();
if self.get_data().len() < position + T::BYTES { if self.get_data().len() < position + T::BYTES {
return None; return None;

View File

@@ -49,10 +49,11 @@ pub trait DataWriteAccess {
fn set_position(&mut self, position: usize); fn set_position(&mut self, position: usize);
} }
pub struct DeferredDataWrite<'a, T: WriteableDataType, U> pub struct DeferredDataWrite<'a, T: WriteableDataType, U>
where where
RefCell<U>: DataWriter, RefCell<U>: DataWriter,
<RefCell<U> as DataWriter>::WriterType: DataWriteAccess { <RefCell<U> as DataWriter>::WriterType: DataWriteAccess,
{
writer: &'a RefCell<U>, writer: &'a RefCell<U>,
position: usize, position: usize,
_phantom_data: PhantomData<T>, _phantom_data: PhantomData<T>,
@@ -64,7 +65,7 @@ pub trait DataWriter {
fn reset(&mut self); fn reset(&mut self);
fn get_position(&self) -> usize; fn get_position(&self) -> usize;
fn get_buffer(&mut self) -> &[u8]; fn get_buffer(&mut self) -> &[u8];
fn push_be<T: WriteableDataType>(&self, data: T) -> Result<(), DataWriterError>; fn push_be<T: WriteableDataType>(&self, data: T) -> Result<(), DataWriterError>;
fn push_le<T: WriteableDataType>(&self, data: T) -> Result<(), DataWriterError>; fn push_le<T: WriteableDataType>(&self, data: T) -> Result<(), DataWriterError>;
fn push(&self, data: &[u8]) -> Result<(), DataWriterError>; fn push(&self, data: &[u8]) -> Result<(), DataWriterError>;
@@ -80,7 +81,7 @@ impl<'a> DataViewWriter<'a> {
pub fn new(data: &'a mut [u8]) -> RefCell<Self> { pub fn new(data: &'a mut [u8]) -> RefCell<Self> {
RefCell::new(Self { RefCell::new(Self {
data, data,
position: 0usize position: 0usize,
}) })
} }
} }
@@ -108,7 +109,7 @@ impl<const LENGTH: usize> DataBufferWriter<LENGTH> {
pub fn new() -> RefCell<Self> { pub fn new() -> RefCell<Self> {
RefCell::new(Self { RefCell::new(Self {
data: [0u8; LENGTH], data: [0u8; LENGTH],
position: 0usize position: 0usize,
}) })
} }
} }
@@ -129,7 +130,7 @@ impl<const LENGTH: usize> DataWriteAccess for DataBufferWriter<LENGTH> {
impl<U: DataWriteAccess> DataWriter for RefCell<U> { impl<U: DataWriteAccess> DataWriter for RefCell<U> {
type WriterType = U; type WriterType = U;
fn reset(&mut self) { fn reset(&mut self) {
self.get_mut().set_position(0); self.get_mut().set_position(0);
} }
@@ -187,7 +188,10 @@ impl<U: DataWriteAccess> DataWriter for RefCell<U> {
} }
} }
impl<'a, T: WriteableDataType, U: DataWriteAccess> DeferredDataWrite<'a, T, U> where RefCell<U>: DataWriter { impl<'a, T: WriteableDataType, U: DataWriteAccess> DeferredDataWrite<'a, T, U>
where
RefCell<U>: DataWriter,
{
pub fn set_be(self, data: T) { pub fn set_be(self, data: T) {
data.to_be_slice(&mut self.writer.borrow_mut().get_data()[self.position..(self.position + T::BYTES)]); data.to_be_slice(&mut self.writer.borrow_mut().get_data()[self.position..(self.position + T::BYTES)]);
} }
@@ -198,9 +202,6 @@ impl<'a, T: WriteableDataType, U: DataWriteAccess> DeferredDataWrite<'a, T, U> w
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use anyhow::Result;
#[test] #[test]
fn test_buffer() -> Result<()> { fn test_buffer() -> Result<()> {
let mut writer = DataBufferWriter::<128>::new(); let mut writer = DataBufferWriter::<128>::new();

View File

@@ -1,6 +1,7 @@
mod shtp; mod shtp;
use crate::data::reader::{DataBufferReader, DataReader}; use crate::data::reader::{DataBufferReader, DataReader};
use crate::data::writer::{DataBufferWriter, DataWriter};
use crate::hardware::error::{NotAvailableError, SpiError}; use crate::hardware::error::{NotAvailableError, SpiError};
use crate::hardware::imu::{Imu, ImuMeasurement}; use crate::hardware::imu::{Imu, ImuMeasurement};
use anyhow::{anyhow, bail, ensure, Result}; use anyhow::{anyhow, bail, ensure, Result};
@@ -8,7 +9,6 @@ use chrono::TimeDelta;
use embedded_hal::spi::SpiDevice; use embedded_hal::spi::SpiDevice;
use log::info; use log::info;
use num_traits::ToPrimitive; use num_traits::ToPrimitive;
use crate::data::writer::{DataBufferWriter, DataWriter};
const RX_BUFFER_LENGTH: usize = 1024; const RX_BUFFER_LENGTH: usize = 1024;
@@ -30,15 +30,15 @@ pub struct Bno085<SPI> {
impl<SPI> Bno085<SPI> impl<SPI> Bno085<SPI>
where where
SPI : SpiDevice<u8>, SPI: SpiDevice<u8>,
SPI::Error : Send, SPI::Error: Send,
SPI::Error : Sync, SPI::Error: Sync,
SPI::Error : 'static, SPI::Error: 'static,
{ {
pub fn new(spi: SPI) -> Self { pub fn new(spi: SPI) -> Self {
Self { Self {
spi, spi,
sequence_number: 0u8 sequence_number: 0u8,
} }
} }
@@ -81,7 +81,7 @@ where
let mut tx = DataBufferWriter::<128>::new(); let mut tx = DataBufferWriter::<128>::new();
self.produce_sensor_enable(&tx)?; self.produce_sensor_enable(&tx)?;
self.spi.write( tx.get_buffer()).map_err(SpiError)?; self.spi.write(tx.get_buffer()).map_err(SpiError)?;
Ok(()) Ok(())
} }
@@ -131,7 +131,7 @@ where
fn produce_sensor_enable( fn produce_sensor_enable(
&mut self, &mut self,
tx: &impl DataWriter tx: &impl DataWriter,
) -> Result<()> { ) -> Result<()> {
let starting_position = tx.get_position(); let starting_position = tx.get_position();
let length = tx.defer::<u16>()?; let length = tx.defer::<u16>()?;
@@ -146,7 +146,7 @@ where
0, 0,
TimeDelta::seconds(1) / 100, // 100Hz TimeDelta::seconds(1) / 100, // 100Hz
TimeDelta::zero(), TimeDelta::zero(),
0 0,
)?; )?;
self.produce_set_feature( self.produce_set_feature(
tx, tx,
@@ -155,7 +155,7 @@ where
0, 0,
TimeDelta::seconds(1) / 100, // 100Hz TimeDelta::seconds(1) / 100, // 100Hz
TimeDelta::zero(), TimeDelta::zero(),
0 0,
)?; )?;
self.produce_set_feature( self.produce_set_feature(
tx, tx,
@@ -164,7 +164,7 @@ where
0, 0,
TimeDelta::seconds(1) / 100, // 100Hz TimeDelta::seconds(1) / 100, // 100Hz
TimeDelta::zero(), TimeDelta::zero(),
0 0,
)?; )?;
length.set_le((tx.get_position() - starting_position) as u16); // Fill in the length as we finish length.set_le((tx.get_position() - starting_position) as u16); // Fill in the length as we finish
@@ -179,7 +179,7 @@ where
change_sensitivity: u16, change_sensitivity: u16,
report_interval: TimeDelta, report_interval: TimeDelta,
batch_interval: TimeDelta, batch_interval: TimeDelta,
configuration_word: u32 configuration_word: u32,
) -> Result<()> { ) -> Result<()> {
tx.push_le(SET_FEATURE_REPORT_ID)?; tx.push_le(SET_FEATURE_REPORT_ID)?;
tx.push_le(feature_report_id)?; tx.push_le(feature_report_id)?;
@@ -198,7 +198,7 @@ where
} }
} }
impl<SPI : SpiDevice> Imu for Bno085<SPI> { impl<SPI: SpiDevice> Imu for Bno085<SPI> {
fn step(&mut self) -> Result<ImuMeasurement> { fn step(&mut self) -> Result<ImuMeasurement> {
todo!("asd") todo!("asd")
} }
@@ -206,7 +206,6 @@ impl<SPI : SpiDevice> Imu for Bno085<SPI> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use crate::test_utils::SilentDrop; use crate::test_utils::SilentDrop;
use embedded_hal_mock::eh1::spi::Mock as SpiMock; use embedded_hal_mock::eh1::spi::Mock as SpiMock;
use embedded_hal_mock::eh1::spi::Transaction as SpiTransaction; use embedded_hal_mock::eh1::spi::Transaction as SpiTransaction;
@@ -258,7 +257,6 @@ mod tests {
bno.spi.done(); bno.spi.done();
Ok(()) Ok(())
} }
} }

View File

@@ -1,21 +1,20 @@
use crate::data::reader::DataReader; use crate::data::reader::DataReader;
use crate::hardware::error::NotAvailableError; use crate::hardware::error::NotAvailableError;
use anyhow::Result;
pub struct Header { pub struct Header {
pub length: u16, pub length: u16,
pub channel: u8, pub channel: u8,
pub sequence_number: u8 pub sequence_number: u8,
} }
impl Header { impl Header {
pub const SIZE: usize = size_of::<u16>() + size_of::<u8>() + size_of::<u8>(); pub const SIZE: usize = size_of::<u16>() + size_of::<u8>() + size_of::<u8>();
pub fn parse(bytes: &mut impl DataReader) -> Result<Self> { pub fn parse(bytes: &mut impl DataReader) -> Result<Self> {
let length = bytes.read_le::<u16>().ok_or(NotAvailableError)?; let length = bytes.read_le::<u16>().ok_or(NotAvailableError)?;
let channel = bytes.read_le::<u8>().ok_or(NotAvailableError)?; let channel = bytes.read_le::<u8>().ok_or(NotAvailableError)?;
let sequence_number = bytes.read_le::<u8>().ok_or(NotAvailableError)?; let sequence_number = bytes.read_le::<u8>().ok_or(NotAvailableError)?;
Ok(Self { Ok(Self {
length, length,
channel, channel,

View File

@@ -10,7 +10,7 @@ impl<ERR: Debug + embedded_hal::i2c::Error> Display for I2cError<ERR> {
} }
} }
impl<ERR: Debug + embedded_hal::i2c::Error> Error for I2cError<ERR> { } impl<ERR: Debug + embedded_hal::i2c::Error> Error for I2cError<ERR> {}
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub struct SpiError<ERR: Debug + embedded_hal::spi::Error>(pub ERR); pub struct SpiError<ERR: Debug + embedded_hal::spi::Error>(pub ERR);
@@ -21,7 +21,7 @@ impl<ERR: Debug + embedded_hal::spi::Error> Display for SpiError<ERR> {
} }
} }
impl<ERR: Debug + embedded_hal::spi::Error> Error for SpiError<ERR> { } impl<ERR: Debug + embedded_hal::spi::Error> Error for SpiError<ERR> {}
// #[derive(Copy, Clone, Debug)] // #[derive(Copy, Clone, Debug)]
// pub struct NotAvailableError; // pub struct NotAvailableError;

View File

@@ -1,5 +1,4 @@
use nalgebra::Vector3; use nalgebra::Vector3;
use anyhow::Result;
pub struct ImuMeasurement { pub struct ImuMeasurement {
pub acceleration: Vector3<f64>, pub acceleration: Vector3<f64>,

View File

@@ -1,9 +1,9 @@
use std::fmt::{Debug, Formatter}; use crate::hardware::error::I2cError;
use std::time::Instant;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use embedded_hal::i2c::I2c; use embedded_hal::i2c::I2c;
use log::{info, trace}; use log::{info, trace};
use crate::hardware::error::I2cError; use std::fmt::{Debug, Formatter};
use std::time::Instant;
pub trait Mcp23017 { pub trait Mcp23017 {
fn init(&mut self) -> Result<()>; fn init(&mut self) -> Result<()>;
@@ -27,9 +27,9 @@ impl<I2C> Debug for Mcp23017Driver<I2C> {
impl<I2C> Mcp23017Driver<I2C> impl<I2C> Mcp23017Driver<I2C>
where where
I2C: I2c, I2C: I2c,
I2C::Error : Send, I2C::Error: Send,
I2C::Error : Sync, I2C::Error: Sync,
I2C::Error : 'static I2C::Error: 'static,
{ {
pub fn new(i2c: I2C, address: u8) -> Self { pub fn new(i2c: I2C, address: u8) -> Self {
trace!("Mcp23017Driver::new(i2c, address: {address:07b})"); trace!("Mcp23017Driver::new(i2c, address: {address:07b})");
@@ -46,9 +46,9 @@ where
impl<I2C> Mcp23017 for Mcp23017Driver<I2C> impl<I2C> Mcp23017 for Mcp23017Driver<I2C>
where where
I2C: I2c, I2C: I2c,
I2C::Error : Send, I2C::Error: Send,
I2C::Error : Sync, I2C::Error: Sync,
I2C::Error : 'static I2C::Error: 'static,
{ {
fn init(&mut self) -> Result<()> { fn init(&mut self) -> Result<()> {
trace!("Mcp23017Driver::init(self: {self:?})"); trace!("Mcp23017Driver::init(self: {self:?})");
@@ -64,10 +64,10 @@ where
let (pin_bank, dirty_flag, pin_index) = match pin { let (pin_bank, dirty_flag, pin_index) = match pin {
0..8 => { 0..8 => {
(&mut self.bank[0], &mut self.dirty, pin as u32) (&mut self.bank[0], &mut self.dirty, pin as u32)
}, }
8 ..16 => { 8..16 => {
(&mut self.bank[1], &mut self.dirty, (pin as u32) - 8) (&mut self.bank[1], &mut self.dirty, (pin as u32) - 8)
}, }
_ => bail!("Invalid Pin ID"), _ => bail!("Invalid Pin ID"),
}; };
let pin_mask = 1u8.unbounded_shl(pin_index); let pin_mask = 1u8.unbounded_shl(pin_index);

View File

@@ -1,12 +1,12 @@
use std::fmt::{Debug, Formatter};
use crate::hardware::error::SpiError; use crate::hardware::error::SpiError;
use anyhow::{ensure, Result}; use anyhow::{ensure, Result};
use embedded_hal::spi::SpiDevice; use embedded_hal::spi::SpiDevice;
use log::trace; use log::trace;
use std::fmt::{Debug, Formatter};
pub struct Mcp3208<SPI> { pub struct Mcp3208<SPI> {
spi: SPI, spi: SPI,
vref: f64 vref: f64,
} }
impl<SPI> Debug for Mcp3208<SPI> { impl<SPI> Debug for Mcp3208<SPI> {
@@ -17,16 +17,16 @@ impl<SPI> Debug for Mcp3208<SPI> {
impl<SPI> Mcp3208<SPI> impl<SPI> Mcp3208<SPI>
where where
SPI : SpiDevice<u8>, SPI: SpiDevice<u8>,
SPI::Error : Send, SPI::Error: Send,
SPI::Error : Sync, SPI::Error: Sync,
SPI::Error : 'static, SPI::Error: 'static,
{ {
pub fn new(spi: SPI, vref: f64) -> Self { pub fn new(spi: SPI, vref: f64) -> Self {
trace!("Mcp3208::new(spi, vref: {vref})"); trace!("Mcp3208::new(spi, vref: {vref})");
Self { Self {
spi, spi,
vref vref,
} }
} }

View File

@@ -2,7 +2,6 @@ use crate::hardware::mcp23017::Mcp23017;
use anyhow::Result; use anyhow::Result;
pub trait Hardware { pub trait Hardware {
fn get_mcp23017_a(&self) -> impl Mcp23017; fn get_mcp23017_a(&self) -> impl Mcp23017;
fn get_mcp23017_b(&self) -> impl Mcp23017; fn get_mcp23017_b(&self) -> impl Mcp23017;

View File

@@ -1,15 +1,15 @@
use std::cell::RefCell; use crate::hardware::mcp23017::{Mcp23017, Mcp23017Driver};
use std::sync::Mutex; use crate::hardware::mcp3208::Mcp3208;
use crate::hardware::Hardware; use crate::hardware::Hardware;
use anyhow::Result; use anyhow::Result;
use embedded_hal_bus::i2c::MutexDevice; use embedded_hal_bus::i2c::MutexDevice;
use log::{debug, info, trace}; use log::{debug, info, trace};
// use rpi_pal::gpio::Gpio; // use rpi_pal::gpio::Gpio;
use rpi_pal::i2c::I2c; use rpi_pal::i2c::I2c;
use rpi_pal::spi::{Bus, Mode, SlaveSelect, Spi};
use crate::hardware::mcp23017::{Mcp23017, Mcp23017Driver};
use crate::hardware::mcp3208::Mcp3208;
use rpi_pal::spi::SimpleHalSpiDevice; use rpi_pal::spi::SimpleHalSpiDevice;
use rpi_pal::spi::{Bus, Mode, SlaveSelect, Spi};
use std::cell::RefCell;
use std::sync::Mutex;
const CLOCK_1MHZ: u32 = 1_000_000; const CLOCK_1MHZ: u32 = 1_000_000;

View File

@@ -1,11 +1,11 @@
use std::thread::sleep;
use std::time::Duration;
use crate::hardware::initialize; use crate::hardware::initialize;
use crate::hardware::mcp23017::Mcp23017;
use crate::hardware::Hardware;
use crate::logger::setup_logger; use crate::logger::setup_logger;
use anyhow::Result; use anyhow::Result;
use log::info; use log::info;
use crate::hardware::Hardware; use std::thread::sleep;
use crate::hardware::mcp23017::Mcp23017; use std::time::Duration;
mod hardware; mod hardware;
mod logger; mod logger;

View File

@@ -1,8 +1,8 @@
use anyhow::Result; use anyhow::Result;
use log::debug;
use std::env; use std::env;
use std::fs::create_dir_all; use std::fs::create_dir_all;
use std::str::FromStr; use std::str::FromStr;
use log::debug;
pub fn setup_logger() -> Result<()> { pub fn setup_logger() -> Result<()> {
let log_file = env::var("LOG_FILE").or_else(|_| { let log_file = env::var("LOG_FILE").or_else(|_| {

View File

@@ -3,7 +3,7 @@ use std::ops::{Deref, DerefMut};
use std::panic; use std::panic;
pub struct SilentDrop<T: panic::UnwindSafe> { pub struct SilentDrop<T: panic::UnwindSafe> {
inner: ManuallyDrop<T> inner: ManuallyDrop<T>,
} }
impl<T: panic::UnwindSafe> SilentDrop<T> { impl<T: panic::UnwindSafe> SilentDrop<T> {