go to stay alive

This commit is contained in:
Empire 2024-01-07 14:33:02 +01:00
parent 5724088780
commit a30dbe0759
12 changed files with 1205 additions and 763 deletions

View File

@ -3,9 +3,16 @@ use std::process::Command;
use vergen::EmitBuilder; use vergen::EmitBuilder;
fn main() { fn main() {
println!("cargo:rerun-if-changed=./src/src_webpack"); println!("cargo:rerun-if-changed=./src/src_webpack");
Command::new("rm").arg("./src/webserver/bundle.js").output().expect("failed to execute process"); Command::new("rm")
.arg("./src/webserver/bundle.js")
.output()
.expect("failed to execute process");
let output = Command::new("npx").arg("webpack").current_dir("./src_webpack").output().expect("failed to execute process"); let output = Command::new("npx")
.arg("webpack")
.current_dir("./src_webpack")
.output()
.expect("failed to execute process");
println!("status: {}", output.status); println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout)); println!("stdout: {}", String::from_utf8_lossy(&output.stdout));

View File

@ -1,2 +1,3 @@
[toolchain] [toolchain]
channel = "esp" channel = "nightly"

View File

@ -1,5 +1,5 @@
# Rust often needs a bit of an extra main task stack size compared to C (the default is 3K) # Rust often needs a bit of an extra main task stack size compared to C (the default is 3K)
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8000 CONFIG_ESP_MAIN_TASK_STACK_SIZE=20000
# Use this to set FreeRTOS kernel tick frequency to 1000 Hz (100 Hz by default). # Use this to set FreeRTOS kernel tick frequency to 1000 Hz (100 Hz by default).
# This allows to use 1 ms granuality for thread sleeps (10 ms by default). # This allows to use 1 ms granuality for thread sleeps (10 ms by default).

View File

