6 Commits

Author SHA1 Message Date
b94b4e5d76 refctor: TankInfo structure (consistent layout)
- fix: use tagged enum serialization for TankError
- fix: rename TankInfo fields for consistent naming (volume_ml, pct, water_temp_c)
- renamed some fields for better clarity on contained value
2026-05-10 14:04:57 +02:00
3f12610ad0 refactor: PlantInfo structure (consistent layout)
- fix: use tagged enum serialization for MoistureSensorError and PumpError
- fix: flatten PlantInfo sensors to SensorTelemetry with top-level moisture_pct
2026-05-10 14:04:55 +02:00
47538081c7 refactor: BatteryInfo structure (consistent layout)
- use tagged enum serialization for BatteryError
- flatten BatteryInfo telemetry with consistent field names and typed error
2026-05-10 14:04:54 +02:00
30b0415b34 fix: serialize firmware/state as JSON instead of Debug format 2026-05-10 14:04:51 +02:00
96023c8dc3 Merge branch 'refactor/mkstatic-util' into legacy/v3-support 2026-05-10 14:04:25 +02:00
7497a8c05d refactor: create util module with shared mk_static
- use crate::util::mk_static in network module
- use crate::util::mk_static in mqtt module
- use crate::util::mk_static in hal module
- remove dead mk_static macro from esp module
2026-05-10 14:01:57 +02:00
9 changed files with 133 additions and 93 deletions

View File

