use std::{ fmt::Display, sync::{atomic::AtomicBool, Arc, Mutex}, }; use anyhow::{bail, Result}; use chrono::{DateTime, Datelike, TimeDelta, Timelike, Utc}; use chrono_tz::{Europe::Berlin, Tz}; use config::Mode; use esp_idf_hal::delay::Delay; use esp_idf_sys::{ esp_ota_get_app_partition_count, esp_ota_get_running_partition, esp_ota_get_state_partition, esp_ota_img_states_t, esp_ota_img_states_t_ESP_OTA_IMG_ABORTED, esp_ota_img_states_t_ESP_OTA_IMG_INVALID, esp_ota_img_states_t_ESP_OTA_IMG_NEW, esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY, esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED, esp_ota_img_states_t_ESP_OTA_IMG_VALID, vTaskDelay }; use log::log; use once_cell::sync::Lazy; use plant_hal::{PlantCtrlBoard, PlantHal, PLANT_COUNT}; use serde::{Deserialize, Serialize}; use crate::{ config::PlantControllerConfig, espota::{mark_app_valid, rollback_and_reboot}, webserver::webserver::httpd, }; mod log; mod config; pub mod espota; pub mod plant_hal; const TIME_ZONE: Tz = Berlin; const MOIST_SENSOR_MAX_FREQUENCY: u32 = 250000; // 60kHz (500Hz margin) const MOIST_SENSOR_MIN_FREQUENCY: u32 = 10000; // 0.5kHz (500Hz margin) const FROM: (f32, f32) = ( MOIST_SENSOR_MIN_FREQUENCY as f32, MOIST_SENSOR_MAX_FREQUENCY as f32, ); const TO: (f32, f32) = (0_f32, 100_f32); pub static BOARD_ACCESS: Lazy> = Lazy::new(|| PlantHal::create().unwrap()); pub static STAY_ALIVE: Lazy = Lazy::new(|| AtomicBool::new(false)); mod webserver { pub mod webserver; } #[derive(Serialize, Deserialize, Debug, PartialEq)] enum WaitType { MissingConfig, ConfigButton, MqttConfig, } #[derive(Serialize, Deserialize, Debug, PartialEq, Default)] struct LightState { active: bool, out_of_work_hour: bool, battery_low: bool, is_day: bool, } #[derive(Debug, PartialEq, Default)] struct PlantState { a: Option, a_raw: Option, b: Option, b_raw: Option, consecutive_pump_count: u32, after_p: Option, do_water: bool, dry: bool, active: bool, pump_error: bool, not_effective: bool, cooldown: bool, no_water: bool, sensor_error_a: Option, sensor_error_b: Option, out_of_work_hour: bool, next_pump: Option>, } #[derive(Serialize, Deserialize, Debug, PartialEq)] enum SensorError { Unknown, ShortCircuit { hz: f32, max: f32 }, OpenCircuit { hz: f32, min: f32 }, } #[derive(Debug, PartialEq, Default)] struct TankState { enough_water: bool, warn_level: bool, left_ml: u32, sensor_error: bool, raw: u16, } #[derive(Serialize)] struct TankStateMQTT { enough_water: bool, warn_level: bool, left_ml: u32, sensor_error: bool, raw: u16, water_frozen: String, } #[derive(Serialize)] struct PlantStateMQTT<'a> { a: &'a str, a_raw: &'a str, b: &'a str, b_raw: &'a str, mode: &'a str, consecutive_pump_count: u32, dry: bool, active: bool, pump_error: bool, not_effective: bool, cooldown: bool, out_of_work_hour: bool, last_pump: &'a str, next_pump: &'a str, } fn safe_main() -> anyhow::Result<()> { // It is necessary to call this function once. Otherwise some patches to the runtime // implemented by esp-idf-sys might not link properly. See https://github.com/esp-rs/esp-idf-template/issues/71 esp_idf_svc::sys::link_patches(); // Bind the log crate to the ESP Logging facilities esp_idf_svc::log::EspLogger::initialize_default(); if esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE < 25000 { bail!( "stack too small: {} bail!", esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE ); return Ok(()); } println!("Startup Rust"); let mut to_config = false; let version = get_version(); println!( "Version useing git has {} build on {}", version.git_hash, version.build_time ); let count = unsafe { esp_ota_get_app_partition_count() }; println!("Partition count is {}", count); let mut ota_state: esp_ota_img_states_t = 0; let running_partition = unsafe { esp_ota_get_running_partition() }; let address = unsafe { (*running_partition).address }; println!("Partition address is {}", address); let ota_state_string = unsafe { esp_ota_get_state_partition(running_partition, &mut ota_state); if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_NEW { "ESP_OTA_IMG_NEW" } else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY { "ESP_OTA_IMG_PENDING_VERIFY" } else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_VALID { "ESP_OTA_IMG_VALID" } else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_INVALID { "ESP_OTA_IMG_INVALID" } else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_ABORTED { "ESP_OTA_IMG_ABORTED" } else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED { "ESP_OTA_IMG_UNDEFINED" } else { &format!("unknown {ota_state}") } }; log(log::LogMessage::partition_state, 0,0, "", ota_state_string); let mut board: std::sync::MutexGuard<'_, PlantCtrlBoard<'_>> = BOARD_ACCESS.lock().unwrap(); board.general_fault(false); log(log::LogMessage::mounting_filesystem, 0,0,"",""); board.mount_file_system()?; let free_space = board.file_system_size()?; log(log::LogMessage::filesystem_mount, free_space.free_size as u32, free_space.total_size as u32, &free_space.used_size.to_string(), ""); let mut cur = match board.get_rtc_time() { Ok(time) => time, Err(err) => { println!("rtc module error: {}", err); board.general_fault(true); let time = board.time(); match time { Ok(cur) => cur, Err(err) => { bail!("time error {}", err); DateTime::from_timestamp_millis(0).unwrap() } } } }; //check if we know the time current > 2020 if cur.year() < 2020 { to_config = true; log(log::LogMessage::year_inplausible_force_config, 0,0,"",""); } println!("cur is {}", cur); if board.get_restart_to_conf() { log(log::LogMessage::config_mode_software_override, 0,0,"",""); for _i in 0..2 { board.general_fault(true); Delay::new_default().delay_ms(100); board.general_fault(false); Delay::new_default().delay_ms(100); } to_config = true; board.general_fault(true); board.set_restart_to_conf(false); } else if board.is_mode_override() { board.general_fault(true); log(log::LogMessage::config_mode_button_override, 0,0,"",""); for _i in 0..5 { board.general_fault(true); Delay::new_default().delay_ms(100); board.general_fault(false); Delay::new_default().delay_ms(100); } if board.is_mode_override() { board.general_fault(true); to_config = true; } else { board.general_fault(false); } } let config: PlantControllerConfig; match board.get_config() { Ok(valid) => { config = valid; } Err(err) => { log(log::LogMessage::config_mode_missing_config, 0,0,"",&err.to_string()); //config upload will trigger reboot! let _ = board.wifi_ap(Option::None); drop(board); let reboot_now = Arc::new(AtomicBool::new(false)); let _webserver = httpd(reboot_now.clone()); wait_infinity(WaitType::MissingConfig, reboot_now.clone()); } } let mut wifi = false; let mut mqtt = false; let mut sntp = false; println!("attempting to connect wifi"); let mut ip_address: Option = None; if config.network.ssid.is_some() { match board.wifi( config.network.ssid.clone().unwrap(), config.network.password.clone(), 10000, ) { Ok(ip_info) => { ip_address = Some(ip_info.ip.to_string()); wifi = true; match board.sntp(1000 * 10) { Ok(new_time) => { println!("Using time from sntp"); let _ = board.set_rtc_time(&new_time); cur = new_time; sntp = true; } Err(err) => { println!("sntp error: {}", err); board.general_fault(true); } } if config.network.mqtt_url.is_some() { match board.mqtt(&config) { Ok(_) => { println!("Mqtt connection ready"); mqtt = true; } Err(err) => { println!("Could not connect mqtt due to {}", err); } } } } Err(_) => { println!("Offline mode"); board.general_fault(true); } } } else { println!("No wifi configured"); } if !wifi && to_config { println!("Could not connect to station and config mode forced, switching to ap mode!"); match board.wifi_ap(Some(config.network.ap_ssid.clone())) { Ok(_) => { println!("Started ap, continuing") } Err(err) => println!( "Could not start config override ap mode due to {}", err.to_string() ), } } let timezone_time = cur.with_timezone(&TIME_ZONE); println!( "Running logic at utc {} and {} {}", cur, TIME_ZONE.name(), timezone_time ); if mqtt { let ip_string = ip_address.unwrap_or("N/A".to_owned()); let _ = board.mqtt_publish(&config, "/firmware/address", ip_string.as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/githash", version.git_hash.as_bytes()); let _ = board.mqtt_publish( &config, "/firmware/buildtime", version.build_time.as_bytes(), ); let _ = board.mqtt_publish( &config, "/firmware/last_online", timezone_time.to_rfc3339().as_bytes(), ); let _ = board.mqtt_publish(&config, "/firmware/ota_state", ota_state_string.as_bytes()); let _ = board.mqtt_publish( &config, "/firmware/partition_address", format!("{:#06x}", address).as_bytes(), ); let _ = board.mqtt_publish(&config, "/state", "online".as_bytes()); publish_battery_state(&mut board, &config); } log(log::LogMessage::startup_info, wifi as u32, sntp as u32,&mqtt.to_string(),""); if to_config { //check if client or ap mode and init wifi println!("executing config mode override"); //config upload will trigger reboot! drop(board); let reboot_now = Arc::new(AtomicBool::new(false)); let _webserver = httpd(reboot_now.clone()); wait_infinity(WaitType::ConfigButton, reboot_now.clone()); } else { log(log::LogMessage::normal_run, 0,0,"",""); } let dry_run = false; let tank_state = determine_tank_state(&mut board, &config); let mut tank_state_mqtt = TankStateMQTT { enough_water: tank_state.enough_water, left_ml: tank_state.left_ml, warn_level: tank_state.warn_level, sensor_error: tank_state.sensor_error, raw: tank_state.raw, water_frozen: "".to_owned(), }; let mut water_frozen = false; let mut temp: Option = None; for _attempt in 0..5 { let water_temperature = board.water_temperature_c(); match water_temperature { Ok(res) => { temp = Some(res); break; } Err(err) => { println!("Could not get water temp {} attempt {}", err, _attempt) } } } match temp { Some(res) => { println!("Water temp is {}", res); if res < 4_f32 { water_frozen = true; } tank_state_mqtt.water_frozen = water_frozen.to_string(); } None => tank_state_mqtt.water_frozen = "tank sensor error".to_owned(), } match serde_json::to_string(&tank_state_mqtt) { Ok(state) => { let _ = board.mqtt_publish(&config, "/water", state.as_bytes()); } Err(err) => { println!("Error publishing tankstate {}", err); } }; let mut plantstate: [PlantState; PLANT_COUNT] = core::array::from_fn(|_| PlantState { ..Default::default() }); let plant_to_pump = determine_next_plant( &mut plantstate, timezone_time, &tank_state, water_frozen, &config, &mut board, ); let pump_required = plantstate.iter().any(|it| it.do_water) && !water_frozen; if pump_required { log(log::LogMessage::enable_main, dry_run as u32,0,"",""); if !dry_run{ board.any_pump(true)?; } for plant in 0..PLANT_COUNT { let state = &mut plantstate[plant]; if state.do_water { let plant_config = &config.plants[plant]; state.consecutive_pump_count = board.consecutive_pump_count(plant) + 1; board.store_consecutive_pump_count(plant, state.consecutive_pump_count); if state.consecutive_pump_count > plant_config.max_consecutive_pump_count as u32 { log(log::LogMessage::consecutive_pump_count_limit, state.consecutive_pump_count as u32,plant_config.max_consecutive_pump_count as u32,&plant.to_string(),""); state.not_effective = true; board.fault(plant, true); } log(log::LogMessage::pump_plant, (plant + 1) as u32,plant_config.pump_time_s as u32,&dry_run.to_string(),""); board.store_last_pump_time(plant, cur); board.last_pump_time(plant); state.active = true; if !dry_run { board.pump(plant, true)?; for _ in 0..plant_config.pump_time_s { Delay::new_default().delay_ms(1000); } board.pump(plant, false)?; } } } } update_plant_state(&mut plantstate, &mut board, &config); let mut light_state = LightState { ..Default::default() }; let is_day = board.is_day(); light_state.is_day = is_day; light_state.out_of_work_hour = !in_time_range( &timezone_time, config.night_lamp.night_lamp_hour_start, config.night_lamp.night_lamp_hour_end, ); let state_of_charge = board.state_charge_percent().unwrap_or(0); if state_of_charge < 30 { board.set_low_voltage_in_cycle(); } else if state_of_charge > 50 { board.clear_low_voltage_in_cycle(); } light_state.battery_low = board.low_voltage_in_cycle(); if !light_state.out_of_work_hour { if config.night_lamp.night_lamp_only_when_dark { if !light_state.is_day { if light_state.battery_low { board.light(false).unwrap(); } else { light_state.active = true; board.light(true).unwrap(); } } } else { if light_state.battery_low { board.light(false).unwrap(); } else { light_state.active = true; board.light(true).unwrap(); } } } else { light_state.active = false; board.light(false).unwrap(); } println!("Lightstate is {:?}", light_state); match serde_json::to_string(&light_state) { Ok(state) => { let _ = board.mqtt_publish(&config, "/light", state.as_bytes()); } Err(err) => { println!("Error publishing lightstate {}", err); } }; let deep_sleep_duration_minutes: u32 = if state_of_charge < 10 { let _ = board.mqtt_publish(&config, "/deepsleep", "low Volt 12h".as_bytes()); 12 * 60 } else if is_day { let _ = board.mqtt_publish(&config, "/deepsleep", "normal 20m".as_bytes()); 20 } else { let _ = board.mqtt_publish(&config, "/deepsleep", "night 1h".as_bytes()); 60 }; let _ = board.mqtt_publish(&config, "/state", "sleep".as_bytes()); //determine next event //is light out of work trigger soon? //is battery low ?? //is deep sleep mark_app_valid(); let stay_alive_mqtt = STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed); let stay_alive = stay_alive_mqtt; println!("Check stay alive, current state is {}", stay_alive); if stay_alive { println!("Go to stay alive move"); drop(board); let reboot_now = Arc::new(AtomicBool::new(false)); let _webserver = httpd(reboot_now.clone()); wait_infinity(WaitType::MqttConfig, reboot_now.clone()); } board.set_restart_to_conf(false); board.deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64); } fn publish_battery_state( board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>, config: &PlantControllerConfig, ) { let bat = board.get_battery_state(); match serde_json::to_string(&bat) { Ok(state) => { let _ = board.mqtt_publish(&config, "/battery", state.as_bytes()); } Err(err) => { println!("Error publishing battery_state {}", err); } }; } fn determine_tank_state( board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>, config: &PlantControllerConfig, ) -> TankState { if config.tank.tank_sensor_enabled { let mut rv: TankState = TankState { ..Default::default() }; let success = board .tank_sensor_percent() .and_then(|raw| { rv.raw = raw; return map_range( ( config.tank.tank_empty_percent as f32, config.tank.tank_full_percent as f32, ), raw as f32, ); }) .and_then(|percent| { rv.left_ml = ((percent * config.tank.tank_useable_ml as f32) / 100_f32) as u32; println!( "Tank sensor returned mv {} as {}% leaving {} ml useable", rv.raw, percent as u8, rv.left_ml ); if config.tank.tank_warn_percent > percent as u8 { board.general_fault(true); println!( "Low water, current percent is {}, minimum warn level is {}", percent as u8, config.tank.tank_warn_percent ); rv.warn_level = true; } if config.tank.tank_empty_percent < percent as u8 { println!( "Enough water, current percent is {}, minimum empty level is {}", percent as u8, config.tank.tank_empty_percent ); rv.enough_water = true; } return Ok(()); }); match success { Err(err) => { println!("Could not determine tank value due to {}", err); board.general_fault(true); rv.sensor_error = true; } Ok(_) => {} } return rv; } return TankState { warn_level: false, enough_water: true, left_ml: 1337, sensor_error: false, raw: 0, }; } fn determine_state_target_moisture_for_plant( board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>, plant: usize, state: &mut PlantState, config: &PlantControllerConfig, tank_state: &TankState, cur: DateTime, ) { let plant_config = &config.plants[plant]; if plant_config.mode == Mode::OFF { return; } match board.measure_moisture_hz(plant, plant_hal::Sensor::A) { Ok(a) => { state.a_raw = Some(a); let mapped = map_range_moisture(a as f32); match mapped { Ok(result) => state.a = Some(result), Err(err) => { state.sensor_error_a = Some(err); } } } Err(_) => { state.sensor_error_a = Some(SensorError::Unknown); } } if plant_config.sensor_b { match board.measure_moisture_hz(plant, plant_hal::Sensor::B) { Ok(b) => { state.b_raw = Some(b); let mapped = map_range_moisture(b as f32); match mapped { Ok(result) => state.b = Some(result), Err(err) => { state.sensor_error_b = Some(err); } } } Err(_) => { state.sensor_error_b = Some(SensorError::Unknown); } } } //FIXME how to average analyze whatever? let a_low = state.a.is_some() && state.a.unwrap() < plant_config.target_moisture; let b_low = state.b.is_some() && state.b.unwrap() < plant_config.target_moisture; if a_low || b_low { state.dry = true; if tank_state.sensor_error && !config.tank.tank_allow_pumping_if_sensor_error { //ignore is ok } else if !tank_state.enough_water { state.no_water = true; } } let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap(); let last_pump = board.last_pump_time(plant); match last_pump { Some(last_pump) => { let next_pump = last_pump + duration; if next_pump > cur { let local_time = next_pump.with_timezone(&TIME_ZONE); state.next_pump = Some(local_time); state.cooldown = true; } } None => { println!( "Could not restore last pump for plant {}, restoring", plant + 1 ); board.store_last_pump_time(plant, DateTime::from_timestamp_millis(0).unwrap()); state.pump_error = true; } } if !in_time_range( &cur, plant_config.pump_hour_start, plant_config.pump_hour_end, ) { state.out_of_work_hour = true; } if state.dry && !state.no_water && !state.cooldown && !state.out_of_work_hour { state.do_water = true; } } fn determine_state_timer_only_for_plant( board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>, plant: usize, state: &mut PlantState, config: &PlantControllerConfig, tank_state: &TankState, cur: DateTime, ) { let plant_config = &config.plants[plant]; let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap(); let last_pump = board.last_pump_time(plant); match last_pump { Some(last_pump) => { let next_pump = last_pump + duration; if next_pump > cur { let europe_time = next_pump.with_timezone(&TIME_ZONE); state.next_pump = Some(europe_time); state.cooldown = true; } else { if tank_state.sensor_error && !config.tank.tank_allow_pumping_if_sensor_error { state.do_water = true; } else if !tank_state.enough_water { state.no_water = true; } } } None => { println!( "Could not restore last pump for plant {}, restoring", plant + 1 ); board.store_last_pump_time(plant, DateTime::from_timestamp_millis(0).unwrap()); state.pump_error = true; } } } fn determine_state_timer_and_deadzone_for_plant( board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>, plant: usize, state: &mut PlantState, config: &PlantControllerConfig, tank_state: &TankState, cur: DateTime, ) { let plant_config = &config.plants[plant]; let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap(); let last_pump = board.last_pump_time(plant); match last_pump { Some(last_pump) => { let next_pump = last_pump + duration; if next_pump > cur { let europe_time = next_pump.with_timezone(&TIME_ZONE); state.next_pump = Some(europe_time); state.cooldown = true; } if !in_time_range( &cur, plant_config.pump_hour_start, plant_config.pump_hour_end, ) { state.out_of_work_hour = true; } if !state.cooldown && !state.out_of_work_hour { if tank_state.sensor_error && !config.tank.tank_allow_pumping_if_sensor_error { state.do_water = true; } else if !tank_state.enough_water { state.no_water = true; } } } None => { println!( "Could not restore last pump for plant {}, restoring", plant + 1 ); board.store_last_pump_time(plant, DateTime::from_timestamp_millis(0).unwrap()); state.pump_error = true; } } } fn determine_next_plant( plantstate: &mut [PlantState; PLANT_COUNT], cur: DateTime, tank_state: &TankState, water_frozen: bool, config: &PlantControllerConfig, board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>, ) { for plant in 0..PLANT_COUNT { let state = &mut plantstate[plant]; let plant_config = &config.plants[plant]; match plant_config.mode { config::Mode::OFF => {} config::Mode::TargetMoisture => { determine_state_target_moisture_for_plant( board, plant, state, config, tank_state, cur, ); } config::Mode::TimerOnly => { determine_state_timer_only_for_plant(board, plant, state, config, tank_state, cur); } config::Mode::TimerAndDeadzone => { determine_state_timer_and_deadzone_for_plant( board, plant, state, config, tank_state, cur, ); } } if state.sensor_error_a.is_some() || state.sensor_error_b.is_some() { board.fault(plant, true); } if !state.dry { state.consecutive_pump_count = 0; board.store_consecutive_pump_count(plant, 0); } println!("Plant {} state is {:?}", plant, state); } } fn update_plant_state( plantstate: &mut [PlantState; PLANT_COUNT], board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>, config: &PlantControllerConfig, ) { for plant in 0..PLANT_COUNT { let state = &plantstate[plant]; let plant_config = &config.plants[plant]; let mode = format!("{:?}", plant_config.mode); let plant_dto = PlantStateMQTT { a: &sensor_to_string( &state.a, &state.sensor_error_a, plant_config.mode != Mode::OFF, ), a_raw: &state.a_raw.unwrap_or(0).to_string(), b: &sensor_to_string(&state.b, &state.sensor_error_b, plant_config.sensor_b), b_raw: &state.b_raw.unwrap_or(0).to_string(), active: state.active, mode: &mode, last_pump: &time_to_string_utc(board.last_pump_time(plant)), next_pump: &time_to_string(state.next_pump), consecutive_pump_count: state.consecutive_pump_count, cooldown: state.cooldown, dry: state.dry, not_effective: state.not_effective, out_of_work_hour: state.out_of_work_hour, pump_error: state.pump_error, }; match serde_json::to_string(&plant_dto) { Ok(state) => { let plant_topic = format!("/plant{}", plant + 1); let _ = board.mqtt_publish(&config, &plant_topic, state.as_bytes()); //reduce speed as else messages will be dropped Delay::new_default().delay_ms(200); } Err(err) => { println!("Error publishing lightstate {}", err); } }; } } fn wait_infinity(wait_type: WaitType, reboot_now: Arc) -> ! { let delay = match wait_type { WaitType::MissingConfig => 500_u32, WaitType::ConfigButton => 100_u32, WaitType::MqttConfig => 200_u32, }; let mut led_count = 8; loop { if wait_type == WaitType::MissingConfig { led_count = led_count + 1; if led_count > 8 { led_count = 1; } }; unsafe { //do not trigger watchdog for i in 0..8 { BOARD_ACCESS.lock().unwrap().fault(i, i < led_count); } BOARD_ACCESS.lock().unwrap().general_fault(true); vTaskDelay(delay); BOARD_ACCESS.lock().unwrap().general_fault(false); for i in 0..8 { BOARD_ACCESS.lock().unwrap().fault(i, false); } vTaskDelay(delay); match wait_type { WaitType::MissingConfig => {} WaitType::ConfigButton => {} WaitType::MqttConfig => { if !STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed) { reboot_now.store(true, std::sync::atomic::Ordering::Relaxed); } } } if reboot_now.load(std::sync::atomic::Ordering::Relaxed) { //ensure clean http answer Delay::new_default().delay_ms(500); BOARD_ACCESS.lock().unwrap().deep_sleep( 1); } } } } fn main() { let result = safe_main(); match result { Ok(_) => { println!("Main app finished, restarting"); BOARD_ACCESS.lock().unwrap().set_restart_to_conf(false); BOARD_ACCESS.lock().unwrap().deep_sleep(1); } Err(err) => { println!("Failed main {}", err); let rollback_successful = rollback_and_reboot(); println!("Failed to rollback :("); rollback_successful.unwrap(); } } } fn time_to_string_utc(value_option: Option>) -> String { let converted = value_option.and_then(|utc| Some(utc.with_timezone(&TIME_ZONE))); return time_to_string(converted); } fn time_to_string(value_option: Option>) -> String { match value_option { Some(value) => { let europe_time = value.with_timezone(&TIME_ZONE); if europe_time.year() > 2023 { return europe_time.to_rfc3339(); } else { //initial value of 0 in rtc memory return "N/A".to_owned(); } } None => return "N/A".to_owned(), }; } fn sensor_to_string(value: &Option, error: &Option, enabled: bool) -> String { if enabled { match error { Some(error) => return format!("{:?}", error), None => match value { Some(v) => return v.to_string(), None => return "Error".to_owned(), }, } } else { return "disabled".to_owned(); }; } fn to_string(value: Result) -> String { return match value { Ok(v) => v.to_string(), Err(err) => { format!("{:?}", err) } }; } fn map_range(from_range: (f32, f32), s: f32) -> anyhow::Result { if s < from_range.0 { anyhow::bail!( "Value out of range, min {} but current is {}", from_range.0, s ); } if s > from_range.1 { anyhow::bail!( "Value out of range, max {} but current is {}", from_range.1, s ); } return Ok(TO.0 + (s - from_range.0) * (TO.1 - TO.0) / (from_range.1 - from_range.0)); } fn map_range_moisture(s: f32) -> Result { if s < FROM.0 { return Err(SensorError::OpenCircuit { hz: s, min: FROM.0 }); } if s > FROM.1 { return Err(SensorError::ShortCircuit { hz: s, max: FROM.1 }); } let tmp = TO.0 + (s - FROM.0) * (TO.1 - TO.0) / (FROM.1 - FROM.0); return Ok(tmp as u8); } fn in_time_range(cur: &DateTime, start: u8, end: u8) -> bool { let curhour = cur.hour() as u8; //eg 10-14 if start < end { return curhour > start && curhour < end; } else { //eg 20-05 return curhour > start || curhour < end; } } fn get_version() -> VersionInfo { let branch = env!("VERGEN_GIT_BRANCH").to_owned(); let hash = &env!("VERGEN_GIT_SHA")[0..8]; let running_partition = unsafe { esp_ota_get_running_partition() }; let address = unsafe { (*running_partition).address }; let partition = if address > 20000 { "ota_1" } else { "ota_0" }; return VersionInfo { git_hash: (branch + "@" + hash), build_time: env!("VERGEN_BUILD_TIMESTAMP").to_owned(), partition: partition.to_owned() }; } #[derive(Serialize, Debug)] struct VersionInfo { git_hash: String, build_time: String, partition: String, }