14 Commits

17 changed files with 245308 additions and 171602 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"board": {
"active_layer": 2,
"active_layer": 39,
"active_layer_preset": "",
"auto_track_width": false,
"hidden_netclasses": [],
@@ -68,9 +68,15 @@
39,
40
],
"visible_layers": "fffffff_ffffffff",
"visible_layers": "ffdfffe_ffffffff",
"zone_display_mode": 1
},
"git": {
"repo_password": "",
"repo_type": "",
"repo_username": "",
"ssh_key": ""
},
"meta": {
"filename": "PlantCtrlESP32.kicad_prl",
"version": 3

View File

@@ -3,14 +3,17 @@
"3dviewports": [],
"design_settings": {
"defaults": {
"board_outline_line_width": 0.049999999999999996,
"copper_line_width": 0.19999999999999998,
"apply_defaults_to_fp_fields": false,
"apply_defaults_to_fp_shapes": false,
"apply_defaults_to_fp_text": false,
"board_outline_line_width": 0.05,
"copper_line_width": 0.2,
"copper_text_italic": false,
"copper_text_size_h": 1.5,
"copper_text_size_v": 1.5,
"copper_text_thickness": 0.3,
"copper_text_upright": false,
"courtyard_line_width": 0.049999999999999996,
"courtyard_line_width": 0.05,
"dimension_precision": 4,
"dimension_units": 3,
"dimensions": {
@@ -21,13 +24,13 @@
"text_position": 0,
"units_format": 1
},
"fab_line_width": 0.09999999999999999,
"fab_line_width": 0.1,
"fab_text_italic": false,
"fab_text_size_h": 1.0,
"fab_text_size_v": 1.0,
"fab_text_thickness": 0.15,
"fab_text_upright": false,
"other_line_width": 0.09999999999999999,
"other_line_width": 0.1,
"other_text_italic": false,
"other_text_size_h": 1.0,
"other_text_size_v": 1.0,
@@ -73,6 +76,7 @@
"duplicate_footprints": "warning",
"extra_footprint": "warning",
"footprint": "error",
"footprint_symbol_mismatch": "warning",
"footprint_type_mismatch": "ignore",
"hole_clearance": "error",
"hole_near_hole": "error",
@@ -116,27 +120,24 @@
"max_error": 0.005,
"min_clearance": 0.0,
"min_connection": 0.0,
"min_copper_edge_clearance": 0.024999999999999998,
"min_copper_edge_clearance": 0.025,
"min_hole_clearance": 0.25,
"min_hole_to_hole": 0.25,
"min_microvia_diameter": 0.19999999999999998,
"min_microvia_drill": 0.09999999999999999,
"min_microvia_diameter": 0.2,
"min_microvia_drill": 0.1,
"min_resolved_spokes": 1,
"min_silk_clearance": 0.0,
"min_text_height": 0.7999999999999999,
"min_text_height": 0.8,
"min_text_thickness": 0.08,
"min_through_hole_diameter": 0.19999999999999998,
"min_track_width": 0.19999999999999998,
"min_via_annular_width": 0.09999999999999999,
"min_via_diameter": 0.39999999999999997,
"min_through_hole_diameter": 0.2,
"min_track_width": 0.2,
"min_via_annular_width": 0.1,
"min_via_diameter": 0.4,
"solder_mask_to_copper_clearance": 0.005,
"use_height_for_length_calcs": true
},
"teardrop_options": [
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 5,
"td_on_pad_in_zone": false,
"td_onpadsmd": true,
"td_onroundshapesonly": false,
"td_ontrackend": false,
@@ -145,29 +146,35 @@
],
"teardrop_parameters": [
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
"td_maxlen": 1.0,
"td_on_pad_in_zone": false,
"td_target_name": "td_round_shape",
"td_width_to_size_filter_ratio": 0.9
},
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
"td_maxlen": 1.0,
"td_on_pad_in_zone": false,
"td_target_name": "td_rect_shape",
"td_width_to_size_filter_ratio": 0.9
},
{
"td_allow_use_two_tracks": true,
"td_curve_segcount": 0,
"td_height_ratio": 1.0,
"td_length_ratio": 0.5,
"td_maxheight": 2.0,
"td_maxlen": 1.0,
"td_on_pad_in_zone": false,
"td_target_name": "td_track_end",
"td_width_to_size_filter_ratio": 0.9
}
@@ -180,6 +187,32 @@
1.5,
2.0
],
"tuning_pattern_settings": {
"diff_pair_defaults": {
"corner_radius_percentage": 80,
"corner_style": 1,
"max_amplitude": 1.0,
"min_amplitude": 0.2,
"single_sided": false,
"spacing": 1.0
},
"diff_pair_skew_defaults": {
"corner_radius_percentage": 80,
"corner_style": 1,
"max_amplitude": 1.0,
"min_amplitude": 0.2,
"single_sided": false,
"spacing": 0.6
},
"single_track_defaults": {
"corner_radius_percentage": 80,
"corner_style": 1,
"max_amplitude": 1.0,
"min_amplitude": 0.2,
"single_sided": false,
"spacing": 0.6
}
},
"via_dimensions": [
{
"diameter": 0.0,
@@ -197,6 +230,13 @@
"zones_allow_external_fillets": true,
"zones_use_no_outline": true
},
"ipc2581": {
"dist": "",
"distpn": "",
"internal_id": "",
"mfg": "",
"mpn": ""
},
"layer_presets": [],
"viewports": []
},
@@ -1000,14 +1040,75 @@
"gencad": "",
"idf": "",
"netlist": "PlantCtrlESP32.net",
"plot": "",
"pos_files": "",
"specctra_dsn": "",
"step": "",
"svg": "",
"vrml": ""
},
"page_layout_descr_file": ""
},
"schematic": {
"annotate_start_num": 0,
"bom_fmt_presets": [],
"bom_fmt_settings": {
"field_delimiter": ",",
"keep_line_breaks": false,
"keep_tabs": false,
"name": "CSV",
"ref_delimiter": ",",
"ref_range_delimiter": "",
"string_delimiter": "\""
},
"bom_presets": [],
"bom_settings": {
"exclude_dnp": false,
"fields_ordered": [
{
"group_by": false,
"label": "Reference",
"name": "Reference",
"show": true
},
{
"group_by": true,
"label": "Value",
"name": "Value",
"show": true
},
{
"group_by": false,
"label": "Datasheet",
"name": "Datasheet",
"show": true
},
{
"group_by": false,
"label": "Footprint",
"name": "Footprint",
"show": true
},
{
"group_by": false,
"label": "Qty",
"name": "${QUANTITY}",
"show": true
},
{
"group_by": true,
"label": "DNP",
"name": "${DNP}",
"show": true
}
],
"filter_string": "",
"group_symbols": true,
"name": "Grouped By Value",
"sort_asc": true,
"sort_field": "Reference"
},
"connection_grid_size": 50.0,
"drawing": {
"dashed_lines_dash_length_ratio": 12.0,
"dashed_lines_gap_length_ratio": 3.0,
@@ -1021,6 +1122,11 @@
"intersheets_ref_suffix": "",
"junction_size_choice": 3,
"label_size_ratio": 0.25,
"operating_point_overlay_i_precision": 3,
"operating_point_overlay_i_range": "~A",
"operating_point_overlay_v_precision": 3,
"operating_point_overlay_v_range": "~V",
"overbar_offset_ratio": 1.23,
"pin_symbol_size": 0.0,
"text_offset_ratio": 0.08
},
@@ -1046,6 +1152,7 @@
"spice_external_command": "spice \"%I\"",
"spice_model_current_sheet_as_root": true,
"spice_save_all_currents": false,
"spice_save_all_dissipations": false,
"spice_save_all_voltages": false,
"subpart_first_id": 65,
"subpart_id_separator": 0
@@ -1053,7 +1160,7 @@
"sheets": [
[
"c26e8d55-0b6e-4c4e-b7c8-b1fed973201c",
""
"Root"
]
],
"text_variables": {}

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,7 @@ target = "xtensa-esp32-espidf"
[target.xtensa-esp32-espidf]
linker = "ldproxy"
#runner = "espflash flash --monitor --partition-table partitions.csv" # Select this runner for espflash v2.x.x
# runner = espflash erase-parts otadata
runner = "espflash flash --monitor --baud 921600 --partition-table partitions.csv" # Select this runner for espflash v2.x.x
#runner = "cargo runner"
rustflags = [ "--cfg", "espidf_time64"] # Extending time_t for ESP IDF 5: https://github.com/esp-rs/rust/issues/110

View File

@@ -76,7 +76,7 @@ serde_json = "1.0.108"
strum = { version = "0.26.1", features = ["derive"] }
once_cell = "1.19.0"
measurements = "0.11.0"
bq34z100 = "0.1.0"
bq34z100 = "0.2.1"
[build-dependencies]
embuild = "0.31.3"

View File

@@ -6,20 +6,37 @@ fn main() {
Command::new("rm")
.arg("./src/webserver/bundle.js")
.output()
.expect("failed to execute process");
.unwrap();
match Command::new("cmd").spawn() {
Ok(_) => {
println!("Assuming build on windows");
let output = Command::new("cmd")
.arg("/K")
.arg("npx")
.arg("webpack")
.current_dir("./src_webpack")
.output()
.unwrap();
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success());
}
Err(_) => {
println!("Assuming build on linux");
let output = Command::new("npx")
.arg("webpack")
.current_dir("./src_webpack")
.output()
.expect("failed to execute process");
.unwrap();
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success());
}
}
embuild::espidf::sysenv::output();
let _ = EmitBuilder::builder().all_git().emit();
let _ = EmitBuilder::builder().all_git().all_build().emit();
}

