chore: cargo fmt

This commit is contained in:
2025-06-20 16:26:03 +02:00
parent 017078ef8e
commit 4b919b9613
10 changed files with 335 additions and 235 deletions

View File

@@ -21,16 +21,16 @@ use std::{
sync::{atomic::AtomicBool, Arc, Mutex},
};
mod config;
mod log;
mod hal;
mod log;
mod plant_state;
mod tank;
use crate::config::BoardVersion::INITIAL;
use crate::hal::battery::BatteryInteraction;
use crate::hal::{BoardInteraction, PlantHal, HAL, PLANT_COUNT};
use plant_state::PlantState;
use tank::*;
use crate::config::BoardVersion::INITIAL;
use crate::hal::{BoardInteraction, PlantHal, HAL, PLANT_COUNT};
use crate::hal::battery::BatteryInteraction;
pub static BOARD_ACCESS: Lazy<Mutex<HAL>> = Lazy::new(|| PlantHal::create().unwrap());
pub static STAY_ALIVE: Lazy<AtomicBool> = Lazy::new(|| AtomicBool::new(false));
@@ -72,7 +72,7 @@ struct LightState {
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
///mqtt stuct to track pump activities
struct PumpInfo{
struct PumpInfo {
enabled: bool,
pump_ineffective: bool,
}
@@ -88,14 +88,16 @@ enum SensorError {
#[derive(Serialize, Debug, PartialEq)]
enum SntpMode {
OFFLINE,
SYNC{
current: DateTime<Utc>
}
SYNC { current: DateTime<Utc> },
}
#[derive(Serialize, Debug, PartialEq)]
enum NetworkMode{
WIFI {sntp: SntpMode, mqtt: bool, ip_address: String},
enum NetworkMode {
WIFI {
sntp: SntpMode,
mqtt: bool,
ip_address: String,
},
OFFLINE,
}
@@ -150,10 +152,13 @@ fn safe_main() -> anyhow::Result<()> {
};
log(LogMessage::PartitionState, 0, 0, "", ota_state_string);
let mut board = BOARD_ACCESS.lock().expect("Could not lock board no other lock should be able to exist during startup!");
let mut board = BOARD_ACCESS
.lock()
.expect("Could not lock board no other lock should be able to exist during startup!");
board.board_hal.general_fault(false);
let cur = board.board_hal
let cur = board
.board_hal
.get_rtc_time()
.or_else(|err| {
println!("rtc module error: {:?}", err);
@@ -172,7 +177,11 @@ fn safe_main() -> anyhow::Result<()> {
}
println!("cur is {}", cur);
match board.board_hal.get_battery_monitor().average_current_milli_ampere() {
match board
.board_hal
.get_battery_monitor()
.average_current_milli_ampere()
{
Ok(charging) => {
let _ = board.board_hal.set_charge_indicator(charging > 20);
}
@@ -208,7 +217,9 @@ fn safe_main() -> anyhow::Result<()> {
}
}
if board.board_hal.get_config().hardware.board == INITIAL && board.board_hal.get_config().network.ssid.is_none(){
if board.board_hal.get_config().hardware.board == INITIAL
&& board.board_hal.get_config().network.ssid.is_none()
{
let _ = board.board_hal.get_esp().wifi_ap();
drop(board);
let reboot_now = Arc::new(AtomicBool::new(false));
@@ -234,7 +245,7 @@ fn safe_main() -> anyhow::Result<()> {
}
}
let timezone = match & board.board_hal.get_config().timezone {
let timezone = match &board.board_hal.get_config().timezone {
Some(tz_str) => tz_str.parse::<Tz>().unwrap_or_else(|_| {
println!("Invalid timezone '{}', falling back to UTC", tz_str);
UTC
@@ -251,16 +262,30 @@ fn safe_main() -> anyhow::Result<()> {
);
if let NetworkMode::WIFI { ref ip_address, .. } = network_mode {
publish_firmware_info(version, address, ota_state_string, &mut board, &ip_address, timezone_time);
publish_firmware_info(
version,
address,
ota_state_string,
&mut board,
&ip_address,
timezone_time,
);
publish_battery_state(&mut board);
}
log(
LogMessage::StartupInfo,
matches!(network_mode, NetworkMode::WIFI { .. }) as u32,
matches!(network_mode, NetworkMode::WIFI { sntp: SntpMode::SYNC { .. }, .. }) as u32,
matches!(network_mode, NetworkMode::WIFI { mqtt: true, .. }).to_string().as_str(),
matches!(
network_mode,
NetworkMode::WIFI {
sntp: SntpMode::SYNC { .. },
..
}
) as u32,
matches!(network_mode, NetworkMode::WIFI { mqtt: true, .. })
.to_string()
.as_str(),
"",
);
@@ -304,7 +329,10 @@ fn safe_main() -> anyhow::Result<()> {
}
// disabled cannot trigger this because of wrapping if is_enabled
board.board_hal.general_fault(true);
} else if tank_state.warn_level(&board.board_hal.get_config().tank).is_ok_and(|warn| warn) {
} else if tank_state
.warn_level(&board.board_hal.get_config().tank)
.is_ok_and(|warn| warn)
{
log(LogMessage::TankWaterLevelLow, 0, 0, "", "");
board.board_hal.general_fault(true);
}
@@ -332,10 +360,17 @@ fn safe_main() -> anyhow::Result<()> {
&& !water_frozen;
if pump_required {
log(LogMessage::EnableMain, dry_run as u32, 0, "", "");
for (plant_id, (state, plant_config)) in plantstate.iter().zip(&board.board_hal.get_config().plants.clone()).enumerate() {
for (plant_id, (state, plant_config)) in plantstate
.iter()
.zip(&board.board_hal.get_config().plants.clone())
.enumerate()
{
if state.needs_to_be_watered(plant_config, &timezone_time) {
let pump_count = board.board_hal.get_esp().consecutive_pump_count(plant_id) + 1;
board.board_hal.get_esp().store_consecutive_pump_count(plant_id, pump_count);
board
.board_hal
.get_esp()
.store_consecutive_pump_count(plant_id, pump_count);
let pump_ineffective = pump_count > plant_config.max_consecutive_pump_count as u32;
if pump_ineffective {
@@ -343,7 +378,7 @@ fn safe_main() -> anyhow::Result<()> {
LogMessage::ConsecutivePumpCountLimit,
pump_count,
plant_config.max_consecutive_pump_count as u32,
&(plant_id+1).to_string(),
&(plant_id + 1).to_string(),
"",
);
board.board_hal.fault(plant_id, true)?;
@@ -355,29 +390,38 @@ fn safe_main() -> anyhow::Result<()> {
&dry_run.to_string(),
"",
);
board.board_hal.get_esp().store_last_pump_time(plant_id, cur);
board
.board_hal
.get_esp()
.store_last_pump_time(plant_id, cur);
board.board_hal.get_esp().last_pump_time(plant_id);
//state.active = true;
pump_info(&mut board, plant_id, true, pump_ineffective);
pump_info(&mut board, plant_id, true, pump_ineffective);
if !dry_run {
board.board_hal.pump(plant_id, true)?;
Delay::new_default().delay_ms(1000 * plant_config.pump_time_s as u32);
board.board_hal.pump(plant_id, false)?;
}
pump_info(&mut board, plant_id, false, pump_ineffective);
pump_info(&mut board, plant_id, false, pump_ineffective);
} else if !state.pump_in_timeout(plant_config, &timezone_time) {
// plant does not need to be watered and is not in timeout
// -> reset consecutive pump count
board.board_hal.get_esp().store_consecutive_pump_count(plant_id, 0);
board
.board_hal
.get_esp()
.store_consecutive_pump_count(plant_id, 0);
}
}
}
let is_day = board.board_hal.is_day();
let state_of_charge = board.board_hal.get_battery_monitor().state_charge_percent().unwrap_or(0);
let state_of_charge = board
.board_hal
.get_battery_monitor()
.state_charge_percent()
.unwrap_or(0);
let mut light_state = LightState {
enabled: board.board_hal.get_config().night_lamp.enabled,
@@ -387,7 +431,11 @@ fn safe_main() -> anyhow::Result<()> {
light_state.is_day = is_day;
light_state.out_of_work_hour = !in_time_range(
&timezone_time,
board.board_hal.get_config().night_lamp.night_lamp_hour_start,
board
.board_hal
.get_config()
.night_lamp
.night_lamp_hour_start,
board.board_hal.get_config().night_lamp.night_lamp_hour_end,
);
@@ -399,7 +447,12 @@ fn safe_main() -> anyhow::Result<()> {
light_state.battery_low = board.board_hal.get_esp().low_voltage_in_cycle();
if !light_state.out_of_work_hour {
if board.board_hal.get_config().night_lamp.night_lamp_only_when_dark {
if board
.board_hal
.get_config()
.night_lamp
.night_lamp_only_when_dark
{
if !light_state.is_day {
if light_state.battery_low {
board.board_hal.light(false)?;
@@ -424,7 +477,10 @@ fn safe_main() -> anyhow::Result<()> {
match serde_json::to_string(&light_state) {
Ok(state) => {
let _ = board.board_hal.get_esp().mqtt_publish( "/light", state.as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/light", state.as_bytes());
}
Err(err) => {
println!("Error publishing lightstate {}", err);
@@ -432,16 +488,28 @@ fn safe_main() -> anyhow::Result<()> {
};
let deep_sleep_duration_minutes: u32 = if state_of_charge < 10 {
let _ = board.board_hal.get_esp().mqtt_publish( "/deepsleep", "low Volt 12h".as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/deepsleep", "low Volt 12h".as_bytes());
12 * 60
} else if is_day {
let _ = board.board_hal.get_esp().mqtt_publish( "/deepsleep", "normal 20m".as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/deepsleep", "normal 20m".as_bytes());
20
} else {
let _ = board.board_hal.get_esp().mqtt_publish( "/deepsleep", "night 1h".as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/deepsleep", "night 1h".as_bytes());
60
};
let _ = board.board_hal.get_esp().mqtt_publish( "/state", "sleep".as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/state", "sleep".as_bytes());
//determine next event
//is light out of work trigger soon?
@@ -462,7 +530,9 @@ fn safe_main() -> anyhow::Result<()> {
wait_infinity(WaitType::MqttConfig, reboot_now.clone());
}
board.board_hal.get_esp().set_restart_to_conf(false);
board.board_hal.deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64);
board
.board_hal
.deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64);
}
fn obtain_tank_temperature(board: &mut MutexGuard<HAL>) -> anyhow::Result<f32> {
@@ -487,10 +557,19 @@ fn obtain_tank_temperature(board: &mut MutexGuard<HAL>) -> anyhow::Result<f32> {
water_temp
}
fn publish_tank_state(board: &mut MutexGuard<HAL>, tank_state: &TankState, water_temp: &anyhow::Result<f32>) {
match serde_json::to_string(&tank_state.as_mqtt_info(&board.board_hal.get_config().tank, water_temp)) {
fn publish_tank_state(
board: &mut MutexGuard<HAL>,
tank_state: &TankState,
water_temp: &anyhow::Result<f32>,
) {
match serde_json::to_string(
&tank_state.as_mqtt_info(&board.board_hal.get_config().tank, water_temp),
) {
Ok(state) => {
let _ = board.board_hal.get_esp().mqtt_publish("/water", state.as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/water", state.as_bytes());
}
Err(err) => {
println!("Error publishing tankstate {}", err);
@@ -498,12 +577,23 @@ fn publish_tank_state(board: &mut MutexGuard<HAL>, tank_state: &TankState, water
};
}
fn publish_plant_states(board: &mut MutexGuard<HAL>, timezone_time: &DateTime<Tz>, plantstate: &[PlantState; 8]) {
for (plant_id, (plant_state, plant_conf)) in plantstate.iter().zip(& board.board_hal.get_config().plants.clone()).enumerate() {
fn publish_plant_states(
board: &mut MutexGuard<HAL>,
timezone_time: &DateTime<Tz>,
plantstate: &[PlantState; 8],
) {
for (plant_id, (plant_state, plant_conf)) in plantstate
.iter()
.zip(&board.board_hal.get_config().plants.clone())
.enumerate()
{
match serde_json::to_string(&plant_state.to_mqtt_info(plant_conf, &timezone_time)) {
Ok(state) => {
let plant_topic = format!("/plant{}", plant_id + 1);
let _ = board.board_hal.get_esp().mqtt_publish(&plant_topic, state.as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish(&plant_topic, state.as_bytes());
//reduce speed as else messages will be dropped
board.board_hal.get_esp().delay.delay_ms(200);
}
@@ -514,26 +604,45 @@ fn publish_plant_states(board: &mut MutexGuard<HAL>, timezone_time: &DateTime<Tz
}
}
fn publish_firmware_info(version: VersionInfo, address: u32, ota_state_string: &str, board: &mut MutexGuard<HAL>, ip_address: &String, timezone_time: DateTime<Tz>) {
let _ = board.board_hal.get_esp().mqtt_publish("/firmware/address", ip_address.as_bytes());
let _ = board.board_hal.get_esp().mqtt_publish( "/firmware/githash", version.git_hash.as_bytes());
let _ = board.board_hal.get_esp().mqtt_publish(
"/firmware/buildtime",
version.build_time.as_bytes(),
);
fn publish_firmware_info(
version: VersionInfo,
address: u32,
ota_state_string: &str,
board: &mut MutexGuard<HAL>,
ip_address: &String,
timezone_time: DateTime<Tz>,
) {
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/firmware/address", ip_address.as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/firmware/githash", version.git_hash.as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/firmware/buildtime", version.build_time.as_bytes());
let _ = board.board_hal.get_esp().mqtt_publish(
"/firmware/last_online",
timezone_time.to_rfc3339().as_bytes(),
);
let _ = board.board_hal.get_esp().mqtt_publish( "/firmware/ota_state", ota_state_string.as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/firmware/ota_state", ota_state_string.as_bytes());
let _ = board.board_hal.get_esp().mqtt_publish(
"/firmware/partition_address",
format!("{:#06x}", address).as_bytes(),
);
let _ = board.board_hal.get_esp().mqtt_publish( "/state", "online".as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/state", "online".as_bytes());
}
fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode{
fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode {
let nw_conf = &board.board_hal.get_config().network.clone();
match board.board_hal.get_esp().wifi(nw_conf) {
Ok(ip_info) => {
@@ -541,7 +650,7 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode{
Ok(new_time) => {
println!("Using time from sntp");
let _ = board.board_hal.set_rtc_time(&new_time);
SntpMode::SYNC {current: new_time}
SntpMode::SYNC { current: new_time }
}
Err(err) => {
println!("sntp error: {}", err);
@@ -567,7 +676,7 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode{
NetworkMode::WIFI {
sntp: sntp_mode,
mqtt: mqtt_connected,
ip_address: ip_info.ip.to_string()
ip_address: ip_info.ip.to_string(),
}
}
Err(_) => {
@@ -578,15 +687,23 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode{
}
}
fn pump_info(board: &mut MutexGuard<HAL>, plant_id: usize, pump_active: bool, pump_ineffective: bool) {
fn pump_info(
board: &mut MutexGuard<HAL>,
plant_id: usize,
pump_active: bool,
pump_ineffective: bool,
) {
let pump_info = PumpInfo {
enabled: pump_active,
pump_ineffective
pump_ineffective,
};
let pump_topic = format!("/pump{}", plant_id + 1);
match serde_json::to_string(&pump_info) {
Ok(state) => {
let _ = board.board_hal.get_esp().mqtt_publish(&pump_topic, state.as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish(&pump_topic, state.as_bytes());
//reduce speed as else messages will be dropped
Delay::new_default().delay_ms(200);
}
@@ -596,11 +713,12 @@ fn pump_info(board: &mut MutexGuard<HAL>, plant_id: usize, pump_active: bool, pu
};
}
fn publish_battery_state(
board: &mut MutexGuard<'_, HAL<'_>>
) {
fn publish_battery_state(board: &mut MutexGuard<'_, HAL<'_>>) {
let state = board.board_hal.get_battery_monitor().get_battery_state();
let _ = board.board_hal.get_esp().mqtt_publish( "/battery", state.as_bytes());
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/battery", state.as_bytes());
}
fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
@@ -611,7 +729,11 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
loop {
unsafe {
let mut board = BOARD_ACCESS.lock().unwrap();
if let Ok(charging) = board.board_hal.get_battery_monitor().average_current_milli_ampere() {
if let Ok(charging) = board
.board_hal
.get_battery_monitor()
.average_current_milli_ampere()
{
let _ = board.board_hal.set_charge_indicator(charging > 20);
}
match wait_type {
@@ -673,7 +795,12 @@ fn main() {
// timeout, this is just a fallback
Ok(_) => {
println!("Main app finished, restarting");
BOARD_ACCESS.lock().unwrap().board_hal.get_esp().set_restart_to_conf(false);
BOARD_ACCESS
.lock()
.unwrap()
.board_hal
.get_esp()
.set_restart_to_conf(false);
BOARD_ACCESS.lock().unwrap().board_hal.deep_sleep(1);
}
// if safe_main exists with an error, rollback to a known good ota version