@@ -27,20 +27,22 @@ pub trait BatteryInteraction {
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
pub struct BatteryInfo { pub struct BatteryInfo {
pub voltage_milli_volt: u16, pub voltage_mv: Option<u16>,
pub average_current_milli_ampere: i16, pub avg_current_ma: Option<i16>,
pub cycle_count: u16, pub soc_pct: Option<f32>,
pub design_milli_ampere_hour: u16, pub soh_pct: Option<u16>,
pub remaining_milli_ampere_hour: u16, pub temperature_c: Option<u16>,
pub state_of_charge: f32, pub cycle_count: Option<u16>,
pub state_of_health: u16, pub remaining_mah: Option<u16>,
pub temperature: u16, pub design_mah: Option<u16>,
pub error: Option<BatteryError>,
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
#[serde(tag = "kind")]
pub enum BatteryError { pub enum BatteryError {
NoBatteryMonitor, NoBatteryMonitor,
CommunicationError(String), CommunicationError { message: String },
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
@@ -180,14 +182,15 @@ impl BatteryInteraction for BQ34Z100G1 {
async fn get_battery_state(&mut self) -> FatResult<BatteryState> { async fn get_battery_state(&mut self) -> FatResult<BatteryState> {
Ok(BatteryState::Info(BatteryInfo { Ok(BatteryState::Info(BatteryInfo {
voltage_milli_volt: self.voltage_milli_volt().await?, voltage_mv: Some(self.voltage_milli_volt().await?),
average_current_milli_ampere: self.average_current_milli_ampere().await?, avg_current_ma: Some(self.average_current_milli_ampere().await?),
cycle_count: self.cycle_count().await?, soc_pct: Some(self.state_charge_percent().await?),
design_milli_ampere_hour: self.design_milli_ampere_hour().await?, soh_pct: Some(self.state_health_percent().await?),
remaining_milli_ampere_hour: self.remaining_milli_ampere_hour().await?, temperature_c: Some(self.bat_temperature().await?),
state_of_charge: self.state_charge_percent().await?, cycle_count: Some(self.cycle_count().await?),
state_of_health: self.state_health_percent().await?, remaining_mah: Some(self.remaining_milli_ampere_hour().await?),
temperature: self.bat_temperature().await?, design_mah: Some(self.design_milli_ampere_hour().await?),
error: None,
})) }))
} }
} }

View File

@@ -120,15 +120,6 @@ pub struct Esp<'a> {
// CPU cores/threads, reconsider this. // CPU cores/threads, reconsider this.
unsafe impl Send for Esp<'_> {} unsafe impl Send for Esp<'_> {}
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
impl Esp<'_> { impl Esp<'_> {
pub fn get_time(&self) -> DateTime<Utc> { pub fn get_time(&self) -> DateTime<Utc> {
DateTime::from_timestamp_micros(self.rtc.current_time_us() as i64) DateTime::from_timestamp_micros(self.rtc.current_time_us() as i64)

View File

@@ -282,14 +282,7 @@ pub struct FreePeripherals<'a> {
pub adc1: ADC1<'a>, pub adc1: ADC1<'a>,
} }
macro_rules! mk_static { use crate::util::mk_static;
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
impl PlantHal { impl PlantHal {
pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> { pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {

View File

@@ -43,7 +43,7 @@ use embassy_time::{Duration, Instant, Timer};
use esp_hal::rom::ets_delay_us; use esp_hal::rom::ets_delay_us;
use esp_hal::system::software_reset; use esp_hal::system::software_reset;
use esp_println::{logger, println}; use esp_println::{logger, println};
use hal::battery::BatteryState; use hal::battery::{BatteryError, BatteryInfo, BatteryState};
use log::LogMessage; use log::LogMessage;
use option_lock::OptionLock; use option_lock::OptionLock;
use plant_state::PlantState; use plant_state::PlantState;
@@ -71,6 +71,7 @@ mod mqtt;
mod network; mod network;
mod plant_state; mod plant_state;
mod tank; mod tank;
mod util;
mod webserver; mod webserver;
extern crate alloc; extern crate alloc;
@@ -309,7 +310,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
if let Some(err) = tank_state.got_error(&board.board_hal.get_config().tank) { if let Some(err) = tank_state.got_error(&board.board_hal.get_config().tank) {
match err { match err {
TankError::SensorDisabled => { /* unreachable */ } TankError::SensorDisabled => { /* unreachable */ }
TankError::SensorMissing(raw_value_mv) => log( TankError::SensorMissing { raw_mv: raw_value_mv } => log(
LogMessage::TankSensorMissing, LogMessage::TankSensorMissing,
raw_value_mv as u32, raw_value_mv as u32,
0, 0,
@@ -323,8 +324,8 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
&format!("{value}"), &format!("{value}"),
"", "",
), ),
TankError::BoardError(err) => { TankError::BoardError { message: err } => {
log(LogMessage::TankSensorBoardError, 0, 0, "", &err.to_string()) log(LogMessage::TankSensorBoardError, 0, 0, "", &err)
} }
} }
// disabled cannot trigger this because of wrapping if is_enabled // disabled cannot trigger this because of wrapping if is_enabled
@@ -734,7 +735,7 @@ async fn publish_firmware_info(
timezone_time: &str, timezone_time: &str,
) { ) {
mqtt::publish("/firmware/address", ip_address).await; mqtt::publish("/firmware/address", ip_address).await;
mqtt::publish("/firmware/state", format!("{:?}", &version).as_str()) mqtt::publish("/firmware/state", &serde_json::to_string(&version).unwrap())
.await; .await;
mqtt::publish("/firmware/last_online", timezone_time) mqtt::publish("/firmware/last_online", timezone_time)
.await; .await;
@@ -786,20 +787,40 @@ async fn publish_mppt_state(
async fn publish_battery_state( async fn publish_battery_state(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>, board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
) -> () { ) -> () {
let state = board let telemetry = match board
.board_hal .board_hal
.get_battery_monitor() .get_battery_monitor()
.get_battery_state() .get_battery_state()
.await; .await
let value = match state {
Ok(state) => {
let json = serde_json::to_string(&state).unwrap().to_owned();
json.to_owned()
}
Err(_) => "error".to_owned(),
};
{ {
let _ = mqtt::publish("/battery", &*value).await; Ok(BatteryState::Info(info)) => info,
Ok(BatteryState::Unknown) => BatteryInfo {
voltage_mv: None,
avg_current_ma: None,
soc_pct: None,
soh_pct: None,
temperature_c: None,
cycle_count: None,
remaining_mah: None,
design_mah: None,
error: Some(BatteryError::NoBatteryMonitor),
},
Err(e) => BatteryInfo {
voltage_mv: None,
avg_current_ma: None,
soc_pct: None,
soh_pct: None,
temperature_c: None,
cycle_count: None,
remaining_mah: None,
design_mah: None,
error: Some(BatteryError::CommunicationError {
message: alloc::format!("{:?}", e),
}),
},
};
if let Ok(json) = serde_json::to_string(&telemetry) {
let _ = mqtt::publish("/battery", &json).await;
} }
} }

View File

@@ -110,14 +110,7 @@ async fn publish_inner(subtopic: &str, message: &str) -> FatResult<()> {
} }
} }
macro_rules! mk_static { use crate::util::mk_static;
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
pub async fn mqtt_init( pub async fn mqtt_init(
network_config: &'static NetworkConfig, network_config: &'static NetworkConfig,

View File

@@ -3,6 +3,7 @@ use crate::config::NetworkConfig;
use crate::fat_error::{ContextExt, FatError, FatResult}; use crate::fat_error::{ContextExt, FatError, FatResult};
use crate::hal::{PlantHal, HAL}; use crate::hal::{PlantHal, HAL};
use crate::mqtt; use crate::mqtt;
use crate::util::mk_static;
use alloc::string::{String, ToString}; use alloc::string::{String, ToString};
use alloc::sync::Arc; use alloc::sync::Arc;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
@@ -196,15 +197,6 @@ pub(crate) async fn run_dhcp(stack: Stack<'static>, ip: Ipv4Addr) {
} }
} }
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
pub async fn wifi_ap( pub async fn wifi_ap(
ssid: String, ssid: String,
interface_ap: Interface<'static>, interface_ap: Interface<'static>,

View File

@@ -11,11 +11,12 @@ use serde::{Deserialize, Serialize};
const MOIST_SENSOR_MAX_FREQUENCY: f32 = 7500.; // 60kHz (500Hz margin) const MOIST_SENSOR_MAX_FREQUENCY: f32 = 7500.; // 60kHz (500Hz margin)
const MOIST_SENSOR_MIN_FREQUENCY: f32 = 150.; // this is really, really dry, think like cactus levels const MOIST_SENSOR_MIN_FREQUENCY: f32 = 150.; // this is really, really dry, think like cactus levels
#[derive(Debug, PartialEq, Serialize)] #[derive(Debug, PartialEq, Clone, Serialize)]
#[serde(tag = "kind")]
pub enum MoistureSensorError { pub enum MoistureSensorError {
ShortCircuit { hz: f32, max: f32 }, ShortCircuit { hz: f32, max: f32 },
OpenLoop { hz: f32, min: f32 }, OpenLoop { hz: f32, min: f32 },
BoardError(String), BoardError { message: String },
} }
#[derive(Debug, PartialEq, Serialize)] #[derive(Debug, PartialEq, Serialize)]
@@ -49,6 +50,14 @@ impl MoistureSensorState {
impl MoistureSensorState {} impl MoistureSensorState {}
#[derive(Debug, PartialEq, Serialize)] #[derive(Debug, PartialEq, Serialize)]
pub struct SensorTelemetry {
pub moisture_pct: Option<f32>,
pub raw_hz: Option<f32>,
pub error: Option<MoistureSensorError>,
}
#[derive(Debug, PartialEq, Serialize)]
#[serde(tag = "kind")]
pub enum PumpError { pub enum PumpError {
PumpNotWorking { PumpNotWorking {
failed_attempts: usize, failed_attempts: usize,
@@ -134,9 +143,9 @@ impl PlantState {
}, },
Err(err) => MoistureSensorState::SensorError(err), Err(err) => MoistureSensorState::SensorError(err),
}, },
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError( Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError {
err.to_string(), message: err.to_string(),
)), })
} }
} else { } else {
MoistureSensorState::Disabled MoistureSensorState::Disabled
@@ -159,9 +168,9 @@ impl PlantState {
}, },
Err(err) => MoistureSensorState::SensorError(err), Err(err) => MoistureSensorState::SensorError(err),
}, },
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError( Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError {
err.to_string(), message: err.to_string(),
)), })
} }
} else { } else {
MoistureSensorState::Disabled MoistureSensorState::Disabled
@@ -277,13 +286,15 @@ impl PlantState {
&self, &self,
plant_conf: &PlantConfig, plant_conf: &PlantConfig,
current_time: &DateTime<Tz>, current_time: &DateTime<Tz>,
) -> PlantInfo<'_> { ) -> PlantInfo {
let (moisture_pct, _) = self.plant_moisture();
PlantInfo { PlantInfo {
sensor_a: &self.sensor_a, moisture_pct,
sensor_b: &self.sensor_b, sensor_a: Self::sensor_to_telemetry(&self.sensor_a),
sensor_b: Self::sensor_to_telemetry(&self.sensor_b),
mode: plant_conf.mode, mode: plant_conf.mode,
do_water: self.needs_to_be_watered(plant_conf, current_time), do_water: self.needs_to_be_watered(plant_conf, current_time),
dry: if let Some(moisture_percent) = self.plant_moisture().0 { dry: if let Some(moisture_percent) = moisture_pct {
moisture_percent < plant_conf.target_moisture moisture_percent < plant_conf.target_moisture
} else { } else {
false false
@@ -316,15 +327,40 @@ impl PlantState {
}, },
} }
} }
fn sensor_to_telemetry(sensor: &MoistureSensorState) -> SensorTelemetry {
match sensor {
MoistureSensorState::Disabled => SensorTelemetry {
moisture_pct: None,
raw_hz: None,
error: None,
},
MoistureSensorState::MoistureValue {
raw_hz,
moisture_percent,
} => SensorTelemetry {
moisture_pct: Some(*moisture_percent),
raw_hz: Some(*raw_hz),
error: None,
},
MoistureSensorState::SensorError(err) => SensorTelemetry {
moisture_pct: None,
raw_hz: None,
error: Some(err.clone()),
},
}
}
} }
#[derive(Debug, PartialEq, Serialize)] #[derive(Debug, PartialEq, Serialize)]
/// State of a single plant to be tracked /// State of a single plant to be tracked
pub struct PlantInfo<'a> { pub struct PlantInfo {
/// combined plant moisture from available sensors
moisture_pct: Option<f32>,
/// state of humidity sensor on bank a /// state of humidity sensor on bank a
sensor_a: &'a MoistureSensorState, sensor_a: SensorTelemetry,
/// state of humidity sensor on bank b /// state of humidity sensor on bank b
sensor_b: &'a MoistureSensorState, sensor_b: SensorTelemetry,
/// configured plant watering mode /// configured plant watering mode
mode: PlantWateringMode, mode: PlantWateringMode,
/// the plant needs to be watered /// the plant needs to be watered

View File

@@ -10,11 +10,12 @@ const OPEN_TANK_VOLTAGE: f32 = 3.0;
pub const WATER_FROZEN_THRESH: f32 = 4.0; pub const WATER_FROZEN_THRESH: f32 = 4.0;
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind")]
pub enum TankError { pub enum TankError {
SensorDisabled, SensorDisabled,
SensorMissing(f32), SensorMissing { raw_mv: f32 },
SensorValueError { value: f32, min: f32, max: f32 }, SensorValueError { value: f32, min: f32, max: f32 },
BoardError(String), BoardError { message: String },
} }
pub enum TankState { pub enum TankState {
@@ -25,7 +26,7 @@ pub enum TankState {
fn raw_voltage_to_divider_percent(raw_value_mv: f32) -> Result<f32, TankError> { fn raw_voltage_to_divider_percent(raw_value_mv: f32) -> Result<f32, TankError> {
if raw_value_mv > OPEN_TANK_VOLTAGE { if raw_value_mv > OPEN_TANK_VOLTAGE {
return Err(TankError::SensorMissing(raw_value_mv)); return Err(TankError::SensorMissing { raw_mv: raw_value_mv });
} }
let r2 = raw_value_mv * 50.0 / (3.3 - raw_value_mv); let r2 = raw_value_mv * 50.0 / (3.3 - raw_value_mv);
@@ -141,15 +142,15 @@ impl TankState {
TankInfo { TankInfo {
enough_water, enough_water,
warn_level, warn_level,
left_ml, volume_ml: left_ml,
sensor_error: tank_err, sensor_error: tank_err,
raw, fill_raw_v: raw,
water_frozen: water_temp water_frozen: water_temp
.as_ref() .as_ref()
.is_ok_and(|temp| *temp < WATER_FROZEN_THRESH), .is_ok_and(|temp| *temp < WATER_FROZEN_THRESH),
water_temp: water_temp.as_ref().copied().ok(), water_temp_c: water_temp.as_ref().copied().ok(),
temp_sensor_error: water_temp.as_ref().err().map(|err| err.to_string()), temp_sensor_error: water_temp.as_ref().err().map(|err| err.to_string()),
percent, fill_pct: percent,
} }
} }
} }
@@ -164,7 +165,7 @@ pub async fn determine_tank_state(
.and_then(|f| core::prelude::v1::Ok(f.tank_sensor_voltage())) .and_then(|f| core::prelude::v1::Ok(f.tank_sensor_voltage()))
{ {
Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv.await.unwrap()), Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv.await.unwrap()),
Err(err) => TankState::Error(TankError::BoardError(err.to_string())), Err(err) => TankState::Error(TankError::BoardError { message: err.to_string() }),
} }
} else { } else {
TankState::Disabled TankState::Disabled
@@ -179,16 +180,16 @@ pub struct TankInfo {
/// warning that water needs to be refilled soon /// warning that water needs to be refilled soon
pub(crate) warn_level: bool, pub(crate) warn_level: bool,
/// estimation how many ml are still in the tank /// estimation how many ml are still in the tank
pub(crate) left_ml: Option<f32>, pub(crate) volume_ml: Option<f32>,
/// if there is an issue with the water level sensor /// if there is an issue with the water level sensor
pub(crate) sensor_error: Option<TankError>, pub(crate) sensor_error: Option<TankError>,
/// raw water sensor value /// raw water sensor value
pub(crate) raw: Option<f32>, pub(crate) fill_raw_v: Option<f32>,
/// percent value /// percent value
pub(crate) percent: Option<f32>, pub(crate) fill_pct: Option<f32>,
/// water in the tank might be frozen /// water in the tank might be frozen
pub(crate) water_frozen: bool, pub(crate) water_frozen: bool,
/// water temperature /// water temperature
pub(crate) water_temp: Option<f32>, pub(crate) water_temp_c: Option<f32>,
pub(crate) temp_sensor_error: Option<String>, pub(crate) temp_sensor_error: Option<String>,
} }

10
rust/src/util.rs Normal file
View File

@@ -0,0 +1,10 @@
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
pub(crate) use mk_static;