4 Commits

Author SHA1 Message Date
judge a8893974a5 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 13:39:18 +02:00
judge 1b2ace0612 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 13:39:16 +02:00
judge 9015a6376d refactor: BatteryInfo structure (consistent layout)
- use tagged enum serialization for BatteryError
- flatten BatteryInfo telemetry with consistent field names and typed error
2026-05-10 13:39:15 +02:00
judge 4893cbce55 fix: serialize firmware/state as JSON instead of Debug format 2026-05-10 13:39:11 +02:00
9 changed files with 156 additions and 140 deletions
+20 -17
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,
})) }))
} }
} }
+9
View File
@@ -120,6 +120,15 @@ 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)
+8 -1
View File
@@ -282,7 +282,14 @@ pub struct FreePeripherals<'a> {
pub adc1: ADC1<'a>, pub adc1: ADC1<'a>,
} }
use crate::util::mk_static; 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 PlantHal { impl PlantHal {
pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> { pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {
+35 -32
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,7 +71,6 @@ 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;
@@ -268,7 +267,6 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
publish_firmware_info(&mut board, version, ip_address, &timezone_time.to_rfc3339()).await; publish_firmware_info(&mut board, version, ip_address, &timezone_time.to_rfc3339()).await;
publish_battery_state(&mut board).await; publish_battery_state(&mut board).await;
let _ = publish_mppt_state(&mut board).await; let _ = publish_mppt_state(&mut board).await;
publish_config(&mut board).await;
} }
log( log(
@@ -311,7 +309,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,
@@ -325,8 +323,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
@@ -736,7 +734,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;
@@ -788,38 +786,43 @@ 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;
} }
} }
async fn publish_config(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'_>>,
) {
let config = board.board_hal.get_config();
match serde_json::to_string(&config) {
Ok(serialized) => {
let _ = mqtt::publish("/config", &serialized).await;
}
Err(err) => {
info!("Error serializing config: {}", err);
}
}
}
async fn wait_infinity( async fn wait_infinity(
board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>, board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
wait_type: WaitType, wait_type: WaitType,
+11 -52
View File
@@ -4,12 +4,10 @@ use crate::fat_error::{ContextExt, FatError, FatResult};
use crate::hal::PlantHal; use crate::hal::PlantHal;
use crate::log::{log, LogMessage}; use crate::log::{log, LogMessage};
use alloc::string::String; use alloc::string::String;
use alloc::{format, string::ToString, vec::Vec}; use alloc::{format, string::ToString};
use core::sync::atomic::Ordering; use core::sync::atomic::Ordering;
use embassy_executor::Spawner; use embassy_executor::Spawner;
use embassy_net::Stack; use embassy_net::Stack;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::Mutex;
use embassy_sync::once_lock::OnceLock; use embassy_sync::once_lock::OnceLock;
use embassy_time::{Duration, Timer, WithTimeout}; use embassy_time::{Duration, Timer, WithTimeout};
use log::info; use log::info;
@@ -39,7 +37,6 @@ static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false);
static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false); static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false);
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false); pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new(); static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new();
static MQTT_CONFIG_UPDATE_PAYLOAD: Mutex<CriticalSectionRawMutex, Option<String>> = Mutex::new(None);
pub fn is_stay_alive() -> bool { pub fn is_stay_alive() -> bool {
MQTT_STAY_ALIVE.load(Ordering::Relaxed) MQTT_STAY_ALIVE.load(Ordering::Relaxed)
@@ -113,7 +110,14 @@ async fn publish_inner(subtopic: &str, message: &str) -> FatResult<()> {
} }
} }
use crate::util::mk_static; 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 mqtt_init( pub async fn mqtt_init(
network_config: &'static NetworkConfig, network_config: &'static NetworkConfig,
@@ -144,8 +148,6 @@ pub async fn mqtt_init(
let last_will_topic = format!("{base_topic}/state"); let last_will_topic = format!("{base_topic}/state");
let round_trip_topic = format!("{base_topic}/internal/roundtrip"); let round_trip_topic = format!("{base_topic}/internal/roundtrip");
let stay_alive_topic = format!("{base_topic}/stay_alive"); let stay_alive_topic = format!("{base_topic}/stay_alive");
let config_update_payload_topic = format!("{base_topic}/config/update_payload");
let config_update_topic = format!("{base_topic}/config/update");
let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> = let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> =
McutieBuilder::new(stack, "plant ctrl", mqtt_url); McutieBuilder::new(stack, "plant ctrl", mqtt_url);
@@ -164,12 +166,10 @@ pub async fn mqtt_init(
//TODO make configurable //TODO make configurable
builder = builder.with_device_id("plantctrl"); builder = builder.with_device_id("plantctrl");
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 4> = builder let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 2> = builder
.with_subscriptions([ .with_subscriptions([
Topic::General(round_trip_topic.clone()), Topic::General(round_trip_topic.clone()),
Topic::General(stay_alive_topic.clone()), Topic::General(stay_alive_topic.clone()),
Topic::General(config_update_payload_topic.clone()),
Topic::General(config_update_topic.clone()),
]); ]);
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16; let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
@@ -179,8 +179,6 @@ pub async fn mqtt_init(
receiver, receiver,
round_trip_topic.clone(), round_trip_topic.clone(),
stay_alive_topic.clone(), stay_alive_topic.clone(),
config_update_payload_topic.clone(),
config_update_topic.clone(),
)?); )?);
spawner.spawn(mqtt_runner(task)?); spawner.spawn(mqtt_runner(task)?);
@@ -227,7 +225,7 @@ pub async fn mqtt_init(
#[embassy_executor::task] #[embassy_executor::task]
async fn mqtt_runner( async fn mqtt_runner(
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 4>, task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 2>,
) { ) {
task.run().await; task.run().await;
} }
@@ -237,8 +235,6 @@ async fn mqtt_incoming_task(
receiver: McutieReceiver, receiver: McutieReceiver,
round_trip_topic: String, round_trip_topic: String,
stay_alive_topic: String, stay_alive_topic: String,
config_update_payload_topic: String,
config_update_topic: String,
) { ) {
loop { loop {
let message = receiver.receive().await; let message = receiver.receive().await;
@@ -264,43 +260,6 @@ async fn mqtt_incoming_task(
}; };
log(LogMessage::MqttStayAliveRec, a, 0, "", ""); log(LogMessage::MqttStayAliveRec, a, 0, "", "");
MQTT_STAY_ALIVE.store(value, Ordering::Relaxed); MQTT_STAY_ALIVE.store(value, Ordering::Relaxed);
} else if subtopic.eq(config_update_payload_topic.as_str()) {
let payload_str = String::from_utf8_lossy(&payload[..]).to_string();
let mut buffer = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
*buffer = Some(payload_str);
info!("MQTT config update payload received");
} else if subtopic.eq(config_update_topic.as_str()) {
let update_requested = payload.eq_ignore_ascii_case("true".as_ref())
|| payload.eq_ignore_ascii_case("1".as_ref());
if update_requested {
info!("MQTT config update requested");
let payload_lock = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
if let Some(payload_str) = payload_lock.as_ref() {
match serde_json::from_str::<crate::config::PlantControllerConfig>(payload_str) {
Ok(config) => {
info!("Deserialized config, applying...");
let board_mutex = crate::BOARD_ACCESS.get().await;
let mut board = board_mutex.lock().await;
if let Err(e) = board.board_hal.get_esp().save_config(payload_str.as_bytes().to_vec()).await {
info!("Error saving config to flash: {}", e);
let _ = publish("/config/update", "false").await;
} else {
board.board_hal.set_config(config);
info!("Config applied, rebooting");
let _ = publish("/config/update", "false").await;
board.board_hal.get_esp().deep_sleep_ms(0);
}
}
Err(e) => {
info!("Error deserializing config: {}", e);
let _ = publish("/config/update", "false").await;
}
}
} else {
info!("No config update payload available");
let _ = publish("/config/update", "false").await;
}
}
} else { } else {
log(LogMessage::UnknownTopic, 0, 0, "", &topic); log(LogMessage::UnknownTopic, 0, 0, "", &topic);
} }
+9 -1
View File
@@ -3,7 +3,6 @@ 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};
@@ -197,6 +196,15 @@ 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>,
+51 -15
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
+13 -12
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
View File
@@ -1,10 +0,0 @@
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;