6 Commits

Author SHA1 Message Date
bd257b89f0 implement async mqtt config update trigger and fix mqtt.rs corruption 2026-05-10 17:55:53 +02:00
4debbfb39e feat: implement config update via MQTT trigger 2026-05-10 17:35:30 +02:00
d83189417a feat: store MQTT config update payload 2026-05-10 17:30:02 +02:00
3c92cf0c26 feat: publish current config to MQTT 2026-05-10 17:25:32 +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 140 additions and 156 deletions

View File

@@ -27,22 +27,20 @@ pub trait BatteryInteraction {
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
pub struct BatteryInfo { pub struct BatteryInfo {
pub voltage_mv: Option<u16>, pub voltage_milli_volt: u16,
pub avg_current_ma: Option<i16>, pub average_current_milli_ampere: i16,
pub soc_pct: Option<f32>, pub cycle_count: u16,
pub soh_pct: Option<u16>, pub design_milli_ampere_hour: u16,
pub temperature_c: Option<u16>, pub remaining_milli_ampere_hour: u16,
pub cycle_count: Option<u16>, pub state_of_charge: f32,
pub remaining_mah: Option<u16>, pub state_of_health: u16,
pub design_mah: Option<u16>, pub temperature: u16,
pub error: Option<BatteryError>,
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
#[serde(tag = "kind")]
pub enum BatteryError { pub enum BatteryError {
NoBatteryMonitor, NoBatteryMonitor,
CommunicationError { message: String }, CommunicationError(String),
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
@@ -182,15 +180,14 @@ 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_mv: Some(self.voltage_milli_volt().await?), voltage_milli_volt: self.voltage_milli_volt().await?,
avg_current_ma: Some(self.average_current_milli_ampere().await?), average_current_milli_ampere: self.average_current_milli_ampere().await?,
soc_pct: Some(self.state_charge_percent().await?), cycle_count: self.cycle_count().await?,
soh_pct: Some(self.state_health_percent().await?), design_milli_ampere_hour: self.design_milli_ampere_hour().await?,
temperature_c: Some(self.bat_temperature().await?), remaining_milli_ampere_hour: self.remaining_milli_ampere_hour().await?,
cycle_count: Some(self.cycle_count().await?), state_of_charge: self.state_charge_percent().await?,
remaining_mah: Some(self.remaining_milli_ampere_hour().await?), state_of_health: self.state_health_percent().await?,
design_mah: Some(self.design_milli_ampere_hour().await?), temperature: self.bat_temperature().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::{BatteryError, BatteryInfo, BatteryState}; use hal::battery::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;
@@ -267,6 +268,7 @@ 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(
@@ -309,7 +311,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_mv: raw_value_mv } => log( TankError::SensorMissing(raw_value_mv) => log(
LogMessage::TankSensorMissing, LogMessage::TankSensorMissing,
raw_value_mv as u32, raw_value_mv as u32,
0, 0,
@@ -323,8 +325,8 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
&format!("{value}"), &format!("{value}"),
"", "",
), ),
TankError::BoardError { message: err } => { TankError::BoardError(err) => {
log(LogMessage::TankSensorBoardError, 0, 0, "", &err) log(LogMessage::TankSensorBoardError, 0, 0, "", &err.to_string())
} }
} }
// disabled cannot trigger this because of wrapping if is_enabled // disabled cannot trigger this because of wrapping if is_enabled
@@ -734,7 +736,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", &serde_json::to_string(&version).unwrap()) mqtt::publish("/firmware/state", format!("{:?}", &version).as_str())
.await; .await;
mqtt::publish("/firmware/last_online", timezone_time) mqtt::publish("/firmware/last_online", timezone_time)
.await; .await;
@@ -786,43 +788,38 @@ 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 telemetry = match board let state = board
.board_hal .board_hal
.get_battery_monitor() .get_battery_monitor()
.get_battery_state() .get_battery_state()
.await .await;
{ let value = match state {
Ok(BatteryState::Info(info)) => info, Ok(state) => {
Ok(BatteryState::Unknown) => BatteryInfo { let json = serde_json::to_string(&state).unwrap().to_owned();
voltage_mv: None, json.to_owned()
avg_current_ma: None, }
soc_pct: None, Err(_) => "error".to_owned(),
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; let _ = mqtt::publish("/battery", &*value).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,

View File

@@ -4,10 +4,12 @@ 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}; use alloc::{format, string::ToString, vec::Vec};
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;
@@ -37,6 +39,7 @@ 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)
@@ -110,14 +113,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,
@@ -148,6 +144,8 @@ 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);
@@ -166,10 +164,12 @@ 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>, 2> = builder let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 4> = 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,6 +179,8 @@ 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)?);
@@ -225,7 +227,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>, 2>, task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 4>,
) { ) {
task.run().await; task.run().await;
} }
@@ -235,6 +237,8 @@ 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;
@@ -260,6 +264,43 @@ 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);
} }

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,12 +11,11 @@ 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, Clone, Serialize)] #[derive(Debug, PartialEq, 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 { message: String }, BoardError(String),
} }
#[derive(Debug, PartialEq, Serialize)] #[derive(Debug, PartialEq, Serialize)]
@@ -50,14 +49,6 @@ 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,
@@ -143,9 +134,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(
message: err.to_string(), err.to_string(),
}) )),
} }
} else { } else {
MoistureSensorState::Disabled MoistureSensorState::Disabled
@@ -168,9 +159,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(
message: err.to_string(), err.to_string(),
}) )),
} }
} else { } else {
MoistureSensorState::Disabled MoistureSensorState::Disabled
@@ -286,15 +277,13 @@ 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 {
moisture_pct, sensor_a: &self.sensor_a,
sensor_a: Self::sensor_to_telemetry(&self.sensor_a), sensor_b: &self.sensor_b,
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) = moisture_pct { dry: if let Some(moisture_percent) = self.plant_moisture().0 {
moisture_percent < plant_conf.target_moisture moisture_percent < plant_conf.target_moisture
} else { } else {
false false
@@ -327,40 +316,15 @@ 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 { pub struct PlantInfo<'a> {
/// 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: SensorTelemetry, sensor_a: &'a MoistureSensorState,
/// state of humidity sensor on bank b /// state of humidity sensor on bank b
sensor_b: SensorTelemetry, sensor_b: &'a MoistureSensorState,
/// 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,12 +10,11 @@ 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 { raw_mv: f32 }, SensorMissing(f32),
SensorValueError { value: f32, min: f32, max: f32 }, SensorValueError { value: f32, min: f32, max: f32 },
BoardError { message: String }, BoardError(String),
} }
pub enum TankState { pub enum TankState {
@@ -26,7 +25,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_mv: raw_value_mv }); return Err(TankError::SensorMissing(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);
@@ -142,15 +141,15 @@ impl TankState {
TankInfo { TankInfo {
enough_water, enough_water,
warn_level, warn_level,
volume_ml: left_ml, left_ml,
sensor_error: tank_err, sensor_error: tank_err,
fill_raw_v: raw, 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_c: water_temp.as_ref().copied().ok(), water_temp: 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()),
fill_pct: percent, percent,
} }
} }
} }
@@ -165,7 +164,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 { message: err.to_string() }), Err(err) => TankState::Error(TankError::BoardError(err.to_string())),
} }
} else { } else {
TankState::Disabled TankState::Disabled
@@ -180,16 +179,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) volume_ml: Option<f32>, pub(crate) left_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) fill_raw_v: Option<f32>, pub(crate) raw: Option<f32>,
/// percent value /// percent value
pub(crate) fill_pct: Option<f32>, pub(crate) percent: 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_c: Option<f32>, pub(crate) water_temp: 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;