move to central config, make TZ compile time const, confgureable later!

This commit is contained in:
Empire 2024-11-13 22:04:47 +01:00
parent 7957cf4003
commit bfcf5e150c
10 changed files with 591 additions and 838 deletions

View File

@ -77,6 +77,7 @@ serde_json = "1.0.108"
#timezone #timezone
chrono = { version = "0.4.23", default-features = false , features = ["iana-time-zone" , "alloc"] } chrono = { version = "0.4.23", default-features = false , features = ["iana-time-zone" , "alloc"] }
chrono-tz = {version="0.8.0", default-features = false , features = [ "filter-by-regex" ]} chrono-tz = {version="0.8.0", default-features = false , features = [ "filter-by-regex" ]}
eeprom24x = "0.7.2"
[patch.crates-io] [patch.crates-io]

View File

@ -1,4 +1,4 @@
use std::{fmt, str::FromStr}; use std::{array::from_fn, str::FromStr};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -6,8 +6,13 @@ use crate::PLANT_COUNT;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Config { pub struct Config {
pub mqtt_url: heapless::String<128>, pub ap_ssid: heapless::String<32>,
pub base_topic: heapless::String<64>,
pub ssid: Option<heapless::String<32>>,
pub password: Option<heapless::String<64>>,
pub mqtt_url: Option<heapless::String<128>>,
pub base_topic: Option<heapless::String<64>>,
pub max_consecutive_pump_count: u8, pub max_consecutive_pump_count: u8,
pub tank_allow_pumping_if_sensor_error: bool, pub tank_allow_pumping_if_sensor_error: bool,
@ -27,15 +32,20 @@ pub struct Config {
impl Default for Config { impl Default for Config {
fn default() -> Self { fn default() -> Self {
Self { Self {
base_topic: heapless::String::from_str("plant/one").unwrap(), ap_ssid: heapless::String::from_str("Plantctrl").unwrap(),
mqtt_url: heapless::String::from_str("mqtt://192.168.1.1:1883").unwrap(), ssid: None,
password: None,
base_topic: Some(heapless::String::from_str("plant/one").unwrap()),
mqtt_url: Some(heapless::String::from_str("mqtt://192.168.1.1:1883").unwrap()),
tank_allow_pumping_if_sensor_error: true, tank_allow_pumping_if_sensor_error: true,
tank_sensor_enabled: 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: from_fn(|_i| Plant::default()),
max_consecutive_pump_count: 15, max_consecutive_pump_count: 15,
tank_useable_ml: 5000, tank_useable_ml: 5000,
tank_empty_percent: 0_u8, tank_empty_percent: 0_u8,
@ -43,7 +53,7 @@ impl Default for Config {
} }
} }
} }
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Mode { pub enum Mode {
OFF, OFF,
TargetMoisture, TargetMoisture,
@ -51,7 +61,7 @@ pub enum Mode {
TimerAndDeadzone, TimerAndDeadzone,
} }
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Plant { pub struct Plant {
pub mode: Mode, pub mode: Mode,
pub target_moisture: u8, pub target_moisture: u8,
@ -74,15 +84,3 @@ impl Default for Plant {
} }
} }
} }
#[derive(Serialize, Deserialize, Debug)]
pub struct WifiConfig {
pub ssid: heapless::String<32>,
pub password: Option<heapless::String<64>>,
}
impl fmt::Display for WifiConfig {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, ****)", self.ssid)
}
}

View File

