more async migration
This commit is contained in:
377
rust/src/main.rs
377
rust/src/main.rs
@@ -11,23 +11,28 @@ use crate::{
|
||||
hal::{PlantHal, HAL, PLANT_COUNT},
|
||||
//webserver::httpd,
|
||||
};
|
||||
use core::sync::atomic::Ordering;
|
||||
use ::log::{error, info, warn};
|
||||
use alloc::borrow::ToOwned;
|
||||
use alloc::sync::Arc;
|
||||
use alloc::fmt::format;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::sync::Arc;
|
||||
use alloc::{format, vec};
|
||||
use anyhow::{bail, Context};
|
||||
use chrono::{DateTime, Datelike, Timelike, Utc};
|
||||
use chrono_tz::Tz::{self, UTC};
|
||||
use core::sync::atomic::Ordering;
|
||||
use embassy_executor::Spawner;
|
||||
use hal::battery::BatteryState;
|
||||
use esp_hal::{timer::systimer::SystemTimer, clock::CpuClock, delay::Delay};
|
||||
use embassy_sync::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
|
||||
use embassy_sync::lazy_lock::LazyLock;
|
||||
use embassy_sync::mutex::Mutex;
|
||||
use embassy_sync::mutex::MutexGuard;
|
||||
use embassy_time::Timer;
|
||||
use esp_hal::{clock::CpuClock, delay::Delay, timer::systimer::SystemTimer};
|
||||
use esp_println::logger;
|
||||
use hal::battery::BatteryState;
|
||||
use log::{log, LogMessage};
|
||||
use plant_state::PlantState;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use embassy_sync::{Mutex, LazyLock, mutex::MutexGuard};
|
||||
use portable_atomic::AtomicBool;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tank::*;
|
||||
mod config;
|
||||
mod hal;
|
||||
@@ -38,8 +43,9 @@ mod tank;
|
||||
extern crate alloc;
|
||||
//mod webserver;
|
||||
|
||||
pub static BOARD_ACCESS: LazyLock<Mutex<HAL>> = LazyLock::new(|| PlantHal::create().unwrap());
|
||||
pub static STAY_ALIVE: LazyLock<AtomicBool> = LazyLock::new(|| AtomicBool::new(false));
|
||||
pub static BOARD_ACCESS: LazyLock<Mutex<CriticalSectionRawMutex, HAL>> =
|
||||
LazyLock::new(|| PlantHal::create().unwrap());
|
||||
pub static STAY_ALIVE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||
enum WaitType {
|
||||
@@ -55,11 +61,11 @@ struct Solar {
|
||||
}
|
||||
|
||||
impl WaitType {
|
||||
fn blink_pattern(&self) -> u32 {
|
||||
fn blink_pattern(&self) -> u64 {
|
||||
match self {
|
||||
WaitType::MissingConfig => 500_u32,
|
||||
WaitType::ConfigButton => 100_u32,
|
||||
WaitType::MqttConfig => 200_u32,
|
||||
WaitType::MissingConfig => 500_u64,
|
||||
WaitType::ConfigButton => 100_u64,
|
||||
WaitType::MqttConfig => 200_u64,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,14 +122,13 @@ enum NetworkMode {
|
||||
OFFLINE,
|
||||
}
|
||||
|
||||
fn safe_main() -> anyhow::Result<()> {
|
||||
|
||||
log::info!("Startup Rust");
|
||||
async fn safe_main() -> anyhow::Result<()> {
|
||||
info!("Startup Rust");
|
||||
|
||||
let mut to_config = false;
|
||||
|
||||
let version = get_version();
|
||||
log::info!(
|
||||
info!(
|
||||
"Version using git has {} build on {}",
|
||||
version.git_hash, version.build_time
|
||||
);
|
||||
@@ -133,41 +138,42 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
//log::info!("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 };
|
||||
//let partition_address = unsafe { (*running_partition).address };
|
||||
//log::info!("Partition address is {}", address);
|
||||
let partition_address = 0x1337;
|
||||
|
||||
// TODO
|
||||
//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}")
|
||||
//}
|
||||
//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(LogMessage::PartitionState, 0, 0, "", ota_state_string);
|
||||
let ota_state_string = "unknown";
|
||||
|
||||
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 mut board = BOARD_ACCESS.get().lock().await;
|
||||
board.board_hal.general_fault(false).await;
|
||||
|
||||
let cur = board
|
||||
.board_hal
|
||||
.get_rtc_module()
|
||||
.get_rtc_time()
|
||||
.await
|
||||
.or_else(|err| {
|
||||
log::info!("rtc module error: {:?}", err);
|
||||
info!("rtc module error: {:?}", err);
|
||||
board.board_hal.general_fault(true);
|
||||
board.board_hal.get_esp().time()
|
||||
})
|
||||
@@ -182,35 +188,35 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
log(LogMessage::YearInplausibleForceConfig, 0, 0, "", "");
|
||||
}
|
||||
|
||||
log::info!("cur is {}", cur);
|
||||
update_charge_indicator(&mut board);
|
||||
info!("cur is {}", cur);
|
||||
update_charge_indicator().await;
|
||||
|
||||
if board.board_hal.get_esp().get_restart_to_conf() {
|
||||
log(LogMessage::ConfigModeSoftwareOverride, 0, 0, "", "");
|
||||
for _i in 0..2 {
|
||||
board.board_hal.general_fault(true);
|
||||
Delay::new_default().delay_ms(100);
|
||||
board.board_hal.general_fault(false);
|
||||
Delay::new_default().delay_ms(100);
|
||||
board.board_hal.general_fault(true).await;
|
||||
Timer::after_millis(100).await;
|
||||
board.board_hal.general_fault(false).await;
|
||||
Timer::after_millis(100).await;
|
||||
}
|
||||
to_config = true;
|
||||
board.board_hal.general_fault(true);
|
||||
board.board_hal.general_fault(true).await;
|
||||
board.board_hal.get_esp().set_restart_to_conf(false);
|
||||
} else if board.board_hal.get_esp().mode_override_pressed() {
|
||||
board.board_hal.general_fault(true);
|
||||
board.board_hal.general_fault(true).await;
|
||||
log(LogMessage::ConfigModeButtonOverride, 0, 0, "", "");
|
||||
for _i in 0..5 {
|
||||
board.board_hal.general_fault(true);
|
||||
Delay::new_default().delay_ms(100);
|
||||
board.board_hal.general_fault(false);
|
||||
Delay::new_default().delay_ms(100);
|
||||
board.board_hal.general_fault(true).await;
|
||||
Timer::after_millis(100).await;
|
||||
board.board_hal.general_fault(false).await;
|
||||
Timer::after_millis(100).await;
|
||||
}
|
||||
|
||||
if board.board_hal.get_esp().mode_override_pressed() {
|
||||
board.board_hal.general_fault(true);
|
||||
board.board_hal.general_fault(true).await;
|
||||
to_config = true;
|
||||
} else {
|
||||
board.board_hal.general_fault(false);
|
||||
board.board_hal.general_fault(false).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,39 +228,39 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
let reboot_now = Arc::new(AtomicBool::new(false));
|
||||
//TODO
|
||||
//let _webserver = httpd(reboot_now.clone());
|
||||
wait_infinity(WaitType::MissingConfig, reboot_now.clone());
|
||||
wait_infinity(WaitType::MissingConfig, reboot_now.clone()).await;
|
||||
}
|
||||
|
||||
log::info!("attempting to connect wifi");
|
||||
info!("attempting to connect wifi");
|
||||
let network_mode = if board.board_hal.get_config().network.ssid.is_some() {
|
||||
try_connect_wifi_sntp_mqtt(&mut board)
|
||||
try_connect_wifi_sntp_mqtt().await
|
||||
} else {
|
||||
log::info!("No wifi configured");
|
||||
info!("No wifi configured");
|
||||
//the current sensors require this amount to stabilize, in case of wifi this is already handles for sure;
|
||||
board.board_hal.get_esp().delay.delay_ms(100);
|
||||
Timer::after_millis(100).await;
|
||||
NetworkMode::OFFLINE
|
||||
};
|
||||
|
||||
if matches!(network_mode, NetworkMode::OFFLINE) && to_config {
|
||||
log::info!("Could not connect to station and config mode forced, switching to ap mode!");
|
||||
match board.board_hal.get_esp().wifi_ap() {
|
||||
info!("Could not connect to station and config mode forced, switching to ap mode!");
|
||||
match board.board_hal.get_esp().wifi_ap().await {
|
||||
Ok(_) => {
|
||||
log::info!("Started ap, continuing")
|
||||
info!("Started ap, continuing")
|
||||
}
|
||||
Err(err) => log::info!("Could not start config override ap mode due to {}", err),
|
||||
Err(err) => info!("Could not start config override ap mode due to {}", err),
|
||||
}
|
||||
}
|
||||
|
||||
let timezone = match &board.board_hal.get_config().timezone {
|
||||
Some(tz_str) => tz_str.parse::<Tz>().unwrap_or_else(|_| {
|
||||
log::info!("Invalid timezone '{}', falling back to UTC", tz_str);
|
||||
info!("Invalid timezone '{}', falling back to UTC", tz_str);
|
||||
UTC
|
||||
}),
|
||||
None => UTC, // Fallback to UTC if no timezone is set
|
||||
};
|
||||
|
||||
let timezone_time = cur.with_timezone(&timezone);
|
||||
log::info!(
|
||||
info!(
|
||||
"Running logic at utc {} and {} {}",
|
||||
cur,
|
||||
timezone.name(),
|
||||
@@ -264,14 +270,14 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
if let NetworkMode::WIFI { ref ip_address, .. } = network_mode {
|
||||
publish_firmware_info(
|
||||
version,
|
||||
address,
|
||||
partition_address,
|
||||
ota_state_string,
|
||||
&mut board,
|
||||
ip_address,
|
||||
timezone_time,
|
||||
);
|
||||
publish_battery_state(&mut board);
|
||||
let _ = publish_mppt_state(&mut board);
|
||||
)
|
||||
.await;
|
||||
publish_battery_state().await;
|
||||
let _ = publish_mppt_state().await;
|
||||
}
|
||||
|
||||
log(
|
||||
@@ -290,15 +296,16 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
"",
|
||||
);
|
||||
|
||||
drop(board);
|
||||
|
||||
if to_config {
|
||||
//check if client or ap mode and init Wi-Fi
|
||||
log::info!("executing config mode override");
|
||||
info!("executing config mode override");
|
||||
//config upload will trigger reboot!
|
||||
drop(board);
|
||||
let reboot_now = Arc::new(AtomicBool::new(false));
|
||||
//TODO
|
||||
//let _webserver = httpd(reboot_now.clone());
|
||||
wait_infinity(WaitType::ConfigButton, reboot_now.clone());
|
||||
wait_infinity(WaitType::ConfigButton, reboot_now.clone()).await;
|
||||
} else {
|
||||
log(LogMessage::NormalRun, 0, 0, "", "");
|
||||
}
|
||||
@@ -345,7 +352,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
.board_hal
|
||||
.get_tank_sensor()
|
||||
.context("no sensor")
|
||||
.and_then(|f| f.water_temperature_c());
|
||||
.and_then(async |f| f.water_temperature_c().await);
|
||||
|
||||
if let Ok(res) = water_temp {
|
||||
if res < WATER_FROZEN_THRESH {
|
||||
@@ -353,11 +360,11 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
publish_tank_state(&mut board, &tank_state, &water_temp);
|
||||
publish_tank_state(&tank_state, &water_temp);
|
||||
|
||||
let plantstate: [PlantState; PLANT_COUNT] =
|
||||
core::array::from_fn(|i| PlantState::read_hardware_state(i, &mut board));
|
||||
publish_plant_states(&mut board, &timezone_time, &plantstate);
|
||||
core::array::from_fn(|i| PlantState::read_hardware_state(i, &mut board).await);
|
||||
publish_plant_states(&timezone_time, &plantstate).await;
|
||||
|
||||
let pump_required = plantstate
|
||||
.iter()
|
||||
@@ -387,7 +394,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
&(plant_id + 1).to_string(),
|
||||
"",
|
||||
);
|
||||
board.board_hal.fault(plant_id, true)?;
|
||||
board.board_hal.fault(plant_id, true).await?;
|
||||
}
|
||||
log(
|
||||
LogMessage::PumpPlant,
|
||||
@@ -403,12 +410,11 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
board.board_hal.get_esp().last_pump_time(plant_id);
|
||||
//state.active = true;
|
||||
|
||||
pump_info(&mut board, plant_id, true, pump_ineffective, 0, 0, 0, false);
|
||||
pump_info(plant_id, true, pump_ineffective, 0, 0, 0, false).await;
|
||||
|
||||
let result = do_secure_pump(&mut board, plant_id, plant_config, dry_run)?;
|
||||
board.board_hal.pump(plant_id, false)?;
|
||||
let result = do_secure_pump(plant_id, plant_config, dry_run).await?;
|
||||
board.board_hal.pump(plant_id, false).await?;
|
||||
pump_info(
|
||||
&mut board,
|
||||
plant_id,
|
||||
false,
|
||||
pump_ineffective,
|
||||
@@ -416,7 +422,8 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
result.max_current_ma,
|
||||
result.min_current_ma,
|
||||
result.error,
|
||||
);
|
||||
)
|
||||
.await;
|
||||
} 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
|
||||
@@ -433,6 +440,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
.board_hal
|
||||
.get_battery_monitor()
|
||||
.state_charge_percent()
|
||||
.await
|
||||
.unwrap_or(0.);
|
||||
|
||||
// try to load full battery state if failed the battery state is unknown
|
||||
@@ -440,6 +448,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
.board_hal
|
||||
.get_battery_monitor()
|
||||
.get_battery_state()
|
||||
.await
|
||||
.unwrap_or(BatteryState::Unknown);
|
||||
|
||||
let mut light_state = LightState {
|
||||
@@ -505,7 +514,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
board.board_hal.light(false)?;
|
||||
}
|
||||
|
||||
log::info!("Lightstate is {:?}", light_state);
|
||||
info!("Lightstate is {:?}", light_state);
|
||||
}
|
||||
|
||||
match serde_json::to_string(&light_state) {
|
||||
@@ -513,10 +522,11 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/light", state.as_bytes());
|
||||
.mqtt_publish("/light", state.as_bytes())
|
||||
.await;
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error publishing lightstate {}", err);
|
||||
info!("Error publishing lightstate {}", err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -526,25 +536,26 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/deepsleep", "low Volt 12h".as_bytes());
|
||||
.mqtt_publish("/deepsleep", "low Volt 12h".as_bytes()).await;
|
||||
12 * 60
|
||||
} else if is_day {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/deepsleep", "normal 20m".as_bytes());
|
||||
.mqtt_publish("/deepsleep", "normal 20m".as_bytes()).await;
|
||||
20
|
||||
} else {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/deepsleep", "night 1h".as_bytes());
|
||||
.mqtt_publish("/deepsleep", "night 1h".as_bytes()).await;
|
||||
60
|
||||
};
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/state", "sleep".as_bytes());
|
||||
.mqtt_publish("/state", "sleep".as_bytes())
|
||||
.await;
|
||||
|
||||
//determine next event
|
||||
//is light out of work trigger soon?
|
||||
@@ -556,25 +567,24 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
let stay_alive_mqtt = STAY_ALIVE.load(Ordering::Relaxed);
|
||||
|
||||
let stay_alive = stay_alive_mqtt;
|
||||
log::info!("Check stay alive, current state is {}", stay_alive);
|
||||
info!("Check stay alive, current state is {}", stay_alive);
|
||||
|
||||
if stay_alive {
|
||||
log::info!("Go to stay alive move");
|
||||
info!("Go to stay alive move");
|
||||
drop(board);
|
||||
let reboot_now = Arc::new(AtomicBool::new(false));
|
||||
//TODO
|
||||
//let _webserver = httpd(reboot_now.clone());
|
||||
wait_infinity(WaitType::MqttConfig, reboot_now.clone());
|
||||
wait_infinity(WaitType::MqttConfig, reboot_now.clone()).await;
|
||||
} else {
|
||||
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.get_esp().set_restart_to_conf(false);
|
||||
board
|
||||
.board_hal
|
||||
.deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
pub fn do_secure_pump(
|
||||
board: &mut MutexGuard<HAL>,
|
||||
pub async fn do_secure_pump(
|
||||
plant_id: usize,
|
||||
plant_config: &PlantConfig,
|
||||
dry_run: bool,
|
||||
@@ -584,6 +594,7 @@ pub fn do_secure_pump(
|
||||
let mut error = false;
|
||||
let mut first_error = true;
|
||||
let mut pump_time_s = 0;
|
||||
let board = &mut BOARD_ACCESS.get().lock().await;
|
||||
if !dry_run {
|
||||
board
|
||||
.board_hal
|
||||
@@ -595,8 +606,8 @@ pub fn do_secure_pump(
|
||||
.get_tank_sensor()
|
||||
.unwrap()
|
||||
.start_flow_meter();
|
||||
board.board_hal.pump(plant_id, true)?;
|
||||
Delay::new_default().delay_ms(10);
|
||||
board.board_hal.pump(plant_id, true).await?;
|
||||
Timer::after_millis(10).await;
|
||||
for step in 0..plant_config.pump_time_s as usize {
|
||||
let flow_value = board
|
||||
.board_hal
|
||||
@@ -606,16 +617,16 @@ pub fn do_secure_pump(
|
||||
flow_collector[step] = flow_value;
|
||||
let flow_value_ml = flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
|
||||
|
||||
log::info!(
|
||||
info!(
|
||||
"Flow value is {} ml, limit is {} ml raw sensor {}",
|
||||
flow_value_ml, plant_config.pump_limit_ml, flow_value
|
||||
);
|
||||
if flow_value_ml > plant_config.pump_limit_ml as f32 {
|
||||
log::info!("Flow value is reached, stopping");
|
||||
info!("Flow value is reached, stopping");
|
||||
break;
|
||||
}
|
||||
|
||||
let current = board.board_hal.pump_current(plant_id);
|
||||
let current = board.board_hal.pump_current(plant_id).await;
|
||||
match current {
|
||||
Ok(current) => {
|
||||
let current_ma = current.as_milliamperes() as u16;
|
||||
@@ -630,8 +641,8 @@ pub fn do_secure_pump(
|
||||
plant_config.max_pump_current_ma.to_string().as_str(),
|
||||
step.to_string().as_str(),
|
||||
);
|
||||
board.board_hal.general_fault(true);
|
||||
board.board_hal.fault(plant_id, true)?;
|
||||
board.board_hal.general_fault(true).await;
|
||||
board.board_hal.fault(plant_id, true).await?;
|
||||
if !plant_config.ignore_current_error {
|
||||
error = true;
|
||||
break;
|
||||
@@ -649,8 +660,8 @@ pub fn do_secure_pump(
|
||||
plant_config.min_pump_current_ma.to_string().as_str(),
|
||||
step.to_string().as_str(),
|
||||
);
|
||||
board.board_hal.general_fault(true);
|
||||
board.board_hal.fault(plant_id, true)?;
|
||||
board.board_hal.general_fault(true).await;
|
||||
board.board_hal.fault(plant_id, true).await?;
|
||||
if !plant_config.ignore_current_error {
|
||||
error = true;
|
||||
break;
|
||||
@@ -661,7 +672,7 @@ pub fn do_secure_pump(
|
||||
}
|
||||
Err(err) => {
|
||||
if !plant_config.ignore_current_error {
|
||||
log::info!("Error getting pump current: {}", err);
|
||||
info!("Error getting pump current: {}", err);
|
||||
log(
|
||||
LogMessage::PumpMissingSensorCurrent,
|
||||
plant_id as u32,
|
||||
@@ -676,7 +687,7 @@ pub fn do_secure_pump(
|
||||
}
|
||||
}
|
||||
}
|
||||
Delay::new_default().delay_ms(1000);
|
||||
Timer::after_millis(1000).await;
|
||||
pump_time_s += 1;
|
||||
}
|
||||
}
|
||||
@@ -687,7 +698,7 @@ pub fn do_secure_pump(
|
||||
.unwrap()
|
||||
.get_flow_meter_value();
|
||||
let flow_value_ml = final_flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
|
||||
log::info!(
|
||||
info!(
|
||||
"Final flow value is {} with {} ml",
|
||||
final_flow_value, flow_value_ml
|
||||
);
|
||||
@@ -703,9 +714,10 @@ pub fn do_secure_pump(
|
||||
})
|
||||
}
|
||||
|
||||
fn update_charge_indicator(board: &mut MutexGuard<HAL>) {
|
||||
async fn update_charge_indicator() {
|
||||
let board = BOARD_ACCESS.get().lock().await;
|
||||
//we have mppt controller, ask it for charging current
|
||||
if let Ok(current) = board.board_hal.get_mptt_current() {
|
||||
if let Ok(current) = board.board_hal.get_mptt_current().await {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.set_charge_indicator(current.as_milliamperes() > 20_f64);
|
||||
@@ -723,11 +735,8 @@ fn update_charge_indicator(board: &mut MutexGuard<HAL>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_tank_state(
|
||||
board: &mut MutexGuard<HAL>,
|
||||
tank_state: &TankState,
|
||||
water_temp: &anyhow::Result<f32>,
|
||||
) {
|
||||
async fn publish_tank_state(tank_state: &TankState, water_temp: &anyhow::Result<f32>) {
|
||||
let board = &mut BOARD_ACCESS.get().lock().await;
|
||||
match serde_json::to_string(
|
||||
&tank_state.as_mqtt_info(&board.board_hal.get_config().tank, water_temp),
|
||||
) {
|
||||
@@ -738,16 +747,13 @@ fn publish_tank_state(
|
||||
.mqtt_publish("/water", state.as_bytes());
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error publishing tankstate {}", err);
|
||||
info!("Error publishing tankstate {}", err);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn publish_plant_states(
|
||||
board: &mut MutexGuard<HAL>,
|
||||
timezone_time: &DateTime<Tz>,
|
||||
plantstate: &[PlantState; 8],
|
||||
) {
|
||||
async fn publish_plant_states(timezone_time: &DateTime<Tz>, plantstate: &[PlantState; 8]) {
|
||||
let board = &mut BOARD_ACCESS.get().lock().await;
|
||||
for (plant_id, (plant_state, plant_conf)) in plantstate
|
||||
.iter()
|
||||
.zip(&board.board_hal.get_config().plants.clone())
|
||||
@@ -759,37 +765,41 @@ fn publish_plant_states(
|
||||
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);
|
||||
.mqtt_publish(&plant_topic, state.as_bytes())
|
||||
.await;
|
||||
//TODO? reduce speed as else messages will be dropped
|
||||
Timer::after_millis(200).await
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error publishing plant state {}", err);
|
||||
error!("Error publishing plant state {}", err);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_firmware_info(
|
||||
async 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 = &mut BOARD_ACCESS.get().lock().await;
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/firmware/address", ip_address.as_bytes());
|
||||
.mqtt_publish("/firmware/address", ip_address.as_bytes())
|
||||
.await;
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/firmware/githash", version.git_hash.as_bytes());
|
||||
.mqtt_publish("/firmware/githash", version.git_hash.as_bytes())
|
||||
.await;
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/firmware/buildtime", version.build_time.as_bytes());
|
||||
.mqtt_publish("/firmware/buildtime", version.build_time.as_bytes())
|
||||
.await;
|
||||
let _ = board.board_hal.get_esp().mqtt_publish(
|
||||
"/firmware/last_online",
|
||||
timezone_time.to_rfc3339().as_bytes(),
|
||||
@@ -797,7 +807,8 @@ fn publish_firmware_info(
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/firmware/ota_state", ota_state_string.as_bytes());
|
||||
.mqtt_publish("/firmware/ota_state", ota_state_string.as_bytes())
|
||||
.await;
|
||||
let _ = board.board_hal.get_esp().mqtt_publish(
|
||||
"/firmware/partition_address",
|
||||
format!("{:#06x}", address).as_bytes(),
|
||||
@@ -805,34 +816,36 @@ fn publish_firmware_info(
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/state", "online".as_bytes());
|
||||
.mqtt_publish("/state", "online".as_bytes())
|
||||
.await;
|
||||
}
|
||||
|
||||
fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode {
|
||||
async fn try_connect_wifi_sntp_mqtt() -> NetworkMode {
|
||||
let board = BOARD_ACCESS.get().lock().await;
|
||||
let nw_conf = &board.board_hal.get_config().network.clone();
|
||||
match board.board_hal.get_esp().wifi(nw_conf) {
|
||||
match board.board_hal.get_esp().wifi(nw_conf).await {
|
||||
Ok(ip_info) => {
|
||||
let sntp_mode: SntpMode = match board.board_hal.get_esp().sntp(1000 * 10) {
|
||||
let sntp_mode: SntpMode = match board.board_hal.get_esp().sntp(1000 * 10).await {
|
||||
Ok(new_time) => {
|
||||
log::info!("Using time from sntp");
|
||||
info!("Using time from sntp");
|
||||
let _ = board.board_hal.get_rtc_module().set_rtc_time(&new_time);
|
||||
SntpMode::SYNC { current: new_time }
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("sntp error: {}", err);
|
||||
board.board_hal.general_fault(true);
|
||||
warn!("sntp error: {}", err);
|
||||
board.board_hal.general_fault(true).await;
|
||||
SntpMode::OFFLINE
|
||||
}
|
||||
};
|
||||
let mqtt_connected = if board.board_hal.get_config().network.mqtt_url.is_some() {
|
||||
let nw_config = &board.board_hal.get_config().network.clone();
|
||||
match board.board_hal.get_esp().mqtt(nw_config) {
|
||||
match board.board_hal.get_esp().mqtt(nw_config).await {
|
||||
Ok(_) => {
|
||||
log::info!("Mqtt connection ready");
|
||||
info!("Mqtt connection ready");
|
||||
true
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Could not connect mqtt due to {}", err);
|
||||
warn!("Could not connect mqtt due to {}", err);
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -846,15 +859,14 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode {
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
log::info!("Offline mode");
|
||||
info!("Offline mode");
|
||||
board.board_hal.general_fault(true);
|
||||
NetworkMode::OFFLINE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pump_info(
|
||||
board: &mut MutexGuard<HAL>,
|
||||
async fn pump_info(
|
||||
plant_id: usize,
|
||||
pump_active: bool,
|
||||
pump_ineffective: bool,
|
||||
@@ -871,24 +883,30 @@ fn pump_info(
|
||||
min_current_ma: min_current_ma,
|
||||
};
|
||||
let pump_topic = format!("/pump{}", plant_id + 1);
|
||||
|
||||
match serde_json::to_string(&pump_info) {
|
||||
Ok(state) => {
|
||||
let _ = board
|
||||
let _ = BOARD_ACCESS
|
||||
.get()
|
||||
.lock()
|
||||
.await
|
||||
.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);
|
||||
//TODO maybee not required for low level hal?
|
||||
Timer::after_millis(200).await;
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error publishing pump state {}", err);
|
||||
warn!("Error publishing pump state {}", err);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn publish_mppt_state(board: &mut MutexGuard<'_, HAL<'_>>) -> anyhow::Result<()> {
|
||||
let current = board.board_hal.get_mptt_current()?;
|
||||
let voltage = board.board_hal.get_mptt_voltage()?;
|
||||
async fn publish_mppt_state() -> anyhow::Result<()> {
|
||||
let board_hal = &mut BOARD_ACCESS.get().lock().await.board_hal;
|
||||
let current = board_hal.get_mptt_current().await?;
|
||||
let voltage = board_hal.get_mptt_voltage().await?;
|
||||
let solar_state = Solar {
|
||||
current_ma: current.as_milliamperes() as u32,
|
||||
voltage_ma: voltage.as_millivolts() as u32,
|
||||
@@ -896,35 +914,33 @@ fn publish_mppt_state(board: &mut MutexGuard<'_, HAL<'_>>) -> anyhow::Result<()>
|
||||
if let Ok(serialized_solar_state_bytes) =
|
||||
serde_json::to_string(&solar_state).map(|s| s.into_bytes())
|
||||
{
|
||||
let _ = board
|
||||
.board_hal
|
||||
let _ = board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/mppt", &serialized_solar_state_bytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn publish_battery_state(board: &mut MutexGuard<'_, HAL<'_>>) {
|
||||
async fn publish_battery_state() -> () {
|
||||
let board = BOARD_ACCESS.get().lock().await;
|
||||
let state = board.board_hal.get_battery_monitor().get_battery_state();
|
||||
if let Ok(serialized_battery_state_bytes) =
|
||||
serde_json::to_string(&state).map(|s| s.into_bytes())
|
||||
{
|
||||
let _ = board
|
||||
board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/battery", &serialized_battery_state_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
||||
async fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
||||
let delay = wait_type.blink_pattern();
|
||||
let mut led_count = 8;
|
||||
let mut pattern_step = 0;
|
||||
let delay_handle = Delay::new_default();
|
||||
loop {
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
update_charge_indicator(&mut board);
|
||||
|
||||
update_charge_indicator().await;
|
||||
let mut board = BOARD_ACCESS.get().lock().await;
|
||||
match wait_type {
|
||||
WaitType::MissingConfig => {
|
||||
// Keep existing behavior: circular filling pattern
|
||||
@@ -952,9 +968,9 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
||||
|
||||
board.board_hal.general_fault(true);
|
||||
drop(board);
|
||||
//cannot use shared delay as that is inside the mutex here
|
||||
delay_handle.delay_ms(delay);
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
|
||||
Timer::after_millis(delay).await;
|
||||
let mut board = BOARD_ACCESS.get().lock().await;
|
||||
board.board_hal.general_fault(false);
|
||||
|
||||
// Clear all LEDs
|
||||
@@ -962,17 +978,15 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
||||
let _ = board.board_hal.fault(i, false);
|
||||
}
|
||||
drop(board);
|
||||
delay_handle.delay_ms(delay);
|
||||
Timer::after_millis(delay).await;
|
||||
|
||||
if wait_type == WaitType::MqttConfig
|
||||
&& !STAY_ALIVE.load(Ordering::Relaxed)
|
||||
{
|
||||
if wait_type == WaitType::MqttConfig && !STAY_ALIVE.load(Ordering::Relaxed) {
|
||||
reboot_now.store(true, Ordering::Relaxed);
|
||||
}
|
||||
if reboot_now.load(Ordering::Relaxed) {
|
||||
//ensure clean http answer
|
||||
Delay::new_default().delay_ms(500);
|
||||
BOARD_ACCESS.lock().unwrap().board_hal.deep_sleep(1);
|
||||
Timer::after_millis(500).await;
|
||||
BOARD_ACCESS.get().lock().await.board_hal.deep_sleep(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -980,7 +994,7 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
||||
#[esp_hal_embassy::main]
|
||||
async fn main(spawner: Spawner) {
|
||||
// intialize embassy
|
||||
esp_log::info::logger::init_logger_from_env();
|
||||
logger::init_logger_from_env();
|
||||
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
|
||||
let peripherals = esp_hal::init(config);
|
||||
|
||||
@@ -991,26 +1005,23 @@ async fn main(spawner: Spawner) {
|
||||
|
||||
info!("Embassy initialized!");
|
||||
|
||||
let result = safe_main();
|
||||
let result = safe_main().await;
|
||||
match result {
|
||||
// this should not get triggered, safe_main should not return but go into deep sleep with sensible
|
||||
// timeout, this is just a fallback
|
||||
Ok(_) => {
|
||||
log::info!("Main app finished, restarting");
|
||||
BOARD_ACCESS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.set_restart_to_conf(false);
|
||||
BOARD_ACCESS.lock().unwrap().board_hal.deep_sleep(1);
|
||||
warn!("Main app finished, but should never do, restarting");
|
||||
let board = &mut BOARD_ACCESS.get().lock().await.board_hal;
|
||||
|
||||
board.get_esp().set_restart_to_conf(false);
|
||||
board.deep_sleep(1);
|
||||
}
|
||||
// if safe_main exists with an error, rollback to a known good ota version
|
||||
Err(err) => {
|
||||
log::info!("Failed main {}", err);
|
||||
error!("Failed main {}", err);
|
||||
//TODO
|
||||
//let _rollback_successful = rollback_and_reboot();
|
||||
panic!("Failed to rollback :(");
|
||||
//panic!("Failed to rollback :(");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user