refactor: BatteryInfo structure (consistent layout)

- use tagged enum serialization for BatteryError
- flatten BatteryInfo telemetry with consistent field names and typed error
This commit is contained in:
2026-05-10 14:04:54 +02:00
parent 7866604a40
commit df3159aa16
2 changed files with 64 additions and 32 deletions

View File

@@ -1,5 +1,6 @@
use crate::fat_error::{FatError, FatResult};
use crate::hal::Box;
use alloc::string::String;
use async_trait::async_trait;
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
@@ -18,15 +19,23 @@ pub trait BatteryInteraction {
async fn reset(&mut self) -> FatResult<()>;
}
#[derive(Debug, Serialize, Copy, Clone)]
#[derive(Debug, Serialize, Clone)]
pub struct BatteryInfo {
pub voltage_milli_volt: u32,
pub average_current_milli_ampere: i32,
pub design_milli_ampere_hour: u32,
pub remaining_milli_ampere_hour: u32,
pub state_of_charge: u8,
pub state_of_health: u32,
pub temperature: i32,
pub voltage_mv: Option<u32>,
pub avg_current_ma: Option<i32>,
pub design_mah: Option<u32>,
pub remaining_mah: Option<u32>,
pub soc_pct: Option<f32>,
pub soh_pct: Option<f32>,
pub temperature_c: Option<i32>,
pub error: Option<BatteryError>,
}
#[derive(Debug, Serialize, Clone)]
#[serde(tag = "kind")]
pub enum BatteryError {
NoBatteryMonitor,
CommunicationError { message: String },
}
#[derive(Debug, Serialize)]
@@ -71,17 +80,18 @@ impl BatteryInteraction for WCHI2CSlave<'_> {
let config = Config::read_from_i2c(&mut self.i2c)?;
let state_of_charge =
(state.remaining_capacity_mah * 100 / state.lifetime_capacity_mah) as u8;
let state_of_health = state.lifetime_capacity_mah / config.capacity_mah * 100;
state.remaining_capacity_mah as f32 * 100. / state.lifetime_capacity_mah as f32;
let state_of_health = state.lifetime_capacity_mah as f32 / config.capacity_mah as f32 * 100.;
Ok(BatteryState::Info(BatteryInfo {
voltage_milli_volt: state.current_mv,
average_current_milli_ampere: 1337,
design_milli_ampere_hour: config.capacity_mah,
remaining_milli_ampere_hour: state.remaining_capacity_mah,
state_of_charge,
state_of_health,
temperature: state.temperature_celcius,
voltage_mv: Some(state.current_mv),
avg_current_ma: Some(1337),
design_mah: Some(config.capacity_mah),
remaining_mah: Some(state.remaining_capacity_mah),
soc_pct: Some(state_of_charge),
soh_pct: Some(state_of_health),
temperature_c: Some(state.temperature_celcius),
error: None
}))
}