From cc2f49340167345d15573478c70b0b8081984268 Mon Sep 17 00:00:00 2001 From: Alex Janka Date: Thu, 9 Jan 2025 09:51:30 +1100 Subject: [PATCH] ccs: pl: retry reads --- charge-controller-supervisor/src/pl.rs | 45 ++++++++++++++++++++------ 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/charge-controller-supervisor/src/pl.rs b/charge-controller-supervisor/src/pl.rs index 54c105b..b8dd9d0 100644 --- a/charge-controller-supervisor/src/pl.rs +++ b/charge-controller-supervisor/src/pl.rs @@ -163,7 +163,7 @@ impl Pli { pub async fn process_request(&mut self, message: PliRequest) -> eyre::Result<()> { match message { PliRequest::ReadRam(address) => { - let data = self.read_ram(address).await?; + let data = self.read_ram_with_retires(address).await?; log::warn!("Read RAM at {address}: data {data}"); } PliRequest::ReadEeprom(address) => { @@ -232,14 +232,21 @@ impl Pli { // let external_load_ah = u16::from_le_bytes([ext_load_low, ext_load_high]); Ok(PlState { - battery_voltage: f64::from(self.read_ram(PlRamAddress::Batv).await?) * (4. / 10.), - target_voltage: f64::from(self.read_ram(PlRamAddress::Vreg).await?) * (4. / 10.), - duty_cycle: f64::from(self.read_ram(PlRamAddress::Dutycyc).await?) / 255., - internal_charge_current: f64::from(self.read_ram(PlRamAddress::Cint).await?) + battery_voltage: f64::from(self.read_ram_with_retires(PlRamAddress::Batv).await?) * (4. / 10.), - internal_load_current: f64::from(self.read_ram(PlRamAddress::Lint).await?) * (2. / 10.), - battery_temp: f64::from(self.read_ram(PlRamAddress::Battemp).await?), - regulator_state: self.read_ram(PlRamAddress::Rstate).await?.into(), + target_voltage: f64::from(self.read_ram_with_retires(PlRamAddress::Vreg).await?) + * (4. / 10.), + duty_cycle: f64::from(self.read_ram_with_retires(PlRamAddress::Dutycyc).await?) / 255., + internal_charge_current: f64::from( + self.read_ram_with_retires(PlRamAddress::Cint).await?, + ) * (4. / 10.), + internal_load_current: f64::from(self.read_ram_with_retires(PlRamAddress::Lint).await?) + * (2. / 10.), + battery_temp: f64::from(self.read_ram_with_retires(PlRamAddress::Battemp).await?), + regulator_state: self + .read_ram_with_retires(PlRamAddress::Rstate) + .await? + .into(), // internal_charge_ah_accumulator, // external_charge_ah_accumulator, // internal_load_ah_accumulator, @@ -268,7 +275,27 @@ impl Pli { Ok(buf) } - async fn read_ram(&mut self, address: T) -> eyre::Result + async fn read_ram_with_retires(&mut self, address: T) -> eyre::Result + where + T: Into, + { + const READ_TRIES: usize = 3; + let address: u8 = address.into(); + + let mut last_err = None; + for _ in 0..READ_TRIES { + match self.read_ram_single(address).await { + Ok(v) => return Ok(v), + Err(e) => last_err = Some(e), + } + } + + Err(last_err.unwrap_or(eyre::eyre!( + "no error was stored in read_ram_with_retries: this should be unreachable??" + ))) + } + + async fn read_ram_single(&mut self, address: T) -> eyre::Result where T: Into, {