Compare commits
6 Commits
a8893974a5
...
feature/mq
| Author | SHA1 | Date | |
|---|---|---|---|
| bd257b89f0 | |||
| 4debbfb39e | |||
| d83189417a | |||
| 3c92cf0c26 | |||
|
96023c8dc3
|
|||
|
7497a8c05d
|
@@ -27,22 +27,20 @@ pub trait BatteryInteraction {
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct BatteryInfo {
|
||||
pub voltage_mv: Option<u16>,
|
||||
pub avg_current_ma: Option<i16>,
|
||||
pub soc_pct: Option<f32>,
|
||||
pub soh_pct: Option<u16>,
|
||||
pub temperature_c: Option<u16>,
|
||||
pub cycle_count: Option<u16>,
|
||||
pub remaining_mah: Option<u16>,
|
||||
pub design_mah: Option<u16>,
|
||||
pub error: Option<BatteryError>,
|
||||
pub voltage_milli_volt: u16,
|
||||
pub average_current_milli_ampere: i16,
|
||||
pub cycle_count: u16,
|
||||
pub design_milli_ampere_hour: u16,
|
||||
pub remaining_milli_ampere_hour: u16,
|
||||
pub state_of_charge: f32,
|
||||
pub state_of_health: u16,
|
||||
pub temperature: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind")]
|
||||
pub enum BatteryError {
|
||||
NoBatteryMonitor,
|
||||
CommunicationError { message: String },
|
||||
CommunicationError(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -182,15 +180,14 @@ impl BatteryInteraction for BQ34Z100G1 {
|
||||
|
||||
async fn get_battery_state(&mut self) -> FatResult<BatteryState> {
|
||||
Ok(BatteryState::Info(BatteryInfo {
|
||||
voltage_mv: Some(self.voltage_milli_volt().await?),
|
||||
avg_current_ma: Some(self.average_current_milli_ampere().await?),
|
||||
soc_pct: Some(self.state_charge_percent().await?),
|
||||
soh_pct: Some(self.state_health_percent().await?),
|
||||
temperature_c: Some(self.bat_temperature().await?),
|
||||
cycle_count: Some(self.cycle_count().await?),
|
||||
remaining_mah: Some(self.remaining_milli_ampere_hour().await?),
|
||||
design_mah: Some(self.design_milli_ampere_hour().await?),
|
||||
error: None,
|
||||
voltage_milli_volt: self.voltage_milli_volt().await?,
|
||||
average_current_milli_ampere: self.average_current_milli_ampere().await?,
|
||||
cycle_count: self.cycle_count().await?,
|
||||
design_milli_ampere_hour: self.design_milli_ampere_hour().await?,
|
||||
remaining_milli_ampere_hour: self.remaining_milli_ampere_hour().await?,
|
||||
state_of_charge: self.state_charge_percent().await?,
|
||||
state_of_health: self.state_health_percent().await?,
|
||||
temperature: self.bat_temperature().await?,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,15 +120,6 @@ pub struct Esp<'a> {
|
||||
// CPU cores/threads, reconsider this.
|
||||
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<'_> {
|
||||
pub fn get_time(&self) -> DateTime<Utc> {
|
||||
DateTime::from_timestamp_micros(self.rtc.current_time_us() as i64)
|
||||
|
||||
@@ -282,14 +282,7 @@ pub struct FreePeripherals<'a> {
|
||||
pub adc1: ADC1<'a>,
|
||||
}
|
||||
|
||||
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
|
||||
}};
|
||||
}
|
||||
use crate::util::mk_static;
|
||||
|
||||
impl PlantHal {
|
||||
pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {
|
||||
|
||||
@@ -43,7 +43,7 @@ use embassy_time::{Duration, Instant, Timer};
|
||||
use esp_hal::rom::ets_delay_us;
|
||||
use esp_hal::system::software_reset;
|
||||
use esp_println::{logger, println};
|
||||
use hal::battery::{BatteryError, BatteryInfo, BatteryState};
|
||||
use hal::battery::BatteryState;
|
||||
use log::LogMessage;
|
||||
use option_lock::OptionLock;
|
||||
use plant_state::PlantState;
|
||||
@@ -71,6 +71,7 @@ mod mqtt;
|
||||
mod network;
|
||||
mod plant_state;
|
||||
mod tank;
|
||||
mod util;
|
||||
mod webserver;
|
||||
|
||||
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_battery_state(&mut board).await;
|
||||
let _ = publish_mppt_state(&mut board).await;
|
||||
publish_config(&mut board).await;
|
||||
}
|
||||
|
||||
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) {
|
||||
match err {
|
||||
TankError::SensorDisabled => { /* unreachable */ }
|
||||
TankError::SensorMissing { raw_mv: raw_value_mv } => log(
|
||||
TankError::SensorMissing(raw_value_mv) => log(
|
||||
LogMessage::TankSensorMissing,
|
||||
raw_value_mv as u32,
|
||||
0,
|
||||
@@ -323,8 +325,8 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
&format!("{value}"),
|
||||
"",
|
||||
),
|
||||
TankError::BoardError { message: err } => {
|
||||
log(LogMessage::TankSensorBoardError, 0, 0, "", &err)
|
||||
TankError::BoardError(err) => {
|
||||
log(LogMessage::TankSensorBoardError, 0, 0, "", &err.to_string())
|
||||
}
|
||||
}
|
||||
// disabled cannot trigger this because of wrapping if is_enabled
|
||||
@@ -734,7 +736,7 @@ async fn publish_firmware_info(
|
||||
timezone_time: &str,
|
||||
) {
|
||||
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;
|
||||
mqtt::publish("/firmware/last_online", timezone_time)
|
||||
.await;
|
||||
@@ -786,43 +788,38 @@ async fn publish_mppt_state(
|
||||
async fn publish_battery_state(
|
||||
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
|
||||
) -> () {
|
||||
let telemetry = match board
|
||||
let state = board
|
||||
.board_hal
|
||||
.get_battery_monitor()
|
||||
.get_battery_state()
|
||||
.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),
|
||||
}),
|
||||
},
|
||||
.await;
|
||||
let value = match state {
|
||||
Ok(state) => {
|
||||
let json = serde_json::to_string(&state).unwrap().to_owned();
|
||||
json.to_owned()
|
||||
}
|
||||
Err(_) => "error".to_owned(),
|
||||
};
|
||||
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(
|
||||
board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
|
||||
wait_type: WaitType,
|
||||
|
||||
@@ -4,10 +4,12 @@ use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||
use crate::hal::PlantHal;
|
||||
use crate::log::{log, LogMessage};
|
||||
use alloc::string::String;
|
||||
use alloc::{format, string::ToString};
|
||||
use alloc::{format, string::ToString, vec::Vec};
|
||||
use core::sync::atomic::Ordering;
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_net::Stack;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::mutex::Mutex;
|
||||
use embassy_sync::once_lock::OnceLock;
|
||||
use embassy_time::{Duration, Timer, WithTimeout};
|
||||
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);
|
||||
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
|
||||
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 {
|
||||
MQTT_STAY_ALIVE.load(Ordering::Relaxed)
|
||||
@@ -110,14 +113,7 @@ async fn publish_inner(subtopic: &str, message: &str) -> FatResult<()> {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}};
|
||||
}
|
||||
use crate::util::mk_static;
|
||||
|
||||
pub async fn mqtt_init(
|
||||
network_config: &'static NetworkConfig,
|
||||
@@ -148,6 +144,8 @@ pub async fn mqtt_init(
|
||||
let last_will_topic = format!("{base_topic}/state");
|
||||
let round_trip_topic = format!("{base_topic}/internal/roundtrip");
|
||||
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> =
|
||||
McutieBuilder::new(stack, "plant ctrl", mqtt_url);
|
||||
@@ -166,10 +164,12 @@ pub async fn mqtt_init(
|
||||
//TODO make configurable
|
||||
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([
|
||||
Topic::General(round_trip_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;
|
||||
@@ -179,6 +179,8 @@ pub async fn mqtt_init(
|
||||
receiver,
|
||||
round_trip_topic.clone(),
|
||||
stay_alive_topic.clone(),
|
||||
config_update_payload_topic.clone(),
|
||||
config_update_topic.clone(),
|
||||
)?);
|
||||
spawner.spawn(mqtt_runner(task)?);
|
||||
|
||||
@@ -225,7 +227,7 @@ pub async fn mqtt_init(
|
||||
|
||||
#[embassy_executor::task]
|
||||
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;
|
||||
}
|
||||
@@ -235,6 +237,8 @@ async fn mqtt_incoming_task(
|
||||
receiver: McutieReceiver,
|
||||
round_trip_topic: String,
|
||||
stay_alive_topic: String,
|
||||
config_update_payload_topic: String,
|
||||
config_update_topic: String,
|
||||
) {
|
||||
loop {
|
||||
let message = receiver.receive().await;
|
||||
@@ -260,6 +264,43 @@ async fn mqtt_incoming_task(
|
||||
};
|
||||
log(LogMessage::MqttStayAliveRec, a, 0, "", "");
|
||||
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 {
|
||||
log(LogMessage::UnknownTopic, 0, 0, "", &topic);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::config::NetworkConfig;
|
||||
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||
use crate::hal::{PlantHal, HAL};
|
||||
use crate::mqtt;
|
||||
use crate::util::mk_static;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::sync::Arc;
|
||||
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(
|
||||
ssid: String,
|
||||
interface_ap: Interface<'static>,
|
||||
|
||||
@@ -11,12 +11,11 @@ use serde::{Deserialize, Serialize};
|
||||
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
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Serialize)]
|
||||
#[serde(tag = "kind")]
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
pub enum MoistureSensorError {
|
||||
ShortCircuit { hz: f32, max: f32 },
|
||||
OpenLoop { hz: f32, min: f32 },
|
||||
BoardError { message: String },
|
||||
BoardError(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
@@ -50,14 +49,6 @@ impl MoistureSensorState {
|
||||
impl MoistureSensorState {}
|
||||
|
||||
#[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 {
|
||||
PumpNotWorking {
|
||||
failed_attempts: usize,
|
||||
@@ -143,9 +134,9 @@ impl PlantState {
|
||||
},
|
||||
Err(err) => MoistureSensorState::SensorError(err),
|
||||
},
|
||||
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError {
|
||||
message: err.to_string(),
|
||||
})
|
||||
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError(
|
||||
err.to_string(),
|
||||
)),
|
||||
}
|
||||
} else {
|
||||
MoistureSensorState::Disabled
|
||||
@@ -168,9 +159,9 @@ impl PlantState {
|
||||
},
|
||||
Err(err) => MoistureSensorState::SensorError(err),
|
||||
},
|
||||
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError {
|
||||
message: err.to_string(),
|
||||
})
|
||||
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError(
|
||||
err.to_string(),
|
||||
)),
|
||||
}
|
||||
} else {
|
||||
MoistureSensorState::Disabled
|
||||
@@ -286,15 +277,13 @@ impl PlantState {
|
||||
&self,
|
||||
plant_conf: &PlantConfig,
|
||||
current_time: &DateTime<Tz>,
|
||||
) -> PlantInfo {
|
||||
let (moisture_pct, _) = self.plant_moisture();
|
||||
) -> PlantInfo<'_> {
|
||||
PlantInfo {
|
||||
moisture_pct,
|
||||
sensor_a: Self::sensor_to_telemetry(&self.sensor_a),
|
||||
sensor_b: Self::sensor_to_telemetry(&self.sensor_b),
|
||||
sensor_a: &self.sensor_a,
|
||||
sensor_b: &self.sensor_b,
|
||||
mode: plant_conf.mode,
|
||||
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
|
||||
} else {
|
||||
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)]
|
||||
/// State of a single plant to be tracked
|
||||
pub struct PlantInfo {
|
||||
/// combined plant moisture from available sensors
|
||||
moisture_pct: Option<f32>,
|
||||
pub struct PlantInfo<'a> {
|
||||
/// state of humidity sensor on bank a
|
||||
sensor_a: SensorTelemetry,
|
||||
sensor_a: &'a MoistureSensorState,
|
||||
/// state of humidity sensor on bank b
|
||||
sensor_b: SensorTelemetry,
|
||||
sensor_b: &'a MoistureSensorState,
|
||||
/// configured plant watering mode
|
||||
mode: PlantWateringMode,
|
||||
/// the plant needs to be watered
|
||||
|
||||
@@ -10,12 +10,11 @@ const OPEN_TANK_VOLTAGE: f32 = 3.0;
|
||||
pub const WATER_FROZEN_THRESH: f32 = 4.0;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(tag = "kind")]
|
||||
pub enum TankError {
|
||||
SensorDisabled,
|
||||
SensorMissing { raw_mv: f32 },
|
||||
SensorMissing(f32),
|
||||
SensorValueError { value: f32, min: f32, max: f32 },
|
||||
BoardError { message: String },
|
||||
BoardError(String),
|
||||
}
|
||||
|
||||
pub enum TankState {
|
||||
@@ -26,7 +25,7 @@ pub enum TankState {
|
||||
|
||||
fn raw_voltage_to_divider_percent(raw_value_mv: f32) -> Result<f32, TankError> {
|
||||
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);
|
||||
@@ -142,15 +141,15 @@ impl TankState {
|
||||
TankInfo {
|
||||
enough_water,
|
||||
warn_level,
|
||||
volume_ml: left_ml,
|
||||
left_ml,
|
||||
sensor_error: tank_err,
|
||||
fill_raw_v: raw,
|
||||
raw,
|
||||
water_frozen: water_temp
|
||||
.as_ref()
|
||||
.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()),
|
||||
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()))
|
||||
{
|
||||
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 {
|
||||
TankState::Disabled
|
||||
@@ -180,16 +179,16 @@ pub struct TankInfo {
|
||||
/// warning that water needs to be refilled soon
|
||||
pub(crate) warn_level: bool,
|
||||
/// 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
|
||||
pub(crate) sensor_error: Option<TankError>,
|
||||
/// raw water sensor value
|
||||
pub(crate) fill_raw_v: Option<f32>,
|
||||
pub(crate) raw: Option<f32>,
|
||||
/// percent value
|
||||
pub(crate) fill_pct: Option<f32>,
|
||||
pub(crate) percent: Option<f32>,
|
||||
/// water in the tank might be frozen
|
||||
pub(crate) water_frozen: bool,
|
||||
/// water temperature
|
||||
pub(crate) water_temp_c: Option<f32>,
|
||||
pub(crate) water_temp: Option<f32>,
|
||||
pub(crate) temp_sensor_error: Option<String>,
|
||||
}
|
||||
|
||||
10
rust/src/util.rs
Normal file
10
rust/src/util.rs
Normal 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;
|
||||
Reference in New Issue
Block a user