webserver improvements

This commit is contained in:
2023-12-27 17:33:11 +01:00
parent 1e40e2e3ba
commit 4c02b99ea7
11 changed files with 361 additions and 202 deletions

View File

@@ -6,28 +6,47 @@ use crate::PLANT_COUNT;
#[derive(Serialize, Deserialize)]
#[derive(Debug)]
pub struct Config {
tank_sensor_enabled: bool,
tank_full_ml: u32,
tank_warn_percent: u8,
plantcount: u16,
night_lamp_hour_start: u8,
night_lamp_hour_end: u8,
night_lamp_only_when_dark: u8,
night_lamp_only_when_dark: bool,
plants: [Plant;PLANT_COUNT]
}
#[derive(Serialize, Deserialize)]
impl Default for Config {
fn default() -> Self {
Self { tank_sensor_enabled: true,
tank_full_ml: 5000,
tank_warn_percent: 50,
night_lamp_hour_start: 21,
night_lamp_hour_end: 2,
night_lamp_only_when_dark: true,
plants: [Plant::default();PLANT_COUNT]
}
}
}
#[derive(Serialize, Deserialize, Copy, Clone)]
#[derive(Debug)]
pub struct Plant{
target_moisture: u8,
pump_time_s: u16,
pump_cooldown_min: u16,
pump_hour_start: heapless::String<5>,
pump_hour_end: heapless::String<5>
pump_hour_start: u8,
pump_hour_end: u8
}
impl Default for Plant {
fn default() -> Self {
Self { target_moisture: 40, pump_time_s: 60, pump_cooldown_min: 60, pump_hour_start: 8, pump_hour_end: 20 }
}
}
#[derive(Serialize, Deserialize)]
#[derive(Debug)]
pub struct WifiConfig {

View File

@@ -1,4 +1,4 @@
use std::{sync::{Arc, Mutex}, env};
use std::{sync::{Arc, Mutex, atomic::AtomicBool}, env};
use chrono::{Datelike, NaiveDateTime, Timelike};
@@ -9,7 +9,7 @@ use esp_idf_sys::{esp_restart, vTaskDelay};
use plant_hal::{CreatePlantHal, PlantCtrlBoard, PlantCtrlBoardInteraction, PlantHal, PLANT_COUNT};
use crate::{config::{Config, WifiConfig}, webserver::webserver::httpd_initial};
use crate::{config::{Config, WifiConfig}, webserver::webserver::{httpd_initial, httpd}};
mod config;
pub mod plant_hal;
mod webserver {
@@ -27,32 +27,47 @@ enum OnlineMode {
enum WaitType{
InitialConfig,
FlashError
FlashError,
NormalConfig
}
fn wait_infinity(board_access: Arc<Mutex<PlantCtrlBoard<'_>>>, wait_type:WaitType) -> !{
fn wait_infinity(wait_type:WaitType, reboot_now:Arc<AtomicBool>) -> !{
let delay = match wait_type {
WaitType::InitialConfig => 250_u32,
WaitType::FlashError => 100_u32,
WaitType::NormalConfig => 500_u32
};
board_access.lock().unwrap().light(true).unwrap();
let led_count = match wait_type {
WaitType::InitialConfig => 8,
WaitType::FlashError => 8,
WaitType::NormalConfig => 4
};
BOARD_ACCESS.lock().unwrap().light(true).unwrap();
loop {
unsafe {
//do not trigger watchdog
for i in 0..8 {
board_access.lock().unwrap().fault(i, true);
BOARD_ACCESS.lock().unwrap().fault(i, i <led_count);
}
board_access.lock().unwrap().general_fault(true);
BOARD_ACCESS.lock().unwrap().general_fault(true);
vTaskDelay(delay);
board_access.lock().unwrap().general_fault(false);
BOARD_ACCESS.lock().unwrap().general_fault(false);
for i in 0..8 {
board_access.lock().unwrap().fault(i, false);
BOARD_ACCESS.lock().unwrap().fault(i, false);
}
vTaskDelay(delay);
if reboot_now.load(std::sync::atomic::Ordering::Relaxed) {
println!("Rebooting");
esp_restart();
}
}
}
}
static BOARD_ACCESS: Lazy<PlantCtrlBoard> = Lazy::new(|| {
PlantHal::create()?;
});
fn main() -> Result<()> {
// It is necessary to call this function once. Otherwise some patches to the runtime
// implemented by esp-idf-sys might not link properly. See https://github.com/esp-rs/esp-idf-template/issues/71
@@ -67,8 +82,7 @@ fn main() -> Result<()> {
println!("Version useing git has {}", git_hash);
println!("Board hal init");
let board_access = PlantHal::create()?;
let mut board = board_access.lock().unwrap();
let mut board = BOARD_ACCESS.lock().unwrap();
println!("Mounting filesystem");
board.mountFileSystem()?;
let free_space = board.fileSystemSize()?;
@@ -103,16 +117,14 @@ fn main() -> Result<()> {
if board.is_config_reset() {
println!("Reset config is still pressed, deleting configs and reboot");
match board.remove_configs() {
Ok(_) => {
println!("Removed config files, restarting");
unsafe {
esp_restart();
}
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( board_access.clone(), WaitType::FlashError);
wait_infinity(WaitType::FlashError, Arc::new(AtomicBool::new(false)));
}
}
}
@@ -130,14 +142,13 @@ fn main() -> Result<()> {
board.wifi_ap().unwrap();
//config upload will trigger reboot!
drop(board);
let _webserver = httpd_initial(board_access.clone());
wait_infinity(board_access.clone(), WaitType::InitialConfig);
let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd_initial(BOARD_ACCESS.clone(), reboot_now.clone());
wait_infinity(WaitType::InitialConfig, reboot_now.clone());
},
};
// let proceed = config.unwrap();
//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
@@ -203,6 +214,21 @@ fn main() -> Result<()> {
println!("Running logic at europe/berlin {}", europe_time);
}
let config:Config;
match (board.get_config()){
Ok(valid) => {
config = valid;
},
Err(err) => {
println!("Missing normal config, entering config mode {}", err);
//config upload will trigger reboot!
drop(board);
let reboot_now = Arc::new(AtomicBool::new(false));
let _webserver = httpd(BOARD_ACCESS.clone(),reboot_now.clone());
wait_infinity(BOARD_ACCESS.clone(), WaitType::NormalConfig, reboot_now.clone());
},
}
if online_mode == OnlineMode::SnTp {
//mqtt here
}

View File

@@ -11,6 +11,7 @@ use plant_ctrl2::sipo::ShiftRegister40;
use anyhow::anyhow;
use anyhow::{bail, Ok, Result};
use strum::EnumString;
use std::ffi::CString;
use std::fs::File;
use std::io::Read;
@@ -23,7 +24,6 @@ use chrono::{DateTime, NaiveDateTime, Utc};
use ds18b20::Ds18b20;
use embedded_hal::digital::v2::OutputPin;
use esp_idf_hal::adc::config::Config;
use esp_idf_hal::adc::{attenuation, AdcChannelDriver, AdcDriver};
use esp_idf_hal::delay::Delay;
use esp_idf_hal::gpio::{AnyInputPin, Gpio39, Gpio4, Level, PinDriver};
@@ -37,7 +37,7 @@ use esp_idf_svc::systime::EspSystemTime;
use esp_idf_sys::{EspError, vTaskDelay};
use one_wire_bus::OneWire;
use crate::config::{self, WifiConfig};
use crate::config::{self, WifiConfig, Config};
pub const PLANT_COUNT: usize = 8;
const PINS_PER_PLANT: usize = 5;
@@ -80,6 +80,14 @@ pub struct FileSystemSizeInfo {
pub free_size: usize,
}
#[derive(strum::Display)]
pub enum ClearConfigType {
WifiConfig,
Config,
None
}
#[derive(Debug)]
pub enum Sensor {
A,
@@ -121,8 +129,9 @@ pub trait PlantCtrlBoardInteraction {
//config
fn is_config_reset(&mut self) -> bool;
fn remove_configs(&mut self) -> Result<()>;
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<()>;
@@ -137,7 +146,7 @@ pub trait CreatePlantHal<'a> {
pub struct PlantHal {}
impl CreatePlantHal<'_> for PlantHal {
fn create() -> Result<Arc<Mutex<PlantCtrlBoard<'static>>>> {
fn create() -> Result<Mutex<PlantCtrlBoard<'static>>> {
let peripherals = Peripherals::take()?;
let mut clock = PinDriver::output(peripherals.pins.gpio21)?;
@@ -213,7 +222,7 @@ impl CreatePlantHal<'_> for PlantHal {
let last_watering_timestamp = Mutex::new(unsafe { LAST_WATERING_TIMESTAMP });
let consecutive_watering_plant = Mutex::new(unsafe { CONSECUTIVE_WATERING_PLANT });
let low_voltage_detected = Mutex::new(unsafe { LOW_VOLTAGE_DETECTED });
let tank_driver = AdcDriver::new(peripherals.adc1, &Config::new())?;
let tank_driver = AdcDriver::new(peripherals.adc1, &esp_idf_hal::adc::config::Config::new())?;
let tank_channel: AdcChannelDriver<'_, { attenuation::DB_11 }, Gpio39> =
AdcChannelDriver::new(peripherals.pins.gpio39)?;
let solar_is_day = PinDriver::input(peripherals.pins.gpio25)?;
@@ -228,7 +237,7 @@ impl CreatePlantHal<'_> for PlantHal {
println!("After stuff");
let rv = Arc::new(Mutex::new(PlantCtrlBoard {
let rv = Mutex::new(PlantCtrlBoard {
shift_register : shift_register,
last_watering_timestamp: last_watering_timestamp,
consecutive_watering_plant: consecutive_watering_plant,
@@ -244,7 +253,7 @@ impl CreatePlantHal<'_> for PlantHal {
one_wire_bus: one_wire_bus,
signal_counter: counter_unit1,
wifi_driver: wifi_driver,
}));
});
return Ok(rv);
}
}
@@ -534,19 +543,26 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
return self.boot_button.get_level() == Level::Low;
}
fn remove_configs(&mut self) -> Result<()> {
let wifi_config = Path::new(WIFI_CONFIG_FILE);
if wifi_config.exists() {
println!("Removing wifi config");
std::fs::remove_file(wifi_config)?;
}
fn remove_configs(&mut self) -> Result<ClearConfigType> {
let config = Path::new(CONFIG_FILE);
if config.exists() {
println!("Removing config");
std::fs::remove_file(config)?;
return Ok(ClearConfigType::Config);
}
Ok(())
let wifi_config = Path::new(WIFI_CONFIG_FILE);
if wifi_config.exists() {
println!("Removing wifi config");
std::fs::remove_file(wifi_config)?;
Ok(ClearConfigType::WifiConfig);
}
Ok((ClearConfigType::None));
}
fn get_wifi(&mut self) -> Result<config::WifiConfig> {
@@ -563,12 +579,16 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
}
fn get_config(&mut self) -> Result<config::Config> {
let mut cfg = File::open(CONFIG_FILE)?;
let mut data: [u8; 512] = [0; 512];
let read = cfg.read(&mut data)?;
println!("Read file {}", from_utf8(&data[0..read])?);
let cfg = File::open(CONFIG_FILE)?;
let config: Config = serde_json::from_reader(cfg)?;
return Ok(config);
}
bail!("todo")
fn set_config(&mut self, config: &Config) -> Result<()> {
let mut cfg = File::create(CONFIG_FILE)?;
serde_json::to_writer(&mut cfg, &config)?;
println!("Wrote config config {:?}", config);
return Ok(());
}
fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>> {

View File

@@ -32,9 +32,11 @@
<h3>Light:</h3>
<div>
Start
<input type="time" id="night_lamp_time_start">
<select type="time" id="night_lamp_time_start">
</select>
Stop
<input type="time" id="night_lamp_time_end">
<select type="time" id="night_lamp_time_end">
</select>
</div>
<div>
<input type="checkbox" id="night_lamp_only_when_dark">

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -23,7 +23,7 @@
<option value="Not scanned yet">
</datalist>
<label for="ssid">Password:</label>
<input type="text" id="password" list="ssidlist">
<input type="text" id="password">
<input type="button" id="save" value="Save & Restart">
<div id="wifistatus"></div>
<br>

View File

@@ -1,14 +1,14 @@
//offer ota and config mode
use std::sync::{Mutex, Arc};
use std::{sync::{Mutex, Arc, atomic::AtomicBool}, str::from_utf8};
use embedded_svc::http::Method;
use embedded_svc::http::{Method, Headers};
use esp_idf_svc::http::server::EspHttpServer;
use esp_ota::OtaUpdate;
use heapless::String;
use serde::Serialize;
use crate::{plant_hal::{PlantCtrlBoard, PlantCtrlBoardInteraction}, config::WifiConfig};
use crate::{plant_hal::{PlantCtrlBoard, PlantCtrlBoardInteraction, PLANT_COUNT}, config::{WifiConfig, Config, Plant}};
#[derive(Serialize)]
#[derive(Debug)]
@@ -16,7 +16,7 @@ struct SSIDList<'a> {
ssids: Vec<&'a String<32>>
}
pub fn httpd_initial(board_access:Arc<Mutex<PlantCtrlBoard<'static>>>) -> Box<EspHttpServer<'static>> {
pub fn httpd_initial(board_access:Arc<Mutex<PlantCtrlBoard<'static>>>, 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()?;
@@ -37,9 +37,9 @@ pub fn httpd_initial(board_access:Arc<Mutex<PlantCtrlBoard<'static>>>) -> Box<Es
scan_result.iter().for_each(|s|
ssids.push(&s.ssid)
);
response.write( serde_json::to_string(
&SSIDList{ssids}
)?.as_bytes())?;
let ssid_json = serde_json::to_string( &SSIDList{ssids})?;
println!("Sending ssid list {}", &ssid_json);
response.write( &ssid_json.as_bytes())?;
},
}
return Ok(())
@@ -48,6 +48,7 @@ pub fn httpd_initial(board_access:Arc<Mutex<PlantCtrlBoard<'static>>>) -> Box<Es
let board_access_for_save = board_access.clone();
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(){
@@ -57,6 +58,8 @@ pub fn httpd_initial(board_access:Arc<Mutex<PlantCtrlBoard<'static>>>) -> Box<Es
return 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();
@@ -68,6 +71,7 @@ pub fn httpd_initial(board_access:Arc<Mutex<PlantCtrlBoard<'static>>>) -> Box<Es
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);
return Ok(())
}).unwrap();
@@ -81,7 +85,7 @@ pub fn httpd_initial(board_access:Arc<Mutex<PlantCtrlBoard<'static>>>) -> Box<Es
return server
}
pub fn httpd(board:&mut Box<PlantCtrlBoard<'static>>) -> Box<EspHttpServer<'static>> {
pub fn httpd(board_access:Arc<Mutex<PlantCtrlBoard<'static>>>, reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let mut server = shared();
server
@@ -91,12 +95,57 @@ pub fn httpd(board:&mut Box<PlantCtrlBoard<'static>>) -> Box<EspHttpServer<'stat
return Ok(())
}).unwrap();
let board_access_for_get_config= board_access.clone();
server
.fn_handler("/get_config",Method::Get, move |request| {
let mut response = request.into_ok_response()?;
let mut board = board_access_for_get_config.lock()?;
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())?;
},
}
return Ok(())
}).unwrap();
let board_access_for_set_config= board_access.clone();
server.fn_handler("/set_config",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 Ok(());
}
let actual_data = &buf[0..read.unwrap()];
println!("raw {:?}", actual_data);
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 wificonfig {}", error_text);
request.into_status_response(500)?.write(error_text.as_bytes())?;
return Ok(());
}
let mut board = board_access_for_set_config.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);
return Ok(())
}).unwrap();
return server;
}
pub fn shared() -> Box<EspHttpServer<'static>> {
let mut server = Box::new(EspHttpServer::new(&Default::default()).unwrap());
let mut server: Box<EspHttpServer<'static>> = Box::new(EspHttpServer::new(&Default::default()).unwrap());
server
.fn_handler("/version",Method::Get, |request| {
@@ -110,6 +159,12 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
response.write(include_bytes!("bundle.js"))?;
return Ok(())
}).unwrap();
server
.fn_handler("/favicon.ico",Method::Get, |request| {
let mut response = request.into_ok_response()?;
response.write(include_bytes!("favicon.ico"))?;
return Ok(())
}).unwrap();
server
.fn_handler("/ota", Method::Post, |mut request| {
let ota = OtaUpdate::begin();