View File

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

View File

@@ -1,8 +1,8 @@
# 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=20000
CONFIG_ESP_MAIN_TASK_STACK_SIZE=25000
# 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).
CONFIG_FREERTOS_HZ=1000
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=true
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y

View File

@@ -60,7 +60,7 @@ pub struct Plant {
pub pump_hour_start: u8,
pub pump_hour_end: u8,
pub sensor_b: bool,
pub sensor_p: bool
pub sensor_p: bool,
}
impl Default for Plant {
fn default() -> Self {
@@ -72,7 +72,7 @@ impl Default for Plant {
pump_hour_end: 20,
mode: Mode::OFF,
sensor_b: false,
sensor_p : false
sensor_p: false,
}
}
}

View File

@@ -1,16 +1,11 @@
use std::{
env,
sync::{atomic::AtomicBool, Arc, Mutex},
};
use std::sync::{atomic::AtomicBool, Arc, Mutex};
use chrono::{DateTime, Datelike, Duration, NaiveDateTime, Timelike};
use chrono::{DateTime, Datelike, TimeDelta, Timelike};
use chrono_tz::{Europe::Berlin, Tz};
use config::Plant;
use embedded_svc::mqtt;
use esp_idf_hal::delay::Delay;
use esp_idf_sys::{
esp_deep_sleep, esp_restart, gpio_deep_sleep_hold_dis, gpio_deep_sleep_hold_en, vTaskDelay,
CONFIG_FREERTOS_HZ,
esp_deep_sleep, esp_ota_get_app_partition_count, esp_ota_get_running_partition, esp_ota_get_state_partition, esp_ota_img_states_t, esp_ota_img_states_t_ESP_OTA_IMG_ABORTED, esp_ota_img_states_t_ESP_OTA_IMG_INVALID, esp_ota_img_states_t_ESP_OTA_IMG_NEW, esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY, esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED, esp_ota_img_states_t_ESP_OTA_IMG_VALID, esp_restart, gpio_deep_sleep_hold_dis, gpio_deep_sleep_hold_en, vTaskDelay, CONFIG_FREERTOS_HZ
};
use log::error;
use once_cell::sync::Lazy;
@@ -19,7 +14,7 @@ use serde::{Deserialize, Serialize};
use crate::{
config::{Config, WifiConfig},
espota::rollback_and_reboot,
espota::{mark_app_valid, rollback_and_reboot},
webserver::webserver::{httpd, httpd_initial},
};
mod config;
@@ -66,11 +61,12 @@ struct LightState {
is_day: bool,
}
#[derive(Copy, Clone, Debug, PartialEq, Default)]
#[derive(Clone, Copy, Debug, PartialEq, Default)]
struct PlantState {
a: Option<u8>,
b: Option<u8>,
p: Option<u8>,
consecutive_pump_count: u32,
after_p: Option<u8>,
do_water: bool,
frozen: bool,
@@ -84,7 +80,7 @@ struct PlantState {
sensor_error_b: Option<SensorError>,
sensor_error_p: Option<SensorError>,
out_of_work_hour: bool,
next_pump: Option<DateTime<Tz>>
next_pump: Option<DateTime<Tz>>,
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
@@ -110,7 +106,7 @@ fn safe_main() -> anyhow::Result<()> {
// Bind the log crate to the ESP Logging facilities
esp_idf_svc::log::EspLogger::initialize_default();
if esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE < 20000 {
if esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE < 25000 {
error!(
"stack too small: {} bail!",
esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE
@@ -121,28 +117,41 @@ fn safe_main() -> anyhow::Result<()> {
log::info!("Startup Rust");
let git_hash = env!("VERGEN_GIT_DESCRIBE");
println!("Version useing git has {}", git_hash);
let build_timestamp = env!("VERGEN_BUILD_TIMESTAMP");
println!(
"Version useing git has {} build on {}",
git_hash, build_timestamp
);
let 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);
}
let count = unsafe { esp_ota_get_app_partition_count() };
println!("Partition count is {}", count);
let mut ota_state: esp_ota_img_states_t = 0;
let running_partition = unsafe { esp_ota_get_running_partition() };
let address = unsafe {
(*running_partition).address
};
println!("Partition address is {}", address);
let ota_state_string = unsafe {
esp_ota_get_state_partition(running_partition, &mut ota_state);
if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_NEW {
format!("Partition state is {}", "ESP_OTA_IMG_NEW")
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY {
format!("Partition state is {}", "ESP_OTA_IMG_PENDING_VERIFY")
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_VALID {
format!("Partition state is {}", "ESP_OTA_IMG_VALID")
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_INVALID {
format!("Partition state is {}", "ESP_OTA_IMG_INVALID")
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_ABORTED {
format!("Partition state is {}", "ESP_OTA_IMG_ABORTED")
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED {
format!("Partition state is {}", "ESP_OTA_IMG_UNDEFINED")
} else {
format!("Partition state is {}", ota_state)
}
};
println!("{}", ota_state_string);
println!("Board hal init");
let mut board: std::sync::MutexGuard<'_, PlantCtrlBoard<'_>> = BOARD_ACCESS.lock().unwrap();
@@ -160,7 +169,7 @@ fn safe_main() -> anyhow::Result<()> {
Ok(cur) => cur,
Err(err) => {
log::error!("time error {}", err);
NaiveDateTime::from_timestamp_millis(0).unwrap().and_utc()
DateTime::from_timestamp_millis(0).unwrap()
}
};
//check if we know the time current > 2020
@@ -212,14 +221,10 @@ fn safe_main() -> anyhow::Result<()> {
}
Err(err) => {
if board.is_wifi_config_file_existant() {
match partition_state {
embedded_svc::ota::SlotState::Invalid
| embedded_svc::ota::SlotState::Unverified => {
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();
@@ -232,8 +237,10 @@ fn safe_main() -> anyhow::Result<()> {
};
println!("attempting to connect wifi");
let mut ip_address: Option<String> = None;
match board.wifi(wifi.ssid, wifi.password, 10000) {
Ok(_) => {
Ok(ip_info) => {
ip_address = Some(ip_info.ip.to_string());
online_mode = OnlineMode::Wifi;
}
Err(_) => {
@@ -288,50 +295,80 @@ fn safe_main() -> anyhow::Result<()> {
}
if online_mode == OnlineMode::Online {
match ip_address {
Some(add_some) => {
let _ = board.mqtt_publish(&config, "/firmware/address", add_some.as_bytes());
},
None => {
let _ = board.mqtt_publish(&config, "/firmware/address", "N/A?".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/last_online", europe_time.to_rfc3339().as_bytes());
let _ = board.mqtt_publish(&config, "/firmware/ota_state", ota_state_string.as_bytes());
let _ = board.mqtt_publish(&config, "/firmware/partition_address", format!("{:#06x}",address).as_bytes());
let _ = board.mqtt_publish(&config, "/state", "online".as_bytes());
let _ = board.mqtt_publish(&config, "/last_online", europe_time.to_rfc3339().as_bytes());
publish_battery_state(&mut board, &config);
}
let tank_state = determine_tank_state(&mut board, &config);
if online_mode == OnlineMode::Online {
if tank_state.sensor_error {
let _ = board.mqtt_publish(&config, "/water/ml", "error".to_string().as_bytes());
} else {
let _ = board.mqtt_publish(&config, "/water/ml", tank_state.left_ml.to_string().as_bytes());
let _ = board.mqtt_publish(&config, "/water/enough_water", tank_state.enough_water.to_string().as_bytes());
let _ = board.mqtt_publish(&config, "/water/raw", tank_state.raw.to_string().as_bytes());
}
}
let mut water_frozen = false;
let mut temp:Option<f32> = None;
for _attempt in 0..5 {
let water_temperature = board.water_temperature_c();
match water_temperature {
Ok(temp) => {
Ok(res) => {
temp = Some(res);
break;
}
Err(err) => {
println!("Could not get water temp {} attempt {}", err, _attempt)
}
}
}
match temp {
Some(res) => {
println!("Water temp is {}", res);
if res < 4_f32 {
water_frozen = true;
}
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/water/temperature",
temp.to_string().as_bytes(),
res.to_string().as_bytes(),
);
}
//FIXME mqtt here
println!("Water temp is {}", temp);
if temp < 4_f32 {
water_frozen = true;
}
break;
}
Err(err) => {
},
None => {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(&config, "/water/temperature", "Error".as_bytes());
}
println!("Could not get water temp {}", err)
}
}
},
}
let mut plantstate = [PlantState {
..Default::default()
}; PLANT_COUNT];
let plant_to_pump = determine_next_plant(
online_mode,
&mut plantstate,
europe_time,
&tank_state,
@@ -346,18 +383,22 @@ fn safe_main() -> anyhow::Result<()> {
let _webserver = httpd(reboot_now.clone());
wait_infinity(WaitType::StayAlive, reboot_now.clone());
}
let mut did_pump = false;
match plant_to_pump {
Some(plant) => {
let mut state = plantstate[plant];
let consecutive_pump_count = board.consecutive_pump_count(plant) + 1;
board.store_consecutive_pump_count(plant, consecutive_pump_count);
let plant_config = config.plants[plant];
let state = &mut plantstate[plant];
state.consecutive_pump_count = board.consecutive_pump_count(plant) + 1;
board.store_consecutive_pump_count(plant, state.consecutive_pump_count);
if state.consecutive_pump_count > config.max_consecutive_pump_count.into() {
state.not_effective = true;
board.fault(plant, true);
}
let plant_config = config.plants[plant];
if plant_config.sensor_p {
match map_range_moisture(
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)? as f32
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)? as f32,
) {
Ok(p) => state.p = Some(p),
Err(err) => {
@@ -371,25 +412,24 @@ fn safe_main() -> anyhow::Result<()> {
"Trying to pump for {}s with pump {} now",
plant_config.pump_time_s, plant
);
did_pump = true;
board.any_pump(true)?;
board.store_last_pump_time(plant, cur);
board.pump(plant, true)?;
board.last_pump_time(plant);
state.active = true;
for t in 0..plant_config.pump_time_s {
//FIXME do periodic pump test here and state update
for _ in 0..plant_config.pump_time_s {
unsafe { vTaskDelay(CONFIG_FREERTOS_HZ) };
if plant_config.sensor_p {
let moist = map_range_moisture(
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)? as f32);
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)? as f32,
);
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
format!("/plant{}/Sensor P after", plant + 1).as_str(),
option_to_string(moist.ok()).as_bytes(),
);
}
} else {
if online_mode == OnlineMode::Online {
@@ -400,13 +440,12 @@ fn safe_main() -> anyhow::Result<()> {
);
}
}
}
board.pump(plant, false)?;
if plant_config.sensor_p {
match map_range_moisture(
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)? as f32
board.measure_moisture_hz(plant, plant_hal::Sensor::PUMP)? as f32,
) {
Ok(p) => state.after_p = Some(p),
Err(err) => {
@@ -423,7 +462,6 @@ fn safe_main() -> anyhow::Result<()> {
//mqtt sync pump error value
}
}
}
None => {
println!("Nothing to do");
@@ -435,7 +473,8 @@ fn safe_main() -> anyhow::Result<()> {
let mut light_state = LightState {
..Default::default()
};
light_state.is_day = board.is_day();
let is_day = board.is_day();
light_state.is_day = is_day;
light_state.out_of_work_hour = !in_time_range(
europe_time,
config.night_lamp_hour_start,
@@ -490,12 +529,57 @@ fn safe_main() -> anyhow::Result<()> {
unsafe { gpio_deep_sleep_hold_dis() };
unsafe { gpio_deep_sleep_hold_en() };
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(),
);
}
12 * 60
} else if is_day {
if did_pump {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/deepsleep",
"after pump".as_bytes(),
);
}
0
} else {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/deepsleep",
"normal 20m".as_bytes(),
);
}
20
}
} else {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/deepsleep",
"night 1h".as_bytes(),
);
}
60
};
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(&config, "/state", "sleep".as_bytes());
}
//determine next event
//is light out of work trigger soon?
//is battery low ??
//is deep sleep
mark_app_valid();
unsafe { esp_deep_sleep(1000 * 1000 * 20) };
unsafe { esp_deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64) };
}
fn publish_battery_state(
@@ -637,7 +721,7 @@ fn determine_tank_state(
);
})
.and_then(|percent| {
rv.left_ml = (percent * config.tank_useable_ml as f32) as u32;
rv.left_ml = ((percent * config.tank_useable_ml as f32) / 100_f32) as u32;
println!(
"Tank sensor returned mv {} as {}% leaving {} ml useable",
rv.raw, percent as u8, rv.left_ml
@@ -649,12 +733,12 @@ fn determine_tank_state(
percent as u8, config.tank_warn_percent
);
}
if config.tank_empty_percent > percent as u8 {
if config.tank_empty_percent < percent as u8 {
println!(
"Empty water, current percent is {}, minimum empty level is {}",
"Enough water, current percent is {}, minimum empty level is {}",
percent as u8, config.tank_empty_percent
);
rv.enough_water = false;
rv.enough_water = true;
}
return Ok(());
});
@@ -771,13 +855,14 @@ fn determine_state_target_moisture_for_plant(
if a_low || b_low {
state.dry = true;
if tank_state.sensor_error && !config.tank_allow_pumping_if_sensor_error
|| !tank_state.enough_water
{
if tank_state.sensor_error && !config.tank_allow_pumping_if_sensor_error {
//ignore is ok
}
else if !tank_state.enough_water {
state.no_water = true;
}
}
let duration = Duration::minutes((plant_config.pump_cooldown_min).into());
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let next_pump = board.last_pump_time(plant) + duration;
if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin);
@@ -804,7 +889,6 @@ fn determine_state_target_moisture_for_plant(
}
fn determine_next_plant(
online_mode: OnlineMode,
plantstate: &mut [PlantState; PLANT_COUNT],
cur: DateTime<Tz>,
tank_state: &TankState,
@@ -829,7 +913,7 @@ fn determine_next_plant(
);
}
config::Mode::TimerOnly => {
let duration = Duration::minutes((plant_config.pump_cooldown_min).into());
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let next_pump = board.last_pump_time(plant) + duration;
if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin);
@@ -844,7 +928,7 @@ fn determine_next_plant(
}
}
config::Mode::TimerAndDeadzone => {
let duration = Duration::minutes((60 * plant_config.pump_cooldown_min).into());
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let next_pump = board.last_pump_time(plant) + duration;
if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin);
@@ -874,19 +958,12 @@ fn determine_next_plant(
{
board.fault(plant, true);
}
if state.do_water {
if board.consecutive_pump_count(plant) > config.max_consecutive_pump_count.into() {
state.not_effective = true;
board.fault(plant, true);
}
} else {
if !state.dry {
state.consecutive_pump_count = 0;
board.store_consecutive_pump_count(plant, 0);
}
println!("Plant {} state is {:?}", plant, state);
}
if online_mode == OnlineMode::Online {
update_plant_state(plantstate, board, config);
}
for plant in 0..PLANT_COUNT {
let state = &plantstate[plant];
println!(
@@ -901,11 +978,26 @@ fn determine_next_plant(
return None;
}
fn update_plant_state(plantstate: &mut [PlantState; PLANT_COUNT], board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>, config: &Config){
fn update_plant_state(
plantstate: &mut [PlantState; PLANT_COUNT],
board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>,
config: &Config,
) {
for plant in 0..PLANT_COUNT {
let state = &plantstate[plant];
let plant_config = config.plants[plant];
let _ = board.mqtt_publish(
&config,
format!("/plant{}/mode", plant + 1).as_str(),
match plant_config.mode {
config::Mode::OFF => "OFF".as_bytes(),
config::Mode::TargetMoisture => "TargetMoisture".as_bytes(),
config::Mode::TimerOnly => "TimerOnly".as_bytes(),
config::Mode::TimerAndDeadzone => "TimerAndDeadzone".as_bytes(),
},
);
let last_time = board.last_pump_time(plant);
let europe_time = last_time.with_timezone(&Berlin);
if europe_time.year() > 2023 {
@@ -931,17 +1023,20 @@ fn update_plant_state(plantstate: &mut [PlantState; PLANT_COUNT], board: &mut st
format!("/plant{}/next pump", plant + 1).as_str(),
time.as_bytes(),
);
},
}
None => {
let _ = board.mqtt_publish(
&config,
format!("/plant{}/next pump", plant + 1).as_str(),
"N/A".as_bytes(),
);
},
}
}
let _ = board.mqtt_publish(
&config,
format!("/plant{}/active", plant + 1).as_str(),
state.active.to_string().as_bytes(),
);
let _ = board.mqtt_publish(
&config,
format!("/plant{}/Sensor A", plant + 1).as_str(),
@@ -1025,6 +1120,13 @@ fn update_plant_state(plantstate: &mut [PlantState; PLANT_COUNT], board: &mut st
format!("/plant{}/Out of Work Hour", plant + 1).as_str(),
state.out_of_work_hour.to_string().as_bytes(),
);
let _ = board.mqtt_publish(
&config,
format!("/plant{}/consecutive pump count", plant + 1).as_str(),
state.consecutive_pump_count.to_string().as_bytes(),
);
}
}
@@ -1069,7 +1171,18 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
fn main() {
let result = safe_main();
result.unwrap();
match result {
Ok(_) => {
println!("Main app finished, restarting");
unsafe { esp_restart() };
},
Err(err) => {
println!("Failed main {}", err);
let rollback_successful = rollback_and_reboot();
println!("Failed to rollback :(");
rollback_successful.unwrap();
},
}
}
//error codes
//error_reading_config_after_upgrade

View File

@@ -7,6 +7,7 @@ use embedded_svc::wifi::{
use esp_idf_hal::i2c::{I2cConfig, I2cDriver, I2cError};
use esp_idf_hal::units::FromValueType;
use esp_idf_svc::eventloop::EspSystemEventLoop;
use esp_idf_svc::ipv4::IpInfo;
use esp_idf_svc::mqtt::client::QoS::AtLeastOnce;
use esp_idf_svc::mqtt::client::QoS::ExactlyOnce;
use esp_idf_svc::mqtt::client::{EspMqttClient, LwtConfiguration, MqttClientConfiguration};
@@ -22,7 +23,7 @@ use std::ffi::CString;
use std::fs::File;
use std::path::Path;
use chrono::{DateTime, NaiveDateTime, Utc};
use chrono::{DateTime, Utc};
use ds18b20::Ds18b20;
use std::result::Result::Ok as OkStd;
use std::str::FromStr;
@@ -82,6 +83,7 @@ pub enum ClearConfigType {
}
#[derive(Debug)]
#[derive(PartialEq)]
pub enum Sensor {
A,
B,
@@ -94,7 +96,7 @@ pub trait PlantCtrlBoardInteraction {
ssid: heapless::String<32>,
password: Option<heapless::String<64>>,
max_wait: u32,
) -> Result<()>;
) -> 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>;
@@ -142,6 +144,7 @@ pub trait PlantCtrlBoardInteraction {
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<()>;
@@ -159,7 +162,6 @@ pub struct PlantCtrlBoard<'a> {
PinDriver<'a, esp_idf_hal::gpio::Gpio22, InputOutput>,
PinDriver<'a, esp_idf_hal::gpio::Gpio19, InputOutput>,
>,
low_voltage_detected: Mutex<bool>,
tank_driver: AdcDriver<'a, esp_idf_hal::adc::ADC1>,
tank_channel: esp_idf_hal::adc::AdcChannelDriver<'a, { attenuation::DB_11 }, Gpio39>,
solar_is_day: PinDriver<'a, esp_idf_hal::gpio::Gpio25, esp_idf_hal::gpio::Input>,
@@ -240,12 +242,11 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
let mut percent = r2 / 190_f32 * 100_f32;
percent = percent.clamp(0.0, 100.0);
let quantizised = quantize_to_next_5_percent(percent as f64) as u16;
println!(
"Tank sensor raw {} percent {} quantized {}",
median, percent, quantizised
"Tank sensor raw {} percent {}",
median, percent
);
return Ok(quantizised);
return Ok(percent as u16);
}
fn set_low_voltage_in_cycle(&mut self) {
@@ -278,8 +279,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
fn last_pump_time(&self, plant: usize) -> chrono::DateTime<Utc> {
let ts = unsafe { LAST_WATERING_TIMESTAMP }[plant];
let timestamp = NaiveDateTime::from_timestamp_millis(ts).unwrap();
DateTime::<Utc>::from_naive_utc_and_offset(timestamp, Utc)
return DateTime::from_timestamp_millis(ts).unwrap();
}
fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>) {
@@ -323,9 +323,9 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
fn time(&mut self) -> Result<chrono::DateTime<Utc>> {
let time = EspSystemTime {}.now().as_millis();
let smaller_time = time as i64;
let local_time = NaiveDateTime::from_timestamp_millis(smaller_time)
let local_time = DateTime::from_timestamp_millis(smaller_time)
.ok_or(anyhow!("could not convert timestamp"))?;
Ok(local_time.and_utc())
Ok(local_time)
}
fn sntp(&mut self, max_wait_ms: u32) -> Result<chrono::DateTime<Utc>> {
@@ -359,12 +359,20 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
let factor = 1000 as f32 / measurement as f32;
self.shift_register.decompose()[index].set_high().unwrap();
if plant == 0 && sensor == Sensor::A {
let index = plant * PINS_PER_PLANT + PLANT_MOIST_PUMP_OFFSET;
//self.shift_register.decompose()[index].set_high().unwrap();
}
//give some time to stabilize
delay.delay_ms(10);
self.signal_counter.counter_resume()?;
delay.delay_ms(measurement);
self.signal_counter.counter_pause()?;
self.shift_register.decompose()[index].set_low().unwrap();
if plant == 0 && sensor == Sensor::A {
let index = plant * PINS_PER_PLANT + PLANT_MOIST_PUMP_OFFSET;
//self.shift_register.decompose()[index].set_low().unwrap();
}
let unscaled = self.signal_counter.get_counter_value()? as i32;
let hz = (unscaled as f32 * factor) as i32;
println!("Measuring {:?} @ {} with {}", sensor, plant, hz);
@@ -394,7 +402,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
ssid: heapless::String<32>,
password: Option<heapless::String<64>>,
max_wait: u32,
) -> Result<()> {
) -> Result<IpInfo> {
match password {
Some(pw) => {
//TODO expect error due to invalid pw or similar! //call this during configuration and check if works, revert to config mode if not
@@ -449,7 +457,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
//update freertos registers ;)
let address = self.wifi_driver.sta_netif().get_ip_info().unwrap();
println!("IP info: {:?}", address);
Ok(())
Ok(address)
}
fn mount_file_system(&mut self) -> Result<()> {
@@ -568,6 +576,15 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(self.wifi_driver.get_scan_result()?)
}
fn test_pump(&mut self, plant:usize) -> Result<()> {
self.any_pump(true)?;
self.pump(plant, true)?;
unsafe { vTaskDelay(30000) };
self.pump(plant, false)?;
self.any_pump(false)?;
Ok(())
}
fn test(&mut self) -> Result<()> {
self.general_fault(true);
unsafe { vTaskDelay(100) };
@@ -621,6 +638,8 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
qos: AtLeastOnce,
retain: true,
}),
client_id: Some("plantctrl"),
keep_alive_interval : Some(Duration::from_secs(60*60*2)),
//room for improvement
..Default::default()
};
@@ -715,14 +734,25 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
println!("Some error assembling full_topic 2");
bail!("Some error assembling full_topic 2")
};
client.publish(
let publish = client.publish(
&full_topic,
embedded_svc::mqtt::client::QoS::ExactlyOnce,
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);
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)?
},
}
return Ok(());
;
}
fn state_charge_percent(&mut self) -> Result<u8> {
@@ -780,6 +810,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Err(err) => bail!("Error reading State of Health {:?}", err),
}
}
}
fn print_battery(
@@ -908,9 +939,8 @@ impl CreatePlantHal<'_> for PlantHal {
);
for i in 0..PLANT_COUNT {
let smaller_time = LAST_WATERING_TIMESTAMP[i];
let local_time = NaiveDateTime::from_timestamp_millis(smaller_time)
let utc_time = DateTime::from_timestamp_millis(smaller_time)
.ok_or(anyhow!("could not convert timestamp"))?;
let utc_time = local_time.and_utc();
let europe_time = utc_time.with_timezone(&Berlin);
println!(
@@ -963,8 +993,6 @@ impl CreatePlantHal<'_> for PlantHal {
let nvs = EspDefaultNvsPartition::take()?;
let wifi_driver = EspWifi::new(peripherals.modem, sys_loop, Some(nvs))?;
let low_voltage_detected = Mutex::new(unsafe { LOW_VOLTAGE_DETECTED });
let adc_config = esp_idf_hal::adc::config::Config {
resolution: esp_idf_hal::adc::config::Resolution::Resolution12Bit,
calibration: true,
@@ -1001,7 +1029,6 @@ impl CreatePlantHal<'_> for PlantHal {
}
let rv = Mutex::new(PlantCtrlBoard {
shift_register,
low_voltage_detected,
tank_driver,
tank_channel,
solar_is_day,
@@ -1019,21 +1046,3 @@ impl CreatePlantHal<'_> for PlantHal {
Ok(rv)
}
}
fn quantize_to_next_5_percent(value: f64) -> i32 {
// Multiply by 100 to work with integer values
let multiplied_value = (value * 100.0).round() as i32;
// Calculate the remainder when divided by 5
let remainder = multiplied_value % 5;
// If the remainder is greater than or equal to half of 5, round up to the next 5%
let rounded_value = if remainder >= 2 {
multiplied_value + (5 - remainder)
} else {
multiplied_value - remainder
};
// Divide by 100 to get back to a float
rounded_value / 100
}

View File

@@ -1,6 +1,14 @@
<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>
<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>
@@ -9,6 +17,8 @@
<p id="loaded_n_total"></p>
</form>
<h2>config</h2>
<div id="configform">
@@ -40,7 +50,7 @@
</div>
<div>
<input type="number" min="1" max="500000" id="tank_warn_percent">
Tank Warn below mL
Tank Warn Percent (mapped in relation to empty and full)
</div>
<div>
<input type="number" min="0" max="100" id="tank_empty_percent">

View File

@@ -1,7 +1,11 @@
<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">

View File

@@ -10,7 +10,7 @@ use core::result::Result::Ok;
use embedded_svc::http::Method;
use esp_idf_svc::http::server::{Configuration, EspHttpServer};
use heapless::String;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use crate::{
config::{Config, WifiConfig},
@@ -22,6 +22,17 @@ struct SSIDList<'a> {
ssids: Vec<&'a String<32>>,
}
#[derive(Serialize, Debug)]
struct VersionInfo<'a> {
git_hash: &'a str,
build_time: &'a str
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct TestPump{
pump: usize
}
pub fn httpd_initial(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let mut server = shared();
server
@@ -85,15 +96,6 @@ pub fn httpd_initial(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>>
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/boardtest", Method::Post, move |_| {
let mut board = BOARD_ACCESS.lock().unwrap();
board.test()?;
anyhow::Ok(())
})
.unwrap();
server
}
@@ -170,7 +172,14 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
server
.fn_handler("/version", Method::Get, |request| {
let mut response = request.into_ok_response()?;
response.write(env!("VERGEN_GIT_DESCRIBE").as_bytes())?;
let git_hash = env!("VERGEN_GIT_DESCRIBE");
let build_time = env!("VERGEN_BUILD_TIMESTAMP");
let version_info = VersionInfo{
git_hash,
build_time,
};
let version_info_json = serde_json::to_string(&version_info)?;
response.write(version_info_json.as_bytes())?;
anyhow::Ok(())
})
.unwrap();
@@ -244,4 +253,39 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
})
.unwrap();
server
.fn_handler("/boardtest", Method::Post, move |_| {
let mut board = BOARD_ACCESS.lock().unwrap();
board.test()?;
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/pumptest", Method::Post, |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 testrequest {}", 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 pump_test: Result<TestPump, serde_json::Error> = serde_json::from_slice(actual_data);
if pump_test.is_err() {
let error_text = pump_test.unwrap_err().to_string();
println!("Could not parse TestPump {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(());
}
let mut board = BOARD_ACCESS.lock().unwrap();
board.test_pump(pump_test.unwrap().pump)?;
anyhow::Ok(())
})
.unwrap();
server
}

View File

@@ -24,6 +24,10 @@ interface PlantConfig {
}[]
}
interface TestPump{
pump: number
}
let plants = document.getElementById("plants") as HTMLInputElement;
let fromWrapper = (() => {
@@ -77,9 +81,33 @@ let fromWrapper = (() => {
header.textContent = "Plant " + (i + 1);
plant.appendChild(header);
{
let holder = document.createElement("div");
plant.appendChild(holder);
let testButton = document.createElement("button");
testButton.innerText = "Test";
testButton.id = "plant_" + i + "_test";
testButton.onclick = function (){
var body:TestPump = {
pump: i
}
var pretty = JSON.stringify(body, undefined, 1);
fetch("/pumptest", {
method :"POST",
body: pretty
})
.then(response => response.text())
.then(text => submit_status.innerText = text)
};
holder.appendChild(testButton);
let br = document.createElement("br");
holder.appendChild(br);
let inputf = document.createElement("select");
inputf.id = "plant_" + i + "_mode";
inputf.onchange = updateJson;

View File

@@ -33,5 +33,23 @@ export function uploadFile() {
ajax.send(file);
}
interface VersionInfo{
git_hash:string,
build_time: string
}
let file1Upload = document.getElementById("file1") as HTMLInputElement;
file1Upload.onchange = uploadFile;
let firmware_buildtime = document.getElementById("firmware_buildtime") as HTMLDivElement;
let firmware_githash = document.getElementById("firmware_githash") as HTMLDivElement;
document.addEventListener('DOMContentLoaded', function() {
fetch("/version")
.then(response => response.json())
.then(json => json as VersionInfo)
.then(versionInfo => {
firmware_buildtime.innerText = versionInfo.build_time;
firmware_githash.innerText = versionInfo.git_hash;
})
}, false);