@ -1,54 +1,78 @@
use std::fmt; use std::fmt;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use crate::PLANT_COUNT; use crate::PLANT_COUNT;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[derive(Debug)]
pub struct Config { pub struct Config {
tank_sensor_enabled: bool, pub mqtt_url: heapless::String<128>,
tank_full_ml: u32, pub base_topic: heapless::String<64>,
tank_warn_percent: u8, pub max_consecutive_pump_count: u8,
night_lamp_hour_start: u8, pub tank_allow_pumping_if_sensor_error: bool,
night_lamp_hour_end: u8, pub tank_sensor_enabled: bool,
night_lamp_only_when_dark: bool, pub tank_useable_ml: u32,
pub tank_warn_percent: u8,
pub tank_empty_mv: f32,
pub tank_full_mv: f32,
plants: [Plant;PLANT_COUNT] pub night_lamp_hour_start: u8,
pub night_lamp_hour_end: u8,
pub night_lamp_only_when_dark: bool,
pub plants: [Plant; PLANT_COUNT],
} }
impl Default for Config { impl Default for Config {
fn default() -> Self { fn default() -> Self {
Self { tank_sensor_enabled: true, Self {
tank_full_ml: 5000, base_topic: "plant/one".into(),
mqtt_url: "mqtt://192.168.1.1:1883".into(),
tank_allow_pumping_if_sensor_error: true,
tank_sensor_enabled: true,
tank_warn_percent: 50, tank_warn_percent: 50,
night_lamp_hour_start: 21, night_lamp_hour_start: 21,
night_lamp_hour_end: 2, night_lamp_hour_end: 2,
night_lamp_only_when_dark: true, night_lamp_only_when_dark: true,
plants: [Plant::default();PLANT_COUNT] plants: [Plant::default(); PLANT_COUNT],
max_consecutive_pump_count: 15,
tank_useable_ml: 5000,
tank_empty_mv: 0.1,
tank_full_mv: 3.3,
} }
} }
} }
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
pub enum Mode {
OFF,
TargetMoisture,
TimerOnly,
}
#[derive(Serialize, Deserialize, Copy, Clone)] #[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
#[derive(Debug)]
pub struct Plant { pub struct Plant {
target_moisture: u8, pub mode: Mode,
pump_time_s: u16, pub target_moisture: u8,
pump_cooldown_min: u16, pub pump_time_s: u16,
pump_hour_start: u8, pub pump_cooldown_min: u16,
pump_hour_end: u8 pub pump_hour_start: u8,
pub pump_hour_end: u8,
} }
impl Default for Plant { impl Default for Plant {
fn default() -> Self { fn default() -> Self {
Self { target_moisture: 40, pump_time_s: 60, pump_cooldown_min: 60, pump_hour_start: 8, pump_hour_end: 20 } Self {
target_moisture: 40,
pump_time_s: 60,
pump_cooldown_min: 60,
pump_hour_start: 8,
pump_hour_end: 20,
mode: Mode::OFF,
}
} }
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize, Debug)]
#[derive(Debug)]
pub struct WifiConfig { pub struct WifiConfig {
pub ssid: heapless::String<32>, pub ssid: heapless::String<32>,
pub password: Option<heapless::String<64>>, pub password: Option<heapless::String<64>>,

View File

@ -1,47 +1,81 @@
use std::{sync::{Arc, Mutex, atomic::AtomicBool}, env}; use std::{
env,
sync::{atomic::AtomicBool, Arc, Mutex},
};
use chrono::{Datelike, NaiveDateTime, Timelike};
use once_cell::sync::Lazy;
use anyhow::Result; use anyhow::Result;
use chrono::{Datelike, Duration, NaiveDateTime, Timelike};
use chrono_tz::Europe::Berlin; use chrono_tz::Europe::Berlin;
use esp_idf_hal::delay::Delay; use esp_idf_hal::delay::Delay;
use esp_idf_sys::{esp_restart, vTaskDelay}; use esp_idf_sys::{esp_restart, uxTaskGetStackHighWaterMark, vTaskDelay};
use esp_ota::rollback_and_reboot;
use log::error;
use once_cell::sync::Lazy;
use plant_hal::{CreatePlantHal, PlantCtrlBoard, PlantCtrlBoardInteraction, PlantHal, PLANT_COUNT}; use plant_hal::{CreatePlantHal, PlantCtrlBoard, PlantCtrlBoardInteraction, PlantHal, PLANT_COUNT};
use serde::{Deserialize, Serialize};
use crate::{config::{Config, WifiConfig}, webserver::webserver::{httpd_initial, httpd}}; use crate::{
config::{Config, WifiConfig},
webserver::webserver::{httpd, httpd_initial},
};
mod config; mod config;
pub mod plant_hal; pub mod plant_hal;
const MOIST_SENSOR_MAX_FREQUENCY: u32 = 5200; // 60kHz (500Hz margin)
const MOIST_SENSOR_MIN_FREQUENCY: u32 = 500; // 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);
mod webserver { mod webserver {
pub mod webserver; pub mod webserver;
} }
#[derive(PartialEq)] #[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
enum OnlineMode { enum OnlineMode {
Offline, Offline,
Wifi, Wifi,
SnTp, SnTp,
Mqtt,
MqttRoundtrip
} }
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
enum WaitType { enum WaitType {
InitialConfig, InitialConfig,
FlashError, FlashError,
NormalConfig NormalConfig,
StayAlive,
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Default)]
struct PlantState {
a: u8,
b: u8,
p: u8,
after_p: u8,
dry: bool,
active: bool,
pump_error: bool,
not_effective: bool,
cooldown: bool,
no_water: bool,
} }
fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! { fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
let delay = match wait_type { let delay = match wait_type {
WaitType::InitialConfig => 250_u32, WaitType::InitialConfig => 250_u32,
WaitType::FlashError => 100_u32, WaitType::FlashError => 100_u32,
WaitType::NormalConfig => 500_u32 WaitType::NormalConfig => 500_u32,
WaitType::StayAlive => 1000_u32,
}; };
let led_count = match wait_type { let led_count = match wait_type {
WaitType::InitialConfig => 8, WaitType::InitialConfig => 8,
WaitType::FlashError => 8, WaitType::FlashError => 8,
WaitType::NormalConfig => 4 WaitType::NormalConfig => 4,
WaitType::StayAlive => 2,
}; };
BOARD_ACCESS.lock().unwrap().light(true).unwrap();
loop { loop {
unsafe { unsafe {
//do not trigger watchdog //do not trigger watchdog
@ -55,6 +89,9 @@ fn wait_infinity(wait_type:WaitType, reboot_now:Arc<AtomicBool>) -> !{
BOARD_ACCESS.lock().unwrap().fault(i, false); BOARD_ACCESS.lock().unwrap().fault(i, false);
} }
vTaskDelay(delay); vTaskDelay(delay);
if wait_type == WaitType::StayAlive
&& !STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed)
{}
if reboot_now.load(std::sync::atomic::Ordering::Relaxed) { if reboot_now.load(std::sync::atomic::Ordering::Relaxed) {
println!("Rebooting"); println!("Rebooting");
esp_restart(); esp_restart();
@ -63,9 +100,12 @@ fn wait_infinity(wait_type:WaitType, reboot_now:Arc<AtomicBool>) -> !{
} }
} }
pub static BOARD_ACCESS: Lazy<Mutex<PlantCtrlBoard>> = Lazy::new(|| { pub static BOARD_ACCESS: Lazy<Mutex<PlantCtrlBoard>> = Lazy::new(|| PlantHal::create().unwrap());
PlantHal::create().unwrap() pub static STAY_ALIVE: Lazy<AtomicBool> = Lazy::new(|| AtomicBool::new(false));
});
fn map_range(from_range: (f32, f32), to_range: (f32, f32), s: f32) -> f32 {
to_range.0 + (s - from_range.0) * (to_range.1 - to_range.0) / (from_range.1 - from_range.0)
}
fn main() -> Result<()> { fn main() -> Result<()> {
// It is necessary to call this function once. Otherwise some patches to the runtime // It is necessary to call this function once. Otherwise some patches to the runtime
@ -75,16 +115,45 @@ fn main() -> Result<()> {
// Bind the log crate to the ESP Logging facilities // Bind the log crate to the ESP Logging facilities
esp_idf_svc::log::EspLogger::initialize_default(); esp_idf_svc::log::EspLogger::initialize_default();
if esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE < 20000 {
error!(
"stack too small: {} bail!",
esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE
);
return Ok(());
}
log::info!("Startup Rust"); log::info!("Startup Rust");
let git_hash = env!("VERGEN_GIT_DESCRIBE"); let git_hash = env!("VERGEN_GIT_DESCRIBE");
println!("Version useing git has {}", git_hash); println!("Version useing git has {}", git_hash);
let mut partition_state: embedded_svc::ota::SlotState = embedded_svc::ota::SlotState::Unknown;
// match esp_idf_svc::ota::EspOta::new() {
// Ok(ota) => {
// match ota.get_running_slot(){
// Ok(slot) => {
// partition_state = slot.state;
// println!(
// "Booting from {} with state {:?}",
// slot.label, partition_state
// );
// },
// Err(err) => {
// println!("Error getting running slot {}", err);
// },
// }
// },
// Err(err) => {
// println!("Error obtaining ota info {}", err);
// },
// }
println!("Board hal init"); println!("Board hal init");
let mut board = BOARD_ACCESS.lock().unwrap(); let mut board: std::sync::MutexGuard<'_, PlantCtrlBoard<'_>> = BOARD_ACCESS.lock().unwrap();
println!("Mounting filesystem"); println!("Mounting filesystem");
board.mountFileSystem()?; board.mount_file_system()?;
let free_space = board.fileSystemSize()?; let free_space = board.file_system_size()?;
println!( println!(
"Mounted, total space {} used {} free {}", "Mounted, total space {} used {} free {}",
free_space.total_size, free_space.used_size, free_space.free_size free_space.total_size, free_space.used_size, free_space.free_size
@ -111,8 +180,15 @@ fn main() -> Result<()> {
println!("cur is {}", cur); println!("cur is {}", cur);
if board.is_config_reset() { if board.is_config_reset() {
board.general_fault(true);
println!("Reset config is pressed, waiting 5s"); println!("Reset config is pressed, waiting 5s");
Delay::new_default().delay_ms(5000); for i in 0..25 {
board.general_fault(true);
Delay::new_default().delay_ms(50);
board.general_fault(false);
Delay::new_default().delay_ms(50);
}
if board.is_config_reset() { if board.is_config_reset() {
println!("Reset config is still pressed, deleting configs and reboot"); println!("Reset config is still pressed, deleting configs and reboot");
match board.remove_configs() { match board.remove_configs() {
@ -126,6 +202,8 @@ fn main() -> Result<()> {
wait_infinity(WaitType::FlashError, Arc::new(AtomicBool::new(false))); wait_infinity(WaitType::FlashError, Arc::new(AtomicBool::new(false)));
} }
} }
} else {
board.general_fault(false);
} }
} }
@ -135,8 +213,18 @@ fn main() -> Result<()> {
match wifi_conf { match wifi_conf {
Ok(conf) => { Ok(conf) => {
wifi = conf; wifi = conf;
}, }
Err(err) => { Err(err) => {
if board.is_wifi_config_file_existant() {
match partition_state {
embedded_svc::ota::SlotState::Invalid
| embedded_svc::ota::SlotState::Unverified => {
println!("Config seem to be unparsable after upgrade, reverting");
rollback_and_reboot()?;
}
_ => {}
}
}
println!("Missing wifi config, entering initial config mode {}", err); println!("Missing wifi config, entering initial config mode {}", err);
board.wifi_ap().unwrap(); board.wifi_ap().unwrap();
//config upload will trigger reboot! //config upload will trigger reboot!
@ -144,48 +232,9 @@ fn main() -> Result<()> {
let reboot_now = Arc::new(AtomicBool::new(false)); let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd_initial(reboot_now.clone()); let _webserver = httpd_initial(reboot_now.clone());
wait_infinity(WaitType::InitialConfig, reboot_now.clone()); wait_infinity(WaitType::InitialConfig, reboot_now.clone());
}, }
}; };
//check if we have a config file
// if not found or parsing error -> error very fast blink general fault
//if this happens after a firmeware upgrade (check image state), mark as invalid
//blink general fault error_reading_config_after_upgrade, reboot after
// open accesspoint with webserver for wlan mqtt setup
//blink general fault error_no_config_after_upgrade
//once config is set store it and reboot
//if proceed.tank_sensor_enabled() {
//}
//is tank sensor enabled in config?
//measure tank level (without wifi due to interference)
//TODO this should be a result// detect invalid measurement value
let tank_value = board.tank_sensor_mv();
match tank_value {
Ok(tank_raw) => {
println!("Tank sensor returned {}", tank_raw);
}
Err(_) => {
//if not possible value, blink general fault error_tank_sensor_fault
board.general_fault(true);
//set general fault persistent
//set tank sensor state to fault
}
}
//measure each plant moisture
let mut initial_measurements_a: [i32; PLANT_COUNT] = [0; PLANT_COUNT];
let mut initial_measurements_b: [i32; PLANT_COUNT] = [0; PLANT_COUNT];
let mut initial_measurements_p: [i32; PLANT_COUNT] = [0; PLANT_COUNT];
for plant in 0..PLANT_COUNT {
initial_measurements_a[plant] = board.measure_moisture_hz(plant, plant_hal::Sensor::A)?;
initial_measurements_b[plant] = board.measure_moisture_hz(plant, plant_hal::Sensor::B)?;
initial_measurements_p[plant] =
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)?;
}
println!("attempting to connect wifi"); println!("attempting to connect wifi");
match board.wifi(&wifi.ssid, wifi.password.as_deref(), 10000) { match board.wifi(&wifi.ssid, wifi.password.as_deref(), 10000) {
Ok(_) => { Ok(_) => {
@ -202,7 +251,7 @@ fn main() -> Result<()> {
Ok(new_time) => { Ok(new_time) => {
cur = new_time; cur = new_time;
online_mode = OnlineMode::SnTp; online_mode = OnlineMode::SnTp;
}, }
Err(err) => { Err(err) => {
println!("sntp error: {}", err); println!("sntp error: {}", err);
board.general_fault(true); board.general_fault(true);
@ -214,10 +263,10 @@ fn main() -> Result<()> {
} }
let config: Config; let config: Config;
match (board.get_config()){ match board.get_config() {
Ok(valid) => { Ok(valid) => {
config = valid; config = valid;
}, }
Err(err) => { Err(err) => {
println!("Missing normal config, entering config mode {}", err); println!("Missing normal config, entering config mode {}", err);
//config upload will trigger reboot! //config upload will trigger reboot!
@ -225,50 +274,151 @@ fn main() -> Result<()> {
let reboot_now = Arc::new(AtomicBool::new(false)); let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd(reboot_now.clone()); let _webserver = httpd(reboot_now.clone());
wait_infinity(WaitType::NormalConfig, reboot_now.clone()); wait_infinity(WaitType::NormalConfig, reboot_now.clone());
}, }
} }
//do mqtt before config check, as mqtt might configure
if online_mode == OnlineMode::SnTp { if online_mode == OnlineMode::SnTp {
//mqtt here match board.mqtt(&config) {
Ok(_) => {
println!("Mqtt connection ready");
}
Err(err) => {
println!("Could not connect mqtt due to {}", err);
}
}
}
match board.battery_state() {
Ok(_state) => {}
Err(err) => {
board.general_fault(true);
println!("Could not read battery state, assuming low power {}", err);
}
}
let mut enough_water = true;
if config.tank_sensor_enabled {
let tank_value = board.tank_sensor_mv();
match tank_value {
Ok(tank_raw) => {
//FIXME clear
let percent = map_range(
(config.tank_empty_mv, config.tank_full_mv),
(0_f32, 100_f32),
tank_raw.into(),
);
let left_ml = ((percent / 100_f32) * config.tank_useable_ml as f32) as u32;
println!(
"Tank sensor returned mv {} as {}% leaving {} ml useable",
tank_raw, percent as u8, left_ml
);
if config.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_warn_percent
);
//FIXME warn here
}
if config.tank_warn_percent <= 0 {
enough_water = false;
}
}
Err(_) => {
board.general_fault(true);
if !config.tank_allow_pumping_if_sensor_error {
enough_water = false;
}
//set tank sensor state to fault
}
}
}
let plantstate = [PlantState {
..Default::default()
}; PLANT_COUNT];
for plant in 0..PLANT_COUNT {
let mut state = plantstate[plant];
//return mapf(mMoisture_raw.getMedian(), MOIST_SENSOR_MIN_FRQ, MOIST_SENSOR_MAX_FRQ, 0, 100);
state.a = map_range(
FROM,
TO,
board.measure_moisture_hz(plant, plant_hal::Sensor::A)? as f32,
) as u8;
state.b = map_range(
FROM,
TO,
board.measure_moisture_hz(plant, plant_hal::Sensor::B)? as f32,
) as u8;
state.p = map_range(
FROM,
TO,
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)? as f32,
) as u8;
let plant_config = config.plants[plant];
//FIXME how to average analyze whatever?
if state.a < plant_config.target_moisture || state.b < plant_config.target_moisture {
state.dry = true;
if !enough_water {
state.no_water = true;
}
}
let duration = Duration::minutes((60 * plant_config.pump_cooldown_min).into());
if (board.last_pump_time(plant)? + duration) > cur {
state.cooldown = true;
}
if state.dry {
let consecutive_pump_count = board.consecutive_pump_count(plant) + 1;
board.store_consecutive_pump_count(plant, consecutive_pump_count);
if consecutive_pump_count > config.max_consecutive_pump_count.into() {
state.not_effective = true;
board.fault(plant, true);
}
} else {
board.store_consecutive_pump_count(plant, 0);
}
//TODO update mqtt state here!
}
if (STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed)) {
drop(board);
let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd(reboot_now.clone());
wait_infinity(WaitType::StayAlive, reboot_now.clone());
}
'eachplant: for plant in 0..PLANT_COUNT {
let mut state = plantstate[plant];
if (state.dry && !state.cooldown) {
println!("Trying to pump with pump {} now", plant);
let plant_config = config.plants[plant];
board.any_pump(true)?;
board.store_last_pump_time(plant, cur);
board.pump(plant, true)?;
board.last_pump_time(plant)?;
state.active = true;
unsafe { vTaskDelay(plant_config.pump_time_s.into()) };
state.after_p = map_range(
FROM,
TO,
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)? as f32,
) as u8;
if state.after_p < state.p + 5 {
state.pump_error = true;
board.fault(plant, true);
}
break 'eachplant;
} }
if online_mode == OnlineMode::Mqtt {
//mqtt roundtrip here
} }
//TODO configmode webserver logic here
/* /*
//if config battery mode
//read battery level
//if not possible set general fault persistent, but do continue
//else
//assume 12v and max capacity
//if tank sensor is enabled
//if tank sensor fault abort if config require is set
//check if water is > minimum allowed || fault
//if not, set all plants requiring water to persistent fault
//for each plant
//check if moisture is < target
//state += dry
//check if in cooldown
//state += cooldown
//check if consecutive pumps > limit
//state += notworking
//set plant fault persistent
//pump one cycle
// set last pump time to now
//during pump state += active
//after pump check if Pump moisture value is increased by config delta x
// state -= active
// state += cooldown
// if not set plant error persistent fault
// state += notworking
//set consecutive pumps+=1
//check if during light time //check if during light time
//lightstate += out of worktime //lightstate += out of worktime
//check battery level //check battery level
@ -287,7 +437,7 @@ fn main() -> Result<()> {
} }
*/ */
//deepsleep here? //deepsleep here?
return Ok(()); Ok(())
} }
//error codes //error codes

File diff suppressed because it is too large Load Diff

View File

@ -10,21 +10,21 @@ trait ShiftRegisterInternal {
} }
/// Output pin of the shift register /// Output pin of the shift register
pub struct ShiftRegisterPin<'a> pub struct ShiftRegisterPin<'a> {
{
shift_register: &'a dyn ShiftRegisterInternal, shift_register: &'a dyn ShiftRegisterInternal,
index: usize, index: usize,
} }
impl<'a> ShiftRegisterPin<'a> impl<'a> ShiftRegisterPin<'a> {
{
fn new(shift_register: &'a dyn ShiftRegisterInternal, index: usize) -> Self { fn new(shift_register: &'a dyn ShiftRegisterInternal, index: usize) -> Self {
ShiftRegisterPin { shift_register, index } ShiftRegisterPin {
shift_register,
index,
}
} }
} }
impl OutputPin for ShiftRegisterPin<'_> impl OutputPin for ShiftRegisterPin<'_> {
{
type Error = (); type Error = ();
fn set_low(&mut self) -> Result<(), Self::Error> { fn set_low(&mut self) -> Result<(), Self::Error> {
@ -42,9 +42,10 @@ macro_rules! ShiftRegisterBuilder {
($name: ident, $size: expr) => { ($name: ident, $size: expr) => {
/// Serial-in parallel-out shift register /// Serial-in parallel-out shift register
pub struct $name<Pin1, Pin2, Pin3> pub struct $name<Pin1, Pin2, Pin3>
where Pin1: OutputPin, where
Pin1: OutputPin,
Pin2: OutputPin, Pin2: OutputPin,
Pin3: OutputPin Pin3: OutputPin,
{ {
clock: RefCell<Pin1>, clock: RefCell<Pin1>,
latch: RefCell<Pin2>, latch: RefCell<Pin2>,
@ -53,9 +54,10 @@ macro_rules! ShiftRegisterBuilder {
} }
impl<Pin1, Pin2, Pin3> ShiftRegisterInternal for $name<Pin1, Pin2, Pin3> impl<Pin1, Pin2, Pin3> ShiftRegisterInternal for $name<Pin1, Pin2, Pin3>
where Pin1: OutputPin, where
Pin1: OutputPin,
Pin2: OutputPin, Pin2: OutputPin,
Pin3: OutputPin Pin3: OutputPin,
{ {
/// Sets the value of the shift register output at `index` to value `command` /// Sets the value of the shift register output at `index` to value `command`
fn update(&self, index: usize, command: bool) -> Result<(), ()> { fn update(&self, index: usize, command: bool) -> Result<(), ()> {
@ -78,11 +80,11 @@ macro_rules! ShiftRegisterBuilder {
} }
} }
impl<Pin1, Pin2, Pin3> $name<Pin1, Pin2, Pin3> impl<Pin1, Pin2, Pin3> $name<Pin1, Pin2, Pin3>
where Pin1: OutputPin, where
Pin1: OutputPin,
Pin2: OutputPin, Pin2: OutputPin,
Pin3: OutputPin Pin3: OutputPin,
{ {
/// Creates a new SIPO shift register from clock, latch, and data output pins /// Creates a new SIPO shift register from clock, latch, and data output pins
pub fn new(clock: Pin1, latch: Pin2, data: Pin3) -> Self { pub fn new(clock: Pin1, latch: Pin2, data: Pin3) -> Self {
@ -96,13 +98,11 @@ macro_rules! ShiftRegisterBuilder {
/// Get embedded-hal output pins to control the shift register outputs /// Get embedded-hal output pins to control the shift register outputs
pub fn decompose(&self) -> [ShiftRegisterPin; $size] { pub fn decompose(&self) -> [ShiftRegisterPin; $size] {
// Create an uninitialized array of `MaybeUninit`. The `assume_init` is // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
// safe because the type we are claiming to have initialized here is a // safe because the type we are claiming to have initialized here is a
// bunch of `MaybeUninit`s, which do not require initialization. // bunch of `MaybeUninit`s, which do not require initialization.
let mut pins: [MaybeUninit<ShiftRegisterPin>; $size] = unsafe { let mut pins: [MaybeUninit<ShiftRegisterPin>; $size] =
MaybeUninit::uninit().assume_init() unsafe { MaybeUninit::uninit().assume_init() };
};
// Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop, // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop,
// we have a memory leak, but there is no memory safety issue. // we have a memory leak, but there is no memory safety issue.
@ -117,12 +117,16 @@ macro_rules! ShiftRegisterBuilder {
/// Consume the shift register and return the original clock, latch, and data output pins /// Consume the shift register and return the original clock, latch, and data output pins
pub fn release(self) -> (Pin1, Pin2, Pin3) { pub fn release(self) -> (Pin1, Pin2, Pin3) {
let Self{clock, latch, data, output_state: _} = self; let Self {
clock,
latch,
data,
output_state: _,
} = self;
(clock.into_inner(), latch.into_inner(), data.into_inner()) (clock.into_inner(), latch.into_inner(), data.into_inner())
} }
} }
};
}
} }
ShiftRegisterBuilder!(ShiftRegister8, 8); ShiftRegisterBuilder!(ShiftRegister8, 8);

View File

@ -11,23 +11,45 @@
<h2>config</h2> <h2>config</h2>
<button id="dummy">Create</button>
<div id="configform"> <div id="configform">
<h3>Mqtt:</h3>
<div>
<input type="text" id="mqtt_url">
MQTT Url
</div>
<div>
<input type="text" id="base_topic">
Base Topic
</div>
<h3>Tank:</h3> <h3>Tank:</h3>
<div> <div>
<input type="checkbox" id="tank_sensor_enabled"> <input type="checkbox" id="tank_sensor_enabled">
Enable Tank Sensor Enable Tank Sensor
</div> </div>
<div>
<input type="checkbox" id="tank_allow_pumping_if_sensor_error">
Allow Pumping if Sensor Error
</div>
<div> <div>
<input type="number" min="2" max="500000" id="tank_full_ml"> <input type="number" min="2" max="500000" id="tank_useable_ml">
Tank Size mL Tank Size mL
</div> </div>
<div> <div>
<input type="number" min="1" max="500000" id="tank_warn_percent"> <input type="number" min="1" max="500000" id="tank_warn_percent">
Tank Warn below mL Tank Warn below mL
</div> </div>
<div>
<input type="number" min="1" max="500000" id="tank_empty_mv">
Tank Empty Voltage (mv)
</div>
<div>
<input type="number" min="1" max="500000" id="tank_full_mv">
Tank Full Voltage (mv)
</div>
<h3>Light:</h3> <h3>Light:</h3>
<div> <div>
@ -44,9 +66,17 @@
</div> </div>
<h3>Plants:</h3> <h3>Plants:</h3>
<div>
<input type="number" min="2" max="100" id="max_consecutive_pump_count">
Max consecutive pump count:
</div>
<div id="plants"></div> <div id="plants"></div>
</div> </div>
<button id="submit">Submit</button> <button id="submit">Submit</button>
<div id="submit_status"></div>
<br> <br>
<textarea id="json" cols=50 rows=10></textarea> <textarea id="json" cols=50 rows=10></textarea>
<script src="bundle.js"></script> <script src="bundle.js"></script>

View File

@ -1,69 +1,80 @@
//offer ota and config mode //offer ota and config mode
use std::{sync::{Mutex, Arc, atomic::AtomicBool}, str::from_utf8}; use std::{
str::from_utf8,
sync::{atomic::AtomicBool, Arc},
};
use embedded_svc::http::{Method, Headers}; use crate::BOARD_ACCESS;
use esp_idf_svc::http::server::EspHttpServer; use embedded_svc::http::Method;
use esp_idf_svc::http::server::{Configuration, EspHttpServer};
use esp_ota::OtaUpdate; use esp_ota::OtaUpdate;
use heapless::String; use heapless::String;
use serde::Serialize; use serde::Serialize;
use crate::BOARD_ACCESS;
use crate::{plant_hal::{PlantCtrlBoard, PlantCtrlBoardInteraction, PLANT_COUNT}, config::{WifiConfig, Config, Plant}}; use crate::{
config::{Config, WifiConfig},
plant_hal::PlantCtrlBoardInteraction,
};
#[derive(Serialize)] #[derive(Serialize, Debug)]
#[derive(Debug)]
struct SSIDList<'a> { struct SSIDList<'a> {
ssids: Vec<&'a String<32>> ssids: Vec<&'a String<32>>,
} }
pub fn httpd_initial(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> { pub fn httpd_initial(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let mut server = shared(); let mut server = shared();
server.fn_handler("/",Method::Get, move |request| { server
.fn_handler("/", Method::Get, move |request| {
let mut response = request.into_ok_response()?; let mut response = request.into_ok_response()?;
response.write(include_bytes!("initial_config.html"))?; response.write(include_bytes!("initial_config.html"))?;
return Ok(()) Ok(())
}).unwrap(); })
.unwrap();
server.fn_handler("/wifiscan",Method::Post, move |request| { server
.fn_handler("/wifiscan", Method::Post, move |request| {
let mut response = request.into_ok_response()?; let mut response = request.into_ok_response()?;
let mut board = BOARD_ACCESS.lock().unwrap(); let mut board = BOARD_ACCESS.lock().unwrap();
match board.wifi_scan() { match board.wifi_scan() {
Err(error) => { Err(error) => {
response.write(format!("Error scanning wifi: {}", error).as_bytes())?; response.write(format!("Error scanning wifi: {}", error).as_bytes())?;
}, }
Ok(scan_result) => { Ok(scan_result) => {
let mut ssids: Vec<&String<32>> = Vec::new(); let mut ssids: Vec<&String<32>> = Vec::new();
scan_result.iter().for_each(|s| scan_result.iter().for_each(|s| ssids.push(&s.ssid));
ssids.push(&s.ssid)
);
let ssid_json = serde_json::to_string(&SSIDList { ssids })?; let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
println!("Sending ssid list {}", &ssid_json); println!("Sending ssid list {}", &ssid_json);
response.write( &ssid_json.as_bytes())?; response.write(ssid_json.as_bytes())?;
},
} }
return Ok(()) }
}).unwrap(); Ok(())
})
.unwrap();
server.fn_handler("/wifisave",Method::Post, move |mut request| {
server
.fn_handler("/wifisave", Method::Post, move |mut request| {
let mut buf = [0_u8; 2048]; let mut buf = [0_u8; 2048];
let read = request.read(&mut buf); let read = request.read(&mut buf);
if read.is_err() { if read.is_err() {
let error_text = read.unwrap_err().to_string(); let error_text = read.unwrap_err().to_string();
println!("Could not parse wificonfig {}", error_text); println!("Could not parse wificonfig {}", error_text);
request.into_status_response(500)?.write(error_text.as_bytes())?; request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(()); return Ok(());
} }
let actual_data = &buf[0..read.unwrap()]; let actual_data = &buf[0..read.unwrap()];
println!("raw {:?}", actual_data); println!("raw {:?}", actual_data);
println!("Raw data {}", from_utf8(actual_data).unwrap()); println!("Raw data {}", from_utf8(actual_data).unwrap());
let wifi_config: Result<WifiConfig, serde_json::Error> = serde_json::from_slice(actual_data); let wifi_config: Result<WifiConfig, serde_json::Error> =
serde_json::from_slice(actual_data);
if wifi_config.is_err() { if wifi_config.is_err() {
let error_text = wifi_config.unwrap_err().to_string(); let error_text = wifi_config.unwrap_err().to_string();
println!("Could not parse wificonfig {}", error_text); println!("Could not parse wificonfig {}", error_text);
request.into_status_response(500)?.write(error_text.as_bytes())?; request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(()); return Ok(());
} }
let mut board = BOARD_ACCESS.lock().unwrap(); let mut board = BOARD_ACCESS.lock().unwrap();
@ -71,16 +82,19 @@ pub fn httpd_initial(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>>
let mut response = request.into_status_response(202)?; let mut response = request.into_status_response(202)?;
response.write("saved".as_bytes())?; response.write("saved".as_bytes())?;
reboot_now.store(true, std::sync::atomic::Ordering::Relaxed); reboot_now.store(true, std::sync::atomic::Ordering::Relaxed);
return Ok(()) Ok(())
}).unwrap(); })
.unwrap();
server.fn_handler("/boardtest",Method::Post, move |request| { server
.fn_handler("/boardtest", Method::Post, move |_| {
let mut board = BOARD_ACCESS.lock().unwrap(); let mut board = BOARD_ACCESS.lock().unwrap();
board.test(); board.test()?;
return Ok(()) Ok(())
}).unwrap(); })
.unwrap();
return server server
} }
pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> { pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
@ -90,8 +104,9 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
.fn_handler("/", Method::Get, move |request| { .fn_handler("/", Method::Get, move |request| {
let mut response = request.into_ok_response()?; let mut response = request.into_ok_response()?;
response.write(include_bytes!("config.html"))?; response.write(include_bytes!("config.html"))?;
return Ok(()) Ok(())
}).unwrap(); })
.unwrap();
server server
.fn_handler("/get_config", Method::Get, move |request| { .fn_handler("/get_config", Method::Get, move |request| {
@ -101,32 +116,37 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
Ok(config) => { Ok(config) => {
let config_json = serde_json::to_string(&config)?; let config_json = serde_json::to_string(&config)?;
response.write(config_json.as_bytes())?; response.write(config_json.as_bytes())?;
}, }
Err(_) => { Err(_) => {
let config_json = serde_json::to_string(&Config::default())?; let config_json = serde_json::to_string(&Config::default())?;
response.write(config_json.as_bytes())?; response.write(config_json.as_bytes())?;
},
} }
return Ok(()) }
}).unwrap(); Ok(())
})
.unwrap();
server.fn_handler("/set_config",Method::Post, move |mut request| { server
let mut buf = [0_u8;2048]; .fn_handler("/set_config", Method::Post, move |mut request| {
let mut buf = [0_u8; 3072];
let read = request.read(&mut buf); let read = request.read(&mut buf);
if read.is_err() { if read.is_err() {
let error_text = read.unwrap_err().to_string(); let error_text = read.unwrap_err().to_string();
println!("Could not parse wificonfig {}", error_text); println!("Could not parse config {}", error_text);
request.into_status_response(500)?.write(error_text.as_bytes())?; request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(()); return Ok(());
} }
let actual_data = &buf[0..read.unwrap()]; let actual_data = &buf[0..read.unwrap()];
println!("raw {:?}", actual_data);
println!("Raw data {}", from_utf8(actual_data).unwrap()); println!("Raw data {}", from_utf8(actual_data).unwrap());
let config: Result<Config, serde_json::Error> = serde_json::from_slice(actual_data); let config: Result<Config, serde_json::Error> = serde_json::from_slice(actual_data);
if config.is_err() { if config.is_err() {
let error_text = config.unwrap_err().to_string(); let error_text = config.unwrap_err().to_string();
println!("Could not parse wificonfig {}", error_text); println!("Could not parse config {}", error_text);
request.into_status_response(500)?.write(error_text.as_bytes())?; request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(()); return Ok(());
} }
let mut board = BOARD_ACCESS.lock().unwrap(); let mut board = BOARD_ACCESS.lock().unwrap();
@ -134,39 +154,48 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let mut response = request.into_status_response(202)?; let mut response = request.into_status_response(202)?;
response.write("saved".as_bytes())?; response.write("saved".as_bytes())?;
reboot_now.store(true, std::sync::atomic::Ordering::Relaxed); reboot_now.store(true, std::sync::atomic::Ordering::Relaxed);
return Ok(()) Ok(())
}).unwrap(); })
return server; .unwrap();
server
} }
pub fn shared() -> Box<EspHttpServer<'static>> { pub fn shared() -> Box<EspHttpServer<'static>> {
let mut server: Box<EspHttpServer<'static>> = Box::new(EspHttpServer::new(&Default::default()).unwrap()); let server_config = Configuration {
stack_size: 8192,
..Default::default()
};
let mut server: Box<EspHttpServer<'static>> =
Box::new(EspHttpServer::new(&server_config).unwrap());
server server
.fn_handler("/version", Method::Get, |request| { .fn_handler("/version", Method::Get, |request| {
let mut response = request.into_ok_response()?; let mut response = request.into_ok_response()?;
response.write(env!("VERGEN_GIT_DESCRIBE").as_bytes())?; response.write(env!("VERGEN_GIT_DESCRIBE").as_bytes())?;
return Ok(()) Ok(())
}).unwrap(); })
.unwrap();
server server
.fn_handler("/bundle.js", Method::Get, |request| { .fn_handler("/bundle.js", Method::Get, |request| {
let mut response = request.into_ok_response()?; let mut response = request.into_ok_response()?;
response.write(include_bytes!("bundle.js"))?; response.write(include_bytes!("bundle.js"))?;
return Ok(()) Ok(())
}).unwrap(); })
.unwrap();
server server
.fn_handler("/favicon.ico", Method::Get, |request| { .fn_handler("/favicon.ico", Method::Get, |request| {
let mut response = request.into_ok_response()?; let mut response = request.into_ok_response()?;
response.write(include_bytes!("favicon.ico"))?; response.write(include_bytes!("favicon.ico"))?;
return Ok(()) Ok(())
}).unwrap(); })
.unwrap();
server server
.fn_handler("/ota", Method::Post, |mut request| { .fn_handler("/ota", Method::Post, |mut request| {
let ota = OtaUpdate::begin(); let ota = OtaUpdate::begin();
if ota.is_err() { if ota.is_err() {
let error_text = ota.unwrap_err().to_string(); let error_text = ota.unwrap_err().to_string();
request.into_status_response(500)?.write(error_text.as_bytes())?; request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(()); return Ok(());
} }
let mut ota = ota.unwrap(); let mut ota = ota.unwrap();
@ -182,11 +211,12 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
println!("received {read} bytes ota {total_read}"); println!("received {read} bytes ota {total_read}");
let to_write = &buffer[0..read]; let to_write = &buffer[0..read];
let write_result = ota.write(to_write); let write_result = ota.write(to_write);
if write_result.is_err() { if write_result.is_err() {
let error_text = write_result.unwrap_err().to_string(); let error_text = write_result.unwrap_err().to_string();
request.into_status_response(500)?.write(error_text.as_bytes())?; request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(()); return Ok(());
} }
println!("wrote {read} bytes ota {total_read}"); println!("wrote {read} bytes ota {total_read}");
@ -201,7 +231,9 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
let finalizer = ota.finalize(); let finalizer = ota.finalize();
if finalizer.is_err() { if finalizer.is_err() {
let error_text = finalizer.err().unwrap().to_string(); let error_text = finalizer.err().unwrap().to_string();
request.into_status_response(500)?.write(error_text.as_bytes())?; request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(()); return Ok(());
} }
let mut finalizer = finalizer.unwrap(); let mut finalizer = finalizer.unwrap();
@ -209,6 +241,7 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
println!("changing boot partition"); println!("changing boot partition");
finalizer.set_as_boot_partition().unwrap(); finalizer.set_as_boot_partition().unwrap();
finalizer.restart(); finalizer.restart();
}).unwrap(); })
return server; .unwrap();
server
} }

View File

@ -1,11 +1,19 @@
interface PlantConfig { interface PlantConfig {
mqtt_url: string,
base_topic: string,
tank_sensor_enabled: boolean, tank_sensor_enabled: boolean,
tank_full_ml: number, tank_allow_pumping_if_sensor_error: boolean,
tank_useable_ml: number,
tank_warn_percent: number, tank_warn_percent: number,
tank_empty_mv: number,
tank_full_mv: number,
night_lamp_hour_start: number, night_lamp_hour_start: number,
night_lamp_hour_end: number, night_lamp_hour_end: number,
night_lamp_only_when_dark: boolean, night_lamp_only_when_dark: boolean,
max_consecutive_pump_count: number,
plants: { plants: {
mode: string,
target_moisture: number, target_moisture: number,
pump_time_s: number, pump_time_s: number,
pump_cooldown_min: number, pump_cooldown_min: number,
@ -28,12 +36,26 @@ let fromWrapper = (() => {
} }
} }
let tank_full_ml = document.getElementById("tank_full_ml") as HTMLInputElement;
tank_full_ml.onchange = updateJson let mqtt_url = document.getElementById("mqtt_url") as HTMLInputElement;
mqtt_url.onchange = updateJson
let base_topic = document.getElementById("base_topic") as HTMLInputElement;
base_topic.onchange = updateJson
let max_consecutive_pump_count = document.getElementById("max_consecutive_pump_count") as HTMLInputElement;
max_consecutive_pump_count.onchange = updateJson
let tank_useable_ml = document.getElementById("tank_useable_ml") as HTMLInputElement;
tank_useable_ml.onchange = updateJson
let tank_empty_mv = document.getElementById("tank_empty_mv") as HTMLInputElement;
tank_empty_mv.onchange = updateJson
let tank_full_mv = document.getElementById("tank_full_mv") as HTMLInputElement;
tank_full_mv.onchange = updateJson
let tank_warn_percent = document.getElementById("tank_warn_percent") as HTMLInputElement; let tank_warn_percent = document.getElementById("tank_warn_percent") as HTMLInputElement;
tank_warn_percent.onchange = updateJson tank_warn_percent.onchange = updateJson
let tank_sensor_enabled = document.getElementById("tank_sensor_enabled") as HTMLInputElement; let tank_sensor_enabled = document.getElementById("tank_sensor_enabled") as HTMLInputElement;
tank_sensor_enabled.onchange = updateJson tank_sensor_enabled.onchange = updateJson
let tank_allow_pumping_if_sensor_error = document.getElementById("tank_allow_pumping_if_sensor_error") as HTMLInputElement;
tank_allow_pumping_if_sensor_error.onchange = updateJson
let night_lamp_only_when_dark = document.getElementById("night_lamp_only_when_dark") as HTMLInputElement; let night_lamp_only_when_dark = document.getElementById("night_lamp_only_when_dark") as HTMLInputElement;
night_lamp_only_when_dark.onchange = updateJson night_lamp_only_when_dark.onchange = updateJson
let night_lamp_time_start = document.getElementById("night_lamp_time_start") as HTMLSelectElement; let night_lamp_time_start = document.getElementById("night_lamp_time_start") as HTMLSelectElement;
@ -53,6 +75,33 @@ let fromWrapper = (() => {
header.textContent = "Plant " + (i + 1); header.textContent = "Plant " + (i + 1);
plant.appendChild(header); plant.appendChild(header);
{
let holder = document.createElement("div");
plant.appendChild(holder);
let inputf = document.createElement("select");
inputf.id = "plant_" + i + "_mode";
inputf.onchange = updateJson;
holder.appendChild(inputf)
let optionOff = document.createElement("option");
optionOff.value = "OFF";
optionOff.innerText = "Off";
inputf.appendChild(optionOff);
let optionTargetMoisture = document.createElement("option");
optionTargetMoisture.value = "TargetMoisture";
optionTargetMoisture.innerText = "Target Moisture";
inputf.appendChild(optionTargetMoisture);
let optionTimerOnly = document.createElement("option");
optionTimerOnly.value = "TimerOnly";
optionTimerOnly.innerText = "Timer";
inputf.appendChild(optionTimerOnly);
let text = document.createElement("span");
holder.appendChild(text)
text.innerHTML += "Mode"
}
{ {
let holder = document.createElement("div"); let holder = document.createElement("div");
plant.appendChild(holder); plant.appendChild(holder);
@ -130,16 +179,25 @@ let fromWrapper = (() => {
function sync(current: PlantConfig) { function sync(current: PlantConfig) {
plantcount = current.plants.length plantcount = current.plants.length
tank_full_ml.disabled = !current.tank_sensor_enabled; mqtt_url.value = current.mqtt_url;
tank_warn_percent.disabled = !current.tank_sensor_enabled; base_topic.value = current.base_topic;
max_consecutive_pump_count.value = current.max_consecutive_pump_count.toString();
tank_useable_ml.disabled = !current.tank_sensor_enabled;
tank_warn_percent.disabled = !current.tank_sensor_enabled;
tank_sensor_enabled.checked = current.tank_sensor_enabled; tank_sensor_enabled.checked = current.tank_sensor_enabled;
tank_full_ml.value = current.tank_full_ml.toString(); tank_allow_pumping_if_sensor_error.checked = current.tank_allow_pumping_if_sensor_error;
tank_useable_ml.value = current.tank_useable_ml.toString();
tank_warn_percent.value = current.tank_warn_percent.toString(); tank_warn_percent.value = current.tank_warn_percent.toString();
tank_empty_mv.value = current.tank_empty_mv.toString();
tank_full_mv.value = current.tank_full_mv.toString();
night_lamp_time_start.value = current.night_lamp_hour_start.toString(); night_lamp_time_start.value = current.night_lamp_hour_start.toString();
night_lamp_time_end.value = current.night_lamp_hour_end.toString(); night_lamp_time_end.value = current.night_lamp_hour_end.toString();
for (let i = 0; i < current.plants.length; i++) { for (let i = 0; i < current.plants.length; i++) {
let plant_mode = document.getElementById("plant_" + i + "_mode") as HTMLSelectElement;
plant_mode.value = current.plants[i].mode;
let plant_target_moisture = document.getElementById("plant_" + i + "_target_moisture") as HTMLInputElement; let plant_target_moisture = document.getElementById("plant_" + i + "_target_moisture") as HTMLInputElement;
plant_target_moisture.value = current.plants[i].target_moisture.toString(); plant_target_moisture.value = current.plants[i].target_moisture.toString();
let plant_pump_time_s = document.getElementById("plant_" + i + "_pump_time_s") as HTMLInputElement; let plant_pump_time_s = document.getElementById("plant_" + i + "_pump_time_s") as HTMLInputElement;
@ -155,9 +213,15 @@ let fromWrapper = (() => {
function updateJson() { function updateJson() {
var current: PlantConfig = { var current: PlantConfig = {
max_consecutive_pump_count: +max_consecutive_pump_count.value,
mqtt_url: mqtt_url.value,
base_topic: base_topic.value,
tank_allow_pumping_if_sensor_error: tank_allow_pumping_if_sensor_error.checked,
tank_sensor_enabled: tank_sensor_enabled.checked, tank_sensor_enabled: tank_sensor_enabled.checked,
tank_full_ml: +tank_full_ml.value, tank_useable_ml: +tank_useable_ml.value,
tank_warn_percent: +tank_warn_percent.value, tank_warn_percent: +tank_warn_percent.value,
tank_empty_mv: +tank_empty_mv.value,
tank_full_mv: +tank_full_mv.value,
night_lamp_hour_start: +night_lamp_time_start.value, night_lamp_hour_start: +night_lamp_time_start.value,
night_lamp_hour_end: +night_lamp_time_end.value, night_lamp_hour_end: +night_lamp_time_end.value,
night_lamp_only_when_dark: night_lamp_only_when_dark.checked, night_lamp_only_when_dark: night_lamp_only_when_dark.checked,
@ -166,6 +230,7 @@ let fromWrapper = (() => {
for (let i = 0; i < plantcount; i++) { for (let i = 0; i < plantcount; i++) {
console.log("Adding plant " + i) console.log("Adding plant " + i)
let plant_mode = document.getElementById("plant_" + i + "_mode") as HTMLSelectElement;
let plant_target_moisture = document.getElementById("plant_" + i + "_target_moisture") as HTMLInputElement; let plant_target_moisture = document.getElementById("plant_" + i + "_target_moisture") as HTMLInputElement;
let plant_pump_time_s = document.getElementById("plant_" + i + "_pump_time_s") as HTMLInputElement; let plant_pump_time_s = document.getElementById("plant_" + i + "_pump_time_s") as HTMLInputElement;
let plant_pump_cooldown_min = document.getElementById("plant_" + i + "_pump_cooldown_min") as HTMLInputElement; let plant_pump_cooldown_min = document.getElementById("plant_" + i + "_pump_cooldown_min") as HTMLInputElement;
@ -173,6 +238,7 @@ let fromWrapper = (() => {
let plant_pump_hour_end = document.getElementById("plant_" + i + "_pump_hour_end") as HTMLInputElement; let plant_pump_hour_end = document.getElementById("plant_" + i + "_pump_hour_end") as HTMLInputElement;
current.plants[i] = { current.plants[i] = {
mode: plant_mode.value,
target_moisture: +plant_target_moisture.value, target_moisture: +plant_target_moisture.value,
pump_time_s: +plant_pump_time_s.value, pump_time_s: +plant_pump_time_s.value,
pump_cooldown_min: +plant_pump_cooldown_min.value, pump_cooldown_min: +plant_pump_cooldown_min.value,
@ -184,18 +250,24 @@ let fromWrapper = (() => {
sync(current); sync(current);
console.log(current); console.log(current);
var pretty = JSON.stringify(current, undefined, 4); var pretty = JSON.stringify(current, undefined, 1);
json.value = pretty; json.value = pretty;
} }
let submitFormBtn = document.getElementById("submit") as HTMLButtonElement let submitFormBtn = document.getElementById("submit") as HTMLButtonElement
let submit_status = document.getElementById("submit_status")
if (submitFormBtn) { if (submitFormBtn) {
submitFormBtn.onclick = function (){ submitFormBtn.onclick = function (){
updateJson() updateJson()
fetch("/set_config", { fetch("/set_config", {
method :"POST", method :"POST",
body: json.value body: json.value
}) })
.then(response => response.text())
.then(text => submit_status.innerText = text)
}; };
} }