@ -18,18 +18,20 @@ use esp_idf_sys::{
}; };
use log::error; use log::error;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use plant_hal::{CreatePlantHal, PlantCtrlBoard, PlantCtrlBoardInteraction, PlantHal, PLANT_COUNT}; use plant_hal::{PlantCtrlBoard, PlantHal, PLANT_COUNT};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
config::{Config, WifiConfig}, config::Config,
espota::{mark_app_valid, rollback_and_reboot}, espota::{mark_app_valid, rollback_and_reboot},
webserver::webserver::{httpd, httpd_initial}, webserver::webserver::httpd,
}; };
mod config; mod config;
pub mod espota; pub mod espota;
pub mod plant_hal; pub mod plant_hal;
const TIME_ZONE: Tz = Berlin;
const MOIST_SENSOR_MAX_FREQUENCY: u32 = 50000; // 60kHz (500Hz margin) const MOIST_SENSOR_MAX_FREQUENCY: u32 = 50000; // 60kHz (500Hz margin)
const MOIST_SENSOR_MIN_FREQUENCY: u32 = 500; // 0.5kHz (500Hz margin) const MOIST_SENSOR_MIN_FREQUENCY: u32 = 500; // 0.5kHz (500Hz margin)
@ -46,21 +48,10 @@ mod webserver {
pub mod webserver; pub mod webserver;
} }
#[derive(Serialize, Deserialize, Debug, PartialEq)]
enum OnlineMode {
Offline,
Wifi,
SnTp,
Online,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
enum WaitType { enum WaitType {
InitialConfig, MissingConfig,
FlashError, Config,
NormalConfig,
StayAlive,
StayAliveBtn
} }
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)] #[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
@ -208,20 +199,32 @@ fn safe_main() -> anyhow::Result<()> {
free_space.total_size, free_space.used_size, free_space.free_size free_space.total_size, free_space.used_size, free_space.free_size
); );
let time = board.time(); let mut cur = match board.get_rtc_time() {
let mut cur = match time { Ok(time) => time,
Ok(cur) => cur,
Err(err) => { Err(err) => {
log::error!("time error {}", err); println!("rtc module error: {}", err);
DateTime::from_timestamp_millis(0).unwrap() board.general_fault(true);
let time = board.time();
match time {
Ok(cur) => cur,
Err(err) => {
log::error!("time error {}", err);
DateTime::from_timestamp_millis(0).unwrap()
}
}
} }
}; };
//check if we know the time current > 2020 //check if we know the time current > 2020
if cur.year() < 2020 { if cur.year() < 2020 {
println!("Running time estimation super fallback");
if board.is_day() { if board.is_day() {
//assume TZ safe times ;) //assume TZ safe times ;)
println!("Is day -> 15:00");
cur = *cur.with_hour(15).get_or_insert(cur); cur = *cur.with_hour(15).get_or_insert(cur);
} else { } else {
println!("Is night -> 3:00");
cur = *cur.with_hour(3).get_or_insert(cur); cur = *cur.with_hour(3).get_or_insert(cur);
} }
} }
@ -229,9 +232,9 @@ fn safe_main() -> anyhow::Result<()> {
println!("cur is {}", cur); println!("cur is {}", cur);
let mut to_config = false; let mut to_config = false;
if board.is_config_reset() { if board.is_mode_override() {
board.general_fault(true); board.general_fault(true);
println!("Reset config is pressed, waiting 5s"); println!("config mode override is pressed, waiting 5s");
for _i in 0..5 { for _i in 0..5 {
board.general_fault(true); board.general_fault(true);
Delay::new_default().delay_ms(100); Delay::new_default().delay_ms(100);
@ -239,133 +242,88 @@ fn safe_main() -> anyhow::Result<()> {
Delay::new_default().delay_ms(100); Delay::new_default().delay_ms(100);
} }
if board.is_config_reset() { if board.is_mode_override() {
to_config = true; to_config = true;
println!("Reset config is still pressed, proceed to config mode");
for _i in 0..25 {
board.general_fault(true);
Delay::new_default().delay_ms(25);
board.general_fault(false);
Delay::new_default().delay_ms(25);
}
if board.is_config_reset() {
println!("Reset config is still pressed, proceed to delete configs");
match board.remove_configs() {
Ok(case) => {
println!("Succeeded in deleting config {}", case);
}
Err(err) => {
println!("Could not remove config files, system borked {}", err);
//terminate main app and freeze
wait_infinity(WaitType::FlashError, Arc::new(AtomicBool::new(false)));
}
}
} else {
}
} else { } else {
board.general_fault(false); board.general_fault(false);
} }
} }
let mut online_mode = OnlineMode::Offline;
let wifi_conf = board.get_wifi();
let wifi: WifiConfig;
match wifi_conf {
Ok(conf) => {
wifi = conf;
}
Err(err) => {
if board.is_wifi_config_file_existant() {
if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY {
println!("Config seem to be unparsable after upgrade, reverting");
rollback_and_reboot()?;
}
}
println!("Missing wifi config, entering initial config mode {}", err);
board.wifi_ap().unwrap();
//config upload will trigger reboot!
drop(board);
let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd_initial(reboot_now.clone());
wait_infinity(WaitType::InitialConfig, reboot_now.clone());
}
};
println!("attempting to connect wifi");
let mut ip_address: Option<String> = None;
match board.wifi(wifi.ssid, wifi.password, 10000) {
Ok(ip_info) => {
ip_address = Some(ip_info.ip.to_string());
online_mode = OnlineMode::Wifi;
}
Err(_) => {
println!("Offline mode");
board.general_fault(true);
}
}
if online_mode == OnlineMode::Wifi {
match board.sntp(1000 * 5) {
Ok(new_time) => {
cur = new_time;
online_mode = OnlineMode::SnTp;
}
Err(err) => {
println!("sntp error: {}", err);
board.general_fault(true);
}
}
}
println!("Running logic at utc {}", cur);
let europe_time = cur.with_timezone(&Berlin);
println!("Running logic at europe/berlin {}", europe_time);
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!
let _ = board.wifi_ap();
drop(board); drop(board);
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::MissingConfig, reboot_now.clone());
} }
} }
//do mqtt before config check, as mqtt might configure let mut wifi = false;
if online_mode == OnlineMode::SnTp { let mut mqtt = false;
match board.mqtt(&config) { let mut sntp = false;
Ok(_) => { println!("attempting to connect wifi");
println!("Mqtt connection ready"); let mut ip_address: Option<String> = None;
online_mode = OnlineMode::Online; if config.ssid.is_some() {
match board.wifi(config.ssid.clone().unwrap(), config.password.clone(), 10000) {
Ok(ip_info) => {
ip_address = Some(ip_info.ip.to_string());
wifi = true;
match board.sntp(1000 * 5) {
Ok(new_time) => {
println!("Using time from sntp");
let _ = board.set_rtc_time(&new_time);
cur = new_time;
sntp = true;
}
Err(err) => {
println!("sntp error: {}", err);
board.general_fault(true);
}
}
match board.mqtt(&config) {
Ok(_) => {
println!("Mqtt connection ready");
mqtt = true;
}
Err(err) => {
println!("Could not connect mqtt due to {}", err);
}
}
} }
Err(err) => { Err(_) => {
println!("Could not connect mqtt due to {}", err); println!("Offline mode");
board.general_fault(true);
} }
} }
} else {
println!("No wifi configured");
} }
if online_mode == OnlineMode::Online { let timezone_time = cur.with_timezone(&TIME_ZONE);
match ip_address { println!(
Some(add_some) => { "Running logic at utc {} and {} {}",
let _ = board.mqtt_publish(&config, "/firmware/address", add_some.as_bytes()); cur,
} TIME_ZONE.name(),
None => { timezone_time
let _ = board.mqtt_publish(&config, "/firmware/address", "N/A?".as_bytes()); );
}
} if mqtt {
let ip_string = ip_address.unwrap_or("N/A".to_owned());
let _ = board.mqtt_publish(&config, "/firmware/address", ip_string.as_bytes());
let _ = board.mqtt_publish(&config, "/firmware/githash", git_hash.as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/githash", git_hash.as_bytes());
let _ = board.mqtt_publish(&config, "/firmware/buildtime", build_timestamp.as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/buildtime", build_timestamp.as_bytes());
let _ = board.mqtt_publish( let _ = board.mqtt_publish(
&config, &config,
"/firmware/last_online", "/firmware/last_online",
europe_time.to_rfc3339().as_bytes(), timezone_time.to_rfc3339().as_bytes(),
); );
let _ = board.mqtt_publish(&config, "/firmware/ota_state", ota_state_string.as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/ota_state", ota_state_string.as_bytes());
let _ = board.mqtt_publish( let _ = board.mqtt_publish(
@ -378,6 +336,18 @@ fn safe_main() -> anyhow::Result<()> {
publish_battery_state(&mut board, &config); publish_battery_state(&mut board, &config);
} }
println!("startup state wifi {} sntp {} mqtt {}", wifi, sntp, mqtt);
if to_config {
//check if client or ap mode and init wifi
println!("executing config mode override");
//config upload will trigger reboot!
drop(board);
let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd(reboot_now.clone());
wait_infinity(WaitType::Config, reboot_now.clone());
}
let tank_state = determine_tank_state(&mut board, &config); let tank_state = determine_tank_state(&mut board, &config);
let mut tank_state_mqtt = TankStateMQTT { let mut tank_state_mqtt = TankStateMQTT {
enough_water: tank_state.enough_water, enough_water: tank_state.enough_water,
@ -413,30 +383,27 @@ fn safe_main() -> anyhow::Result<()> {
None => tank_state_mqtt.water_frozen = "tank sensor error".to_owned(), None => tank_state_mqtt.water_frozen = "tank sensor error".to_owned(),
} }
if online_mode == OnlineMode::Online { match serde_json::to_string(&tank_state_mqtt) {
match serde_json::to_string(&tank_state_mqtt) { Ok(state) => {
Ok(state) => { let _ = board.mqtt_publish(&config, "/water", state.as_bytes());
let _ = board.mqtt_publish(&config, "/water", state.as_bytes()); }
} Err(err) => {
Err(err) => { println!("Error publishing tankstate {}", err);
println!("Error publishing tankstate {}", err); }
} };
};
}
let mut plantstate: [PlantState; PLANT_COUNT] = core::array::from_fn(|_| PlantState { let mut plantstate: [PlantState; PLANT_COUNT] = core::array::from_fn(|_| PlantState {
..Default::default() ..Default::default()
}); });
let plant_to_pump = determine_next_plant( let plant_to_pump = determine_next_plant(
&mut plantstate, &mut plantstate,
europe_time, timezone_time,
&tank_state, &tank_state,
water_frozen, water_frozen,
&config, &config,
&mut board, &mut board,
); );
let stay_alive_mqtt = STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed); let stay_alive_mqtt = STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed);
let stay_alive = stay_alive_mqtt; let stay_alive = stay_alive_mqtt;
println!("Check stay alive, current state is {}", stay_alive); println!("Check stay alive, current state is {}", stay_alive);
@ -452,7 +419,7 @@ fn safe_main() -> anyhow::Result<()> {
board.fault(plant, true); board.fault(plant, true);
} }
let plant_config = config.plants[plant]; let plant_config = &config.plants[plant];
println!( println!(
"Trying to pump for {}s with pump {} now", "Trying to pump for {}s with pump {} now",
@ -477,16 +444,15 @@ fn safe_main() -> anyhow::Result<()> {
println!("Nothing to do"); println!("Nothing to do");
} }
} }
if online_mode == OnlineMode::Online { update_plant_state(&mut plantstate, &mut board, &config);
update_plant_state(&mut plantstate, &mut board, &config);
}
let mut light_state = LightState { let mut light_state = LightState {
..Default::default() ..Default::default()
}; };
let is_day = board.is_day(); let is_day = board.is_day();
light_state.is_day = is_day; light_state.is_day = is_day;
light_state.out_of_work_hour = !in_time_range( light_state.out_of_work_hour = !in_time_range(
&europe_time, &timezone_time,
config.night_lamp_hour_start, config.night_lamp_hour_start,
config.night_lamp_hour_end, config.night_lamp_hour_end,
); );
@ -524,43 +490,32 @@ fn safe_main() -> anyhow::Result<()> {
println!("Lightstate is {:?}", light_state); println!("Lightstate is {:?}", light_state);
if online_mode == OnlineMode::Online { match serde_json::to_string(&light_state) {
match serde_json::to_string(&light_state) { Ok(state) => {
Ok(state) => { let _ = board.mqtt_publish(&config, "/light", state.as_bytes());
let _ = board.mqtt_publish(&config, "/light", state.as_bytes()); }
} Err(err) => {
Err(err) => { println!("Error publishing lightstate {}", err);
println!("Error publishing lightstate {}", err); }
} };
};
}
let deep_sleep_duration_minutes: u32 = if state_of_charge < 10 { let deep_sleep_duration_minutes: u32 = if state_of_charge < 10 {
if online_mode == OnlineMode::Online { let _ = board.mqtt_publish(&config, "/deepsleep", "low Volt 12h".as_bytes());
let _ = board.mqtt_publish(&config, "/deepsleep", "low Volt 12h".as_bytes());
}
12 * 60 12 * 60
} else if is_day { } else if is_day {
if did_pump { if did_pump {
if online_mode == OnlineMode::Online { let _ = board.mqtt_publish(&config, "/deepsleep", "after pump".as_bytes());
let _ = board.mqtt_publish(&config, "/deepsleep", "after pump".as_bytes());
}
0 0
} else { } else {
if online_mode == OnlineMode::Online { let _ = board.mqtt_publish(&config, "/deepsleep", "normal 20m".as_bytes());
let _ = board.mqtt_publish(&config, "/deepsleep", "normal 20m".as_bytes());
}
20 20
} }
} else { } else {
if online_mode == OnlineMode::Online { let _ = board.mqtt_publish(&config, "/deepsleep", "night 1h".as_bytes());
let _ = board.mqtt_publish(&config, "/deepsleep", "night 1h".as_bytes());
}
60 60
}; };
if online_mode == OnlineMode::Online { let _ = board.mqtt_publish(&config, "/state", "sleep".as_bytes());
let _ = board.mqtt_publish(&config, "/state", "sleep".as_bytes());
}
//determine next event //determine next event
//is light out of work trigger soon? //is light out of work trigger soon?
@ -568,19 +523,12 @@ fn safe_main() -> anyhow::Result<()> {
//is deep sleep //is deep sleep
mark_app_valid(); mark_app_valid();
if to_config {
println!("Go to button triggerd stay alive");
drop(board);
let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd(reboot_now.clone());
wait_infinity(WaitType::StayAliveBtn, reboot_now.clone());
}
if stay_alive { if stay_alive {
println!("Go to stay alive move"); println!("Go to stay alive move");
drop(board); drop(board);
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::StayAlive, reboot_now.clone()); wait_infinity(WaitType::Config, reboot_now.clone());
} }
unsafe { esp_deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64) }; unsafe { esp_deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64) };
@ -734,8 +682,8 @@ fn determine_state_target_moisture_for_plant(
Some(last_pump) => { Some(last_pump) => {
let next_pump = last_pump + duration; let next_pump = last_pump + duration;
if next_pump > cur { if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin); let local_time = next_pump.with_timezone(&TIME_ZONE);
state.next_pump = Some(europe_time); state.next_pump = Some(local_time);
state.cooldown = true; state.cooldown = true;
} }
} }
@ -777,7 +725,7 @@ fn determine_state_timer_only_for_plant(
Some(last_pump) => { Some(last_pump) => {
let next_pump = last_pump + duration; let next_pump = last_pump + duration;
if next_pump > cur { if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin); let europe_time = next_pump.with_timezone(&TIME_ZONE);
state.next_pump = Some(europe_time); state.next_pump = Some(europe_time);
state.cooldown = true; state.cooldown = true;
} else { } else {
@ -815,7 +763,7 @@ fn determine_state_timer_and_deadzone_for_plant(
Some(last_pump) => { Some(last_pump) => {
let next_pump = last_pump + duration; let next_pump = last_pump + duration;
if next_pump > cur { if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin); let europe_time = next_pump.with_timezone(&TIME_ZONE);
state.next_pump = Some(europe_time); state.next_pump = Some(europe_time);
state.cooldown = true; state.cooldown = true;
} }
@ -905,7 +853,7 @@ fn update_plant_state(
) { ) {
for plant in 0..PLANT_COUNT { for plant in 0..PLANT_COUNT {
let state = &plantstate[plant]; let state = &plantstate[plant];
let plant_config = config.plants[plant]; let plant_config = &config.plants[plant];
let mode = format!("{:?}", plant_config.mode); let mode = format!("{:?}", plant_config.mode);
@ -946,20 +894,17 @@ fn update_plant_state(
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::MissingConfig => 500_u32,
WaitType::FlashError => 100_u32, WaitType::Config => 100_u32,
WaitType::NormalConfig => 500_u32,
WaitType::StayAlive => 1000_u32,
WaitType::StayAliveBtn => 25_u32
};
let led_count = match wait_type {
WaitType::InitialConfig => 8,
WaitType::FlashError => 8,
WaitType::NormalConfig => 4,
WaitType::StayAlive => 2,
WaitType::StayAliveBtn => 5
}; };
let mut led_count = 8;
loop { loop {
if wait_type == WaitType::MissingConfig {
led_count = led_count + 1;
if led_count > 8 {
led_count = 1;
}
};
unsafe { unsafe {
//do not trigger watchdog //do not trigger watchdog
for i in 0..8 { for i in 0..8 {
@ -972,10 +917,13 @@ 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 match wait_type {
&& !STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed) WaitType::MissingConfig => {}
{ WaitType::Config => {
reboot_now.store(true, std::sync::atomic::Ordering::Relaxed); if !STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed) {
reboot_now.store(true, std::sync::atomic::Ordering::Relaxed);
}
}
} }
if reboot_now.load(std::sync::atomic::Ordering::Relaxed) { if reboot_now.load(std::sync::atomic::Ordering::Relaxed) {
println!("Rebooting"); println!("Rebooting");
@ -1002,14 +950,14 @@ fn main() {
} }
fn time_to_string_utc(value_option: Option<DateTime<Utc>>) -> String { fn time_to_string_utc(value_option: Option<DateTime<Utc>>) -> String {
let converted = value_option.and_then(|utc| Some(utc.with_timezone(&Berlin))); let converted = value_option.and_then(|utc| Some(utc.with_timezone(&TIME_ZONE)));
return time_to_string(converted); return time_to_string(converted);
} }
fn time_to_string(value_option: Option<DateTime<Tz>>) -> String { fn time_to_string(value_option: Option<DateTime<Tz>>) -> String {
match value_option { match value_option {
Some(value) => { Some(value) => {
let europe_time = value.with_timezone(&Berlin); let europe_time = value.with_timezone(&TIME_ZONE);
if europe_time.year() > 2023 { if europe_time.year() > 2023 {
return europe_time.to_rfc3339(); return europe_time.to_rfc3339();
} else { } else {

View File

@ -1,14 +1,15 @@
use bq34z100::{Bq34Z100Error, Bq34z100g1, Bq34z100g1Driver}; use bq34z100::{Bq34Z100Error, Bq34z100g1, Bq34z100g1Driver};
use chrono_tz::Europe::Berlin; use ds323x::{DateTimeAccess, Ds323x};
use ds323x::Ds323x;
use eeprom24x::{Eeprom24x, SlaveAddr};
use embedded_hal_bus::i2c::MutexDevice; use embedded_hal_bus::i2c::MutexDevice;
use embedded_svc::wifi::{ use embedded_svc::wifi::{
AccessPointConfiguration, AccessPointInfo, AuthMethod, ClientConfiguration, Configuration, AccessPointConfiguration, AccessPointInfo, AuthMethod, ClientConfiguration, Configuration,
}; };
use esp_idf_hal::adc::{attenuation, Resolution};
use esp_idf_hal::adc::oneshot::config::AdcChannelConfig; use esp_idf_hal::adc::oneshot::config::AdcChannelConfig;
use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver}; use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver};
use esp_idf_hal::adc::{attenuation, Resolution};
use esp_idf_hal::i2c::{APBTickType, I2cConfig, I2cDriver, I2cError}; use esp_idf_hal::i2c::{APBTickType, I2cConfig, I2cDriver, I2cError};
use esp_idf_hal::units::FromValueType; use esp_idf_hal::units::FromValueType;
use esp_idf_svc::eventloop::EspSystemEventLoop; use esp_idf_svc::eventloop::EspSystemEventLoop;
@ -20,13 +21,13 @@ use esp_idf_svc::nvs::EspDefaultNvsPartition;
use esp_idf_svc::wifi::config::{ScanConfig, ScanType}; use esp_idf_svc::wifi::config::{ScanConfig, ScanType};
use esp_idf_svc::wifi::EspWifi; use esp_idf_svc::wifi::EspWifi;
use measurements::Temperature; use measurements::Temperature;
use once_cell::sync::Lazy;
use plant_ctrl2::sipo::ShiftRegister40; use plant_ctrl2::sipo::ShiftRegister40;
use anyhow::anyhow; use anyhow::{anyhow, Context};
use anyhow::{bail, Ok, Result}; use anyhow::{bail, Ok, Result};
use std::ffi::CString; use std::ffi::CString;
use std::fs::File; use std::fs::File;
use std::ops::Deref;
use std::path::Path; use std::path::Path;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
@ -47,10 +48,10 @@ use esp_idf_hal::prelude::Peripherals;
use esp_idf_hal::reset::ResetReason; use esp_idf_hal::reset::ResetReason;
use esp_idf_svc::sntp::{self, SyncStatus}; use esp_idf_svc::sntp::{self, SyncStatus};
use esp_idf_svc::systime::EspSystemTime; use esp_idf_svc::systime::EspSystemTime;
use esp_idf_sys::{esp, gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError}; use esp_idf_sys::{gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError};
use one_wire_bus::OneWire; use one_wire_bus::OneWire;
use crate::config::{self, Config, WifiConfig}; use crate::config::{self, Config};
use crate::{plant_hal, STAY_ALIVE}; use crate::{plant_hal, STAY_ALIVE};
//Only support for 8 right now! //Only support for 8 right now!
@ -58,7 +59,6 @@ pub const PLANT_COUNT: usize = 8;
const REPEAT_MOIST_MEASURE: usize = 3; const REPEAT_MOIST_MEASURE: usize = 3;
const SPIFFS_PARTITION_NAME: &str = "storage"; const SPIFFS_PARTITION_NAME: &str = "storage";
const WIFI_CONFIG_FILE: &str = "/spiffs/wifi.cfg";
const CONFIG_FILE: &str = "/spiffs/config.cfg"; const CONFIG_FILE: &str = "/spiffs/config.cfg";
const TANK_MULTI_SAMPLE: usize = 11; const TANK_MULTI_SAMPLE: usize = 11;
@ -122,10 +122,9 @@ pub struct FileSystemSizeInfo {
} }
#[derive(strum::Display)] #[derive(strum::Display)]
pub enum ClearConfigType { pub enum StartMode {
WifiConfig, AP,
Config, Normal,
None,
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
@ -133,73 +132,6 @@ pub enum Sensor {
A, A,
B, B,
} }
pub trait PlantCtrlBoardInteraction {
fn time(&mut self) -> Result<chrono::DateTime<Utc>>;
fn wifi(
&mut self,
ssid: heapless::String<32>,
password: Option<heapless::String<64>>,
max_wait: u32,
) -> Result<IpInfo>;
fn sntp(&mut self, max_wait: u32) -> Result<chrono::DateTime<Utc>>;
fn mount_file_system(&mut self) -> Result<()>;
fn file_system_size(&mut self) -> Result<FileSystemSizeInfo>;
fn state_charge_percent(&mut self) -> Result<u8>;
fn remaining_milli_ampere_hour(&mut self) -> Result<u16>;
fn max_milli_ampere_hour(&mut self) -> Result<u16>;
fn design_milli_ampere_hour(&mut self) -> Result<u16>;
fn voltage_milli_volt(&mut self) -> Result<u16>;
fn average_current_milli_ampere(&mut self) -> Result<i16>;
fn cycle_count(&mut self) -> Result<u16>;
fn state_health_percent(&mut self) -> Result<u8>;
fn general_fault(&mut self, enable: bool);
fn is_day(&self) -> bool;
fn water_temperature_c(&mut self) -> Result<f32>;
fn tank_sensor_percent(&mut self) -> Result<u16>;
fn set_low_voltage_in_cycle(&mut self);
fn clear_low_voltage_in_cycle(&mut self);
fn low_voltage_in_cycle(&mut self) -> bool;
fn any_pump(&mut self, enabled: bool) -> Result<()>;
//keep state during deepsleep
fn light(&mut self, enable: bool) -> Result<()>;
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<i32>;
fn pump(&self, plant: usize, enable: bool) -> Result<()>;
fn last_pump_time(&self, plant: usize) -> Option<chrono::DateTime<Utc>>;
fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>);
fn store_consecutive_pump_count(&mut self, plant: usize, count: u32);
fn consecutive_pump_count(&mut self, plant: usize) -> u32;
//keep state during deepsleep
fn fault(&self, plant: usize, enable: bool);
//config
fn is_config_reset(&mut self) -> bool;
fn remove_configs(&mut self) -> Result<ClearConfigType>;
fn get_config(&mut self) -> Result<config::Config>;
fn set_config(&mut self, wifi: &Config) -> Result<()>;
fn get_wifi(&mut self) -> Result<config::WifiConfig>;
fn set_wifi(&mut self, wifi: &WifiConfig) -> Result<()>;
fn wifi_ap(&mut self) -> Result<()>;
fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>>;
fn test(&mut self) -> Result<()>;
fn test_pump(&mut self, plant: usize) -> Result<()>;
fn is_wifi_config_file_existant(&mut self) -> bool;
fn mqtt(&mut self, config: &Config) -> Result<()>;
fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()>;
fn sensor_multiplexer(&mut self, n: u8) -> Result<()>;
fn flash_bq34_z100(&mut self, line: &str, dryrun: bool) -> Result<()>;
}
pub trait CreatePlantHal<'a> {
fn create() -> Result<Mutex<PlantCtrlBoard<'static>>>;
}
pub struct PlantHal {} pub struct PlantHal {}
@ -222,16 +154,23 @@ pub struct PlantCtrlBoard<'a> {
pub wifi_driver: EspWifi<'a>, pub wifi_driver: EspWifi<'a>,
one_wire_bus: OneWire<PinDriver<'a, Gpio18, esp_idf_hal::gpio::InputOutput>>, one_wire_bus: OneWire<PinDriver<'a, Gpio18, esp_idf_hal::gpio::InputOutput>>,
mqtt_client: Option<EspMqttClient<'a>>, mqtt_client: Option<EspMqttClient<'a>>,
battery_driver: Option<Bq34z100g1Driver<MutexDevice<'a, I2cDriver<'a>>, Delay>>, battery_driver: Bq34z100g1Driver<MutexDevice<'a, I2cDriver<'a>>, Delay>,
rtc: Option<Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>> rtc:
Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>,
eeprom: Eeprom24x<
MutexDevice<'a, I2cDriver<'a>>,
eeprom24x::page_size::B32,
eeprom24x::addr_size::TwoBytes,
eeprom24x::unique_serial::No,
>,
} }
impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> { impl PlantCtrlBoard<'_> {
fn is_day(&self) -> bool { pub fn is_day(&self) -> bool {
self.solar_is_day.get_level().into() self.solar_is_day.get_level().into()
} }
fn water_temperature_c(&mut self) -> Result<f32> { pub fn water_temperature_c(&mut self) -> Result<f32> {
let mut delay = Delay::new_default(); let mut delay = Delay::new_default();
self.one_wire_bus self.one_wire_bus
@ -261,7 +200,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(sensor_data.temperature / 10_f32) Ok(sensor_data.temperature / 10_f32)
} }
fn tank_sensor_percent(&mut self) -> Result<u16> { pub fn tank_sensor_percent(&mut self) -> Result<u16> {
let delay = Delay::new_default(); let delay = Delay::new_default();
self.tank_power.set_high()?; self.tank_power.set_high()?;
//let stabilize //let stabilize
@ -295,26 +234,26 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
return Ok(percent as u16); return Ok(percent as u16);
} }
fn set_low_voltage_in_cycle(&mut self) { pub fn set_low_voltage_in_cycle(&mut self) {
unsafe { unsafe {
LOW_VOLTAGE_DETECTED = true; LOW_VOLTAGE_DETECTED = true;
} }
} }
fn clear_low_voltage_in_cycle(&mut self) { pub fn clear_low_voltage_in_cycle(&mut self) {
unsafe { unsafe {
LOW_VOLTAGE_DETECTED = false; LOW_VOLTAGE_DETECTED = false;
} }
} }
fn light(&mut self, enable: bool) -> Result<()> { pub fn light(&mut self, enable: bool) -> Result<()> {
unsafe { gpio_hold_dis(self.light.pin()) }; unsafe { gpio_hold_dis(self.light.pin()) };
self.light.set_state(enable.into())?; self.light.set_state(enable.into())?;
unsafe { gpio_hold_en(self.light.pin()) }; unsafe { gpio_hold_en(self.light.pin()) };
Ok(()) Ok(())
} }
fn pump(&self, plant: usize, enable: bool) -> Result<()> { pub fn pump(&self, plant: usize, enable: bool) -> Result<()> {
let index = match plant { let index = match plant {
0 => PUMP1_BIT, 0 => PUMP1_BIT,
1 => PUMP2_BIT, 1 => PUMP2_BIT,
@ -331,30 +270,30 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(()) Ok(())
} }
fn last_pump_time(&self, plant: usize) -> Option<chrono::DateTime<Utc>> { pub fn last_pump_time(&self, plant: usize) -> Option<chrono::DateTime<Utc>> {
let ts = unsafe { LAST_WATERING_TIMESTAMP }[plant]; let ts = unsafe { LAST_WATERING_TIMESTAMP }[plant];
return Some(DateTime::from_timestamp_millis(ts)?); return Some(DateTime::from_timestamp_millis(ts)?);
} }
fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>) { pub fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>) {
unsafe { unsafe {
LAST_WATERING_TIMESTAMP[plant] = time.timestamp_millis(); LAST_WATERING_TIMESTAMP[plant] = time.timestamp_millis();
} }
} }
fn store_consecutive_pump_count(&mut self, plant: usize, count: u32) { pub fn store_consecutive_pump_count(&mut self, plant: usize, count: u32) {
unsafe { unsafe {
CONSECUTIVE_WATERING_PLANT[plant] = count; CONSECUTIVE_WATERING_PLANT[plant] = count;
} }
} }
fn consecutive_pump_count(&mut self, plant: usize) -> u32 { pub fn consecutive_pump_count(&mut self, plant: usize) -> u32 {
unsafe { unsafe {
return CONSECUTIVE_WATERING_PLANT[plant]; return CONSECUTIVE_WATERING_PLANT[plant];
} }
} }
fn fault(&self, plant: usize, enable: bool) { pub fn fault(&self, plant: usize, enable: bool) {
let index = match plant { let index = match plant {
0 => FAULT_1, 0 => FAULT_1,
1 => FAULT_2, 1 => FAULT_2,
@ -371,20 +310,20 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
.unwrap() .unwrap()
} }
fn low_voltage_in_cycle(&mut self) -> bool { pub fn low_voltage_in_cycle(&mut self) -> bool {
unsafe { unsafe {
return LOW_VOLTAGE_DETECTED; return LOW_VOLTAGE_DETECTED;
} }
} }
fn any_pump(&mut self, enable: bool) -> Result<()> { pub fn any_pump(&mut self, enable: bool) -> Result<()> {
{ {
self.main_pump.set_state(enable.into()).unwrap(); self.main_pump.set_state(enable.into()).unwrap();
Ok(()) Ok(())
} }
} }
fn time(&mut self) -> Result<chrono::DateTime<Utc>> { pub fn time(&mut self) -> Result<chrono::DateTime<Utc>> {
let time = EspSystemTime {}.now().as_millis(); let time = EspSystemTime {}.now().as_millis();
let smaller_time = time as i64; let smaller_time = time as i64;
let local_time = DateTime::from_timestamp_millis(smaller_time) let local_time = DateTime::from_timestamp_millis(smaller_time)
@ -392,7 +331,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(local_time) Ok(local_time)
} }
fn sntp(&mut self, max_wait_ms: u32) -> Result<chrono::DateTime<Utc>> { pub fn sntp(&mut self, max_wait_ms: u32) -> Result<chrono::DateTime<Utc>> {
let sntp = sntp::EspSntp::new_default()?; let sntp = sntp::EspSntp::new_default()?;
let mut counter = 0; let mut counter = 0;
while sntp.get_sync_status() != SyncStatus::Completed { while sntp.get_sync_status() != SyncStatus::Completed {
@ -407,7 +346,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
self.time() self.time()
} }
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<i32> { pub fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<i32> {
let sensor_channel = match sensor { let sensor_channel = match sensor {
Sensor::A => match plant { Sensor::A => match plant {
0 => SENSOR_A_1, 0 => SENSOR_A_1,
@ -473,13 +412,13 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(results[mid]) Ok(results[mid])
} }
fn general_fault(&mut self, enable: bool) { pub fn general_fault(&mut self, enable: bool) {
unsafe { gpio_hold_dis(self.general_fault.pin()) }; unsafe { gpio_hold_dis(self.general_fault.pin()) };
self.general_fault.set_state(enable.into()).unwrap(); self.general_fault.set_state(enable.into()).unwrap();
unsafe { gpio_hold_en(self.general_fault.pin()) }; unsafe { gpio_hold_en(self.general_fault.pin()) };
} }
fn wifi_ap(&mut self) -> Result<()> { pub fn wifi_ap(&mut self) -> Result<()> {
let apconfig = AccessPointConfiguration { let apconfig = AccessPointConfiguration {
ssid: heapless::String::from_str("PlantCtrl").unwrap(), ssid: heapless::String::from_str("PlantCtrl").unwrap(),
auth_method: AuthMethod::None, auth_method: AuthMethod::None,
@ -493,7 +432,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(()) Ok(())
} }
fn wifi( pub fn wifi(
&mut self, &mut self,
ssid: heapless::String<32>, ssid: heapless::String<32>,
password: Option<heapless::String<64>>, password: Option<heapless::String<64>>,
@ -556,7 +495,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(address) Ok(address)
} }
fn mount_file_system(&mut self) -> Result<()> { pub fn mount_file_system(&mut self) -> Result<()> {
let base_path = CString::new("/spiffs")?; let base_path = CString::new("/spiffs")?;
let storage = CString::new(SPIFFS_PARTITION_NAME)?; let storage = CString::new(SPIFFS_PARTITION_NAME)?;
let conf = esp_idf_sys::esp_vfs_spiffs_conf_t { let conf = esp_idf_sys::esp_vfs_spiffs_conf_t {
@ -572,7 +511,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
} }
} }
fn file_system_size(&mut self) -> Result<FileSystemSizeInfo> { pub fn file_system_size(&mut self) -> Result<FileSystemSizeInfo> {
let storage = CString::new(SPIFFS_PARTITION_NAME)?; let storage = CString::new(SPIFFS_PARTITION_NAME)?;
let mut total_size = 0; let mut total_size = 0;
let mut used_size = 0; let mut used_size = 0;
@ -590,59 +529,56 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
}) })
} }
fn is_config_reset(&mut self) -> bool { pub fn is_mode_override(&mut self) -> bool {
self.boot_button.get_level() == Level::Low self.boot_button.get_level() == Level::Low
} }
fn remove_configs(&mut self) -> Result<ClearConfigType> { pub fn factory_reset(&mut self) -> Result<()> {
println!("factory resetting");
let config = Path::new(CONFIG_FILE); let config = Path::new(CONFIG_FILE);
if config.exists() { if config.exists() {
println!("Removing config"); println!("Removing config");
std::fs::remove_file(config)?; std::fs::remove_file(config)?;
return Ok(ClearConfigType::Config);
} }
//TODO clear eeprom
let wifi_config = Path::new(WIFI_CONFIG_FILE);
if wifi_config.exists() {
println!("Removing wifi config");
std::fs::remove_file(wifi_config)?;
return Ok(ClearConfigType::WifiConfig);
}
Ok(ClearConfigType::None)
}
fn get_wifi(&mut self) -> Result<config::WifiConfig> {
let cfg = File::open(WIFI_CONFIG_FILE)?;
let config: WifiConfig = serde_json::from_reader(cfg)?;
Ok(config)
}
fn set_wifi(&mut self, wifi: &WifiConfig) -> Result<()> {
let mut cfg = File::create(WIFI_CONFIG_FILE)?;
serde_json::to_writer(&mut cfg, &wifi)?;
println!("Wrote wifi config {}", wifi);
Ok(()) Ok(())
} }
fn get_config(&mut self) -> Result<config::Config> { pub fn get_rtc_time(&mut self) -> Result<DateTime<Utc>> {
let cfg = File::open(CONFIG_FILE)?; match self.rtc.datetime() {
let mut config: Config = serde_json::from_reader(cfg)?; OkStd(rtc_time) => {
//remove duplicate end of topic return Ok(rtc_time.and_utc());
if config.base_topic.ends_with("/") { }
config.base_topic.pop(); Err(err) => {
bail!("Error getting rtc time {:?}", err)
}
} }
}
pub fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> Result<()> {
let naive_time = time.naive_utc();
match self.rtc.set_datetime(&naive_time) {
OkStd(_) => Ok(()),
Err(err) => {
bail!("Error getting rtc time {:?}", err)
}
}
}
pub fn get_config(&mut self) -> Result<config::Config> {
let cfg = File::open(CONFIG_FILE)?;
let config: Config = serde_json::from_reader(cfg)?;
Ok(config) Ok(config)
} }
fn set_config(&mut self, config: &Config) -> Result<()> { pub fn set_config(&mut self, config: &Config) -> Result<()> {
let mut cfg = File::create(CONFIG_FILE)?; let mut cfg = File::create(CONFIG_FILE)?;
serde_json::to_writer(&mut cfg, &config)?; serde_json::to_writer(&mut cfg, &config)?;
println!("Wrote config config {:?}", config); println!("Wrote config config {:?}", config);
Ok(()) Ok(())
} }
fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>> { pub fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>> {
self.wifi_driver.start_scan( self.wifi_driver.start_scan(
&ScanConfig { &ScanConfig {
scan_type: ScanType::Passive(Duration::from_secs(5)), scan_type: ScanType::Passive(Duration::from_secs(5)),
@ -654,7 +590,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(self.wifi_driver.get_scan_result()?) Ok(self.wifi_driver.get_scan_result()?)
} }
fn test_pump(&mut self, plant: usize) -> Result<()> { pub fn test_pump(&mut self, plant: usize) -> Result<()> {
self.any_pump(true)?; self.any_pump(true)?;
self.pump(plant, true)?; self.pump(plant, true)?;
unsafe { vTaskDelay(30000) }; unsafe { vTaskDelay(30000) };
@ -663,7 +599,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(()) Ok(())
} }
fn test(&mut self) -> Result<()> { pub fn test(&mut self) -> Result<()> {
self.general_fault(true); self.general_fault(true);
unsafe { vTaskDelay(100) }; unsafe { vTaskDelay(100) };
self.general_fault(false); self.general_fault(false);
@ -698,13 +634,16 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(()) Ok(())
} }
fn is_wifi_config_file_existant(&mut self) -> bool { pub fn is_wifi_config_file_existant(&mut self) -> bool {
let config = Path::new(CONFIG_FILE); let config = Path::new(CONFIG_FILE);
config.exists() config.exists()
} }
fn mqtt(&mut self, config: &Config) -> Result<()> { pub fn mqtt(&mut self, config: &Config) -> Result<()> {
let last_will_topic = format!("{}/state", config.base_topic); let base_topic = config.base_topic.as_ref().context("missing base topic")?;
let mqtt_url = config.mqtt_url.as_ref().context("missing mqtt url")?;
let last_will_topic = format!("{}/state", base_topic);
let mqtt_client_config = MqttClientConfiguration { let mqtt_client_config = MqttClientConfiguration {
lwt: Some(LwtConfiguration { lwt: Some(LwtConfiguration {
topic: &last_will_topic, topic: &last_will_topic,
@ -722,9 +661,8 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
let mqtt_connected_event_ok = Arc::new(AtomicBool::new(false)); let mqtt_connected_event_ok = Arc::new(AtomicBool::new(false));
let round_trip_ok = Arc::new(AtomicBool::new(false)); let round_trip_ok = Arc::new(AtomicBool::new(false));
let round_trip_topic = format!("{}/internal/roundtrip", config.base_topic); let round_trip_topic = format!("{}/internal/roundtrip", base_topic);
let stay_alive_topic = format!("{}/stay_alive", config.base_topic); let stay_alive_topic = format!("{}/stay_alive", base_topic);
println!("Round trip topic is {}", round_trip_topic);
println!("Stay alive topic is {}", stay_alive_topic); println!("Stay alive topic is {}", stay_alive_topic);
let mqtt_connected_event_received_copy = mqtt_connected_event_received.clone(); let mqtt_connected_event_received_copy = mqtt_connected_event_received.clone();
@ -734,60 +672,55 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
let round_trip_ok_copy = round_trip_ok.clone(); let round_trip_ok_copy = round_trip_ok.clone();
println!( println!(
"Connecting mqtt {} with id {}", "Connecting mqtt {} with id {}",
config.mqtt_url, mqtt_url,
mqtt_client_config.client_id.unwrap_or("not set") mqtt_client_config.client_id.unwrap_or("not set")
); );
let mut client = let mut client = EspMqttClient::new_cb(&mqtt_url, &mqtt_client_config, move |event| {
EspMqttClient::new_cb(&config.mqtt_url, &mqtt_client_config, move |event| { let payload = event.payload();
let payload = event.payload(); match payload {
match payload { embedded_svc::mqtt::client::EventPayload::Received {
embedded_svc::mqtt::client::EventPayload::Received { id: _,
id: _, topic,
topic, data,
data, details: _,
details: _, } => {
} => { let data = String::from_utf8_lossy(data);
let data = String::from_utf8_lossy(data); if let Some(topic) = topic {
if let Some(topic) = topic { //todo use enums
//todo use enums if topic.eq(round_trip_topic_copy.as_str()) {
if topic.eq(round_trip_topic_copy.as_str()) { round_trip_ok_copy.store(true, std::sync::atomic::Ordering::Relaxed);
round_trip_ok_copy } else if topic.eq(stay_alive_topic_copy.as_str()) {
.store(true, std::sync::atomic::Ordering::Relaxed); let value =
} else if topic.eq(stay_alive_topic_copy.as_str()) { data.eq_ignore_ascii_case("true") || data.eq_ignore_ascii_case("1");
let value = data.eq_ignore_ascii_case("true") println!("Received stay alive with value {}", value);
|| data.eq_ignore_ascii_case("1"); STAY_ALIVE.store(value, std::sync::atomic::Ordering::Relaxed);
println!("Received stay alive with value {}", value); } else {
STAY_ALIVE.store(value, std::sync::atomic::Ordering::Relaxed); println!("Unknown topic recieved {}", topic);
} else {
println!("Unknown topic recieved {}", topic);
}
} }
} }
embedded_svc::mqtt::client::EventPayload::Connected(_) => {
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt connected");
}
embedded_svc::mqtt::client::EventPayload::Disconnected => {
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy
.store(false, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt disconnected");
}
embedded_svc::mqtt::client::EventPayload::Error(esp_error) => {
println!("EspMqttError reported {:?}", esp_error);
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy
.store(false, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt error");
}
_ => {}
} }
})?; embedded_svc::mqtt::client::EventPayload::Connected(_) => {
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy.store(true, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt connected");
}
embedded_svc::mqtt::client::EventPayload::Disconnected => {
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt disconnected");
}
embedded_svc::mqtt::client::EventPayload::Error(esp_error) => {
println!("EspMqttError reported {:?}", esp_error);
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt error");
}
_ => {}
}
})?;
let wait_for_connections_event = 0; let wait_for_connections_event = 0;
while wait_for_connections_event < 100 { while wait_for_connections_event < 100 {
@ -836,7 +769,10 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
bail!("Mqtt did not fire connection callback in time"); bail!("Mqtt did not fire connection callback in time");
} }
fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()> { pub fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()> {
if self.mqtt_client.is_none() {
return Ok(());
}
if !subtopic.starts_with("/") { if !subtopic.starts_with("/") {
println!("Subtopic without / at start {}", subtopic); println!("Subtopic without / at start {}", subtopic);
bail!("Subtopic without / at start {}", subtopic); bail!("Subtopic without / at start {}", subtopic);
@ -845,136 +781,112 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
println!("Subtopic exceeds 192 chars {}", subtopic); println!("Subtopic exceeds 192 chars {}", subtopic);
bail!("Subtopic exceeds 192 chars {}", subtopic); bail!("Subtopic exceeds 192 chars {}", subtopic);
} }
if self.mqtt_client.is_none() { let client = self.mqtt_client.as_mut().unwrap();
println!("Not connected to mqtt"); let mut full_topic: heapless::String<256> = heapless::String::new();
bail!("Not connected to mqtt"); if full_topic
} .push_str(&config.base_topic.as_ref().unwrap())
match &mut self.mqtt_client { .is_err()
Some(client) => { {
let mut full_topic: heapless::String<256> = heapless::String::new(); println!("Some error assembling full_topic 1");
if full_topic.push_str(&config.base_topic).is_err() { bail!("Some error assembling full_topic 1")
println!("Some error assembling full_topic 1"); };
bail!("Some error assembling full_topic 1") if full_topic.push_str(subtopic).is_err() {
}; println!("Some error assembling full_topic 2");
if full_topic.push_str(subtopic).is_err() { bail!("Some error assembling full_topic 2")
println!("Some error assembling full_topic 2"); };
bail!("Some error assembling full_topic 2") let publish = client.publish(
}; &full_topic,
let publish = client.publish( embedded_svc::mqtt::client::QoS::ExactlyOnce,
&full_topic, true,
embedded_svc::mqtt::client::QoS::ExactlyOnce, message,
true, );
message, Delay::new(10).delay_ms(50);
match publish {
OkStd(message_id) => {
println!(
"Published mqtt topic {} with message {:#?} msgid is {:?}",
full_topic,
String::from_utf8_lossy(message),
message_id
); );
Delay::new(10).delay_ms(50); return Ok(());
match publish {
OkStd(message_id) => {
println!(
"Published mqtt topic {} with message {:#?} msgid is {:?}",
full_topic,
String::from_utf8_lossy(message),
message_id
);
return Ok(());
}
Err(err) => {
println!(
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
full_topic,
String::from_utf8_lossy(message),
err
);
return Err(err)?;
}
};
} }
None => { Err(err) => {
bail!("No mqtt client"); println!(
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
full_topic,
String::from_utf8_lossy(message),
err
);
return Err(err)?;
} }
};
}
pub fn state_charge_percent(&mut self) -> Result<u8> {
match self.battery_driver.state_of_charge() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading SoC {:?}", err),
} }
} }
fn state_charge_percent(&mut self) -> Result<u8> { pub fn remaining_milli_ampere_hour(&mut self) -> Result<u16> {
match &mut self.battery_driver { match self.battery_driver.remaining_capacity() {
Some(driver) => match driver.state_of_charge() { OkStd(r) => Ok(r),
OkStd(r) => Ok(r), Err(err) => bail!("Error reading Remaining Capacity {:?}", err),
Err(err) => bail!("Error reading SoC {:?}", err),
},
None => bail!("Error reading SoC bq34z100 not found"),
} }
} }
fn remaining_milli_ampere_hour(&mut self) -> Result<u16> { pub fn max_milli_ampere_hour(&mut self) -> Result<u16> {
match &mut self.battery_driver { match self.battery_driver.full_charge_capacity() {
Some(driver) => match driver.remaining_capacity() { OkStd(r) => Ok(r),
OkStd(r) => Ok(r), Err(err) => bail!("Error reading Full Charge Capacity {:?}", err),
Err(err) => bail!("Error reading Remaining Capacity {:?}", err),
},
None => bail!("Error reading Remaining Capacity bq34z100 not found"),
} }
} }
fn max_milli_ampere_hour(&mut self) -> Result<u16> { pub fn design_milli_ampere_hour(&mut self) -> Result<u16> {
match &mut self.battery_driver { match self.battery_driver.design_capacity() {
Some(driver) => match driver.full_charge_capacity() { OkStd(r) => Ok(r),
OkStd(r) => Ok(r), Err(err) => bail!("Error reading Design Capacity {:?}", err),
Err(err) => bail!("Error reading Full Charge Capacity {:?}", err),
},
None => bail!("Error reading Full Charge Capacity bq34z100 not found"),
} }
} }
fn design_milli_ampere_hour(&mut self) -> Result<u16> { pub fn voltage_milli_volt(&mut self) -> Result<u16> {
match &mut self.battery_driver { match self.battery_driver.voltage() {
Some(driver) => match driver.design_capacity() { OkStd(r) => Ok(r),
OkStd(r) => Ok(r), Err(err) => bail!("Error reading voltage {:?}", err),
Err(err) => bail!("Error reading Design Capacity {:?}", err),
},
None => bail!("Error reading Design Capacity bq34z100 not found"),
} }
} }
fn voltage_milli_volt(&mut self) -> Result<u16> { pub fn average_current_milli_ampere(&mut self) -> Result<i16> {
match &mut self.battery_driver { match self.battery_driver.average_current() {
Some(driver) => match driver.voltage() { OkStd(r) => Ok(r),
OkStd(r) => Ok(r), Err(err) => bail!("Error reading Average Current {:?}", err),
Err(err) => bail!("Error reading voltage {:?}", err),
},
None => bail!("Error reading voltage bq34z100 not found"),
} }
} }
fn average_current_milli_ampere(&mut self) -> Result<i16> { pub fn cycle_count(&mut self) -> Result<u16> {
match &mut self.battery_driver { match self.battery_driver.cycle_count() {
Some(driver) => match driver.average_current() { OkStd(r) => Ok(r),
OkStd(r) => Ok(r), Err(err) => bail!("Error reading Cycle Count {:?}", err),
Err(err) => bail!("Error reading Average Current {:?}", err),
},
None => bail!("Error reading Average Current bq34z100 not found"),
} }
} }
fn cycle_count(&mut self) -> Result<u16> { pub fn state_health_percent(&mut self) -> Result<u8> {
match &mut self.battery_driver { match self.battery_driver.state_of_health() {
Some(driver) => match driver.cycle_count() { OkStd(r) => Ok(r as u8),
OkStd(r) => Ok(r), Err(err) => bail!("Error reading State of Health {:?}", err),
Err(err) => bail!("Error reading Cycle Count {:?}", err),
},
None => bail!("Error reading Cycle Count bq34z100 not found"),
} }
} }
fn state_health_percent(&mut self) -> Result<u8> { pub fn flash_bq34_z100(&mut self, line: &str, dryrun: bool) -> Result<()> {
match &mut self.battery_driver { match self.battery_driver.write_flash_stream_i2c(line, dryrun) {
Some(driver) => match driver.state_of_health() { OkStd(r) => Ok(r),
OkStd(r) => Ok(r as u8), Err(err) => bail!("Error reading SoC {:?}", err),
Err(err) => bail!("Error reading State of Health {:?}", err),
},
None => bail!("Error reading State of Health bq34z100 not found"),
} }
} }
fn sensor_multiplexer(&mut self, n: u8) -> Result<()> { pub fn sensor_multiplexer(&mut self, n: u8) -> Result<()> {
assert!(n < 16); assert!(n < 16);
let is_bit_set = |b: u8| -> bool { n & (1 << b) != 0 }; let is_bit_set = |b: u8| -> bool { n & (1 << b) != 0 };
@ -1004,20 +916,10 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
} }
Ok(()) Ok(())
} }
fn flash_bq34_z100(&mut self, line: &str, dryrun: bool) -> Result<()> {
match &mut self.battery_driver {
Some(driver) => match driver.write_flash_stream_i2c(line, dryrun) {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading SoC {:?}", err),
},
None => bail!("Error reading SoC bq34z100 not found"),
}
}
} }
fn print_battery( fn print_battery(
battery_driver: &mut Bq34z100g1Driver<MutexDevice<'_, I2cDriver<'_>>, Delay>, battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
) -> Result<(), Bq34Z100Error<I2cError>> { ) -> Result<(), Bq34Z100Error<I2cError>> {
println!("Try communicating with battery"); println!("Try communicating with battery");
let fwversion = battery_driver.fw_version().unwrap_or_else(|e| { let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
@ -1074,37 +976,61 @@ fn print_battery(
return Result::Ok(()); return Result::Ok(());
} }
impl CreatePlantHal<'_> for PlantHal { pub static I2C_DRIVER: Lazy<Mutex<I2cDriver<'static>>> = Lazy::new(|| PlantHal::create_i2c());
fn create() -> Result<Mutex<PlantCtrlBoard<'static>>> { impl PlantHal {
let peripherals = Peripherals::take()?; fn create_i2c() -> Mutex<I2cDriver<'static>> {
let peripherals = unsafe { Peripherals::new() };
let i2c = peripherals.i2c0;
let config = I2cConfig::new() let config = I2cConfig::new()
.scl_enable_pullup(true) .scl_enable_pullup(true)
.sda_enable_pullup(true) .sda_enable_pullup(true)
.baudrate(400_u32.kHz().into()) .baudrate(100_u32.kHz().into())
.timeout(APBTickType::from(Duration::from_millis(100))); .timeout(APBTickType::from(Duration::from_millis(100)));
let i2c = peripherals.i2c0;
let scl = peripherals.pins.gpio19.downgrade(); let scl = peripherals.pins.gpio19.downgrade();
let sda = peripherals.pins.gpio20.downgrade(); let sda = peripherals.pins.gpio20.downgrade();
let driver = I2cDriver::new(i2c, sda, scl, &config).unwrap(); Mutex::new(I2cDriver::new(i2c, sda, scl, &config).unwrap())
let i2c_port = driver.port(); }
let mut timeout: i32 = 0; pub fn create() -> Result<Mutex<PlantCtrlBoard<'static>>> {
esp!(unsafe { esp_idf_sys::i2c_get_timeout(i2c_port, &mut timeout) }).unwrap(); let peripherals = Peripherals::take()?;
println!("init i2c timeout is {}", timeout);
let i2c_mutex = Arc::new(Mutex::new(driver)); println!("Init battery driver");
let mut battery_driver = Bq34z100g1Driver {
let i2c_battery_device = MutexDevice::new(&i2c_mutex); i2c: MutexDevice::new(&I2C_DRIVER),
let mut battery_driver: Bq34z100g1Driver<MutexDevice<I2cDriver>, Delay> = Bq34z100g1Driver {
i2c: i2c_battery_device,
delay: Delay::new(0), delay: Delay::new(0),
flash_block_data: [0; 32], flash_block_data: [0; 32],
}; };
let i2c_rtc_device = MutexDevice::new(&i2c_mutex); println!("Init rtc driver");
let rtc = Ds323x::new_ds3231(i2c_rtc_device); let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
println!("Init rtc eeprom driver");
let mut eeprom = {
Eeprom24x::new_24x32(
MutexDevice::new(&I2C_DRIVER),
SlaveAddr::Alternative(true, true, true),
)
};
let rtc_time = rtc.datetime();
match rtc_time {
OkStd(tt) => {
println!("Rtc Module reports time at UTC {}", tt);
}
Err(err) => {
println!("Rtc Module could not be read {:?}", err);
}
}
match eeprom.read_byte(0) {
OkStd(byte) => {
println!("Read first byte with status {}", byte);
}
Err(err) => {
println!("Eeprom could not read first byte {:?}", err);
}
}
let mut clock = PinDriver::input_output(peripherals.pins.gpio15.downgrade())?; let mut clock = PinDriver::input_output(peripherals.pins.gpio15.downgrade())?;
clock.set_pull(Pull::Floating).unwrap(); clock.set_pull(Pull::Floating).unwrap();
@ -1165,14 +1091,9 @@ impl CreatePlantHal<'_> for PlantHal {
LOW_VOLTAGE_DETECTED LOW_VOLTAGE_DETECTED
); );
for i in 0..PLANT_COUNT { for i in 0..PLANT_COUNT {
let smaller_time = LAST_WATERING_TIMESTAMP[i];
let utc_time = DateTime::from_timestamp_millis(smaller_time)
.ok_or(anyhow!("could not convert timestamp"))?;
let europe_time = utc_time.with_timezone(&Berlin);
println!( println!(
"LAST_WATERING_TIMESTAMP[{}] = {} as europe {}", "LAST_WATERING_TIMESTAMP[{}] = UTC {}",
i, LAST_WATERING_TIMESTAMP[i], europe_time i, LAST_WATERING_TIMESTAMP[i]
); );
} }
for i in 0..PLANT_COUNT { for i in 0..PLANT_COUNT {
@ -1275,8 +1196,9 @@ impl CreatePlantHal<'_> for PlantHal {
signal_counter: counter_unit1, signal_counter: counter_unit1,
wifi_driver, wifi_driver,
mqtt_client: None, mqtt_client: None,
battery_driver: Some(battery_driver), battery_driver: battery_driver,
rtc: Some(rtc) rtc: rtc,
eeprom: eeprom,
}); });
let _ = rv.lock().is_ok_and(|mut board| { let _ = rv.lock().is_ok_and(|mut board| {

View File

@ -17,15 +17,21 @@
<p id="loaded_n_total"></p> <p id="loaded_n_total"></p>
</form> </form>
<h2>Battery Firmeware (bq34z100 may be R2)</h2> <div>
<form id="upload_form" method="post"> <h2>WIFI</h2>
<input type="file" name="battery_flash_file" id="battery_flash_file"><br> <input type="button" id="scan" value="Scan">
<progress id="battery_flash_progressBar" value="0" max="100" style="width:300px;"></progress> <br>
<input type="button" name="battery_flash_button" id="battery_flash_button"><br> <label for="ap_ssid">AP SSID:</label>
<h3 id="battery_flash_status"></h3> <input type="text" id="ap_ssid" list="ssidlist">
<p id="battery_flash_loaded_n_total"></p>
<div style="height: 100px; display: block; overflow-y: auto;" id = "battery_flash_message"></div> <label for="ssid">SSID:</label>
</form> <input type="text" id="ssid" list="ssidlist">
<datalist id="ssidlist">
<option value="Not scanned yet">
</datalist>
<label for="ssid">Password:</label>
<input type="text" id="password">
</div>
<h2>config</h2> <h2>config</h2>
@ -84,6 +90,16 @@
Light only when dark Light only when dark
</div> </div>
<h2>Battery Firmeware (bq34z100 may be R2)</h2>
<form id="upload_form" method="post">
<input type="file" name="battery_flash_file" id="battery_flash_file"><br>
<progress id="battery_flash_progressBar" value="0" max="100" style="width:300px;"></progress>
<input type="button" name="battery_flash_button" id="battery_flash_button"><br>
<h3 id="battery_flash_status"></h3>
<p id="battery_flash_loaded_n_total"></p>
<div style="height: 100px; display: block; overflow-y: auto;" id = "battery_flash_message"></div>
</form>
<h3>Plants:</h3> <h3>Plants:</h3>

View File

@ -1,47 +0,0 @@
<html>
<body>
<input type="button" id="test" value="Test">
<h2>Current Firmware</h2>
<div>
<div id="firmware_buildtime">Buildtime loading</div>
<div id="firmware_githash">Build githash loading</div>
</div>
<div>
<h2>firmeware OTA v3</h2>
<form id="upload_form" method="post">
<input type="file" name="file1" id="file1"><br>
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<h3 id="answer"></h3>
<p id="loaded_n_total"></p>
</form>
</div>
<h2>Battery Firmeware (bq34z100 may be R2)</h2>
<form id="upload_form" method="post">
<input type="file" name="battery_flash_file" id="battery_flash_file"><br>
<progress id="battery_flash_progressBar" value="0" max="100" style="width:300px;"></progress>
<input type="button" name="battery_flash_button" id="battery_flash_button"><br>
<h3 id="battery_flash_status"></h3>
<p id="battery_flash_loaded_n_total"></p>
<div style="height: 100px; display: block; overflow-y: auto;" id = "battery_flash_message"></div>
</form>
<div>
<h2>WIFI</h2>
<input type="button" id="scan" value="Scan">
<br>
<label for="ssid">SSID:</label>
<input type="text" id="ssid" list="ssidlist">
<datalist id="ssidlist">
<option value="Not scanned yet">
</datalist>
<label for="ssid">Password:</label>
<input type="text" id="password">
<input type="button" id="save" value="Save & Restart">
<div id="wifistatus"></div>
<br>
</div>
<script src="bundle.js"></script>
</body>
</html>

View File

@ -15,10 +15,7 @@ use esp_idf_svc::http::server::{Configuration, EspHttpServer};
use heapless::String; use heapless::String;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::config::Config;
config::{Config, WifiConfig},
plant_hal::PlantCtrlBoardInteraction,
};
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
struct SSIDList<'a> { struct SSIDList<'a> {
@ -36,138 +33,9 @@ pub struct TestPump {
pump: usize, pump: usize,
} }
pub fn httpd_initial(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let mut server = shared();
server
.fn_handler("/", Method::Get, move |request| {
let mut response = request.into_ok_response()?;
response.write(include_bytes!("initial_config.html"))?;
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/wifiscan", Method::Post, move |request| {
let mut response = request.into_ok_response()?;
let mut board = BOARD_ACCESS.lock().unwrap();
match board.wifi_scan() {
Err(error) => {
response.write(format!("Error scanning wifi: {}", error).as_bytes())?;
}
Ok(scan_result) => {
let mut ssids: Vec<&String<32>> = Vec::new();
scan_result.iter().for_each(|s| ssids.push(&s.ssid));
let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
println!("Sending ssid list {}", &ssid_json);
response.write(ssid_json.as_bytes())?;
}
}
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/wifisave", Method::Post, move |mut request| {
let mut buf = [0_u8; 2048];
let read = request.read(&mut buf);
if read.is_err() {
let error_text = read.unwrap_err().to_string();
println!("Could not parse wificonfig {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return anyhow::Ok(());
}
let actual_data = &buf[0..read.unwrap()];
println!("raw {:?}", actual_data);
println!("Raw data {}", from_utf8(actual_data).unwrap());
let wifi_config: Result<WifiConfig, serde_json::Error> =
serde_json::from_slice(actual_data);
if wifi_config.is_err() {
let error_text = wifi_config.unwrap_err().to_string();
println!("Could not parse wificonfig {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return anyhow::Ok(());
}
let mut board = BOARD_ACCESS.lock().unwrap();
board.set_wifi(&wifi_config.unwrap())?;
let mut response = request.into_status_response(202)?;
response.write("saved".as_bytes())?;
reboot_now.store(true, std::sync::atomic::Ordering::Relaxed);
anyhow::Ok(())
})
.unwrap();
server
}
pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> { pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let mut server = shared();
server
.fn_handler("/", Method::Get, move |request| {
let mut response = request.into_ok_response()?;
response.write(include_bytes!("config.html"))?;
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/get_config", Method::Get, move |request| {
let mut response = request.into_ok_response()?;
let mut board = BOARD_ACCESS.lock().unwrap();
match board.get_config() {
Ok(config) => {
let config_json = serde_json::to_string(&config)?;
response.write(config_json.as_bytes())?;
}
Err(_) => {
let config_json = serde_json::to_string(&Config::default())?;
response.write(config_json.as_bytes())?;
}
}
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/set_config", Method::Post, move |mut request| {
let mut buf = [0_u8; 3072];
let read = request.read(&mut buf);
if read.is_err() {
let error_text = read.unwrap_err().to_string();
println!("Could not parse config {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return anyhow::Ok(());
}
let actual_data = &buf[0..read.unwrap()];
println!("Raw data {}", from_utf8(actual_data).unwrap());
let config: Result<Config, serde_json::Error> = serde_json::from_slice(actual_data);
if config.is_err() {
let error_text = config.unwrap_err().to_string();
println!("Could not parse config {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(());
}
let mut board = BOARD_ACCESS.lock().unwrap();
board.set_config(&config.unwrap())?;
let mut response = request.into_status_response(202)?;
response.write("saved".as_bytes())?;
reboot_now.store(true, std::sync::atomic::Ordering::Relaxed);
Ok(())
})
.unwrap();
server
}
pub fn shared() -> Box<EspHttpServer<'static>> {
let server_config = Configuration { let server_config = Configuration {
stack_size: 8192, stack_size: 32768,
..Default::default() ..Default::default()
}; };
let mut server: Box<EspHttpServer<'static>> = let mut server: Box<EspHttpServer<'static>> =
@ -293,6 +161,7 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
.unwrap(); .unwrap();
server server
.fn_handler("/flashbattery", Method::Post, move |mut request| { .fn_handler("/flashbattery", Method::Post, move |mut request| {
let mut board = BOARD_ACCESS.lock().unwrap(); let mut board = BOARD_ACCESS.lock().unwrap();
let mut buffer: [u8; 128] = [0; 128]; let mut buffer: [u8; 128] = [0; 128];
let mut line_buffer: VecDeque<u8> = VecDeque::new(); let mut line_buffer: VecDeque<u8> = VecDeque::new();
@ -302,6 +171,7 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
let mut toggle = true; let mut toggle = true;
let delay = Delay::new(1); let delay = Delay::new(1);
todo!("Write to storage before attempting to flash!");
loop { loop {
delay.delay_us(2); delay.delay_us(2);
let read = request.read(&mut buffer).unwrap(); let read = request.read(&mut buffer).unwrap();
@ -325,7 +195,6 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
line_buffer.write_all(to_write).unwrap(); line_buffer.write_all(to_write).unwrap();
board.general_fault(toggle); board.general_fault(toggle);
toggle = !toggle; toggle = !toggle;
loop { loop {
let has_line = line_buffer.contains(&b'\n'); let has_line = line_buffer.contains(&b'\n');
if !has_line { if !has_line {
@ -357,5 +226,82 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
anyhow::Ok(()) anyhow::Ok(())
}) })
.unwrap(); .unwrap();
server
.fn_handler("/wifiscan", Method::Post, move |request| {
let mut response = request.into_ok_response()?;
let mut board = BOARD_ACCESS.lock().unwrap();
match board.wifi_scan() {
Err(error) => {
response.write(format!("Error scanning wifi: {}", error).as_bytes())?;
}
Ok(scan_result) => {
let mut ssids: Vec<&String<32>> = Vec::new();
scan_result.iter().for_each(|s| ssids.push(&s.ssid));
let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
println!("Sending ssid list {}", &ssid_json);
response.write(ssid_json.as_bytes())?;
}
}
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/", Method::Get, move |request| {
let mut response = request.into_ok_response()?;
response.write(include_bytes!("config.html"))?;
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/get_config", Method::Get, move |request| {
let mut response = request.into_ok_response()?;
let mut board = BOARD_ACCESS.lock().unwrap();
match board.get_config() {
Ok(config) => {
let config_json = serde_json::to_string(&config)?;
response.write(config_json.as_bytes())?;
}
Err(_) => {
let config_json = serde_json::to_string(&Config::default())?;
response.write(config_json.as_bytes())?;
}
}
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/set_config", Method::Post, move |mut request| {
let mut buf = [0_u8; 3072];
let read = request.read(&mut buf);
if read.is_err() {
let error_text = read.unwrap_err().to_string();
println!("Could not parse config {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return anyhow::Ok(());
}
let actual_data = &buf[0..read.unwrap()];
println!("Raw data {}", from_utf8(actual_data).unwrap());
let config: Result<Config, serde_json::Error> = serde_json::from_slice(actual_data);
if config.is_err() {
let error_text = config.unwrap_err().to_string();
println!("Could not parse config {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(());
}
let mut board = BOARD_ACCESS.lock().unwrap();
board.set_config(&config.unwrap())?;
let mut response = request.into_status_response(202)?;
response.write("saved".as_bytes())?;
reboot_now.store(true, std::sync::atomic::Ordering::Relaxed);
Ok(())
})
.unwrap();
server server
} }

View File

@ -1,4 +1,7 @@
interface PlantConfig { interface PlantConfig {
ap_ssid: string,
ssid: string,
password: string,
mqtt_url: string, mqtt_url: string,
base_topic: string, base_topic: string,
tank_sensor_enabled: boolean, tank_sensor_enabled: boolean,
@ -24,12 +27,53 @@ interface PlantConfig {
}[] }[]
} }
interface SSIDList {
ssids : [string]
}
interface TestPump{ interface TestPump{
pump: number pump: number
} }
let plants = document.getElementById("plants") as HTMLInputElement; let plants = document.getElementById("plants") as HTMLInputElement;
let scanWifiBtn = document.getElementById("scan") as HTMLButtonElement;
if(scanWifiBtn){
scanWifiBtn.onclick = scanWifi;
}
export function scanWifi(){
var scanButton = (document.getElementById("scan") as HTMLButtonElement);
scanButton.disabled = true;
var ajax = new XMLHttpRequest();
ajax.responseType = 'json';
ajax.onreadystatechange = () => {
if (ajax.readyState === 4) {
callback(ajax.response);
}
};
ajax.onerror = (evt) => {
console.log(evt)
scanButton.disabled = false;
alert("Failed to start see console")
}
ajax.open("POST", "/wifiscan");
ajax.send();
}
function callback(data:SSIDList){
var ssidlist = document.getElementById("ssidlist")
ssidlist.innerHTML = ''
for (var ssid of data.ssids) {
var wi = document.createElement("option");
wi.value = ssid;
ssidlist.appendChild(wi);
}
}
let fromWrapper = (() => { let fromWrapper = (() => {
let plantcount = 0; let plantcount = 0;
@ -42,7 +86,12 @@ let fromWrapper = (() => {
} }
} }
var ap_ssid = (document.getElementById("ap_ssid") as HTMLInputElement);
ap_ssid.onchange = updateJson
var ssid = (document.getElementById("ssid") as HTMLInputElement);
ssid.onchange = updateJson
var password = (document.getElementById("password") as HTMLInputElement);
password.onchange = updateJson
let mqtt_url = document.getElementById("mqtt_url") as HTMLInputElement; let mqtt_url = document.getElementById("mqtt_url") as HTMLInputElement;
mqtt_url.onchange = updateJson mqtt_url.onchange = updateJson
let base_topic = document.getElementById("base_topic") as HTMLInputElement; let base_topic = document.getElementById("base_topic") as HTMLInputElement;
@ -235,6 +284,11 @@ let fromWrapper = (() => {
function sync(current: PlantConfig) { function sync(current: PlantConfig) {
plantcount = current.plants.length plantcount = current.plants.length
ap_ssid.value = current.ap_ssid;
ssid.value = current.ssid;
password.value = current.password;
mqtt_url.value = current.mqtt_url; mqtt_url.value = current.mqtt_url;
base_topic.value = current.base_topic; base_topic.value = current.base_topic;
max_consecutive_pump_count.value = current.max_consecutive_pump_count.toString(); max_consecutive_pump_count.value = current.max_consecutive_pump_count.toString();
@ -274,6 +328,9 @@ let fromWrapper = (() => {
function updateJson() { function updateJson() {
var current: PlantConfig = { var current: PlantConfig = {
ap_ssid: ap_ssid.value,
ssid: ssid.value,
password: password.value,
max_consecutive_pump_count: +max_consecutive_pump_count.value, max_consecutive_pump_count: +max_consecutive_pump_count.value,
mqtt_url: mqtt_url.value, mqtt_url: mqtt_url.value,
base_topic: base_topic.value, base_topic: base_topic.value,
@ -339,7 +396,12 @@ let fromWrapper = (() => {
fetch("/get_config") fetch("/get_config")
.then(response => response.json()) .then(response => response.json())
.then(json => { createForm(json as PlantConfig); } .then(loaded => {
var currentConfig = loaded as PlantConfig;
createForm(currentConfig);
var pretty = JSON.stringify(currentConfig, undefined, 1);
json.value = pretty;
}
) )
}) })
if (plants) { if (plants) {

View File

@ -1,93 +0,0 @@
interface WifiConfig {
ssid: string;
password: string;
}
interface SSIDList {
ssids : [string]
}
export function saveWifi(){
var saveButton = (document.getElementById("save") as HTMLButtonElement);
saveButton.disabled = true;
var ssid = (document.getElementById("ssid") as HTMLInputElement).value
var password = (document.getElementById("password") as HTMLInputElement).value
var wifistatus = document.getElementById("wifistatus")
var wificonfig:WifiConfig = {ssid, password}
var pretty = JSON.stringify(wificonfig, undefined, 4);
console.log("Sending config " + pretty)
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = () => {
wifistatus.innerText = ajax.responseText
};
ajax.onerror = (evt) => {
console.log(evt)
wifistatus.innerText = ajax.responseText
saveButton.disabled = false;
alert("Failed to save config see console")
}
ajax.open("POST", "/wifisave");
ajax.send(pretty);
}
export function scanWifi(){
var scanButton = (document.getElementById("scan") as HTMLButtonElement);
scanButton.disabled = true;
var ajax = new XMLHttpRequest();
ajax.responseType = 'json';
ajax.onreadystatechange = () => {
if (ajax.readyState === 4) {
callback(ajax.response);
}
};
ajax.onerror = (evt) => {
console.log(evt)
scanButton.disabled = false;
alert("Failed to start see console")
}
ajax.open("POST", "/wifiscan");
ajax.send();
}
function test(){
var testButton = (document.getElementById("test") as HTMLButtonElement);
testButton.disabled = true;
var ajax = new XMLHttpRequest();
ajax.responseType = 'json';
ajax.onerror = (evt) => {
console.log(evt)
testButton.disabled = false;
alert("Failed to start see console")
}
ajax.open("POST", "/boardtest");
ajax.send();
}
function callback(data:SSIDList){
var ssidlist = document.getElementById("ssidlist")
ssidlist.innerHTML = ''
for (var ssid of data.ssids) {
var wi = document.createElement("option");
wi.value = ssid;
ssidlist.appendChild(wi);
}
}
let testBtn = document.getElementById("test") as HTMLButtonElement;
if(testBtn){
testBtn.onclick = test;
}
let scanWifiBtn = document.getElementById("scan") as HTMLButtonElement;
if(scanWifiBtn){
scanWifiBtn.onclick = scanWifi;
}
let saveWifiBtn = document.getElementById("save") as HTMLButtonElement;
if(saveWifiBtn){
saveWifiBtn.onclick = saveWifi;
}

View File

@ -3,7 +3,7 @@ const path = require('path');
module.exports = { module.exports = {
mode: "development", mode: "development",
entry: ['./src/form.ts','./src/ota.ts','./src/wifi.ts', "./src/battery.ts"], entry: ['./src/form.ts','./src/ota.ts', "./src/battery.ts"],
devtool: 'inline-source-map', devtool: 'inline-source-map',
module: { module: {
rules: [ rules: [