Merge pull request 'Part 1 of V3 extraction in preperation of v4 and v3 software merge' (#16) from boardhal_abstract into develop

Reviewed-on: #16
This commit is contained in:
EmpirePhoenix 2025-06-17 22:22:09 +02:00
commit e24dc77fa9
26 changed files with 1722 additions and 985 deletions

View File

@ -5,8 +5,8 @@ target = "riscv32imac-esp-espidf"
[target.riscv32imac-esp-espidf]
linker = "ldproxy"
#runner = "espflash flash --monitor --baud 921600 --partition-table partitions.csv -b no-reset" # Select this runner in case of usb ttl
#runner = "espflash flash --monitor --baud 921600 --flash-size 16mb --partition-table partitions.csv"
runner = "cargo runner"
runner = "espflash flash --monitor --baud 921600 --flash-size 16mb --partition-table partitions.csv"
#runner = "cargo runner"
#runner = "espflash flash --monitor --partition-table partitions.csv -b no-reset" # create upgrade image file for webupload

View File

@ -88,6 +88,7 @@ text-template = "0.1.0"
strum_macros = "0.27.0"
esp-ota = { version = "0.2.2", features = ["log"] }
unit-enum = "1.4.1"
pca9535 = { version = "2.0.0", features = ["std"] }
[patch.crates-io]

View File

@ -1,6 +1,5 @@
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use crate::plant_state::PlantWateringMode;
use crate::PLANT_COUNT;
@ -13,6 +12,7 @@ pub struct NetworkConfig {
pub password: Option<heapless::String<64>>,
pub mqtt_url: Option<heapless::String<128>>,
pub base_topic: Option<heapless::String<64>>,
pub max_wait: u32
}
impl Default for NetworkConfig {
fn default() -> Self {
@ -22,6 +22,7 @@ impl Default for NetworkConfig {
password: None,
mqtt_url: None,
base_topic: None,
max_wait: 10000,
}
}
}
@ -72,9 +73,31 @@ impl Default for TankConfig {
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub enum BatteryBoardVersion{
#[default]
Disabled,
BQ34Z100G1,
WchI2cSlave
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub enum BoardVersion{
#[default]
INITIAL,
V3,
V4
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub struct BoardHardware {
pub board: BoardVersion,
pub battery: BatteryBoardVersion,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
#[serde(default)]
pub struct PlantControllerConfig {
pub hardware: BoardHardware,
pub network: NetworkConfig,
pub tank: TankConfig,
pub night_lamp: NightLampConfig,

View File

@ -1,8 +1,4 @@
use std::{
fmt::Display,
sync::{atomic::AtomicBool, Arc, Mutex},
};
use std::sync::MutexGuard;
use crate::webserver::webserver::httpd;
use anyhow::bail;
use chrono::{DateTime, Datelike, Timelike, Utc};
use chrono_tz::Tz;
@ -18,19 +14,24 @@ use esp_idf_sys::{
use esp_ota::{mark_app_valid, rollback_and_reboot};
use log::{log, LogMessage};
use once_cell::sync::Lazy;
use plant_hal::{PlantCtrlBoard, PlantHal, PLANT_COUNT};
use plant_hal::{PlantHal, PLANT_COUNT};
use serde::{Deserialize, Serialize};
use crate::{config::PlantControllerConfig, webserver::webserver::httpd};
use std::sync::MutexGuard;
use std::{
fmt::Display,
sync::{atomic::AtomicBool, Arc, Mutex},
};
mod config;
mod log;
pub mod plant_hal;
mod plant_state;
mod tank;
use crate::plant_hal::{BatteryInteraction, BoardHal, BoardInteraction, HAL};
use plant_state::PlantState;
use tank::*;
pub static BOARD_ACCESS: Lazy<Mutex<PlantCtrlBoard>> = Lazy::new(|| PlantHal::create().unwrap());
pub static BOARD_ACCESS: Lazy<Mutex<HAL>> = Lazy::new(|| PlantHal::create().unwrap());
pub static STAY_ALIVE: Lazy<AtomicBool> = Lazy::new(|| AtomicBool::new(false));
mod webserver {
@ -112,7 +113,6 @@ fn safe_main() -> anyhow::Result<()> {
esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE
)
}
println!("Startup Rust");
let mut to_config = false;
@ -150,20 +150,9 @@ fn safe_main() -> anyhow::Result<()> {
};
log(LogMessage::PartitionState, 0, 0, "", ota_state_string);
let mut board: std::sync::MutexGuard<'_, PlantCtrlBoard<'_>> = BOARD_ACCESS.lock().unwrap();
let mut board = BOARD_ACCESS.lock().expect("Could not lock board no other lock should be able to exist during startup!");
board.general_fault(false);
log(LogMessage::MountingFilesystem, 0, 0, "", "");
board.mount_file_system()?;
let free_space = board.file_system_size()?;
log(
LogMessage::FilesystemMount,
free_space.free_size as u32,
free_space.total_size as u32,
&free_space.used_size.to_string(),
"",
);
let cur = board
.get_rtc_time()
.or_else(|err| {
@ -183,7 +172,12 @@ fn safe_main() -> anyhow::Result<()> {
}
println!("cur is {}", cur);
board.update_charge_indicator();
match board.battery_monitor.average_current_milli_ampere() {
Ok(charging) => {
board.set_charge_indicator(charging > 20)
}
Err(_) => {}
}
if board.get_restart_to_conf() {
log(LogMessage::ConfigModeSoftwareOverride, 0, 0, "", "");
@ -214,28 +208,22 @@ fn safe_main() -> anyhow::Result<()> {
}
}
let config: PlantControllerConfig = match board.get_config() {
Ok(valid) => valid,
Err(err) => {
log(
LogMessage::ConfigModeMissingConfig,
0,
0,
"",
&err.to_string(),
);
//config upload will trigger reboot!
let _ = board.wifi_ap(None);
match board.board_hal {
BoardHal::Initial { .. } => {
//config upload will trigger reboot and then switch to selected board_hal
let _ = board.wifi_ap();
drop(board);
let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd(reboot_now.clone());
wait_infinity(WaitType::MissingConfig, reboot_now.clone());
}
};
_ => {}
}
println!("attempting to connect wifi");
let network_mode = if config.network.ssid.is_some() {
try_connect_wifi_sntp_mqtt(&mut board, &config)
let network_mode = if board.config.network.ssid.is_some() {
try_connect_wifi_sntp_mqtt(&mut board)
} else {
println!("No wifi configured");
NetworkMode::OFFLINE
@ -243,7 +231,7 @@ fn safe_main() -> anyhow::Result<()> {
if matches!(network_mode, NetworkMode::OFFLINE) && 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())) {
match board.wifi_ap() {
Ok(_) => {
println!("Started ap, continuing")
}
@ -251,7 +239,7 @@ fn safe_main() -> anyhow::Result<()> {
}
}
let timezone = match &config.timezone {
let timezone = match & board.config.timezone {
Some(tz_str) => tz_str.parse::<Tz>().unwrap_or_else(|_| {
println!("Invalid timezone '{}', falling back to UTC", tz_str);
UTC
@ -268,8 +256,8 @@ fn safe_main() -> anyhow::Result<()> {
);
if let NetworkMode::WIFI { ref ip_address, .. } = network_mode {
publish_firmware_info(version, address, ota_state_string, &mut board, &config, &ip_address, timezone_time);
publish_battery_state(&mut board, &config);
publish_firmware_info(version, address, ota_state_string, &mut board, &ip_address, timezone_time);
publish_battery_state(&mut board);
}
@ -295,10 +283,10 @@ fn safe_main() -> anyhow::Result<()> {
let dry_run = false;
let tank_state = determine_tank_state(&mut board, &config);
let tank_state = determine_tank_state(&mut board);
if tank_state.is_enabled() {
if let Some(err) = tank_state.got_error(&config.tank) {
if let Some(err) = tank_state.got_error(&board.config.tank) {
match err {
TankError::SensorDisabled => { /* unreachable */ }
TankError::SensorMissing(raw_value_mv) => log(
@ -321,7 +309,7 @@ fn safe_main() -> anyhow::Result<()> {
}
// disabled cannot trigger this because of wrapping if is_enabled
board.general_fault(true);
} else if tank_state.warn_level(&config.tank).is_ok_and(|warn| warn) {
} else if tank_state.warn_level(&board.config.tank).is_ok_and(|warn| warn) {
log(LogMessage::TankWaterLevelLow, 0, 0, "", "");
board.general_fault(true);
}
@ -336,15 +324,15 @@ fn safe_main() -> anyhow::Result<()> {
}
}
publish_tank_state(&mut board, &config, &tank_state, &water_temp);
publish_tank_state(&mut board, &tank_state, &water_temp);
let plantstate: [PlantState; PLANT_COUNT] =
core::array::from_fn(|i| PlantState::read_hardware_state(i, &mut board, &config.plants[i]));
publish_plant_states(&mut board, &config, &timezone_time, &plantstate);
core::array::from_fn(|i| PlantState::read_hardware_state(i, &mut board));
publish_plant_states(&mut board, &timezone_time, &plantstate);
let pump_required = plantstate
.iter()
.zip(&config.plants)
.zip(&board.config.plants)
.any(|(it, conf)| it.needs_to_be_watered(conf, &timezone_time))
&& !water_frozen;
if pump_required {
@ -352,7 +340,7 @@ fn safe_main() -> anyhow::Result<()> {
if !dry_run {
board.any_pump(true)?; // enables main power output, eg for a central pump with valve setup or a main water valve for the risk affine
}
for (plant_id, (state, plant_config)) in plantstate.iter().zip(&config.plants).enumerate() {
for (plant_id, (state, plant_config)) in plantstate.iter().zip(&board.config.plants.clone()).enumerate() {
if state.needs_to_be_watered(plant_config, &timezone_time) {
let pump_count = board.consecutive_pump_count(plant_id) + 1;
board.store_consecutive_pump_count(plant_id, pump_count);
@ -361,12 +349,12 @@ fn safe_main() -> anyhow::Result<()> {
if pump_ineffective {
log(
LogMessage::ConsecutivePumpCountLimit,
pump_count as u32,
pump_count,
plant_config.max_consecutive_pump_count as u32,
&(plant_id+1).to_string(),
"",
);
board.fault(plant_id, true);
board.fault(plant_id, true)?;
}
log(
LogMessage::PumpPlant,
@ -379,14 +367,14 @@ fn safe_main() -> anyhow::Result<()> {
board.last_pump_time(plant_id);
//state.active = true;
pump_info(&mut board, &config, plant_id, true, pump_ineffective);
pump_info(&mut board, plant_id, true, pump_ineffective);
if !dry_run {
board.pump(plant_id, true)?;
Delay::new_default().delay_ms(1000 * plant_config.pump_time_s as u32);
board.pump(plant_id, false)?;
}
pump_info(&mut board, &config, 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
@ -400,29 +388,29 @@ fn safe_main() -> anyhow::Result<()> {
}
let is_day = board.is_day();
let state_of_charge = board.state_charge_percent().unwrap_or(0);
let state_of_charge = board.battery_monitor.state_charge_percent().unwrap_or(0);
let mut light_state = LightState {
enabled: config.night_lamp.enabled,
enabled: board.config.night_lamp.enabled,
..Default::default()
};
if light_state.enabled {
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,
board.config.night_lamp.night_lamp_hour_start,
board.config.night_lamp.night_lamp_hour_end,
);
if state_of_charge < config.night_lamp.low_soc_cutoff {
if state_of_charge < board.config.night_lamp.low_soc_cutoff {
board.set_low_voltage_in_cycle();
} else if state_of_charge > config.night_lamp.low_soc_restore {
} else if state_of_charge > board.config.night_lamp.low_soc_restore {
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 board.config.night_lamp.night_lamp_only_when_dark {
if !light_state.is_day {
if light_state.battery_low {
board.light(false)?;
@ -447,7 +435,7 @@ fn safe_main() -> anyhow::Result<()> {
match serde_json::to_string(&light_state) {
Ok(state) => {
let _ = board.mqtt_publish(&config, "/light", state.as_bytes());
let _ = board.mqtt_publish( "/light", state.as_bytes());
}
Err(err) => {
println!("Error publishing lightstate {}", err);
@ -455,16 +443,16 @@ fn safe_main() -> anyhow::Result<()> {
};
let deep_sleep_duration_minutes: u32 = if state_of_charge < 10 {
let _ = board.mqtt_publish(&config, "/deepsleep", "low Volt 12h".as_bytes());
let _ = board.mqtt_publish( "/deepsleep", "low Volt 12h".as_bytes());
12 * 60
} else if is_day {
let _ = board.mqtt_publish(&config, "/deepsleep", "normal 20m".as_bytes());
let _ = board.mqtt_publish( "/deepsleep", "normal 20m".as_bytes());
20
} else {
let _ = board.mqtt_publish(&config, "/deepsleep", "night 1h".as_bytes());
let _ = board.mqtt_publish( "/deepsleep", "night 1h".as_bytes());
60
};
let _ = board.mqtt_publish(&config, "/state", "sleep".as_bytes());
let _ = board.mqtt_publish( "/state", "sleep".as_bytes());
mark_app_valid();
@ -484,7 +472,7 @@ fn safe_main() -> anyhow::Result<()> {
board.deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64);
}
fn obtain_tank_temperature(board: &mut MutexGuard<PlantCtrlBoard>) -> anyhow::Result<f32> {
fn obtain_tank_temperature(board: &mut MutexGuard<HAL>) -> anyhow::Result<f32> {
//multisample should be moved to water_temperature_c
let mut attempt = 1;
let water_temp: Result<f32, anyhow::Error> = loop {
@ -506,10 +494,10 @@ fn obtain_tank_temperature(board: &mut MutexGuard<PlantCtrlBoard>) -> anyhow::Re
water_temp
}
fn publish_tank_state(board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantControllerConfig, tank_state: &TankState, water_temp: &anyhow::Result<f32>) {
match serde_json::to_string(&tank_state.as_mqtt_info(&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.config.tank, water_temp)) {
Ok(state) => {
let _ = board.mqtt_publish(&config, "/water", state.as_bytes());
let _ = board.mqtt_publish("/water", state.as_bytes());
}
Err(err) => {
println!("Error publishing tankstate {}", err);
@ -517,12 +505,12 @@ fn publish_tank_state(board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantCont
};
}
fn publish_plant_states(board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantControllerConfig, timezone_time: &DateTime<Tz>, plantstate: &[PlantState; 8]) {
for (plant_id, (plant_state, plant_conf)) in plantstate.iter().zip(&config.plants).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.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.mqtt_publish(&config, &plant_topic, state.as_bytes());
let _ = board.mqtt_publish(&plant_topic, state.as_bytes());
//reduce speed as else messages will be dropped
Delay::new_default().delay_ms(200);
}
@ -533,34 +521,27 @@ fn publish_plant_states(board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantCo
}
}
fn publish_firmware_info(version: VersionInfo, address: u32, ota_state_string: &str, board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantControllerConfig, ip_address: &String, timezone_time: DateTime<Tz>) {
let _ = board.mqtt_publish(&config, "/firmware/address", ip_address.as_bytes());
let _ = board.mqtt_publish(&config, "/firmware/githash", version.git_hash.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.mqtt_publish("/firmware/address", ip_address.as_bytes());
let _ = board.mqtt_publish( "/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( "/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());
let _ = board.mqtt_publish( "/state", "online".as_bytes());
}
fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantControllerConfig) -> NetworkMode{
match board.wifi(
config.network.ssid.clone().unwrap(),
config.network.password.clone(),
10000,
) {
fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode{
match board.wifi() {
Ok(ip_info) => {
let sntp_mode: SntpMode = match board.sntp(1000 * 10) {
Ok(new_time) => {
@ -574,8 +555,8 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<PlantCtrlBoard>, config: &P
SntpMode::OFFLINE
}
};
let mqtt_connected = if let Some(_) = config.network.mqtt_url {
match board.mqtt(&config) {
let mqtt_connected = if let Some(_) = board.config.network.mqtt_url {
match board.mqtt() {
Ok(_) => {
println!("Mqtt connection ready");
true
@ -603,7 +584,7 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<PlantCtrlBoard>, config: &P
}
//TODO clean this up? better state
fn pump_info(board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantControllerConfig, 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
@ -611,7 +592,7 @@ fn pump_info(board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantControllerCon
let pump_topic = format!("/pump{}", plant_id + 1);
match serde_json::to_string(&pump_info) {
Ok(state) => {
let _ = board.mqtt_publish(config, &pump_topic, state.as_bytes());
let _ = board.mqtt_publish(&pump_topic, state.as_bytes());
//reduce speed as else messages will be dropped
Delay::new_default().delay_ms(200);
}
@ -622,18 +603,10 @@ fn pump_info(board: &mut MutexGuard<PlantCtrlBoard>, config: &PlantControllerCon
}
fn publish_battery_state(
board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>,
config: &PlantControllerConfig,
board: &mut MutexGuard<'_, HAL<'_>>
) {
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);
}
};
let state = board.get_battery_state();
let _ = board.mqtt_publish( "/battery", state.as_bytes());
}
fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
@ -644,28 +617,30 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
loop {
unsafe {
let mut lock = BOARD_ACCESS.lock().unwrap();
lock.update_charge_indicator();
if let Ok(charging) = lock.battery_monitor.average_current_milli_ampere() {
lock.set_charge_indicator(charging > 20)
}
match wait_type {
WaitType::MissingConfig => {
// Keep existing behavior: circular filling pattern
led_count %= 8;
led_count += 1;
for i in 0..8 {
lock.fault(i, i < led_count);
let _ = lock.fault(i, i < led_count);
}
}
WaitType::ConfigButton => {
// Alternating pattern: 1010 1010 -> 0101 0101
pattern_step = (pattern_step + 1) % 2;
for i in 0..8 {
lock.fault(i, (i + pattern_step) % 2 == 0);
let _ = lock.fault(i, (i + pattern_step) % 2 == 0);
}
}
WaitType::MqttConfig => {
// Moving dot pattern
pattern_step = (pattern_step + 1) % 8;
for i in 0..8 {
lock.fault(i, i == pattern_step);
let _ = lock.fault(i, i == pattern_step);
}
}
}
@ -678,7 +653,7 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
// Clear all LEDs
for i in 0..8 {
lock.fault(i, false);
let _ = lock.fault(i, false);
}
drop(lock);
vTaskDelay(delay);

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,7 @@ use chrono_tz::Tz;
use serde::{Deserialize, Serialize};
use crate::{config::PlantConfig, in_time_range, plant_hal};
use crate::plant_hal::BoardInteraction;
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
@ -113,15 +114,14 @@ fn map_range_moisture(
impl PlantState {
pub fn read_hardware_state(
plant_id: usize,
board: &mut plant_hal::PlantCtrlBoard,
config: &PlantConfig,
board: &mut plant_hal::HAL
) -> Self {
let sensor_a = if config.sensor_a {
let sensor_a = if board.config.plants[plant_id].sensor_a {
match board.measure_moisture_hz(plant_id, plant_hal::Sensor::A) {
Ok(raw) => match map_range_moisture(
raw,
config.moisture_sensor_min_frequency,
config.moisture_sensor_max_frequency,
board.config.plants[plant_id].moisture_sensor_min_frequency,
board.config.plants[plant_id].moisture_sensor_max_frequency,
) {
Ok(moisture_percent) => MoistureSensorState::MoistureValue {
raw_hz: raw,
@ -137,12 +137,12 @@ impl PlantState {
MoistureSensorState::Disabled
};
let sensor_b = if config.sensor_b {
let sensor_b = if board.config.plants[plant_id].sensor_b {
match board.measure_moisture_hz(plant_id, plant_hal::Sensor::B) {
Ok(raw) => match map_range_moisture(
raw,
config.moisture_sensor_min_frequency,
config.moisture_sensor_max_frequency,
board.config.plants[plant_id].moisture_sensor_min_frequency,
board.config.plants[plant_id].moisture_sensor_max_frequency,
) {
Ok(moisture_percent) => MoistureSensorState::MoistureValue {
raw_hz: raw,
@ -169,7 +169,7 @@ impl PlantState {
},
};
if state.is_err() {
board.fault(plant_id, true);
let _ = board.fault(plant_id, true);
}
state
}

View File

@ -1,9 +1,7 @@
use serde::Serialize;
use crate::{
config::{PlantControllerConfig, TankConfig},
plant_hal::PlantCtrlBoard,
};
use crate::config::TankConfig;
use crate::plant_hal::{BoardInteraction, HAL};
const OPEN_TANK_VOLTAGE: f32 = 3.0;
pub const WATER_FROZEN_THRESH: f32 = 4.0;
@ -158,10 +156,9 @@ impl TankState {
}
pub fn determine_tank_state(
board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>,
config: &PlantControllerConfig,
board: &mut std::sync::MutexGuard<'_, HAL<'_>>
) -> TankState {
if config.tank.tank_sensor_enabled {
if board.config.tank.tank_sensor_enabled {
match board.tank_sensor_voltage() {
Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv),
Err(err) => TankState::Error(TankError::BoardError(err.to_string())),

View File

@ -8,7 +8,6 @@ use anyhow::bail;
use chrono::DateTime;
use core::result::Result::Ok;
use embedded_svc::http::Method;
use esp_idf_hal::delay::Delay;
use esp_idf_svc::http::server::{Configuration, EspHttpConnection, EspHttpServer, Request};
use esp_idf_sys::{settimeofday, timeval, vTaskDelay};
use esp_ota::OtaUpdate;
@ -21,6 +20,7 @@ use std::{
use url::Url;
use crate::config::PlantControllerConfig;
use crate::plant_hal::BoardInteraction;
use crate::plant_state::MoistureSensorState;
#[derive(Serialize, Debug)]
@ -114,11 +114,9 @@ fn get_timezones(
fn get_live_moisture(
_request: &mut Request<&mut EspHttpConnection>,
) -> Result<Option<std::string::String>, anyhow::Error> {
let mut board = BOARD_ACCESS.lock().unwrap();
let config = board.get_config().unwrap();
let mut board = BOARD_ACCESS.lock().expect("Should never fail");
let plant_state = Vec::from_iter(
(0..PLANT_COUNT).map(|i| PlantState::read_hardware_state(i, &mut board, &config.plants[i])),
(0..PLANT_COUNT).map(|i| PlantState::read_hardware_state(i, &mut board)),
);
let a = Vec::from_iter(
plant_state
@ -159,11 +157,8 @@ fn get_live_moisture(
fn get_config(
_request: &mut Request<&mut EspHttpConnection>,
) -> Result<Option<std::string::String>, anyhow::Error> {
let mut board = BOARD_ACCESS.lock().unwrap();
let json = match board.get_config() {
Ok(config) => serde_json::to_string(&config)?,
Err(_) => serde_json::to_string(&PlantControllerConfig::default())?,
};
let board = BOARD_ACCESS.lock().expect("Should never fail");
let json = serde_json::to_string(&board.config)?;
anyhow::Ok(Some(json))
}
@ -193,7 +188,7 @@ fn get_backup_config(
fn backup_info(
_request: &mut Request<&mut EspHttpConnection>,
) -> Result<Option<std::string::String>, anyhow::Error> {
let mut board = BOARD_ACCESS.lock().unwrap();
let mut board = BOARD_ACCESS.lock().expect("Should never fail");
let header = board.get_backup_info();
let json = match header {
Ok(h) => {
@ -221,8 +216,11 @@ fn set_config(
) -> Result<Option<std::string::String>, anyhow::Error> {
let all = read_up_to_bytes_from_request(request, Some(3072))?;
let config: PlantControllerConfig = serde_json::from_slice(&all)?;
let mut board = BOARD_ACCESS.lock().unwrap();
board.set_config(&config)?;
board.esp.set_config(&config)?;
board.config = config;
anyhow::Ok(Some("saved".to_owned()))
}
@ -268,12 +266,11 @@ fn tank_info(
_request: &mut Request<&mut EspHttpConnection>,
) -> Result<Option<std::string::String>, anyhow::Error> {
let mut board = BOARD_ACCESS.lock().unwrap();
let config = board.get_config()?;
let tank_info = determine_tank_state(&mut board, &config);
let tank_info = determine_tank_state(&mut board);
//should be multsampled
let water_temp = board.water_temperature_c();
Ok(Some(serde_json::to_string(
&tank_info.as_mqtt_info(&config.tank, &water_temp),
&tank_info.as_mqtt_info(&board.config.tank, &water_temp),
)?))
}
@ -302,8 +299,8 @@ fn wifi_scan(
fn list_files(
_request: &mut Request<&mut EspHttpConnection>,
) -> Result<Option<std::string::String>, anyhow::Error> {
let board = BOARD_ACCESS.lock().unwrap();
let result = board.list_files();
let board = BOARD_ACCESS.lock().expect("It should be possible to lock the board for exclusive fs access");
let result = board.esp.list_files();
let file_list_json = serde_json::to_string(&result)?;
anyhow::Ok(Some(file_list_json))
}
@ -328,7 +325,7 @@ fn ota(
let iter = (total_read / 1024) % 8;
if iter != lastiter {
for i in 0..PLANT_COUNT {
board.fault(i, iter == i);
let _ = board.fault(i, iter == i);
}
lastiter = iter;
}
@ -351,45 +348,6 @@ fn ota(
anyhow::Ok(None)
}
fn flash_bq(filename: &str, dryrun: bool) -> anyhow::Result<()> {
let mut board = BOARD_ACCESS.lock().unwrap();
let mut toggle = true;
let delay = Delay::new(1);
let file_handle = board.get_file_handle(filename, false)?;
let mut reader = std::io::BufRead::lines(std::io::BufReader::with_capacity(512, file_handle));
let mut line = 0;
loop {
board.general_fault(toggle);
toggle = !toggle;
delay.delay_us(2);
line += 1;
match reader.next() {
Some(next) => {
let input = next?;
println!("flashing bq34z100 dryrun:{dryrun} line {line} payload: {input}");
match board.flash_bq34_z100(&input, dryrun) {
Ok(_) => {
println!("ok")
}
Err(err) => {
bail!(
"Error flashing bq34z100 in dryrun: {dryrun} line: {line} error: {err}"
)
}
}
}
None => break,
}
}
println!("Finished flashing file {line} lines processed");
board.general_fault(false);
anyhow::Ok(())
}
fn query_param(uri: &str, param_name: &str) -> Option<std::string::String> {
println!("{uri} get {param_name}");
let parsed = Url::parse(&format!("http://127.0.0.1/{uri}")).unwrap();
@ -532,6 +490,7 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let file_handle = BOARD_ACCESS
.lock()
.unwrap()
.esp
.get_file_handle(&filename, false);
match file_handle {
Ok(mut file_handle) => {
@ -567,8 +526,8 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
server
.fn_handler("/file", Method::Post, move |mut request| {
let filename = query_param(request.uri(), "filename").unwrap();
let lock = BOARD_ACCESS.lock().unwrap();
let file_handle = lock.get_file_handle(&filename, true);
let mut lock = BOARD_ACCESS.lock().unwrap();
let file_handle = lock.esp.get_file_handle(&filename, true);
match file_handle {
//TODO get free filesystem size, check against during write if not to large
Ok(mut file_handle) => {
@ -580,7 +539,7 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let iter = (total_read / 1024) % 8;
if iter != lastiter {
for i in 0..PLANT_COUNT {
lock.fault(i, iter == i);
let _ = lock.fault(i, iter == i);
}
lastiter = iter;
}
@ -612,7 +571,7 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let filename = query_param(request.uri(), "filename").unwrap();
let copy = filename.clone();
let board = BOARD_ACCESS.lock().unwrap();
match board.delete_file(&filename) {
match board.esp.delete_file(&filename) {
Ok(_) => {
let info = format!("Deleted file {copy}");
cors_response(request, 200, &info)?;
@ -630,35 +589,6 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
cors_response(request, 200, "")
})
.unwrap();
server
.fn_handler("/flashbattery", Method::Post, move |request| {
let filename = query_param(request.uri(),"filename").unwrap();
let dryrun = true;
match flash_bq(&filename, false) {
Ok(_) => {
if !dryrun {
match flash_bq(&filename, true) {
Ok(_) => {
cors_response(request, 200, "Sucessfully flashed bq34z100")?;
},
Err(err) => {
let info = format!("Could not flash bq34z100, could be bricked now! {filename} {err:?}");
cors_response(request, 500, &info)?;
},
}
} else {
cors_response(request, 200, "Sucessfully processed bq34z100")?;
}
},
Err(err) => {
let info = format!("Could not process firmware file for, bq34z100, refusing to flash! {filename} {err:?}");
cors_response(request, 500, &info)?;
},
};
anyhow::Ok(())
})
.unwrap();
unsafe { vTaskDelay(1) };
server
.fn_handler("/", Method::Get, move |request| {

View File

@ -1,6 +1,6 @@
interface LogArray extends Array<LogEntry>{}
export interface LogArray extends Array<LogEntry>{}
interface LogEntry {
export interface LogEntry {
timestamp: string,
message_id: number,
a: number,
@ -9,27 +9,28 @@ interface LogEntry {
txt_long: string
}
interface LogLocalisation extends Array<LogLocalisationEntry>{}
export interface LogLocalisation extends Array<LogLocalisationEntry>{}
interface LogLocalisationEntry {
export interface LogLocalisationEntry {
msg_type: string,
message: string
}
interface BackupHeader {
export interface BackupHeader {
timestamp: string,
size: number
}
interface NetworkConfig {
export interface NetworkConfig {
ap_ssid: string,
ssid: string,
password: string,
mqtt_url: string,
base_topic: string
base_topic: string,
max_wait: number
}
interface FileList {
export interface FileList {
total: number,
used: number,
files: FileInfo[],
@ -37,12 +38,12 @@ interface FileList {
iter_error: string,
}
interface FileInfo{
export interface FileInfo{
filename: string,
size: number,
}
interface NightLampConfig {
export interface NightLampConfig {
enabled: boolean,
night_lamp_hour_start: number,
night_lamp_hour_end: number,
@ -51,11 +52,11 @@ interface NightLampConfig {
low_soc_restore: number
}
interface NightLampCommand {
export interface NightLampCommand {
active: boolean
}
interface TankConfig {
export interface TankConfig {
tank_sensor_enabled: boolean,
tank_allow_pumping_if_sensor_error: boolean,
tank_useable_ml: number,
@ -64,7 +65,26 @@ interface TankConfig {
tank_full_percent: number,
}
interface PlantControllerConfig {
export enum BatteryBoardVersion {
Disabled = "Disabled",
BQ34Z100G1 = "BQ34Z100G1",
WchI2cSlave = "WchI2cSlave"
}
export enum BoardVersion{
INITIAL = "INITIAL",
V3 = "V3",
V4 = "V4"
}
export interface BoardHardware {
board: BoardVersion,
battery: BatteryBoardVersion,
}
export interface PlantControllerConfig {
hardware: BoardHardware,
network: NetworkConfig,
tank: TankConfig,
night_lamp: NightLampConfig,
@ -72,7 +92,7 @@ interface PlantControllerConfig {
timezone?: string,
}
interface PlantConfig {
export interface PlantConfig {
mode: string,
target_moisture: number,
pump_time_s: number,
@ -88,35 +108,35 @@ interface PlantConfig {
}
interface SSIDList {
export interface SSIDList {
ssids: [string]
}
interface TestPump {
export interface TestPump {
pump: number
}
interface SetTime {
export interface SetTime {
time: string
}
interface GetTime {
export interface GetTime {
rtc: string,
native: string
}
interface Moistures {
export interface Moistures {
moisture_a: [string],
moisture_b: [string],
}
interface VersionInfo {
export interface VersionInfo {
git_hash: string,
build_time: string,
partition: string
}
interface BatteryState {
export interface BatteryState {
temperature: string
voltage_milli_volt: string,
current_milli_ampere: string,
@ -127,7 +147,7 @@ interface BatteryState {
state_of_health: string
}
interface TankInfo {
export interface TankInfo {
/// is there enough water in the tank
enough_water: boolean,
/// warning that water needs to be refilled soon
@ -145,4 +165,4 @@ interface TankInfo {
/// water temperature
water_temp: number | null,
temp_sensor_error: string | null
}
}

View File

@ -1,4 +1,5 @@
import { Controller } from "./main";
import {BatteryState} from "./api";
export class BatteryView{
voltage_milli_volt: HTMLSpanElement;

View File

@ -1,5 +1,5 @@
import {Controller} from "./main";
import {FileInfo, FileList} from "./api";
const regex = /[^a-zA-Z0-9_.]/g;
function sanitize(str:string){

View File

@ -0,0 +1,20 @@
<style>
.boardkey{
min-width: 200px;
}
.boardvalue{
flex-grow: 1;
}
</style>
<div class="subtitle">Hardware:</div>
<div class="flexcontainer">
<div class="boardkey">BoardRevision</div>
<select class="boardvalue" id="hardware_board_value">
</select>
</div>
<div class="flexcontainer" style="text-decoration-line: line-through;">
<div class="boardkey">BatteryMonitor</div>
<select class="boardvalue" id="hardware_battery_value">
</select>
</div>

View File

@ -0,0 +1,45 @@
import { Controller } from "./main";
import {BatteryBoardVersion, BoardHardware, BoardVersion} from "./api";
export class HardwareConfigView {
private readonly hardware_board_value: HTMLSelectElement;
private readonly hardware_battery_value: HTMLSelectElement;
constructor(controller:Controller){
(document.getElementById("hardwareview") as HTMLElement).innerHTML = require('./hardware.html') as string;
this.hardware_board_value = document.getElementById("hardware_board_value") as HTMLSelectElement;
this.hardware_board_value.onchange = controller.configChanged
Object.keys(BoardVersion).forEach(version => {
let option = document.createElement("option");
if (version == BoardVersion.INITIAL.toString()){
option.selected = true
}
option.innerText = version.toString();
this.hardware_board_value.appendChild(option);
})
this.hardware_battery_value = document.getElementById("hardware_battery_value") as HTMLSelectElement;
this.hardware_battery_value.onchange = controller.configChanged
Object.keys(BatteryBoardVersion).forEach(version => {
let option = document.createElement("option");
if (version == BatteryBoardVersion.Disabled.toString()){
option.selected = true
}
option.innerText = version.toString();
this.hardware_battery_value.appendChild(option);
})
}
setConfig(hardware: BoardHardware) {
this.hardware_board_value.value = hardware.board.toString()
this.hardware_battery_value.value = hardware.battery.toString()
}
getConfig(): BoardHardware {
return {
board : BoardVersion[this.hardware_board_value.value as keyof typeof BoardVersion],
battery : BatteryBoardVersion[this.hardware_battery_value.value as keyof typeof BatteryBoardVersion],
}
}
}

View File

@ -1,4 +1,5 @@
import { Controller } from "./main";
import {LogArray, LogLocalisation} from "./api";
export class LogView {
private readonly logpanel: HTMLElement;

View File

@ -138,6 +138,10 @@
<div class="container-xl">
<div style="display:flex; flex-wrap: wrap;">
<div id="hardwareview" class="subcontainer"></div>
</div>
<div style="display:flex; flex-wrap: wrap;">
<div id="firmwareview" class="subcontainer">
</div>

View File

@ -17,6 +17,19 @@ import { OTAView } from "./ota";
import { BatteryView } from "./batteryview";
import { FileView } from './fileview';
import { LogView } from './log';
import {HardwareConfigView} from "./hardware";
import {
BackupHeader,
BatteryState,
GetTime, LogArray, LogLocalisation,
Moistures,
NightLampCommand,
PlantControllerConfig,
SetTime, SSIDList, TankInfo,
TestPump,
VersionInfo,
FileList
} from "./api";
export class Controller {
loadTankInfo() : Promise<void> {
@ -66,7 +79,7 @@ export class Controller {
}
populateTimezones(): Promise<void> {
return fetch('/timezones')
return fetch(PUBLIC_URL+'/timezones')
.then(response => response.json())
.then(json => json as string[])
.then(timezones => {
@ -268,6 +281,12 @@ export class Controller {
}
}
selfTest(){
fetch(PUBLIC_URL + "/boardtest", {
method: "POST"
})
}
testNightLamp(active: boolean){
var body: NightLampCommand = {
active: active
@ -313,6 +332,7 @@ export class Controller {
getConfig(): PlantControllerConfig {
return {
hardware: controller.hardwareView.getConfig(),
network: controller.networkView.getConfig(),
tank: controller.tankView.getConfig(),
night_lamp: controller.nightLampView.getConfig(),
@ -360,6 +380,7 @@ export class Controller {
this.nightLampView.setConfig(current.night_lamp);
this.plantViews.setConfig(current.plants);
this.timeView.setTimeZone(current.timezone);
this.hardwareView.setConfig(current.hardware);
}
measure_moisture() {
@ -437,6 +458,7 @@ export class Controller {
readonly timeView: TimeView;
readonly plantViews: PlantViews;
readonly networkView: NetworkConfigView;
readonly hardwareView: HardwareConfigView;
readonly tankView: TankConfigView;
readonly nightLampView: NightLampView;
readonly submitView: SubmitView;
@ -457,6 +479,7 @@ export class Controller {
this.progressview = new ProgressView(this)
this.fileview = new FileView(this)
this.logView = new LogView(this)
this.hardwareView = new HardwareConfigView(this)
this.rebootBtn = document.getElementById("reboot") as HTMLButtonElement
this.rebootBtn.onclick = () => {
controller.reboot();
@ -466,6 +489,10 @@ export class Controller {
controller.exit();
}
}
selftest() {
}
}
const controller = new Controller();
controller.progressview.removeProgress("rebooting");
@ -505,9 +532,6 @@ executeTasksSequentially().then(r => {
controller.progressview.removeProgress("initial")
});
controller.progressview.removeProgress("rebooting");
window.addEventListener("beforeunload", (event) => {

View File

@ -42,6 +42,11 @@
</datalist>
<input class="basicnetworkkeyssid2" type="button" id="scan" value="Scan">
</div>
<div class="flexcontainer">
<label class="basicnetworkkey" for="max_wait">Max wait:</label>
<input class="basicnetworkvalue" type="number" id="max_wait">
</div>
<div class="flexcontainer">
<label class="basicnetworkkey" for="ssid">Password:</label>

View File

@ -1,4 +1,5 @@
import { Controller } from "./main";
import {NetworkConfig, SSIDList} from "./api";
export class NetworkConfigView {
setScanResult(ssidList: SSIDList) {
@ -14,6 +15,7 @@ export class NetworkConfigView {
private readonly password: HTMLInputElement;
private readonly mqtt_url: HTMLInputElement;
private readonly base_topic: HTMLInputElement;
private readonly max_wait: HTMLInputElement;
private readonly ssidlist: HTMLElement;
constructor(controller: Controller, publicIp: string) {
@ -28,6 +30,9 @@ export class NetworkConfigView {
this.ssid.onchange = controller.configChanged
this.password = (document.getElementById("password") as HTMLInputElement);
this.password.onchange = controller.configChanged
this.max_wait = (document.getElementById("max_wait") as HTMLInputElement);
this.max_wait.onchange = controller.configChanged
this.mqtt_url = document.getElementById("mqtt_url") as HTMLInputElement;
this.mqtt_url.onchange = controller.configChanged
this.base_topic = document.getElementById("base_topic") as HTMLInputElement;
@ -47,10 +52,12 @@ export class NetworkConfigView {
this.password.value = network.password;
this.mqtt_url.value = network.mqtt_url;
this.base_topic.value = network.base_topic;
this.max_wait.value = network.max_wait.toString();
}
getConfig(): NetworkConfig {
return {
max_wait: +this.max_wait.value,
ap_ssid: this.ap_ssid.value,
ssid: this.ssid.value ?? null,
password: this.password.value ?? null,

View File

@ -1,4 +1,5 @@
import { Controller } from "./main";
import {NightLampConfig} from "./api";
export class NightLampView {
private readonly night_lamp_only_when_dark: HTMLInputElement;

View File

@ -37,5 +37,5 @@
</form>
</div>
<div class="display:flex">
<input style="margin-left: 16px; margin-top: 8px;" class="col-6" type="button" id="test" value="Self-Test">
<button style="margin-left: 16px; margin-top: 8px;" class="col-6" type="button" id="test">Self-Test</button>
</div>

View File

@ -1,4 +1,5 @@
import { Controller } from "./main";
import {VersionInfo} from "./api";
export class OTAView {
readonly file1Upload: HTMLInputElement;
@ -9,6 +10,8 @@ export class OTAView {
constructor(controller: Controller) {
(document.getElementById("firmwareview") as HTMLElement).innerHTML = require("./ota.html")
let test = document.getElementById("test") as HTMLButtonElement;
this.firmware_buildtime = document.getElementById("firmware_buildtime") as HTMLDivElement;
this.firmware_githash = document.getElementById("firmware_githash") as HTMLDivElement;
this.firmware_partition = document.getElementById("firmware_partition") as HTMLDivElement;
@ -24,6 +27,10 @@ export class OTAView {
}
controller.uploadNewFirmware(selectedFile);
};
test.onclick = () => {
controller.selftest();
}
}
setVersion(versionInfo: VersionInfo) {

View File

@ -1,3 +1,5 @@
import {PlantConfig} from "./api";
const PLANT_COUNT = 8;

View File

@ -1,4 +1,5 @@
import { Controller } from "./main";
import {BackupHeader} from "./api";
export class SubmitView {
json: HTMLDivElement;

View File

@ -1,4 +1,5 @@
import { Controller } from "./main";
import {TankConfig, TankInfo} from "./api";
export class TankConfigView {
private readonly tank_useable_ml: HTMLInputElement;

View File

@ -9,7 +9,7 @@ console.log("Dev server is " + isDevServer);
var host;
if (isDevServer){
//ensure no trailing /
host = 'http://192.168.251.37';
host = 'http://192.168.71.1';
} else {
host = '';
}

@ -1 +1 @@
Subproject commit 26d1205439b460bee960fd4c29f3c5c20948875f
Subproject commit 1d21656d5efcf6a6b247245d057bf553f3209f39