Compare commits
No commits in common. "goodby-espidf" and "develop" have entirely different histories.
goodby-esp
...
develop
0
battery_board/rust/.cargo/config.toml
Normal file
0
battery_board/rust/.cargo/config.toml
Normal file
0
battery_board/rust/rust-toolchain.toml
Normal file
0
battery_board/rust/rust-toolchain.toml
Normal file
@ -1,28 +1,26 @@
|
|||||||
[build]
|
[build]
|
||||||
rustflags = [
|
#target = "xtensa-esp32-espidf"
|
||||||
# Required to obtain backtraces (e.g. when using the "esp-backtrace" crate.)
|
target = "riscv32imac-esp-espidf"
|
||||||
# NOTE: May negatively impact performance of produced code
|
|
||||||
"-C", "force-frame-pointers",
|
|
||||||
"-Z", "stack-protector=all",
|
|
||||||
]
|
|
||||||
|
|
||||||
target = "riscv32imac-unknown-none-elf"
|
[target.riscv32imac-esp-espidf]
|
||||||
|
linker = "ldproxy"
|
||||||
[target.riscv32imac-unknown-none-elf]
|
|
||||||
runner = "espflash flash --monitor --chip esp32c6"
|
|
||||||
#runner = "espflash flash --monitor --baud 921600 --partition-table partitions.csv -b no-reset" # Select this runner in case of usb ttl
|
#runner = "espflash flash --monitor --baud 921600 --partition-table partitions.csv -b no-reset" # Select this runner in case of usb ttl
|
||||||
#runner = "espflash flash --monitor"
|
runner = "espflash flash --monitor"
|
||||||
#runner = "cargo runner"
|
#runner = "cargo runner"
|
||||||
|
|
||||||
|
|
||||||
#runner = "espflash flash --monitor --partition-table partitions.csv -b no-reset" # create upgrade image file for webupload
|
#runner = "espflash flash --monitor --partition-table partitions.csv -b no-reset" # create upgrade image file for webupload
|
||||||
# runner = espflash erase-parts otadata //ensure flash is clean
|
# runner = espflash erase-parts otadata //ensure flash is clean
|
||||||
|
|
||||||
[env]
|
rustflags = ["--cfg", "espidf_time64"] # Extending time_t for ESP IDF 5: https://github.com/esp-rs/rust/issues/110
|
||||||
CHRONO_TZ_TIMEZONE_FILTER = "UTC|America/New_York|America/Chicago|America/Los_Angeles|Europe/London|Europe/Berlin|Europe/Paris|Asia/Tokyo|Asia/Shanghai|Asia/Kolkata|Australia/Sydney|America/Sao_Paulo|Africa/Johannesburg|Asia/Dubai|Pacific/Auckland"
|
|
||||||
CARGO_WORKSPACE_DIR = { value = "", relative = true }
|
|
||||||
ESP_LOG="info"
|
|
||||||
|
|
||||||
[unstable]
|
[unstable]
|
||||||
build-std = ["alloc", "core"]
|
build-std = ["std", "panic_abort"]
|
||||||
|
|
||||||
|
[env]
|
||||||
|
MCU = "esp32c6"
|
||||||
|
# Note: this variable is not used by the pio builder (`cargo build --features pio`)
|
||||||
|
ESP_IDF_VERSION = "v5.2.1"
|
||||||
|
CHRONO_TZ_TIMEZONE_FILTER = "UTC|America/New_York|America/Chicago|America/Los_Angeles|Europe/London|Europe/Berlin|Europe/Paris|Asia/Tokyo|Asia/Shanghai|Asia/Kolkata|Australia/Sydney|America/Sao_Paulo|Africa/Johannesburg|Asia/Dubai|Pacific/Auckland"
|
||||||
|
CARGO_WORKSPACE_DIR = { value = "", relative = true }
|
||||||
|
RUST_BACKTRACE = "full"
|
101
rust/Cargo.toml
101
rust/Cargo.toml
@ -44,104 +44,59 @@ command = [
|
|||||||
[package.metadata.espflash]
|
[package.metadata.espflash]
|
||||||
partition_table = "partitions.csv"
|
partition_table = "partitions.csv"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["std", "esp-idf-svc/native"]
|
||||||
|
pio = ["esp-idf-svc/pio"]
|
||||||
|
std = ["alloc", "esp-idf-svc/binstart", "esp-idf-svc/std"]
|
||||||
|
alloc = ["esp-idf-svc/alloc"]
|
||||||
|
nightly = ["esp-idf-svc/nightly"]
|
||||||
|
experimental = ["esp-idf-svc/experimental"]
|
||||||
|
#embassy = ["esp-idf-svc/embassy-sync", "esp-idf-svc/critical-section", "esp-idf-svc/embassy-time-driver"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
#ESP stuff
|
#ESP stuff
|
||||||
esp-bootloader-esp-idf = { version = "0.2.0", features = ["esp32c6"] }
|
embedded-svc = { version = "0.28.1", features = ["experimental"] }
|
||||||
esp-hal = { version = "=1.0.0-rc.0", features = [
|
esp-idf-hal = "0.45.2"
|
||||||
"esp32c6",
|
esp-idf-sys = { version = "0.36.1", features = ["binstart", "native"] }
|
||||||
"log-04",
|
esp-idf-svc = { version = "0.51.0", default-features = false }
|
||||||
"unstable",
|
|
||||||
] }
|
|
||||||
log = "0.4.27"
|
|
||||||
|
|
||||||
embassy-net = { version = "0.7.0", features = [
|
|
||||||
"dhcpv4",
|
|
||||||
"log",
|
|
||||||
"medium-ethernet",
|
|
||||||
"tcp",
|
|
||||||
"udp",
|
|
||||||
] }
|
|
||||||
embedded-io = "0.6.1"
|
|
||||||
embedded-io-async = "0.6.1"
|
|
||||||
esp-alloc = "0.8.0"
|
|
||||||
esp-backtrace = { version = "0.17.0", features = [
|
|
||||||
"esp32c6",
|
|
||||||
"exception-handler",
|
|
||||||
"panic-handler",
|
|
||||||
"println",
|
|
||||||
] }
|
|
||||||
esp-println = { version = "0.15.0", features = ["esp32c6", "log-04"] }
|
|
||||||
# for more networking protocol support see https://crates.io/crates/edge-net
|
|
||||||
embassy-executor = { version = "0.7.0", features = [
|
|
||||||
"log",
|
|
||||||
"task-arena-size-20480",
|
|
||||||
] }
|
|
||||||
embassy-time = { version = "0.4.0", features = ["log"] }
|
|
||||||
esp-hal-embassy = { version = "0.9.0", features = ["esp32c6", "log-04"] }
|
|
||||||
esp-wifi = { version = "0.15.0", features = [
|
|
||||||
"builtin-scheduler",
|
|
||||||
"esp-alloc",
|
|
||||||
"esp32c6",
|
|
||||||
"log-04",
|
|
||||||
"smoltcp",
|
|
||||||
"wifi",
|
|
||||||
] }
|
|
||||||
smoltcp = { version = "0.12.0", default-features = false, features = [
|
|
||||||
"log",
|
|
||||||
"medium-ethernet",
|
|
||||||
"multicast",
|
|
||||||
"proto-dhcpv4",
|
|
||||||
"proto-dns",
|
|
||||||
"proto-ipv4",
|
|
||||||
"socket-dns",
|
|
||||||
"socket-icmp",
|
|
||||||
"socket-raw",
|
|
||||||
"socket-tcp",
|
|
||||||
"socket-udp",
|
|
||||||
] }
|
|
||||||
static_cell = "2.1.1"
|
|
||||||
embedded-hal = "1.0.0"
|
embedded-hal = "1.0.0"
|
||||||
heapless = { version = "0.8", features = ["serde"] }
|
heapless = { version = "0.8", features = ["serde"] }
|
||||||
embedded-hal-bus = { version = "0.3.0" }
|
embedded-hal-bus = { version = "0.3.0", features = ["std"] }
|
||||||
|
|
||||||
#Hardware additional driver
|
#Hardware additional driver
|
||||||
#ds18b20 = "0.1.1"
|
ds18b20 = "0.1.1"
|
||||||
#bq34z100 = { version = "0.3.0", default-features = false }
|
bq34z100 = { version = "0.3.0", features = ["flashstream"] }
|
||||||
one-wire-bus = "0.1.1"
|
one-wire-bus = "0.1.1"
|
||||||
ds323x = "0.6.0"
|
ds323x = "0.6.0"
|
||||||
|
|
||||||
#pure code dependencies
|
#pure code dependencies
|
||||||
#once_cell = "1.19.0"
|
once_cell = "1.19.0"
|
||||||
anyhow = { version = "1.0.75", default-features = false }
|
anyhow = { version = "1.0.75", features = ["std", "backtrace"] }
|
||||||
#strum = { version = "0.27.0", default-feature = false, features = ["derive"] }
|
strum = { version = "0.27.0", features = ["derive"] }
|
||||||
measurements = "0.11.0"
|
measurements = "0.11.0"
|
||||||
|
|
||||||
#json
|
#json
|
||||||
serde = { version = "1.0.219", features = ["derive", "alloc"], default-features = false }
|
serde = { version = "1.0.192", features = ["derive"] }
|
||||||
serde_json = { version = "1.0.143", default-features = false, features = ["alloc"] }
|
serde_json = "1.0.108"
|
||||||
|
|
||||||
#timezone
|
#timezone
|
||||||
|
|
||||||
chrono = { version = "0.4.23", default-features = false, features = ["iana-time-zone", "alloc", "serde"] }
|
chrono = { version = "0.4.23", default-features = false, features = ["iana-time-zone", "alloc", "serde"] }
|
||||||
chrono-tz = { version = "0.10.3", default-features = false, features = ["filter-by-regex"] }
|
chrono-tz = { version = "0.10.3", default-features = false, features = ["filter-by-regex"] }
|
||||||
eeprom24x = "0.7.2"
|
eeprom24x = "0.7.2"
|
||||||
#url = "2.5.3"
|
url = "2.5.3"
|
||||||
crc = "3.2.1"
|
crc = "3.2.1"
|
||||||
bincode = { version = "2.0.1", default-features = false, features = ["alloc", "serde"] }
|
bincode = "2.0.1"
|
||||||
ringbuffer = "0.15.0"
|
ringbuffer = "0.15.0"
|
||||||
#text-template = "0.1.0"
|
text-template = "0.1.0"
|
||||||
strum_macros = "0.27.0"
|
strum_macros = "0.27.0"
|
||||||
#esp-ota = { version = "0.2.2", features = ["log"] }
|
esp-ota = { version = "0.2.2", features = ["log"] }
|
||||||
unit-enum = "1.4.1"
|
unit-enum = "1.4.1"
|
||||||
pca9535 = { version = "2.0.0" }
|
pca9535 = { version = "2.0.0", features = ["std"] }
|
||||||
ina219 = { version = "0.2.0" }
|
ina219 = { version = "0.2.0", features = ["std"] }
|
||||||
embedded-storage = "=0.3.1"
|
embedded-storage = "=0.3.1"
|
||||||
ekv = "1.0.0"
|
ekv = "1.0.0"
|
||||||
embedded-can = "0.4.1"
|
embedded-can = "0.4.1"
|
||||||
critical-section = "1.2.0"
|
|
||||||
portable-atomic = "1.11.1"
|
|
||||||
embassy-sync = { version = "0.7.2", features = ["log"] }
|
|
||||||
async-trait = "0.1.89"
|
|
||||||
|
|
||||||
|
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
@ -153,4 +108,6 @@ async-trait = "0.1.89"
|
|||||||
#bq34z100 = { path = "../../bq34z100_rust" }
|
#bq34z100 = { path = "../../bq34z100_rust" }
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
|
cc = "=1.1.30"
|
||||||
|
embuild = { version = "0.32.0", features = ["espidf"] }
|
||||||
vergen = { version = "8.2.6", features = ["build", "git", "gitcl"] }
|
vergen = { version = "8.2.6", features = ["build", "git", "gitcl"] }
|
||||||
|
@ -1,54 +1,6 @@
|
|||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
use vergen::EmitBuilder;
|
use vergen::EmitBuilder;
|
||||||
|
|
||||||
fn linker_be_nice() {
|
|
||||||
let args: Vec<String> = std::env::args().collect();
|
|
||||||
if args.len() > 1 {
|
|
||||||
let kind = &args[1];
|
|
||||||
let what = &args[2];
|
|
||||||
|
|
||||||
match kind.as_str() {
|
|
||||||
"undefined-symbol" => match what.as_str() {
|
|
||||||
"_defmt_timestamp" => {
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("💡 `defmt` not found - make sure `defmt.x` is added as a linker script and you have included `use defmt_rtt as _;`");
|
|
||||||
eprintln!();
|
|
||||||
}
|
|
||||||
"_stack_start" => {
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("💡 Is the linker script `linkall.x` missing?");
|
|
||||||
eprintln!();
|
|
||||||
}
|
|
||||||
"esp_wifi_preempt_enable"
|
|
||||||
| "esp_wifi_preempt_yield_task"
|
|
||||||
| "esp_wifi_preempt_task_create" => {
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("💡 `esp-wifi` has no scheduler enabled. Make sure you have the `builtin-scheduler` feature enabled, or that you provide an external scheduler.");
|
|
||||||
eprintln!();
|
|
||||||
}
|
|
||||||
"embedded_test_linker_file_not_added_to_rustflags" => {
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("💡 `embedded-test` not found - make sure `embedded-test.x` is added as a linker script for tests");
|
|
||||||
eprintln!();
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
},
|
|
||||||
// we don't have anything helpful for "missing-lib" yet
|
|
||||||
_ => {
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::process::exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
println!(
|
|
||||||
"cargo:rustc-link-arg=--error-handling-script={}",
|
|
||||||
std::env::current_exe().unwrap().display()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("cargo:rerun-if-changed=./src/src_webpack");
|
println!("cargo:rerun-if-changed=./src/src_webpack");
|
||||||
Command::new("rm")
|
Command::new("rm")
|
||||||
@ -112,6 +64,7 @@ fn main() {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
linker_be_nice();
|
|
||||||
|
embuild::espidf::sysenv::output();
|
||||||
let _ = EmitBuilder::builder().all_git().all_build().emit();
|
let _ = EmitBuilder::builder().all_git().all_build().emit();
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,22 @@
|
|||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
use async_trait::async_trait;
|
use bq34z100::{Bq34Z100Error, Bq34z100g1, Bq34z100g1Driver};
|
||||||
|
use embedded_hal_bus::i2c::MutexDevice;
|
||||||
|
use esp_idf_hal::delay::Delay;
|
||||||
|
use esp_idf_hal::i2c::{I2cDriver, I2cError};
|
||||||
use measurements::Temperature;
|
use measurements::Temperature;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait BatteryInteraction {
|
pub trait BatteryInteraction {
|
||||||
async fn state_charge_percent(&mut self) -> Result<f32, BatteryError>;
|
fn state_charge_percent(&mut self) -> Result<f32, BatteryError>;
|
||||||
async fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
||||||
async fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
||||||
async fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
||||||
async fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError>;
|
fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError>;
|
||||||
async fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError>;
|
fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError>;
|
||||||
async fn cycle_count(&mut self) -> Result<u16, BatteryError>;
|
fn cycle_count(&mut self) -> Result<u16, BatteryError>;
|
||||||
async fn state_health_percent(&mut self) -> Result<u16, BatteryError>;
|
fn state_health_percent(&mut self) -> Result<u16, BatteryError>;
|
||||||
async fn bat_temperature(&mut self) -> Result<u16, BatteryError>;
|
fn bat_temperature(&mut self) -> Result<u16, BatteryError>;
|
||||||
async fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError>;
|
fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
@ -156,56 +158,56 @@ impl BatteryInteraction for BQ34Z100G1<'_> {
|
|||||||
pub fn print_battery_bq34z100(
|
pub fn print_battery_bq34z100(
|
||||||
battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
|
battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
|
||||||
) -> anyhow::Result<(), Bq34Z100Error<I2cError>> {
|
) -> anyhow::Result<(), Bq34Z100Error<I2cError>> {
|
||||||
log::info!("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| {
|
||||||
log::info!("Firmware {:?}", e);
|
println!("Firmware {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
log::info!("fw version is {}", fwversion);
|
println!("fw version is {}", fwversion);
|
||||||
|
|
||||||
let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
|
let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
|
||||||
log::info!("Design capacity {:?}", e);
|
println!("Design capacity {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
log::info!("Design Capacity {}", design_capacity);
|
println!("Design Capacity {}", design_capacity);
|
||||||
if design_capacity == 1000 {
|
if design_capacity == 1000 {
|
||||||
log::info!("Still stock configuring battery, readouts are likely to be wrong!");
|
println!("Still stock configuring battery, readouts are likely to be wrong!");
|
||||||
}
|
}
|
||||||
|
|
||||||
let flags = battery_driver.get_flags_decoded()?;
|
let flags = battery_driver.get_flags_decoded()?;
|
||||||
log::info!("Flags {:?}", flags);
|
println!("Flags {:?}", flags);
|
||||||
|
|
||||||
let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
|
let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
|
||||||
log::info!("Chemid {:?}", e);
|
println!("Chemid {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
|
|
||||||
let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
|
let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
|
||||||
log::info!("Bat Temp {:?}", e);
|
println!("Bat Temp {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
|
let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
|
||||||
let voltage = battery_driver.voltage().unwrap_or_else(|e| {
|
let voltage = battery_driver.voltage().unwrap_or_else(|e| {
|
||||||
log::info!("Bat volt {:?}", e);
|
println!("Bat volt {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
let current = battery_driver.current().unwrap_or_else(|e| {
|
let current = battery_driver.current().unwrap_or_else(|e| {
|
||||||
log::info!("Bat current {:?}", e);
|
println!("Bat current {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
|
let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
|
||||||
log::info!("Bat Soc {:?}", e);
|
println!("Bat Soc {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
|
let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
|
||||||
log::info!("Bat Charge Volt {:?}", e);
|
println!("Bat Charge Volt {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
|
let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
|
||||||
log::info!("Bat Charge Current {:?}", e);
|
println!("Bat Charge Current {:?}", e);
|
||||||
0
|
0
|
||||||
});
|
});
|
||||||
log::info!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
|
println!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
|
||||||
let _ = battery_driver.unsealed();
|
let _ = battery_driver.unsealed();
|
||||||
let _ = battery_driver.it_enable();
|
let _ = battery_driver.it_enable();
|
||||||
anyhow::Result::Ok(())
|
anyhow::Result::Ok(())
|
||||||
|
@ -4,12 +4,30 @@ use crate::log::{log, LogMessage};
|
|||||||
use crate::STAY_ALIVE;
|
use crate::STAY_ALIVE;
|
||||||
use anyhow::{anyhow, bail, Context};
|
use anyhow::{anyhow, bail, Context};
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use serde::Serialize;
|
use embedded_svc::ipv4::IpInfo;
|
||||||
|
use embedded_svc::mqtt::client::QoS::{AtLeastOnce, ExactlyOnce};
|
||||||
use alloc::{
|
use embedded_svc::wifi::{
|
||||||
string::{String, ToString},
|
AccessPointConfiguration, AccessPointInfo, AuthMethod, ClientConfiguration, Configuration,
|
||||||
vec::Vec,
|
|
||||||
};
|
};
|
||||||
|
use esp_idf_hal::delay::Delay;
|
||||||
|
use esp_idf_hal::gpio::{Level, PinDriver};
|
||||||
|
use esp_idf_svc::mqtt::client::{EspMqttClient, LwtConfiguration, MqttClientConfiguration};
|
||||||
|
use esp_idf_svc::sntp;
|
||||||
|
use esp_idf_svc::sntp::SyncStatus;
|
||||||
|
use esp_idf_svc::systime::EspSystemTime;
|
||||||
|
use esp_idf_svc::wifi::config::{ScanConfig, ScanType};
|
||||||
|
use esp_idf_svc::wifi::EspWifi;
|
||||||
|
use esp_idf_sys::{esp_spiffs_info, vTaskDelay};
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::ffi::CString;
|
||||||
|
use std::fs;
|
||||||
|
use std::fs::File;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::result::Result::Ok as OkStd;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::sync::atomic::AtomicBool;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
#[link_section = ".rtc.data"]
|
#[link_section = ".rtc.data"]
|
||||||
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
|
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
|
||||||
@ -42,38 +60,35 @@ pub struct FileSystemSizeInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct MqttClient<'a> {
|
pub struct MqttClient<'a> {
|
||||||
//mqtt_client: EspMqttClient<'a>,
|
mqtt_client: EspMqttClient<'a>,
|
||||||
base_topic: heapless::String<64>,
|
base_topic: heapless::String<64>,
|
||||||
}
|
}
|
||||||
pub struct Esp<'a> {
|
pub struct Esp<'a> {
|
||||||
pub(crate) mqtt_client: Option<MqttClient<'a>>,
|
pub(crate) mqtt_client: Option<MqttClient<'a>>,
|
||||||
//pub(crate) wifi_driver: EspWifi<'a>,
|
pub(crate) wifi_driver: EspWifi<'a>,
|
||||||
//pub(crate) boot_button: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
|
pub(crate) boot_button: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
|
||||||
|
pub(crate) delay: Delay,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct AccessPointInfo {}
|
|
||||||
|
|
||||||
impl Esp<'_> {
|
impl Esp<'_> {
|
||||||
const SPIFFS_PARTITION_NAME: &'static str = "storage";
|
const SPIFFS_PARTITION_NAME: &'static str = "storage";
|
||||||
const CONFIG_FILE: &'static str = "/spiffs/config.cfg";
|
const CONFIG_FILE: &'static str = "/spiffs/config.cfg";
|
||||||
const BASE_PATH: &'static str = "/spiffs";
|
const BASE_PATH: &'static str = "/spiffs";
|
||||||
|
|
||||||
pub(crate) fn mode_override_pressed(&mut self) -> bool {
|
pub(crate) fn mode_override_pressed(&mut self) -> bool {
|
||||||
todo!();
|
self.boot_button.get_level() == Level::Low
|
||||||
//self.boot_button.get_level() == Level::Low
|
|
||||||
}
|
}
|
||||||
pub(crate) async fn sntp(&mut self, max_wait_ms: u32) -> anyhow::Result<DateTime<Utc>> {
|
pub(crate) fn sntp(&mut self, max_wait_ms: u32) -> anyhow::Result<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 {
|
||||||
// self.delay.delay_ms(100);
|
self.delay.delay_ms(100);
|
||||||
// counter += 100;
|
counter += 100;
|
||||||
// if counter > max_wait_ms {
|
if counter > max_wait_ms {
|
||||||
// bail!("Reached sntp timeout, aborting")
|
bail!("Reached sntp timeout, aborting")
|
||||||
// }
|
}
|
||||||
//}
|
}
|
||||||
//self.time()
|
self.time()
|
||||||
todo!();
|
|
||||||
}
|
}
|
||||||
pub(crate) fn time(&mut self) -> anyhow::Result<DateTime<Utc>> {
|
pub(crate) fn time(&mut self) -> anyhow::Result<DateTime<Utc>> {
|
||||||
let time = EspSystemTime {}.now().as_millis();
|
let time = EspSystemTime {}.now().as_millis();
|
||||||
@ -82,8 +97,7 @@ impl Esp<'_> {
|
|||||||
.ok_or(anyhow!("could not convert timestamp"))?;
|
.ok_or(anyhow!("could not convert timestamp"))?;
|
||||||
anyhow::Ok(local_time)
|
anyhow::Ok(local_time)
|
||||||
}
|
}
|
||||||
|
pub(crate) fn wifi_scan(&mut self) -> anyhow::Result<Vec<AccessPointInfo>> {
|
||||||
pub(crate) async fn wifi_scan(&mut self) -> anyhow::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)),
|
||||||
@ -135,7 +149,7 @@ impl Esp<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn wifi_ap(&mut self) -> anyhow::Result<()> {
|
pub(crate) fn wifi_ap(&mut self) -> anyhow::Result<()> {
|
||||||
let ssid = match self.load_config() {
|
let ssid = match self.load_config() {
|
||||||
Ok(config) => config.network.ap_ssid.clone(),
|
Ok(config) => config.network.ap_ssid.clone(),
|
||||||
Err(_) => heapless::String::from_str("PlantCtrl Emergency Mode").unwrap(),
|
Err(_) => heapless::String::from_str("PlantCtrl Emergency Mode").unwrap(),
|
||||||
@ -153,7 +167,7 @@ impl Esp<'_> {
|
|||||||
anyhow::Ok(())
|
anyhow::Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn wifi(&mut self, network_config: &NetworkConfig) -> anyhow::Result<IpInfo> {
|
pub(crate) fn wifi(&mut self, network_config: &NetworkConfig) -> anyhow::Result<IpInfo> {
|
||||||
let ssid = network_config
|
let ssid = network_config
|
||||||
.ssid
|
.ssid
|
||||||
.clone()
|
.clone()
|
||||||
@ -198,7 +212,7 @@ impl Esp<'_> {
|
|||||||
bail!("Did not manage wifi connection within timeout");
|
bail!("Did not manage wifi connection within timeout");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log::info!("Should be connected now, waiting for link to be up");
|
println!("Should be connected now, waiting for link to be up");
|
||||||
|
|
||||||
while !self.wifi_driver.is_up()? {
|
while !self.wifi_driver.is_up()? {
|
||||||
delay.delay_ms(250);
|
delay.delay_ms(250);
|
||||||
@ -215,37 +229,31 @@ impl Esp<'_> {
|
|||||||
log(LogMessage::WifiInfo, 0, 0, "", &format!("{address:?}"));
|
log(LogMessage::WifiInfo, 0, 0, "", &format!("{address:?}"));
|
||||||
anyhow::Ok(address)
|
anyhow::Ok(address)
|
||||||
}
|
}
|
||||||
pub(crate) async fn load_config(&mut self) -> anyhow::Result<PlantControllerConfig> {
|
pub(crate) fn load_config(&mut self) -> anyhow::Result<PlantControllerConfig> {
|
||||||
let cfg = File::open(Self::CONFIG_FILE)?;
|
let cfg = File::open(Self::CONFIG_FILE)?;
|
||||||
let config: PlantControllerConfig = serde_json::from_reader(cfg)?;
|
let config: PlantControllerConfig = serde_json::from_reader(cfg)?;
|
||||||
anyhow::Ok(config)
|
anyhow::Ok(config)
|
||||||
}
|
}
|
||||||
pub(crate) async fn save_config(
|
pub(crate) fn save_config(&mut self, config: &PlantControllerConfig) -> anyhow::Result<()> {
|
||||||
&mut self,
|
|
||||||
config: &PlantControllerConfig,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let mut cfg = File::create(Self::CONFIG_FILE)?;
|
let mut cfg = File::create(Self::CONFIG_FILE)?;
|
||||||
serde_json::to_writer(&mut cfg, &config)?;
|
serde_json::to_writer(&mut cfg, &config)?;
|
||||||
log::info!("Wrote config config {:?}", config);
|
println!("Wrote config config {:?}", config);
|
||||||
anyhow::Ok(())
|
anyhow::Ok(())
|
||||||
}
|
}
|
||||||
pub(crate) async fn mount_file_system(&mut self) -> anyhow::Result<()> {
|
pub(crate) fn mount_file_system(&mut self) -> anyhow::Result<()> {
|
||||||
log(LogMessage::MountingFilesystem, 0, 0, "", "");
|
log(LogMessage::MountingFilesystem, 0, 0, "", "");
|
||||||
let base_path = String::try_from("/spiffs")?;
|
let base_path = CString::new("/spiffs")?;
|
||||||
let storage = String::try_from(Self::SPIFFS_PARTITION_NAME)?;
|
let storage = CString::new(Self::SPIFFS_PARTITION_NAME)?;
|
||||||
let conf = todo!();
|
let conf = esp_idf_sys::esp_vfs_spiffs_conf_t {
|
||||||
|
base_path: base_path.as_ptr(),
|
||||||
|
partition_label: storage.as_ptr(),
|
||||||
|
max_files: 5,
|
||||||
|
format_if_mount_failed: true,
|
||||||
|
};
|
||||||
|
|
||||||
//let conf = esp_idf_sys::esp_vfs_spiffs_conf_t {
|
unsafe {
|
||||||
//base_path: base_path.as_ptr(),
|
esp_idf_sys::esp!(esp_idf_sys::esp_vfs_spiffs_register(&conf))?;
|
||||||
//partition_label: storage.as_ptr(),
|
}
|
||||||
//max_files: 5,
|
|
||||||
//format_if_mount_failed: true,
|
|
||||||
//};
|
|
||||||
|
|
||||||
//TODO
|
|
||||||
//unsafe {
|
|
||||||
//esp_idf_sys::esp!(esp_idf_sys::esp_vfs_spiffs_register(&conf))?;
|
|
||||||
//}
|
|
||||||
|
|
||||||
let free_space = self.file_system_size()?;
|
let free_space = self.file_system_size()?;
|
||||||
log(
|
log(
|
||||||
@ -257,7 +265,7 @@ impl Esp<'_> {
|
|||||||
);
|
);
|
||||||
anyhow::Ok(())
|
anyhow::Ok(())
|
||||||
}
|
}
|
||||||
async fn file_system_size(&mut self) -> anyhow::Result<FileSystemSizeInfo> {
|
fn file_system_size(&mut self) -> anyhow::Result<FileSystemSizeInfo> {
|
||||||
let storage = CString::new(Self::SPIFFS_PARTITION_NAME)?;
|
let storage = CString::new(Self::SPIFFS_PARTITION_NAME)?;
|
||||||
let mut total_size = 0;
|
let mut total_size = 0;
|
||||||
let mut used_size = 0;
|
let mut used_size = 0;
|
||||||
@ -275,7 +283,7 @@ impl Esp<'_> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn list_files(&self) -> FileList {
|
pub(crate) fn list_files(&self) -> FileList {
|
||||||
let storage = CString::new(Self::SPIFFS_PARTITION_NAME).unwrap();
|
let storage = CString::new(Self::SPIFFS_PARTITION_NAME).unwrap();
|
||||||
|
|
||||||
let mut file_system_corrupt = None;
|
let mut file_system_corrupt = None;
|
||||||
@ -322,7 +330,7 @@ impl Esp<'_> {
|
|||||||
iter_error,
|
iter_error,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub(crate) async fn delete_file(&self, filename: &str) -> anyhow::Result<()> {
|
pub(crate) fn delete_file(&self, filename: &str) -> anyhow::Result<()> {
|
||||||
let filepath = Path::new(Self::BASE_PATH).join(Path::new(filename));
|
let filepath = Path::new(Self::BASE_PATH).join(Path::new(filename));
|
||||||
match fs::remove_file(filepath) {
|
match fs::remove_file(filepath) {
|
||||||
OkStd(_) => anyhow::Ok(()),
|
OkStd(_) => anyhow::Ok(()),
|
||||||
@ -331,11 +339,7 @@ impl Esp<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub(crate) async fn get_file_handle(
|
pub(crate) fn get_file_handle(&self, filename: &str, write: bool) -> anyhow::Result<File> {
|
||||||
&self,
|
|
||||||
filename: &str,
|
|
||||||
write: bool,
|
|
||||||
) -> anyhow::Result<File> {
|
|
||||||
let filepath = Path::new(Self::BASE_PATH).join(Path::new(filename));
|
let filepath = Path::new(Self::BASE_PATH).join(Path::new(filename));
|
||||||
anyhow::Ok(if write {
|
anyhow::Ok(if write {
|
||||||
File::create(filepath)?
|
File::create(filepath)?
|
||||||
@ -373,24 +377,22 @@ impl Esp<'_> {
|
|||||||
"",
|
"",
|
||||||
);
|
);
|
||||||
for i in 0..PLANT_COUNT {
|
for i in 0..PLANT_COUNT {
|
||||||
log::info!(
|
println!(
|
||||||
"LAST_WATERING_TIMESTAMP[{}] = UTC {}",
|
"LAST_WATERING_TIMESTAMP[{}] = UTC {}",
|
||||||
i,
|
i, LAST_WATERING_TIMESTAMP[i]
|
||||||
LAST_WATERING_TIMESTAMP[i]
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
for i in 0..PLANT_COUNT {
|
for i in 0..PLANT_COUNT {
|
||||||
log::info!(
|
println!(
|
||||||
"CONSECUTIVE_WATERING_PLANT[{}] = {}",
|
"CONSECUTIVE_WATERING_PLANT[{}] = {}",
|
||||||
i,
|
i, CONSECUTIVE_WATERING_PLANT[i]
|
||||||
CONSECUTIVE_WATERING_PLANT[i]
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn mqtt(&mut self, network_config: &NetworkConfig) -> anyhow::Result<()> {
|
pub(crate) fn mqtt(&mut self, network_config: &NetworkConfig) -> anyhow::Result<()> {
|
||||||
let base_topic = network_config
|
let base_topic = network_config
|
||||||
.base_topic
|
.base_topic
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@ -466,35 +468,35 @@ impl Esp<'_> {
|
|||||||
mqtt_connected_event_received_copy
|
mqtt_connected_event_received_copy
|
||||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
mqtt_connected_event_ok_copy.store(true, std::sync::atomic::Ordering::Relaxed);
|
mqtt_connected_event_ok_copy.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
log::info!("Mqtt connected");
|
println!("Mqtt connected");
|
||||||
}
|
}
|
||||||
esp_idf_svc::mqtt::client::EventPayload::Disconnected => {
|
esp_idf_svc::mqtt::client::EventPayload::Disconnected => {
|
||||||
mqtt_connected_event_received_copy
|
mqtt_connected_event_received_copy
|
||||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
|
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
|
||||||
log::info!("Mqtt disconnected");
|
println!("Mqtt disconnected");
|
||||||
}
|
}
|
||||||
esp_idf_svc::mqtt::client::EventPayload::Error(esp_error) => {
|
esp_idf_svc::mqtt::client::EventPayload::Error(esp_error) => {
|
||||||
log::info!("EspMqttError reported {:?}", esp_error);
|
println!("EspMqttError reported {:?}", esp_error);
|
||||||
mqtt_connected_event_received_copy
|
mqtt_connected_event_received_copy
|
||||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
|
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
|
||||||
log::info!("Mqtt error");
|
println!("Mqtt error");
|
||||||
}
|
}
|
||||||
esp_idf_svc::mqtt::client::EventPayload::BeforeConnect => {
|
esp_idf_svc::mqtt::client::EventPayload::BeforeConnect => {
|
||||||
log::info!("Mqtt before connect")
|
println!("Mqtt before connect")
|
||||||
}
|
}
|
||||||
esp_idf_svc::mqtt::client::EventPayload::Subscribed(_) => {
|
esp_idf_svc::mqtt::client::EventPayload::Subscribed(_) => {
|
||||||
log::info!("Mqtt subscribed")
|
println!("Mqtt subscribed")
|
||||||
}
|
}
|
||||||
esp_idf_svc::mqtt::client::EventPayload::Unsubscribed(_) => {
|
esp_idf_svc::mqtt::client::EventPayload::Unsubscribed(_) => {
|
||||||
log::info!("Mqtt unsubscribed")
|
println!("Mqtt unsubscribed")
|
||||||
}
|
}
|
||||||
esp_idf_svc::mqtt::client::EventPayload::Published(_) => {
|
esp_idf_svc::mqtt::client::EventPayload::Published(_) => {
|
||||||
log::info!("Mqtt published")
|
println!("Mqtt published")
|
||||||
}
|
}
|
||||||
esp_idf_svc::mqtt::client::EventPayload::Deleted(_) => {
|
esp_idf_svc::mqtt::client::EventPayload::Deleted(_) => {
|
||||||
log::info!("Mqtt deleted")
|
println!("Mqtt deleted")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
@ -504,12 +506,10 @@ impl Esp<'_> {
|
|||||||
wait_for_connections_event += 1;
|
wait_for_connections_event += 1;
|
||||||
match mqtt_connected_event_received.load(std::sync::atomic::Ordering::Relaxed) {
|
match mqtt_connected_event_received.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
true => {
|
true => {
|
||||||
log::info!("Mqtt connection callback received, progressing");
|
println!("Mqtt connection callback received, progressing");
|
||||||
match mqtt_connected_event_ok.load(std::sync::atomic::Ordering::Relaxed) {
|
match mqtt_connected_event_ok.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
true => {
|
true => {
|
||||||
log::info!(
|
println!("Mqtt did callback as connected, testing with roundtrip now");
|
||||||
"Mqtt did callback as connected, testing with roundtrip now"
|
|
||||||
);
|
|
||||||
//subscribe to roundtrip
|
//subscribe to roundtrip
|
||||||
client.subscribe(round_trip_topic.as_str(), ExactlyOnce)?;
|
client.subscribe(round_trip_topic.as_str(), ExactlyOnce)?;
|
||||||
client.subscribe(stay_alive_topic.as_str(), ExactlyOnce)?;
|
client.subscribe(stay_alive_topic.as_str(), ExactlyOnce)?;
|
||||||
@ -526,7 +526,7 @@ impl Esp<'_> {
|
|||||||
wait_for_roundtrip += 1;
|
wait_for_roundtrip += 1;
|
||||||
match round_trip_ok.load(std::sync::atomic::Ordering::Relaxed) {
|
match round_trip_ok.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
true => {
|
true => {
|
||||||
log::info!("Round trip registered, proceeding");
|
println!("Round trip registered, proceeding");
|
||||||
self.mqtt_client = Some(MqttClient {
|
self.mqtt_client = Some(MqttClient {
|
||||||
mqtt_client: client,
|
mqtt_client: client,
|
||||||
base_topic: base_topic_copy,
|
base_topic: base_topic_copy,
|
||||||
@ -552,30 +552,26 @@ impl Esp<'_> {
|
|||||||
}
|
}
|
||||||
bail!("Mqtt did not fire connection callback in time");
|
bail!("Mqtt did not fire connection callback in time");
|
||||||
}
|
}
|
||||||
pub(crate) async fn mqtt_publish(
|
pub(crate) fn mqtt_publish(&mut self, subtopic: &str, message: &[u8]) -> anyhow::Result<()> {
|
||||||
&mut self,
|
|
||||||
subtopic: &str,
|
|
||||||
message: &[u8],
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
if self.mqtt_client.is_none() {
|
if self.mqtt_client.is_none() {
|
||||||
return anyhow::Ok(());
|
return anyhow::Ok(());
|
||||||
}
|
}
|
||||||
if !subtopic.starts_with("/") {
|
if !subtopic.starts_with("/") {
|
||||||
log::info!("Subtopic without / at start {}", subtopic);
|
println!("Subtopic without / at start {}", subtopic);
|
||||||
bail!("Subtopic without / at start {}", subtopic);
|
bail!("Subtopic without / at start {}", subtopic);
|
||||||
}
|
}
|
||||||
if subtopic.len() > 192 {
|
if subtopic.len() > 192 {
|
||||||
log::info!("Subtopic exceeds 192 chars {}", subtopic);
|
println!("Subtopic exceeds 192 chars {}", subtopic);
|
||||||
bail!("Subtopic exceeds 192 chars {}", subtopic);
|
bail!("Subtopic exceeds 192 chars {}", subtopic);
|
||||||
}
|
}
|
||||||
let client = self.mqtt_client.as_mut().unwrap();
|
let client = self.mqtt_client.as_mut().unwrap();
|
||||||
let mut full_topic: heapless::String<256> = heapless::String::new();
|
let mut full_topic: heapless::String<256> = heapless::String::new();
|
||||||
if full_topic.push_str(client.base_topic.as_str()).is_err() {
|
if full_topic.push_str(client.base_topic.as_str()).is_err() {
|
||||||
log::info!("Some error assembling full_topic 1");
|
println!("Some error assembling full_topic 1");
|
||||||
bail!("Some error assembling full_topic 1")
|
bail!("Some error assembling full_topic 1")
|
||||||
};
|
};
|
||||||
if full_topic.push_str(subtopic).is_err() {
|
if full_topic.push_str(subtopic).is_err() {
|
||||||
log::info!("Some error assembling full_topic 2");
|
println!("Some error assembling full_topic 2");
|
||||||
bail!("Some error assembling full_topic 2")
|
bail!("Some error assembling full_topic 2")
|
||||||
};
|
};
|
||||||
let publish = client
|
let publish = client
|
||||||
@ -584,7 +580,7 @@ impl Esp<'_> {
|
|||||||
Delay::new(10).delay_ms(50);
|
Delay::new(10).delay_ms(50);
|
||||||
match publish {
|
match publish {
|
||||||
OkStd(message_id) => {
|
OkStd(message_id) => {
|
||||||
log::info!(
|
println!(
|
||||||
"Published mqtt topic {} with message {:#?} msgid is {:?}",
|
"Published mqtt topic {} with message {:#?} msgid is {:?}",
|
||||||
full_topic,
|
full_topic,
|
||||||
String::from_utf8_lossy(message),
|
String::from_utf8_lossy(message),
|
||||||
@ -593,7 +589,7 @@ impl Esp<'_> {
|
|||||||
anyhow::Ok(())
|
anyhow::Ok(())
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::info!(
|
println!(
|
||||||
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
|
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
|
||||||
full_topic,
|
full_topic,
|
||||||
String::from_utf8_lossy(message),
|
String::from_utf8_lossy(message),
|
||||||
|
@ -9,8 +9,9 @@ use crate::{
|
|||||||
use anyhow::{bail, Result};
|
use anyhow::{bail, Result};
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use embedded_hal::digital::OutputPin;
|
use embedded_hal::digital::OutputPin;
|
||||||
|
use esp_idf_hal::gpio::{IOPin, Pull};
|
||||||
|
use esp_idf_hal::gpio::{InputOutput, PinDriver};
|
||||||
use measurements::{Current, Voltage};
|
use measurements::{Current, Voltage};
|
||||||
use crate::alloc::boxed::Box;
|
|
||||||
|
|
||||||
pub struct Initial<'a> {
|
pub struct Initial<'a> {
|
||||||
pub(crate) general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
pub(crate) general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||||
@ -50,7 +51,7 @@ pub(crate) fn create_initial_board(
|
|||||||
config: PlantControllerConfig,
|
config: PlantControllerConfig,
|
||||||
esp: Esp<'static>,
|
esp: Esp<'static>,
|
||||||
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
||||||
log::info!("Start initial");
|
println!("Start initial");
|
||||||
let mut general_fault = PinDriver::input_output(free_pins.gpio6.downgrade())?;
|
let mut general_fault = PinDriver::input_output(free_pins.gpio6.downgrade())?;
|
||||||
general_fault.set_pull(Pull::Floating)?;
|
general_fault.set_pull(Pull::Floating)?;
|
||||||
general_fault.set_low()?;
|
general_fault.set_low()?;
|
||||||
|
@ -4,10 +4,9 @@ mod initial_hal;
|
|||||||
mod rtc;
|
mod rtc;
|
||||||
mod v3_hal;
|
mod v3_hal;
|
||||||
mod v4_hal;
|
mod v4_hal;
|
||||||
mod v4_sensor;
|
|
||||||
mod water;
|
mod water;
|
||||||
|
mod v4_sensor;
|
||||||
|
|
||||||
use crate::alloc::string::ToString;
|
|
||||||
use crate::hal::rtc::{DS3231Module, RTCModuleInteraction};
|
use crate::hal::rtc::{DS3231Module, RTCModuleInteraction};
|
||||||
use crate::hal::water::TankSensor;
|
use crate::hal::water::TankSensor;
|
||||||
use crate::{
|
use crate::{
|
||||||
@ -18,18 +17,12 @@ use crate::{
|
|||||||
},
|
},
|
||||||
log::{log, LogMessage},
|
log::{log, LogMessage},
|
||||||
};
|
};
|
||||||
use alloc::boxed::Box;
|
|
||||||
use anyhow::{Ok, Result};
|
use anyhow::{Ok, Result};
|
||||||
use async_trait::async_trait;
|
|
||||||
use battery::BQ34Z100G1;
|
use battery::BQ34Z100G1;
|
||||||
use bq34z100::Bq34z100g1Driver;
|
use bq34z100::Bq34z100g1Driver;
|
||||||
use ds323x::{DateTimeAccess, Ds323x};
|
use ds323x::{DateTimeAccess, Ds323x};
|
||||||
use eeprom24x::{Eeprom24x, SlaveAddr, Storage};
|
use eeprom24x::{Eeprom24x, SlaveAddr, Storage};
|
||||||
use embassy_sync::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
|
|
||||||
use embassy_sync::mutex::Mutex;
|
|
||||||
use embassy_sync::{LazyLock, Mutex};
|
|
||||||
use embedded_hal_bus::i2c::MutexDevice;
|
use embedded_hal_bus::i2c::MutexDevice;
|
||||||
use esp_idf_hal::can::CAN;
|
|
||||||
use esp_idf_hal::pcnt::PCNT1;
|
use esp_idf_hal::pcnt::PCNT1;
|
||||||
use esp_idf_hal::{
|
use esp_idf_hal::{
|
||||||
adc::ADC1,
|
adc::ADC1,
|
||||||
@ -52,13 +45,18 @@ use esp_idf_sys::{
|
|||||||
};
|
};
|
||||||
use esp_ota::mark_app_valid;
|
use esp_ota::mark_app_valid;
|
||||||
use measurements::{Current, Voltage};
|
use measurements::{Current, Voltage};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use std::result::Result::Ok as OkStd;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::Duration;
|
||||||
|
use esp_idf_hal::can::CAN;
|
||||||
|
|
||||||
//Only support for 8 right now!
|
//Only support for 8 right now!
|
||||||
pub const PLANT_COUNT: usize = 8;
|
pub const PLANT_COUNT: usize = 8;
|
||||||
|
|
||||||
const TANK_MULTI_SAMPLE: usize = 11;
|
const TANK_MULTI_SAMPLE: usize = 11;
|
||||||
|
|
||||||
pub static I2C_DRIVER: LazyLock<Mutex<I2cDriver<'static>>> = LazyLock::new(PlantHal::create_i2c);
|
pub static I2C_DRIVER: Lazy<Mutex<I2cDriver<'static>>> = Lazy::new(PlantHal::create_i2c);
|
||||||
|
|
||||||
fn deep_sleep(duration_in_ms: u64) -> ! {
|
fn deep_sleep(duration_in_ms: u64) -> ! {
|
||||||
unsafe {
|
unsafe {
|
||||||
@ -90,9 +88,8 @@ pub struct HAL<'a> {
|
|||||||
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
|
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait BoardInteraction<'a> {
|
pub trait BoardInteraction<'a> {
|
||||||
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor>;
|
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>>;
|
||||||
fn get_esp(&mut self) -> &mut Esp<'a>;
|
fn get_esp(&mut self) -> &mut Esp<'a>;
|
||||||
fn get_config(&mut self) -> &PlantControllerConfig;
|
fn get_config(&mut self) -> &PlantControllerConfig;
|
||||||
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send>;
|
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send>;
|
||||||
@ -103,20 +100,20 @@ pub trait BoardInteraction<'a> {
|
|||||||
fn is_day(&self) -> bool;
|
fn is_day(&self) -> bool;
|
||||||
//should be multsampled
|
//should be multsampled
|
||||||
fn light(&mut self, enable: bool) -> Result<()>;
|
fn light(&mut self, enable: bool) -> Result<()>;
|
||||||
async fn pump(&mut self, plant: usize, enable: bool) -> Result<()>;
|
fn pump(&mut self, plant: usize, enable: bool) -> Result<()>;
|
||||||
async fn pump_current(&mut self, plant: usize) -> Result<Current>;
|
fn pump_current(&mut self, plant: usize) -> Result<Current>;
|
||||||
async fn fault(&mut self, plant: usize, enable: bool) -> Result<()>;
|
fn fault(&mut self, plant: usize, enable: bool) -> Result<()>;
|
||||||
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32>;
|
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32>;
|
||||||
async fn general_fault(&mut self, enable: bool);
|
fn general_fault(&mut self, enable: bool);
|
||||||
async fn test(&mut self) -> Result<()>;
|
fn test(&mut self) -> Result<()>;
|
||||||
async fn set_config(&mut self, config: PlantControllerConfig) -> Result<()>;
|
fn set_config(&mut self, config: PlantControllerConfig) -> Result<()>;
|
||||||
async fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage>;
|
fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage>;
|
||||||
async fn get_mptt_current(&mut self) -> anyhow::Result<Current>;
|
fn get_mptt_current(&mut self) -> anyhow::Result<Current>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl dyn BoardInteraction<'_> {
|
impl dyn BoardInteraction<'_> {
|
||||||
//the counter is just some arbitrary number that increases whenever some progress was made, try to keep the updates < 10 per second for ux reasons
|
//the counter is just some arbitrary number that increases whenever some progress was made, try to keep the updates < 10 per second for ux reasons
|
||||||
async fn _progress(&mut self, counter: u32) {
|
fn _progress(&mut self, counter: u32) {
|
||||||
let even = counter % 2 == 0;
|
let even = counter % 2 == 0;
|
||||||
let current = counter / (PLANT_COUNT as u32);
|
let current = counter / (PLANT_COUNT as u32);
|
||||||
for led in 0..PLANT_COUNT {
|
for led in 0..PLANT_COUNT {
|
||||||
@ -181,7 +178,7 @@ impl PlantHal {
|
|||||||
Mutex::new(I2cDriver::new(i2c, sda, scl, &config).unwrap())
|
Mutex::new(I2cDriver::new(i2c, sda, scl, &config).unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>> {
|
pub fn create() -> Result<Mutex<HAL<'static>>> {
|
||||||
let peripherals = Peripherals::take()?;
|
let peripherals = Peripherals::take()?;
|
||||||
let sys_loop = EspSystemEventLoop::take()?;
|
let sys_loop = EspSystemEventLoop::take()?;
|
||||||
let nvs = EspDefaultNvsPartition::take()?;
|
let nvs = EspDefaultNvsPartition::take()?;
|
||||||
@ -269,10 +266,10 @@ impl PlantHal {
|
|||||||
|
|
||||||
let config = esp.load_config();
|
let config = esp.load_config();
|
||||||
|
|
||||||
log::info!("Init rtc driver");
|
println!("Init rtc driver");
|
||||||
let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
|
let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
|
||||||
|
|
||||||
log::info!("Init rtc eeprom driver");
|
println!("Init rtc eeprom driver");
|
||||||
let eeprom = {
|
let eeprom = {
|
||||||
Eeprom24x::new_24x32(
|
Eeprom24x::new_24x32(
|
||||||
MutexDevice::new(&I2C_DRIVER),
|
MutexDevice::new(&I2C_DRIVER),
|
||||||
@ -282,10 +279,10 @@ impl PlantHal {
|
|||||||
let rtc_time = rtc.datetime();
|
let rtc_time = rtc.datetime();
|
||||||
match rtc_time {
|
match rtc_time {
|
||||||
OkStd(tt) => {
|
OkStd(tt) => {
|
||||||
log::info!("Rtc Module reports time at UTC {}", tt);
|
println!("Rtc Module reports time at UTC {}", tt);
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::info!("Rtc Module could not be read {:?}", err);
|
println!("Rtc Module could not be read {:?}", err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,7 +1,4 @@
|
|||||||
use crate::hal::Box;
|
|
||||||
use alloc::vec::Vec;
|
|
||||||
use anyhow::{anyhow, bail};
|
use anyhow::{anyhow, bail};
|
||||||
use async_trait::async_trait;
|
|
||||||
use bincode::config::Configuration;
|
use bincode::config::Configuration;
|
||||||
use bincode::{config, Decode, Encode};
|
use bincode::{config, Decode, Encode};
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
@ -10,20 +7,23 @@ use eeprom24x::addr_size::TwoBytes;
|
|||||||
use eeprom24x::page_size::B32;
|
use eeprom24x::page_size::B32;
|
||||||
use eeprom24x::unique_serial::No;
|
use eeprom24x::unique_serial::No;
|
||||||
use eeprom24x::Storage;
|
use eeprom24x::Storage;
|
||||||
|
use embedded_hal_bus::i2c::MutexDevice;
|
||||||
use embedded_storage::ReadStorage as embedded_storage_ReadStorage;
|
use embedded_storage::ReadStorage as embedded_storage_ReadStorage;
|
||||||
use embedded_storage::Storage as embedded_storage_Storage;
|
use embedded_storage::Storage as embedded_storage_Storage;
|
||||||
|
use esp_idf_hal::delay::Delay;
|
||||||
|
use esp_idf_hal::i2c::I2cDriver;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::result::Result::Ok as OkStd;
|
||||||
|
|
||||||
const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
|
const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
|
||||||
const CONFIG: Configuration = config::standard();
|
const CONFIG: Configuration = config::standard();
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait RTCModuleInteraction {
|
pub trait RTCModuleInteraction {
|
||||||
async fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader>;
|
fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader>;
|
||||||
async fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>>;
|
fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>>;
|
||||||
async fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()>;
|
fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()>;
|
||||||
async fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>>;
|
fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>>;
|
||||||
async fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()>;
|
fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const BACKUP_HEADER_MAX_SIZE: usize = 64;
|
const BACKUP_HEADER_MAX_SIZE: usize = 64;
|
||||||
@ -52,7 +52,7 @@ impl RTCModuleInteraction for DS3231Module<'_> {
|
|||||||
let (header, len): (BackupHeader, usize) =
|
let (header, len): (BackupHeader, usize) =
|
||||||
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
|
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
|
||||||
|
|
||||||
log::info!("Raw header is {:?} with size {}", header_page_buffer, len);
|
println!("Raw header is {:?} with size {}", header_page_buffer, len);
|
||||||
anyhow::Ok(header)
|
anyhow::Ok(header)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -95,10 +95,9 @@ impl RTCModuleInteraction for DS3231Module<'_> {
|
|||||||
};
|
};
|
||||||
let config = config::standard();
|
let config = config::standard();
|
||||||
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
|
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
|
||||||
log::info!(
|
println!(
|
||||||
"Raw header is {:?} with size {}",
|
"Raw header is {:?} with size {}",
|
||||||
header_page_buffer,
|
header_page_buffer, encoded
|
||||||
encoded
|
|
||||||
);
|
);
|
||||||
self.storage
|
self.storage
|
||||||
.write(0, &header_page_buffer)
|
.write(0, &header_page_buffer)
|
||||||
|
@ -10,12 +10,14 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use anyhow::{bail, Ok, Result};
|
use anyhow::{bail, Ok, Result};
|
||||||
use embedded_hal::digital::OutputPin;
|
use embedded_hal::digital::OutputPin;
|
||||||
|
use esp_idf_hal::{
|
||||||
|
gpio::{AnyInputPin, IOPin, InputOutput, PinDriver, Pull},
|
||||||
|
pcnt::{PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex},
|
||||||
|
};
|
||||||
|
use esp_idf_sys::{gpio_hold_dis, gpio_hold_en};
|
||||||
use measurements::{Current, Voltage};
|
use measurements::{Current, Voltage};
|
||||||
use plant_ctrl2::sipo::ShiftRegister40;
|
use plant_ctrl2::sipo::ShiftRegister40;
|
||||||
use core::result::Result::Ok as OkStd;
|
use std::result::Result::Ok as OkStd;
|
||||||
use alloc::string::ToString;
|
|
||||||
use alloc::boxed::Box;
|
|
||||||
use esp_hall::gpio::Pull;
|
|
||||||
|
|
||||||
const PUMP8_BIT: usize = 0;
|
const PUMP8_BIT: usize = 0;
|
||||||
const PUMP1_BIT: usize = 1;
|
const PUMP1_BIT: usize = 1;
|
||||||
@ -92,7 +94,7 @@ pub(crate) fn create_v3(
|
|||||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||||
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
||||||
log::info!("Start v3");
|
println!("Start v3");
|
||||||
let mut clock = PinDriver::input_output(peripherals.gpio15.downgrade())?;
|
let mut clock = PinDriver::input_output(peripherals.gpio15.downgrade())?;
|
||||||
clock.set_pull(Pull::Floating)?;
|
clock.set_pull(Pull::Floating)?;
|
||||||
let mut latch = PinDriver::input_output(peripherals.gpio3.downgrade())?;
|
let mut latch = PinDriver::input_output(peripherals.gpio3.downgrade())?;
|
||||||
|
@ -12,6 +12,12 @@ use crate::log::{log, LogMessage};
|
|||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use embedded_hal::digital::OutputPin;
|
use embedded_hal::digital::OutputPin;
|
||||||
use embedded_hal_bus::i2c::MutexDevice;
|
use embedded_hal_bus::i2c::MutexDevice;
|
||||||
|
use esp_idf_hal::gpio::{AnyInputPin, IOPin, InputOutput, Output, PinDriver, Pull};
|
||||||
|
use esp_idf_hal::i2c::I2cDriver;
|
||||||
|
use esp_idf_hal::pcnt::{
|
||||||
|
PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex,
|
||||||
|
};
|
||||||
|
use esp_idf_sys::{gpio_hold_dis, gpio_hold_en};
|
||||||
use ina219::address::{Address, Pin};
|
use ina219::address::{Address, Pin};
|
||||||
use ina219::calibration::UnCalibrated;
|
use ina219::calibration::UnCalibrated;
|
||||||
use ina219::configuration::{Configuration, OperatingMode};
|
use ina219::configuration::{Configuration, OperatingMode};
|
||||||
@ -21,9 +27,7 @@ use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
|||||||
use std::result::Result::Ok as OkStd;
|
use std::result::Result::Ok as OkStd;
|
||||||
use embedded_can::Frame;
|
use embedded_can::Frame;
|
||||||
use embedded_can::StandardId;
|
use embedded_can::StandardId;
|
||||||
use alloc::string::ToString;
|
use esp_idf_hal::can;
|
||||||
use alloc::boxed::Box;
|
|
||||||
use esp_hal::gpio::Pull;
|
|
||||||
|
|
||||||
pub enum Charger<'a> {
|
pub enum Charger<'a> {
|
||||||
SolarMpptV1 {
|
SolarMpptV1 {
|
||||||
@ -48,7 +52,7 @@ impl Charger<'_> {
|
|||||||
operating_mode: OperatingMode::PowerDown,
|
operating_mode: OperatingMode::PowerDown,
|
||||||
})
|
})
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
log::info!(
|
println!(
|
||||||
"Error setting ina mppt configuration during deep sleep preparation{:?}",
|
"Error setting ina mppt configuration during deep sleep preparation{:?}",
|
||||||
e
|
e
|
||||||
);
|
);
|
||||||
@ -129,7 +133,7 @@ pub(crate) fn create_v4(
|
|||||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||||
) -> anyhow::Result<Box<dyn BoardInteraction<'static> + Send + 'static>> {
|
) -> anyhow::Result<Box<dyn BoardInteraction<'static> + Send + 'static>> {
|
||||||
log::info!("Start v4");
|
println!("Start v4");
|
||||||
let mut awake = PinDriver::output(peripherals.gpio21.downgrade())?;
|
let mut awake = PinDriver::output(peripherals.gpio21.downgrade())?;
|
||||||
awake.set_high()?;
|
awake.set_high()?;
|
||||||
|
|
||||||
@ -159,7 +163,7 @@ pub(crate) fn create_v4(
|
|||||||
let mut sensor_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 34);
|
let mut sensor_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 34);
|
||||||
let sensor = match sensor_expander.pin_into_output(GPIOBank::Bank0, 0) {
|
let sensor = match sensor_expander.pin_into_output(GPIOBank::Bank0, 0) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
log::info!("SensorExpander answered");
|
println!("SensorExpander answered");
|
||||||
//pulse counter version
|
//pulse counter version
|
||||||
let mut signal_counter = PcntDriver::new(
|
let mut signal_counter = PcntDriver::new(
|
||||||
peripherals.pcnt0,
|
peripherals.pcnt0,
|
||||||
@ -196,7 +200,7 @@ pub(crate) fn create_v4(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
log::info!("Can bus mode ");
|
println!("Can bus mode ");
|
||||||
let timing = can::config::Timing::B25K;
|
let timing = can::config::Timing::B25K;
|
||||||
let config = can::config::Config::new().timing(timing);
|
let config = can::config::Config::new().timing(timing);
|
||||||
let can = can::CanDriver::new(peripherals.can, peripherals.gpio0, peripherals.gpio2, &config).unwrap();
|
let can = can::CanDriver::new(peripherals.can, peripherals.gpio0, peripherals.gpio2, &config).unwrap();
|
||||||
@ -207,7 +211,7 @@ pub(crate) fn create_v4(
|
|||||||
can.transmit(&tx_frame, 1000).unwrap();
|
can.transmit(&tx_frame, 1000).unwrap();
|
||||||
|
|
||||||
if let Ok(rx_frame) = can.receive(1000) {
|
if let Ok(rx_frame) = can.receive(1000) {
|
||||||
log::info!("rx {:}:", rx_frame);
|
println!("rx {:}:", rx_frame);
|
||||||
}
|
}
|
||||||
//can bus version
|
//can bus version
|
||||||
SensorImpl::CanBus {
|
SensorImpl::CanBus {
|
||||||
@ -270,7 +274,7 @@ pub(crate) fn create_v4(
|
|||||||
) {
|
) {
|
||||||
Ok(pump_ina) => Some(pump_ina),
|
Ok(pump_ina) => Some(pump_ina),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::info!("Error creating pump ina: {:?}", err);
|
println!("Error creating pump ina: {:?}", err);
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -1,17 +1,16 @@
|
|||||||
use crate::hal::Sensor;
|
|
||||||
use crate::log::{log, LogMessage};
|
|
||||||
use alloc::string::ToString;
|
|
||||||
use embedded_hal_bus::i2c::MutexDevice;
|
use embedded_hal_bus::i2c::MutexDevice;
|
||||||
use esp_idf_hal::can::CanDriver;
|
use esp_idf_hal::can::CanDriver;
|
||||||
use esp_idf_hal::delay::Delay;
|
use esp_idf_hal::delay::Delay;
|
||||||
use esp_idf_hal::i2c::I2cDriver;
|
use esp_idf_hal::i2c::I2cDriver;
|
||||||
use esp_idf_hal::pcnt::PcntDriver;
|
use esp_idf_hal::pcnt::PcntDriver;
|
||||||
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
||||||
|
use crate::hal::Sensor;
|
||||||
|
use crate::log::{log, LogMessage};
|
||||||
|
|
||||||
const REPEAT_MOIST_MEASURE: usize = 10;
|
const REPEAT_MOIST_MEASURE: usize = 10;
|
||||||
|
|
||||||
pub trait SensorInteraction {
|
pub trait SensorInteraction {
|
||||||
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32>;
|
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MS0: u8 = 1_u8;
|
const MS0: u8 = 1_u8;
|
||||||
@ -22,23 +21,19 @@ const MS4: u8 = 2_u8;
|
|||||||
const SENSOR_ON: u8 = 5_u8;
|
const SENSOR_ON: u8 = 5_u8;
|
||||||
|
|
||||||
pub enum SensorImpl<'a> {
|
pub enum SensorImpl<'a> {
|
||||||
PulseCounter {
|
PulseCounter{
|
||||||
signal_counter: PcntDriver<'a>,
|
signal_counter: PcntDriver<'a>,
|
||||||
sensor_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
|
sensor_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
|
||||||
},
|
},
|
||||||
CanBus {
|
CanBus{
|
||||||
can: CanDriver<'a>,
|
can: CanDriver<'a>
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SensorInteraction for SensorImpl<'_> {
|
impl SensorInteraction for SensorImpl<'_> {
|
||||||
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
|
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
|
||||||
match self {
|
match self {
|
||||||
SensorImpl::PulseCounter {
|
SensorImpl::PulseCounter { signal_counter, sensor_expander, .. } => {
|
||||||
signal_counter,
|
|
||||||
sensor_expander,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
|
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
|
||||||
for repeat in 0..REPEAT_MOIST_MEASURE {
|
for repeat in 0..REPEAT_MOIST_MEASURE {
|
||||||
signal_counter.counter_pause()?;
|
signal_counter.counter_pause()?;
|
||||||
@ -75,7 +70,8 @@ impl SensorInteraction for SensorImpl<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
|
||||||
sensor_expander.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
|
sensor_expander
|
||||||
|
.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
|
||||||
|
|
||||||
let delay = Delay::new_default();
|
let delay = Delay::new_default();
|
||||||
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
|
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
|
||||||
@ -87,7 +83,8 @@ impl SensorInteraction for SensorImpl<'_> {
|
|||||||
delay.delay_ms(measurement);
|
delay.delay_ms(measurement);
|
||||||
signal_counter.counter_pause()?;
|
signal_counter.counter_pause()?;
|
||||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
|
sensor_expander
|
||||||
|
.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
|
||||||
|
@ -102,18 +102,18 @@ impl<'a> TankSensor<'a> {
|
|||||||
self.get_flow_meter_value()
|
self.get_flow_meter_value()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn water_temperature_c(&mut self) -> anyhow::Result<f32> {
|
pub fn water_temperature_c(&mut self) -> anyhow::Result<f32> {
|
||||||
//multisample should be moved to water_temperature_c
|
//multisample should be moved to water_temperature_c
|
||||||
let mut attempt = 1;
|
let mut attempt = 1;
|
||||||
let water_temp: Result<f32, anyhow::Error> = loop {
|
let water_temp: Result<f32, anyhow::Error> = loop {
|
||||||
let temp = self.single_temperature_c();
|
let temp = self.single_temperature_c();
|
||||||
match &temp {
|
match &temp {
|
||||||
Ok(res) => {
|
Ok(res) => {
|
||||||
log::info!("Water temp is {}", res);
|
println!("Water temp is {}", res);
|
||||||
break temp;
|
break temp;
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::info!("Could not get water temp {} attempt {}", err, attempt)
|
println!("Could not get water temp {} attempt {}", err, attempt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if attempt == 5 {
|
if attempt == 5 {
|
||||||
@ -124,7 +124,7 @@ impl<'a> TankSensor<'a> {
|
|||||||
water_temp
|
water_temp
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn single_temperature_c(&mut self) -> anyhow::Result<f32> {
|
fn single_temperature_c(&mut self) -> anyhow::Result<f32> {
|
||||||
self.one_wire_bus
|
self.one_wire_bus
|
||||||
.reset(&mut self.delay)
|
.reset(&mut self.delay)
|
||||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||||
@ -152,7 +152,7 @@ impl<'a> TankSensor<'a> {
|
|||||||
anyhow::Ok(sensor_data.temperature / 10_f32)
|
anyhow::Ok(sensor_data.temperature / 10_f32)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
|
pub fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
|
||||||
self.tank_power.set_high()?;
|
self.tank_power.set_high()?;
|
||||||
//let stabilize
|
//let stabilize
|
||||||
self.delay.delay_ms(100);
|
self.delay.delay_ms(100);
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
#![allow(dead_code)]
|
#![allow(dead_code)]
|
||||||
#![no_std]
|
|
||||||
extern crate embedded_hal as hal;
|
extern crate embedded_hal as hal;
|
||||||
|
|
||||||
pub mod sipo;
|
pub mod sipo;
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
use alloc::string::ToString;
|
|
||||||
use alloc::vec::Vec;
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::{collections::HashMap, sync::Mutex};
|
use std::{collections::HashMap, sync::Mutex};
|
||||||
use strum::EnumIter;
|
use strum::EnumIter;
|
||||||
@ -94,7 +92,7 @@ pub fn log(message_key: LogMessage, number_a: u32, number_b: u32, txt_short: &st
|
|||||||
let template = Template::from(template_string);
|
let template = Template::from(template_string);
|
||||||
let serial_entry = template.fill_in(&values);
|
let serial_entry = template.fill_in(&values);
|
||||||
|
|
||||||
log::info!("{serial_entry}");
|
println!("{serial_entry}");
|
||||||
//TODO push to mqtt?
|
//TODO push to mqtt?
|
||||||
|
|
||||||
let entry = LogEntry {
|
let entry = LogEntry {
|
||||||
|
467
rust/src/main.rs
467
rust/src/main.rs
@ -1,51 +1,38 @@
|
|||||||
#![no_std]
|
|
||||||
#![no_main]
|
|
||||||
#![deny(
|
|
||||||
clippy::mem_forget,
|
|
||||||
reason = "mem::forget is generally not safe to do with esp_hal types, especially those \
|
|
||||||
holding buffers for the duration of a data transfer."
|
|
||||||
)]
|
|
||||||
use crate::config::PlantConfig;
|
use crate::config::PlantConfig;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::BoardVersion::INITIAL,
|
config::BoardVersion::INITIAL,
|
||||||
hal::{PlantHal, HAL, PLANT_COUNT},
|
hal::{PlantHal, HAL, PLANT_COUNT},
|
||||||
//webserver::httpd,
|
webserver::httpd,
|
||||||
};
|
};
|
||||||
use ::log::{error, info, warn};
|
|
||||||
use alloc::borrow::ToOwned;
|
|
||||||
use alloc::string::{String, ToString};
|
|
||||||
use alloc::sync::Arc;
|
|
||||||
use alloc::{format, vec};
|
|
||||||
use anyhow::{bail, Context};
|
use anyhow::{bail, Context};
|
||||||
use chrono::{DateTime, Datelike, Timelike, Utc};
|
use chrono::{DateTime, Datelike, Timelike, Utc};
|
||||||
use chrono_tz::Tz::{self, UTC};
|
use chrono_tz::Tz::{self, UTC};
|
||||||
use core::sync::atomic::Ordering;
|
use esp_idf_hal::delay::Delay;
|
||||||
use embassy_executor::Spawner;
|
use esp_idf_sys::{
|
||||||
use embassy_sync::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
|
esp_ota_get_app_partition_count, esp_ota_get_running_partition, esp_ota_get_state_partition,
|
||||||
use embassy_sync::lazy_lock::LazyLock;
|
esp_ota_img_states_t, esp_ota_img_states_t_ESP_OTA_IMG_ABORTED,
|
||||||
use embassy_sync::mutex::Mutex;
|
esp_ota_img_states_t_ESP_OTA_IMG_INVALID, esp_ota_img_states_t_ESP_OTA_IMG_NEW,
|
||||||
use embassy_sync::mutex::MutexGuard;
|
esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY, esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED,
|
||||||
use embassy_time::Timer;
|
esp_ota_img_states_t_ESP_OTA_IMG_VALID,
|
||||||
use esp_hal::{clock::CpuClock, delay::Delay, timer::systimer::SystemTimer};
|
};
|
||||||
use esp_println::logger;
|
use esp_ota::{mark_app_valid, rollback_and_reboot};
|
||||||
use hal::battery::BatteryState;
|
use hal::battery::BatteryState;
|
||||||
use log::{log, LogMessage};
|
use log::{log, LogMessage};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
use plant_state::PlantState;
|
use plant_state::PlantState;
|
||||||
use portable_atomic::AtomicBool;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::sync::{atomic::AtomicBool, Arc, Mutex, MutexGuard};
|
||||||
use tank::*;
|
use tank::*;
|
||||||
|
|
||||||
mod config;
|
mod config;
|
||||||
mod hal;
|
mod hal;
|
||||||
mod log;
|
mod log;
|
||||||
mod plant_state;
|
mod plant_state;
|
||||||
mod tank;
|
mod tank;
|
||||||
|
mod webserver;
|
||||||
|
|
||||||
extern crate alloc;
|
pub static BOARD_ACCESS: Lazy<Mutex<HAL>> = Lazy::new(|| PlantHal::create().unwrap());
|
||||||
//mod webserver;
|
pub static STAY_ALIVE: Lazy<AtomicBool> = Lazy::new(|| AtomicBool::new(false));
|
||||||
|
|
||||||
pub static BOARD_ACCESS: LazyLock<Mutex<CriticalSectionRawMutex, HAL>> =
|
|
||||||
LazyLock::new(|| PlantHal::create().unwrap());
|
|
||||||
pub static STAY_ALIVE: AtomicBool = AtomicBool::new(false);
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||||
enum WaitType {
|
enum WaitType {
|
||||||
@ -61,11 +48,11 @@ struct Solar {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl WaitType {
|
impl WaitType {
|
||||||
fn blink_pattern(&self) -> u64 {
|
fn blink_pattern(&self) -> u32 {
|
||||||
match self {
|
match self {
|
||||||
WaitType::MissingConfig => 500_u64,
|
WaitType::MissingConfig => 500_u32,
|
||||||
WaitType::ConfigButton => 100_u64,
|
WaitType::ConfigButton => 100_u32,
|
||||||
WaitType::MqttConfig => 200_u64,
|
WaitType::MqttConfig => 200_u32,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -122,58 +109,68 @@ enum NetworkMode {
|
|||||||
OFFLINE,
|
OFFLINE,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn safe_main() -> anyhow::Result<()> {
|
fn safe_main() -> anyhow::Result<()> {
|
||||||
info!("Startup Rust");
|
// 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
|
||||||
|
esp_idf_svc::sys::link_patches();
|
||||||
|
|
||||||
|
// 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 < 25000 {
|
||||||
|
bail!(
|
||||||
|
"stack too small: {} bail!",
|
||||||
|
esp_idf_sys::CONFIG_MAIN_TASK_STACK_SIZE
|
||||||
|
)
|
||||||
|
}
|
||||||
|
println!("Startup Rust");
|
||||||
|
|
||||||
let mut to_config = false;
|
let mut to_config = false;
|
||||||
|
|
||||||
let version = get_version();
|
let version = get_version();
|
||||||
info!(
|
println!(
|
||||||
"Version using git has {} build on {}",
|
"Version using git has {} build on {}",
|
||||||
version.git_hash, version.build_time
|
version.git_hash, version.build_time
|
||||||
);
|
);
|
||||||
|
|
||||||
//TODO
|
let count = unsafe { esp_ota_get_app_partition_count() };
|
||||||
//let count = unsafe { esp_ota_get_app_partition_count() };
|
println!("Partition count is {}", count);
|
||||||
//log::info!("Partition count is {}", count);
|
let mut ota_state: esp_ota_img_states_t = 0;
|
||||||
//let mut ota_state: esp_ota_img_states_t = 0;
|
let running_partition = unsafe { esp_ota_get_running_partition() };
|
||||||
//let running_partition = unsafe { esp_ota_get_running_partition() };
|
let address = unsafe { (*running_partition).address };
|
||||||
//let partition_address = unsafe { (*running_partition).address };
|
println!("Partition address is {}", address);
|
||||||
//log::info!("Partition address is {}", address);
|
|
||||||
let partition_address = 0x1337;
|
|
||||||
|
|
||||||
// TODO
|
let ota_state_string = unsafe {
|
||||||
//let ota_state_string = unsafe {
|
esp_ota_get_state_partition(running_partition, &mut ota_state);
|
||||||
//esp_ota_get_state_partition(running_partition, &mut ota_state);
|
if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_NEW {
|
||||||
//if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_NEW {
|
"ESP_OTA_IMG_NEW"
|
||||||
//"ESP_OTA_IMG_NEW"
|
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY {
|
||||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY {
|
"ESP_OTA_IMG_PENDING_VERIFY"
|
||||||
//"ESP_OTA_IMG_PENDING_VERIFY"
|
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_VALID {
|
||||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_VALID {
|
"ESP_OTA_IMG_VALID"
|
||||||
//"ESP_OTA_IMG_VALID"
|
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_INVALID {
|
||||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_INVALID {
|
"ESP_OTA_IMG_INVALID"
|
||||||
//"ESP_OTA_IMG_INVALID"
|
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_ABORTED {
|
||||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_ABORTED {
|
"ESP_OTA_IMG_ABORTED"
|
||||||
//"ESP_OTA_IMG_ABORTED"
|
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED {
|
||||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED {
|
"ESP_OTA_IMG_UNDEFINED"
|
||||||
//"ESP_OTA_IMG_UNDEFINED"
|
} else {
|
||||||
//} else {
|
&format!("unknown {ota_state}")
|
||||||
//&format!("unknown {ota_state}")
|
}
|
||||||
//}
|
};
|
||||||
//};
|
log(LogMessage::PartitionState, 0, 0, "", ota_state_string);
|
||||||
//log(LogMessage::PartitionState, 0, 0, "", ota_state_string);
|
|
||||||
let ota_state_string = "unknown";
|
|
||||||
|
|
||||||
let mut board = BOARD_ACCESS.get().lock().await;
|
let mut board = BOARD_ACCESS
|
||||||
board.board_hal.general_fault(false).await;
|
.lock()
|
||||||
|
.expect("Could not lock board no other lock should be able to exist during startup!");
|
||||||
|
board.board_hal.general_fault(false);
|
||||||
|
|
||||||
let cur = board
|
let cur = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_rtc_module()
|
.get_rtc_module()
|
||||||
.get_rtc_time()
|
.get_rtc_time()
|
||||||
.await
|
|
||||||
.or_else(|err| {
|
.or_else(|err| {
|
||||||
info!("rtc module error: {:?}", err);
|
println!("rtc module error: {:?}", err);
|
||||||
board.board_hal.general_fault(true);
|
board.board_hal.general_fault(true);
|
||||||
board.board_hal.get_esp().time()
|
board.board_hal.get_esp().time()
|
||||||
})
|
})
|
||||||
@ -188,35 +185,35 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
log(LogMessage::YearInplausibleForceConfig, 0, 0, "", "");
|
log(LogMessage::YearInplausibleForceConfig, 0, 0, "", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("cur is {}", cur);
|
println!("cur is {}", cur);
|
||||||
update_charge_indicator().await;
|
update_charge_indicator(&mut board);
|
||||||
|
|
||||||
if board.board_hal.get_esp().get_restart_to_conf() {
|
if board.board_hal.get_esp().get_restart_to_conf() {
|
||||||
log(LogMessage::ConfigModeSoftwareOverride, 0, 0, "", "");
|
log(LogMessage::ConfigModeSoftwareOverride, 0, 0, "", "");
|
||||||
for _i in 0..2 {
|
for _i in 0..2 {
|
||||||
board.board_hal.general_fault(true).await;
|
board.board_hal.general_fault(true);
|
||||||
Timer::after_millis(100).await;
|
Delay::new_default().delay_ms(100);
|
||||||
board.board_hal.general_fault(false).await;
|
board.board_hal.general_fault(false);
|
||||||
Timer::after_millis(100).await;
|
Delay::new_default().delay_ms(100);
|
||||||
}
|
}
|
||||||
to_config = true;
|
to_config = true;
|
||||||
board.board_hal.general_fault(true).await;
|
board.board_hal.general_fault(true);
|
||||||
board.board_hal.get_esp().set_restart_to_conf(false);
|
board.board_hal.get_esp().set_restart_to_conf(false);
|
||||||
} else if board.board_hal.get_esp().mode_override_pressed() {
|
} else if board.board_hal.get_esp().mode_override_pressed() {
|
||||||
board.board_hal.general_fault(true).await;
|
board.board_hal.general_fault(true);
|
||||||
log(LogMessage::ConfigModeButtonOverride, 0, 0, "", "");
|
log(LogMessage::ConfigModeButtonOverride, 0, 0, "", "");
|
||||||
for _i in 0..5 {
|
for _i in 0..5 {
|
||||||
board.board_hal.general_fault(true).await;
|
board.board_hal.general_fault(true);
|
||||||
Timer::after_millis(100).await;
|
Delay::new_default().delay_ms(100);
|
||||||
board.board_hal.general_fault(false).await;
|
board.board_hal.general_fault(false);
|
||||||
Timer::after_millis(100).await;
|
Delay::new_default().delay_ms(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
if board.board_hal.get_esp().mode_override_pressed() {
|
if board.board_hal.get_esp().mode_override_pressed() {
|
||||||
board.board_hal.general_fault(true).await;
|
board.board_hal.general_fault(true);
|
||||||
to_config = true;
|
to_config = true;
|
||||||
} else {
|
} else {
|
||||||
board.board_hal.general_fault(false).await;
|
board.board_hal.general_fault(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -226,41 +223,40 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
let _ = board.board_hal.get_esp().wifi_ap();
|
let _ = board.board_hal.get_esp().wifi_ap();
|
||||||
drop(board);
|
drop(board);
|
||||||
let reboot_now = Arc::new(AtomicBool::new(false));
|
let reboot_now = Arc::new(AtomicBool::new(false));
|
||||||
//TODO
|
let _webserver = httpd(reboot_now.clone());
|
||||||
//let _webserver = httpd(reboot_now.clone());
|
wait_infinity(WaitType::MissingConfig, reboot_now.clone());
|
||||||
wait_infinity(WaitType::MissingConfig, reboot_now.clone()).await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("attempting to connect wifi");
|
println!("attempting to connect wifi");
|
||||||
let network_mode = if board.board_hal.get_config().network.ssid.is_some() {
|
let network_mode = if board.board_hal.get_config().network.ssid.is_some() {
|
||||||
try_connect_wifi_sntp_mqtt().await
|
try_connect_wifi_sntp_mqtt(&mut board)
|
||||||
} else {
|
} else {
|
||||||
info!("No wifi configured");
|
println!("No wifi configured");
|
||||||
//the current sensors require this amount to stabilize, in case of wifi this is already handles for sure;
|
//the current sensors require this amount to stabilize, in case of wifi this is already handles for sure;
|
||||||
Timer::after_millis(100).await;
|
board.board_hal.get_esp().delay.delay_ms(100);
|
||||||
NetworkMode::OFFLINE
|
NetworkMode::OFFLINE
|
||||||
};
|
};
|
||||||
|
|
||||||
if matches!(network_mode, NetworkMode::OFFLINE) && to_config {
|
if matches!(network_mode, NetworkMode::OFFLINE) && to_config {
|
||||||
info!("Could not connect to station and config mode forced, switching to ap mode!");
|
println!("Could not connect to station and config mode forced, switching to ap mode!");
|
||||||
match board.board_hal.get_esp().wifi_ap().await {
|
match board.board_hal.get_esp().wifi_ap() {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
info!("Started ap, continuing")
|
println!("Started ap, continuing")
|
||||||
}
|
}
|
||||||
Err(err) => info!("Could not start config override ap mode due to {}", err),
|
Err(err) => println!("Could not start config override ap mode due to {}", err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let timezone = match &board.board_hal.get_config().timezone {
|
let timezone = match &board.board_hal.get_config().timezone {
|
||||||
Some(tz_str) => tz_str.parse::<Tz>().unwrap_or_else(|_| {
|
Some(tz_str) => tz_str.parse::<Tz>().unwrap_or_else(|_| {
|
||||||
info!("Invalid timezone '{}', falling back to UTC", tz_str);
|
println!("Invalid timezone '{}', falling back to UTC", tz_str);
|
||||||
UTC
|
UTC
|
||||||
}),
|
}),
|
||||||
None => UTC, // Fallback to UTC if no timezone is set
|
None => UTC, // Fallback to UTC if no timezone is set
|
||||||
};
|
};
|
||||||
|
|
||||||
let timezone_time = cur.with_timezone(&timezone);
|
let timezone_time = cur.with_timezone(&timezone);
|
||||||
info!(
|
println!(
|
||||||
"Running logic at utc {} and {} {}",
|
"Running logic at utc {} and {} {}",
|
||||||
cur,
|
cur,
|
||||||
timezone.name(),
|
timezone.name(),
|
||||||
@ -270,14 +266,14 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
if let NetworkMode::WIFI { ref ip_address, .. } = network_mode {
|
if let NetworkMode::WIFI { ref ip_address, .. } = network_mode {
|
||||||
publish_firmware_info(
|
publish_firmware_info(
|
||||||
version,
|
version,
|
||||||
partition_address,
|
address,
|
||||||
ota_state_string,
|
ota_state_string,
|
||||||
|
&mut board,
|
||||||
ip_address,
|
ip_address,
|
||||||
timezone_time,
|
timezone_time,
|
||||||
)
|
);
|
||||||
.await;
|
publish_battery_state(&mut board);
|
||||||
publish_battery_state().await;
|
let _ = publish_mppt_state(&mut board);
|
||||||
let _ = publish_mppt_state().await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
log(
|
log(
|
||||||
@ -296,16 +292,14 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
"",
|
"",
|
||||||
);
|
);
|
||||||
|
|
||||||
drop(board);
|
|
||||||
|
|
||||||
if to_config {
|
if to_config {
|
||||||
//check if client or ap mode and init Wi-Fi
|
//check if client or ap mode and init Wi-Fi
|
||||||
info!("executing config mode override");
|
println!("executing config mode override");
|
||||||
//config upload will trigger reboot!
|
//config upload will trigger reboot!
|
||||||
|
drop(board);
|
||||||
let reboot_now = Arc::new(AtomicBool::new(false));
|
let reboot_now = Arc::new(AtomicBool::new(false));
|
||||||
//TODO
|
let _webserver = httpd(reboot_now.clone());
|
||||||
//let _webserver = httpd(reboot_now.clone());
|
wait_infinity(WaitType::ConfigButton, reboot_now.clone());
|
||||||
wait_infinity(WaitType::ConfigButton, reboot_now.clone()).await;
|
|
||||||
} else {
|
} else {
|
||||||
log(LogMessage::NormalRun, 0, 0, "", "");
|
log(LogMessage::NormalRun, 0, 0, "", "");
|
||||||
}
|
}
|
||||||
@ -352,7 +346,7 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
.board_hal
|
.board_hal
|
||||||
.get_tank_sensor()
|
.get_tank_sensor()
|
||||||
.context("no sensor")
|
.context("no sensor")
|
||||||
.and_then(async |f| f.water_temperature_c().await);
|
.and_then(|f| f.water_temperature_c());
|
||||||
|
|
||||||
if let Ok(res) = water_temp {
|
if let Ok(res) = water_temp {
|
||||||
if res < WATER_FROZEN_THRESH {
|
if res < WATER_FROZEN_THRESH {
|
||||||
@ -360,11 +354,11 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
publish_tank_state(&tank_state, &water_temp);
|
publish_tank_state(&mut board, &tank_state, &water_temp);
|
||||||
|
|
||||||
let plantstate: [PlantState; PLANT_COUNT] =
|
let plantstate: [PlantState; PLANT_COUNT] =
|
||||||
core::array::from_fn(|i| PlantState::read_hardware_state(i, &mut board).await);
|
core::array::from_fn(|i| PlantState::read_hardware_state(i, &mut board));
|
||||||
publish_plant_states(&timezone_time, &plantstate).await;
|
publish_plant_states(&mut board, &timezone_time, &plantstate);
|
||||||
|
|
||||||
let pump_required = plantstate
|
let pump_required = plantstate
|
||||||
.iter()
|
.iter()
|
||||||
@ -394,7 +388,7 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
&(plant_id + 1).to_string(),
|
&(plant_id + 1).to_string(),
|
||||||
"",
|
"",
|
||||||
);
|
);
|
||||||
board.board_hal.fault(plant_id, true).await?;
|
board.board_hal.fault(plant_id, true)?;
|
||||||
}
|
}
|
||||||
log(
|
log(
|
||||||
LogMessage::PumpPlant,
|
LogMessage::PumpPlant,
|
||||||
@ -410,11 +404,12 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
board.board_hal.get_esp().last_pump_time(plant_id);
|
board.board_hal.get_esp().last_pump_time(plant_id);
|
||||||
//state.active = true;
|
//state.active = true;
|
||||||
|
|
||||||
pump_info(plant_id, true, pump_ineffective, 0, 0, 0, false).await;
|
pump_info(&mut board, plant_id, true, pump_ineffective, 0, 0, 0, false);
|
||||||
|
|
||||||
let result = do_secure_pump(plant_id, plant_config, dry_run).await?;
|
let result = do_secure_pump(&mut board, plant_id, plant_config, dry_run)?;
|
||||||
board.board_hal.pump(plant_id, false).await?;
|
board.board_hal.pump(plant_id, false)?;
|
||||||
pump_info(
|
pump_info(
|
||||||
|
&mut board,
|
||||||
plant_id,
|
plant_id,
|
||||||
false,
|
false,
|
||||||
pump_ineffective,
|
pump_ineffective,
|
||||||
@ -422,8 +417,7 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
result.max_current_ma,
|
result.max_current_ma,
|
||||||
result.min_current_ma,
|
result.min_current_ma,
|
||||||
result.error,
|
result.error,
|
||||||
)
|
);
|
||||||
.await;
|
|
||||||
} else if !state.pump_in_timeout(plant_config, &timezone_time) {
|
} else if !state.pump_in_timeout(plant_config, &timezone_time) {
|
||||||
// plant does not need to be watered and is not in timeout
|
// plant does not need to be watered and is not in timeout
|
||||||
// -> reset consecutive pump count
|
// -> reset consecutive pump count
|
||||||
@ -440,7 +434,6 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
.board_hal
|
.board_hal
|
||||||
.get_battery_monitor()
|
.get_battery_monitor()
|
||||||
.state_charge_percent()
|
.state_charge_percent()
|
||||||
.await
|
|
||||||
.unwrap_or(0.);
|
.unwrap_or(0.);
|
||||||
|
|
||||||
// try to load full battery state if failed the battery state is unknown
|
// try to load full battery state if failed the battery state is unknown
|
||||||
@ -448,7 +441,6 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
.board_hal
|
.board_hal
|
||||||
.get_battery_monitor()
|
.get_battery_monitor()
|
||||||
.get_battery_state()
|
.get_battery_state()
|
||||||
.await
|
|
||||||
.unwrap_or(BatteryState::Unknown);
|
.unwrap_or(BatteryState::Unknown);
|
||||||
|
|
||||||
let mut light_state = LightState {
|
let mut light_state = LightState {
|
||||||
@ -514,7 +506,7 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
board.board_hal.light(false)?;
|
board.board_hal.light(false)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("Lightstate is {:?}", light_state);
|
println!("Lightstate is {:?}", light_state);
|
||||||
}
|
}
|
||||||
|
|
||||||
match serde_json::to_string(&light_state) {
|
match serde_json::to_string(&light_state) {
|
||||||
@ -522,11 +514,10 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/light", state.as_bytes())
|
.mqtt_publish("/light", state.as_bytes());
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
info!("Error publishing lightstate {}", err);
|
println!("Error publishing lightstate {}", err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -536,55 +527,52 @@ async fn safe_main() -> anyhow::Result<()> {
|
|||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/deepsleep", "low Volt 12h".as_bytes()).await;
|
.mqtt_publish("/deepsleep", "low Volt 12h".as_bytes());
|
||||||
12 * 60
|
12 * 60
|
||||||
} else if is_day {
|
} else if is_day {
|
||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/deepsleep", "normal 20m".as_bytes()).await;
|
.mqtt_publish("/deepsleep", "normal 20m".as_bytes());
|
||||||
20
|
20
|
||||||
} else {
|
} else {
|
||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/deepsleep", "night 1h".as_bytes()).await;
|
.mqtt_publish("/deepsleep", "night 1h".as_bytes());
|
||||||
60
|
60
|
||||||
};
|
};
|
||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/state", "sleep".as_bytes())
|
.mqtt_publish("/state", "sleep".as_bytes());
|
||||||
.await;
|
|
||||||
|
|
||||||
//determine next event
|
//determine next event
|
||||||
//is light out of work trigger soon?
|
//is light out of work trigger soon?
|
||||||
//is battery low ??
|
//is battery low ??
|
||||||
//is deep sleep
|
//is deep sleep
|
||||||
//TODO
|
mark_app_valid();
|
||||||
//mark_app_valid();
|
|
||||||
|
|
||||||
let stay_alive_mqtt = STAY_ALIVE.load(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;
|
||||||
info!("Check stay alive, current state is {}", stay_alive);
|
println!("Check stay alive, current state is {}", stay_alive);
|
||||||
|
|
||||||
if stay_alive {
|
if stay_alive {
|
||||||
info!("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));
|
||||||
//TODO
|
let _webserver = httpd(reboot_now.clone());
|
||||||
//let _webserver = httpd(reboot_now.clone());
|
wait_infinity(WaitType::MqttConfig, reboot_now.clone());
|
||||||
wait_infinity(WaitType::MqttConfig, reboot_now.clone()).await;
|
|
||||||
} else {
|
|
||||||
board.board_hal.get_esp().set_restart_to_conf(false);
|
|
||||||
board
|
|
||||||
.board_hal
|
|
||||||
.deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64);
|
|
||||||
}
|
}
|
||||||
|
board.board_hal.get_esp().set_restart_to_conf(false);
|
||||||
|
board
|
||||||
|
.board_hal
|
||||||
|
.deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn do_secure_pump(
|
pub fn do_secure_pump(
|
||||||
|
board: &mut MutexGuard<HAL>,
|
||||||
plant_id: usize,
|
plant_id: usize,
|
||||||
plant_config: &PlantConfig,
|
plant_config: &PlantConfig,
|
||||||
dry_run: bool,
|
dry_run: bool,
|
||||||
@ -594,7 +582,6 @@ pub async fn do_secure_pump(
|
|||||||
let mut error = false;
|
let mut error = false;
|
||||||
let mut first_error = true;
|
let mut first_error = true;
|
||||||
let mut pump_time_s = 0;
|
let mut pump_time_s = 0;
|
||||||
let board = &mut BOARD_ACCESS.get().lock().await;
|
|
||||||
if !dry_run {
|
if !dry_run {
|
||||||
board
|
board
|
||||||
.board_hal
|
.board_hal
|
||||||
@ -606,8 +593,8 @@ pub async fn do_secure_pump(
|
|||||||
.get_tank_sensor()
|
.get_tank_sensor()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.start_flow_meter();
|
.start_flow_meter();
|
||||||
board.board_hal.pump(plant_id, true).await?;
|
board.board_hal.pump(plant_id, true)?;
|
||||||
Timer::after_millis(10).await;
|
Delay::new_default().delay_ms(10);
|
||||||
for step in 0..plant_config.pump_time_s as usize {
|
for step in 0..plant_config.pump_time_s as usize {
|
||||||
let flow_value = board
|
let flow_value = board
|
||||||
.board_hal
|
.board_hal
|
||||||
@ -617,16 +604,16 @@ pub async fn do_secure_pump(
|
|||||||
flow_collector[step] = flow_value;
|
flow_collector[step] = flow_value;
|
||||||
let flow_value_ml = flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
|
let flow_value_ml = flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
|
||||||
|
|
||||||
info!(
|
println!(
|
||||||
"Flow value is {} ml, limit is {} ml raw sensor {}",
|
"Flow value is {} ml, limit is {} ml raw sensor {}",
|
||||||
flow_value_ml, plant_config.pump_limit_ml, flow_value
|
flow_value_ml, plant_config.pump_limit_ml, flow_value
|
||||||
);
|
);
|
||||||
if flow_value_ml > plant_config.pump_limit_ml as f32 {
|
if flow_value_ml > plant_config.pump_limit_ml as f32 {
|
||||||
info!("Flow value is reached, stopping");
|
println!("Flow value is reached, stopping");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
let current = board.board_hal.pump_current(plant_id).await;
|
let current = board.board_hal.pump_current(plant_id);
|
||||||
match current {
|
match current {
|
||||||
Ok(current) => {
|
Ok(current) => {
|
||||||
let current_ma = current.as_milliamperes() as u16;
|
let current_ma = current.as_milliamperes() as u16;
|
||||||
@ -641,8 +628,8 @@ pub async fn do_secure_pump(
|
|||||||
plant_config.max_pump_current_ma.to_string().as_str(),
|
plant_config.max_pump_current_ma.to_string().as_str(),
|
||||||
step.to_string().as_str(),
|
step.to_string().as_str(),
|
||||||
);
|
);
|
||||||
board.board_hal.general_fault(true).await;
|
board.board_hal.general_fault(true);
|
||||||
board.board_hal.fault(plant_id, true).await?;
|
board.board_hal.fault(plant_id, true)?;
|
||||||
if !plant_config.ignore_current_error {
|
if !plant_config.ignore_current_error {
|
||||||
error = true;
|
error = true;
|
||||||
break;
|
break;
|
||||||
@ -660,8 +647,8 @@ pub async fn do_secure_pump(
|
|||||||
plant_config.min_pump_current_ma.to_string().as_str(),
|
plant_config.min_pump_current_ma.to_string().as_str(),
|
||||||
step.to_string().as_str(),
|
step.to_string().as_str(),
|
||||||
);
|
);
|
||||||
board.board_hal.general_fault(true).await;
|
board.board_hal.general_fault(true);
|
||||||
board.board_hal.fault(plant_id, true).await?;
|
board.board_hal.fault(plant_id, true)?;
|
||||||
if !plant_config.ignore_current_error {
|
if !plant_config.ignore_current_error {
|
||||||
error = true;
|
error = true;
|
||||||
break;
|
break;
|
||||||
@ -672,7 +659,7 @@ pub async fn do_secure_pump(
|
|||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if !plant_config.ignore_current_error {
|
if !plant_config.ignore_current_error {
|
||||||
info!("Error getting pump current: {}", err);
|
println!("Error getting pump current: {}", err);
|
||||||
log(
|
log(
|
||||||
LogMessage::PumpMissingSensorCurrent,
|
LogMessage::PumpMissingSensorCurrent,
|
||||||
plant_id as u32,
|
plant_id as u32,
|
||||||
@ -687,7 +674,7 @@ pub async fn do_secure_pump(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Timer::after_millis(1000).await;
|
Delay::new_default().delay_ms(1000);
|
||||||
pump_time_s += 1;
|
pump_time_s += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -698,7 +685,7 @@ pub async fn do_secure_pump(
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
.get_flow_meter_value();
|
.get_flow_meter_value();
|
||||||
let flow_value_ml = final_flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
|
let flow_value_ml = final_flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
|
||||||
info!(
|
println!(
|
||||||
"Final flow value is {} with {} ml",
|
"Final flow value is {} with {} ml",
|
||||||
final_flow_value, flow_value_ml
|
final_flow_value, flow_value_ml
|
||||||
);
|
);
|
||||||
@ -714,10 +701,9 @@ pub async fn do_secure_pump(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn update_charge_indicator() {
|
fn update_charge_indicator(board: &mut MutexGuard<HAL>) {
|
||||||
let board = BOARD_ACCESS.get().lock().await;
|
|
||||||
//we have mppt controller, ask it for charging current
|
//we have mppt controller, ask it for charging current
|
||||||
if let Ok(current) = board.board_hal.get_mptt_current().await {
|
if let Ok(current) = board.board_hal.get_mptt_current() {
|
||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.set_charge_indicator(current.as_milliamperes() > 20_f64);
|
.set_charge_indicator(current.as_milliamperes() > 20_f64);
|
||||||
@ -735,8 +721,11 @@ async fn update_charge_indicator() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn publish_tank_state(tank_state: &TankState, water_temp: &anyhow::Result<f32>) {
|
fn publish_tank_state(
|
||||||
let board = &mut BOARD_ACCESS.get().lock().await;
|
board: &mut MutexGuard<HAL>,
|
||||||
|
tank_state: &TankState,
|
||||||
|
water_temp: &anyhow::Result<f32>,
|
||||||
|
) {
|
||||||
match serde_json::to_string(
|
match serde_json::to_string(
|
||||||
&tank_state.as_mqtt_info(&board.board_hal.get_config().tank, water_temp),
|
&tank_state.as_mqtt_info(&board.board_hal.get_config().tank, water_temp),
|
||||||
) {
|
) {
|
||||||
@ -747,13 +736,16 @@ async fn publish_tank_state(tank_state: &TankState, water_temp: &anyhow::Result<
|
|||||||
.mqtt_publish("/water", state.as_bytes());
|
.mqtt_publish("/water", state.as_bytes());
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
info!("Error publishing tankstate {}", err);
|
println!("Error publishing tankstate {}", err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn publish_plant_states(timezone_time: &DateTime<Tz>, plantstate: &[PlantState; 8]) {
|
fn publish_plant_states(
|
||||||
let board = &mut BOARD_ACCESS.get().lock().await;
|
board: &mut MutexGuard<HAL>,
|
||||||
|
timezone_time: &DateTime<Tz>,
|
||||||
|
plantstate: &[PlantState; 8],
|
||||||
|
) {
|
||||||
for (plant_id, (plant_state, plant_conf)) in plantstate
|
for (plant_id, (plant_state, plant_conf)) in plantstate
|
||||||
.iter()
|
.iter()
|
||||||
.zip(&board.board_hal.get_config().plants.clone())
|
.zip(&board.board_hal.get_config().plants.clone())
|
||||||
@ -765,41 +757,37 @@ async fn publish_plant_states(timezone_time: &DateTime<Tz>, plantstate: &[PlantS
|
|||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish(&plant_topic, state.as_bytes())
|
.mqtt_publish(&plant_topic, state.as_bytes());
|
||||||
.await;
|
//reduce speed as else messages will be dropped
|
||||||
//TODO? reduce speed as else messages will be dropped
|
board.board_hal.get_esp().delay.delay_ms(200);
|
||||||
Timer::after_millis(200).await
|
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("Error publishing plant state {}", err);
|
println!("Error publishing plant state {}", err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn publish_firmware_info(
|
fn publish_firmware_info(
|
||||||
version: VersionInfo,
|
version: VersionInfo,
|
||||||
address: u32,
|
address: u32,
|
||||||
ota_state_string: &str,
|
ota_state_string: &str,
|
||||||
|
board: &mut MutexGuard<HAL>,
|
||||||
ip_address: &String,
|
ip_address: &String,
|
||||||
timezone_time: DateTime<Tz>,
|
timezone_time: DateTime<Tz>,
|
||||||
) {
|
) {
|
||||||
let board = &mut BOARD_ACCESS.get().lock().await;
|
|
||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/firmware/address", ip_address.as_bytes())
|
.mqtt_publish("/firmware/address", ip_address.as_bytes());
|
||||||
.await;
|
|
||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/firmware/githash", version.git_hash.as_bytes())
|
.mqtt_publish("/firmware/githash", version.git_hash.as_bytes());
|
||||||
.await;
|
|
||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/firmware/buildtime", version.build_time.as_bytes())
|
.mqtt_publish("/firmware/buildtime", version.build_time.as_bytes());
|
||||||
.await;
|
|
||||||
let _ = board.board_hal.get_esp().mqtt_publish(
|
let _ = board.board_hal.get_esp().mqtt_publish(
|
||||||
"/firmware/last_online",
|
"/firmware/last_online",
|
||||||
timezone_time.to_rfc3339().as_bytes(),
|
timezone_time.to_rfc3339().as_bytes(),
|
||||||
@ -807,8 +795,7 @@ async fn publish_firmware_info(
|
|||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/firmware/ota_state", ota_state_string.as_bytes())
|
.mqtt_publish("/firmware/ota_state", ota_state_string.as_bytes());
|
||||||
.await;
|
|
||||||
let _ = board.board_hal.get_esp().mqtt_publish(
|
let _ = board.board_hal.get_esp().mqtt_publish(
|
||||||
"/firmware/partition_address",
|
"/firmware/partition_address",
|
||||||
format!("{:#06x}", address).as_bytes(),
|
format!("{:#06x}", address).as_bytes(),
|
||||||
@ -816,36 +803,34 @@ async fn publish_firmware_info(
|
|||||||
let _ = board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/state", "online".as_bytes())
|
.mqtt_publish("/state", "online".as_bytes());
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn try_connect_wifi_sntp_mqtt() -> NetworkMode {
|
fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode {
|
||||||
let board = BOARD_ACCESS.get().lock().await;
|
|
||||||
let nw_conf = &board.board_hal.get_config().network.clone();
|
let nw_conf = &board.board_hal.get_config().network.clone();
|
||||||
match board.board_hal.get_esp().wifi(nw_conf).await {
|
match board.board_hal.get_esp().wifi(nw_conf) {
|
||||||
Ok(ip_info) => {
|
Ok(ip_info) => {
|
||||||
let sntp_mode: SntpMode = match board.board_hal.get_esp().sntp(1000 * 10).await {
|
let sntp_mode: SntpMode = match board.board_hal.get_esp().sntp(1000 * 10) {
|
||||||
Ok(new_time) => {
|
Ok(new_time) => {
|
||||||
info!("Using time from sntp");
|
println!("Using time from sntp");
|
||||||
let _ = board.board_hal.get_rtc_module().set_rtc_time(&new_time);
|
let _ = board.board_hal.get_rtc_module().set_rtc_time(&new_time);
|
||||||
SntpMode::SYNC { current: new_time }
|
SntpMode::SYNC { current: new_time }
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("sntp error: {}", err);
|
println!("sntp error: {}", err);
|
||||||
board.board_hal.general_fault(true).await;
|
board.board_hal.general_fault(true);
|
||||||
SntpMode::OFFLINE
|
SntpMode::OFFLINE
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let mqtt_connected = if board.board_hal.get_config().network.mqtt_url.is_some() {
|
let mqtt_connected = if board.board_hal.get_config().network.mqtt_url.is_some() {
|
||||||
let nw_config = &board.board_hal.get_config().network.clone();
|
let nw_config = &board.board_hal.get_config().network.clone();
|
||||||
match board.board_hal.get_esp().mqtt(nw_config).await {
|
match board.board_hal.get_esp().mqtt(nw_config) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
info!("Mqtt connection ready");
|
println!("Mqtt connection ready");
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("Could not connect mqtt due to {}", err);
|
println!("Could not connect mqtt due to {}", err);
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -859,14 +844,15 @@ async fn try_connect_wifi_sntp_mqtt() -> NetworkMode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
info!("Offline mode");
|
println!("Offline mode");
|
||||||
board.board_hal.general_fault(true);
|
board.board_hal.general_fault(true);
|
||||||
NetworkMode::OFFLINE
|
NetworkMode::OFFLINE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn pump_info(
|
fn pump_info(
|
||||||
|
board: &mut MutexGuard<HAL>,
|
||||||
plant_id: usize,
|
plant_id: usize,
|
||||||
pump_active: bool,
|
pump_active: bool,
|
||||||
pump_ineffective: bool,
|
pump_ineffective: bool,
|
||||||
@ -883,30 +869,24 @@ async fn pump_info(
|
|||||||
min_current_ma: min_current_ma,
|
min_current_ma: min_current_ma,
|
||||||
};
|
};
|
||||||
let pump_topic = format!("/pump{}", plant_id + 1);
|
let pump_topic = format!("/pump{}", plant_id + 1);
|
||||||
|
|
||||||
match serde_json::to_string(&pump_info) {
|
match serde_json::to_string(&pump_info) {
|
||||||
Ok(state) => {
|
Ok(state) => {
|
||||||
let _ = BOARD_ACCESS
|
let _ = board
|
||||||
.get()
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish(&pump_topic, state.as_bytes());
|
.mqtt_publish(&pump_topic, state.as_bytes());
|
||||||
//reduce speed as else messages will be dropped
|
//reduce speed as else messages will be dropped
|
||||||
//TODO maybee not required for low level hal?
|
Delay::new_default().delay_ms(200);
|
||||||
Timer::after_millis(200).await;
|
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("Error publishing pump state {}", err);
|
println!("Error publishing pump state {}", err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn publish_mppt_state() -> anyhow::Result<()> {
|
fn publish_mppt_state(board: &mut MutexGuard<'_, HAL<'_>>) -> anyhow::Result<()> {
|
||||||
let board_hal = &mut BOARD_ACCESS.get().lock().await.board_hal;
|
let current = board.board_hal.get_mptt_current()?;
|
||||||
let current = board_hal.get_mptt_current().await?;
|
let voltage = board.board_hal.get_mptt_voltage()?;
|
||||||
let voltage = board_hal.get_mptt_voltage().await?;
|
|
||||||
let solar_state = Solar {
|
let solar_state = Solar {
|
||||||
current_ma: current.as_milliamperes() as u32,
|
current_ma: current.as_milliamperes() as u32,
|
||||||
voltage_ma: voltage.as_millivolts() as u32,
|
voltage_ma: voltage.as_millivolts() as u32,
|
||||||
@ -914,33 +894,35 @@ async fn publish_mppt_state() -> anyhow::Result<()> {
|
|||||||
if let Ok(serialized_solar_state_bytes) =
|
if let Ok(serialized_solar_state_bytes) =
|
||||||
serde_json::to_string(&solar_state).map(|s| s.into_bytes())
|
serde_json::to_string(&solar_state).map(|s| s.into_bytes())
|
||||||
{
|
{
|
||||||
let _ = board_hal
|
let _ = board
|
||||||
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/mppt", &serialized_solar_state_bytes);
|
.mqtt_publish("/mppt", &serialized_solar_state_bytes);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn publish_battery_state() -> () {
|
fn publish_battery_state(board: &mut MutexGuard<'_, HAL<'_>>) {
|
||||||
let board = BOARD_ACCESS.get().lock().await;
|
|
||||||
let state = board.board_hal.get_battery_monitor().get_battery_state();
|
let state = board.board_hal.get_battery_monitor().get_battery_state();
|
||||||
if let Ok(serialized_battery_state_bytes) =
|
if let Ok(serialized_battery_state_bytes) =
|
||||||
serde_json::to_string(&state).map(|s| s.into_bytes())
|
serde_json::to_string(&state).map(|s| s.into_bytes())
|
||||||
{
|
{
|
||||||
board
|
let _ = board
|
||||||
.board_hal
|
.board_hal
|
||||||
.get_esp()
|
.get_esp()
|
||||||
.mqtt_publish("/battery", &serialized_battery_state_bytes);
|
.mqtt_publish("/battery", &serialized_battery_state_bytes);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
||||||
let delay = wait_type.blink_pattern();
|
let delay = wait_type.blink_pattern();
|
||||||
let mut led_count = 8;
|
let mut led_count = 8;
|
||||||
let mut pattern_step = 0;
|
let mut pattern_step = 0;
|
||||||
|
let delay_handle = Delay::new_default();
|
||||||
loop {
|
loop {
|
||||||
update_charge_indicator().await;
|
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||||
let mut board = BOARD_ACCESS.get().lock().await;
|
update_charge_indicator(&mut board);
|
||||||
|
|
||||||
match wait_type {
|
match wait_type {
|
||||||
WaitType::MissingConfig => {
|
WaitType::MissingConfig => {
|
||||||
// Keep existing behavior: circular filling pattern
|
// Keep existing behavior: circular filling pattern
|
||||||
@ -968,9 +950,9 @@ async fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
|||||||
|
|
||||||
board.board_hal.general_fault(true);
|
board.board_hal.general_fault(true);
|
||||||
drop(board);
|
drop(board);
|
||||||
|
//cannot use shared delay as that is inside the mutex here
|
||||||
Timer::after_millis(delay).await;
|
delay_handle.delay_ms(delay);
|
||||||
let mut board = BOARD_ACCESS.get().lock().await;
|
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||||
board.board_hal.general_fault(false);
|
board.board_hal.general_fault(false);
|
||||||
|
|
||||||
// Clear all LEDs
|
// Clear all LEDs
|
||||||
@ -978,50 +960,41 @@ async fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
|||||||
let _ = board.board_hal.fault(i, false);
|
let _ = board.board_hal.fault(i, false);
|
||||||
}
|
}
|
||||||
drop(board);
|
drop(board);
|
||||||
Timer::after_millis(delay).await;
|
delay_handle.delay_ms(delay);
|
||||||
|
|
||||||
if wait_type == WaitType::MqttConfig && !STAY_ALIVE.load(Ordering::Relaxed) {
|
if wait_type == WaitType::MqttConfig
|
||||||
reboot_now.store(true, Ordering::Relaxed);
|
&& !STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed)
|
||||||
|
{
|
||||||
|
reboot_now.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
if reboot_now.load(Ordering::Relaxed) {
|
if reboot_now.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
//ensure clean http answer
|
//ensure clean http answer
|
||||||
Timer::after_millis(500).await;
|
Delay::new_default().delay_ms(500);
|
||||||
BOARD_ACCESS.get().lock().await.board_hal.deep_sleep(1);
|
BOARD_ACCESS.lock().unwrap().board_hal.deep_sleep(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[esp_hal_embassy::main]
|
fn main() {
|
||||||
async fn main(spawner: Spawner) {
|
let result = safe_main();
|
||||||
// intialize embassy
|
|
||||||
logger::init_logger_from_env();
|
|
||||||
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
|
|
||||||
let peripherals = esp_hal::init(config);
|
|
||||||
|
|
||||||
esp_alloc::heap_allocator!(size: 64 * 1024);
|
|
||||||
|
|
||||||
let timer0 = SystemTimer::new(peripherals.SYSTIMER);
|
|
||||||
esp_hal_embassy::init(timer0.alarm0);
|
|
||||||
|
|
||||||
info!("Embassy initialized!");
|
|
||||||
|
|
||||||
let result = safe_main().await;
|
|
||||||
match result {
|
match result {
|
||||||
// this should not get triggered, safe_main should not return but go into deep sleep with sensible
|
// this should not get triggered, safe_main should not return but go into deep sleep with sensible
|
||||||
// timeout, this is just a fallback
|
// timeout, this is just a fallback
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
warn!("Main app finished, but should never do, restarting");
|
println!("Main app finished, restarting");
|
||||||
let board = &mut BOARD_ACCESS.get().lock().await.board_hal;
|
BOARD_ACCESS
|
||||||
|
.lock()
|
||||||
board.get_esp().set_restart_to_conf(false);
|
.unwrap()
|
||||||
board.deep_sleep(1);
|
.board_hal
|
||||||
|
.get_esp()
|
||||||
|
.set_restart_to_conf(false);
|
||||||
|
BOARD_ACCESS.lock().unwrap().board_hal.deep_sleep(1);
|
||||||
}
|
}
|
||||||
// if safe_main exists with an error, rollback to a known good ota version
|
// if safe_main exists with an error, rollback to a known good ota version
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("Failed main {}", err);
|
println!("Failed main {}", err);
|
||||||
//TODO
|
let _rollback_successful = rollback_and_reboot();
|
||||||
//let _rollback_successful = rollback_and_reboot();
|
panic!("Failed to rollback :(");
|
||||||
//panic!("Failed to rollback :(");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1041,10 +1014,8 @@ fn get_version() -> VersionInfo {
|
|||||||
let branch = env!("VERGEN_GIT_BRANCH").to_owned();
|
let branch = env!("VERGEN_GIT_BRANCH").to_owned();
|
||||||
let hash = &env!("VERGEN_GIT_SHA")[0..8];
|
let hash = &env!("VERGEN_GIT_SHA")[0..8];
|
||||||
|
|
||||||
//TODO
|
let running_partition = unsafe { esp_ota_get_running_partition() };
|
||||||
//let running_partition = unsafe { esp_ota_get_running_partition() };
|
let address = unsafe { (*running_partition).address };
|
||||||
let address = 0;
|
|
||||||
//let address = unsafe { (*running_partition).address };
|
|
||||||
let partition = if address > 100000 {
|
let partition = if address > 100000 {
|
||||||
"ota_1 @ "
|
"ota_1 @ "
|
||||||
} else {
|
} else {
|
||||||
|
@ -3,7 +3,6 @@ use crate::{
|
|||||||
hal::{Sensor, HAL},
|
hal::{Sensor, HAL},
|
||||||
in_time_range,
|
in_time_range,
|
||||||
};
|
};
|
||||||
use alloc::string::String;
|
|
||||||
use chrono::{DateTime, TimeDelta, Utc};
|
use chrono::{DateTime, TimeDelta, Utc};
|
||||||
use chrono_tz::Tz;
|
use chrono_tz::Tz;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@ -116,7 +115,7 @@ fn map_range_moisture(
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PlantState {
|
impl PlantState {
|
||||||
pub async fn read_hardware_state(plant_id: usize, board: &mut HAL<'_>) -> Self {
|
pub fn read_hardware_state(plant_id: usize, board: &mut HAL) -> Self {
|
||||||
let sensor_a = if board.board_hal.get_config().plants[plant_id].sensor_a {
|
let sensor_a = if board.board_hal.get_config().plants[plant_id].sensor_a {
|
||||||
match board.board_hal.measure_moisture_hz(plant_id, Sensor::A) {
|
match board.board_hal.measure_moisture_hz(plant_id, Sensor::A) {
|
||||||
Ok(raw) => match map_range_moisture(
|
Ok(raw) => match map_range_moisture(
|
||||||
|
@ -2,9 +2,7 @@
|
|||||||
|
|
||||||
use core::cell::RefCell;
|
use core::cell::RefCell;
|
||||||
use core::mem::{self, MaybeUninit};
|
use core::mem::{self, MaybeUninit};
|
||||||
use core::convert::Infallible;
|
use std::convert::Infallible;
|
||||||
use core::result::{Result, Result::Ok};
|
|
||||||
use core::iter::Iterator;
|
|
||||||
|
|
||||||
use hal::digital::OutputPin;
|
use hal::digital::OutputPin;
|
||||||
|
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
use crate::{config::TankConfig, hal::HAL};
|
use crate::{config::TankConfig, hal::HAL};
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use crate::alloc::string::{String, ToString};
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
const OPEN_TANK_VOLTAGE: f32 = 3.0;
|
const OPEN_TANK_VOLTAGE: f32 = 3.0;
|
||||||
|
@ -187,7 +187,7 @@ fn get_backup_config(
|
|||||||
let json = match board.board_hal.get_rtc_module().get_backup_config() {
|
let json = match board.board_hal.get_rtc_module().get_backup_config() {
|
||||||
Ok(config) => from_utf8(&config)?.to_owned(),
|
Ok(config) => from_utf8(&config)?.to_owned(),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::info!("Error get backup config {:?}", err);
|
println!("Error get backup config {:?}", err);
|
||||||
err.to_string()
|
err.to_string()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -318,7 +318,7 @@ fn wifi_scan(
|
|||||||
let mut ssids: Vec<&String<32>> = Vec::new();
|
let mut ssids: Vec<&String<32>> = Vec::new();
|
||||||
scan_result.iter().for_each(|s| ssids.push(&s.ssid));
|
scan_result.iter().for_each(|s| ssids.push(&s.ssid));
|
||||||
let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
|
let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
|
||||||
log::info!("Sending ssid list {}", &ssid_json);
|
println!("Sending ssid list {}", &ssid_json);
|
||||||
anyhow::Ok(Some(ssid_json))
|
anyhow::Ok(Some(ssid_json))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -338,7 +338,7 @@ fn ota(
|
|||||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||||
let mut ota = OtaUpdate::begin()?;
|
let mut ota = OtaUpdate::begin()?;
|
||||||
log::info!("start ota");
|
println!("start ota");
|
||||||
|
|
||||||
//having a larger buffer is not really faster, requires more stack and prevents the progress bar from working ;)
|
//having a larger buffer is not really faster, requires more stack and prevents the progress bar from working ;)
|
||||||
const BUFFER_SIZE: usize = 512;
|
const BUFFER_SIZE: usize = 512;
|
||||||
@ -366,13 +366,13 @@ fn ota(
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log::info!("wrote bytes ota {total_read}");
|
println!("wrote bytes ota {total_read}");
|
||||||
log::info!("finish ota");
|
println!("finish ota");
|
||||||
let partition = ota.raw_partition();
|
let partition = ota.raw_partition();
|
||||||
log::info!("finalizing and changing boot partition to {partition:?}");
|
println!("finalizing and changing boot partition to {partition:?}");
|
||||||
|
|
||||||
let mut finalizer = ota.finalize()?;
|
let mut finalizer = ota.finalize()?;
|
||||||
log::info!("changing boot partition");
|
println!("changing boot partition");
|
||||||
board.board_hal.get_esp().set_restart_to_conf(true);
|
board.board_hal.get_esp().set_restart_to_conf(true);
|
||||||
drop(board);
|
drop(board);
|
||||||
finalizer.set_as_boot_partition()?;
|
finalizer.set_as_boot_partition()?;
|
||||||
@ -380,7 +380,7 @@ fn ota(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn query_param(uri: &str, param_name: &str) -> Option<std::string::String> {
|
fn query_param(uri: &str, param_name: &str) -> Option<std::string::String> {
|
||||||
log::info!("{uri} get {param_name}");
|
println!("{uri} get {param_name}");
|
||||||
let parsed = Url::parse(&format!("http://127.0.0.1/{uri}")).unwrap();
|
let parsed = Url::parse(&format!("http://127.0.0.1/{uri}")).unwrap();
|
||||||
let value = parsed.query_pairs().find(|it| it.0 == param_name);
|
let value = parsed.query_pairs().find(|it| it.0 == param_name);
|
||||||
match value {
|
match value {
|
||||||
@ -551,14 +551,14 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log::info!("wrote {total_read} for file {filename}");
|
println!("wrote {total_read} for file {filename}");
|
||||||
drop(file_handle);
|
drop(file_handle);
|
||||||
response.flush()?;
|
response.flush()?;
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
//todo set headers here for filename to be error
|
//todo set headers here for filename to be error
|
||||||
let error_text = err.to_string();
|
let error_text = err.to_string();
|
||||||
log::info!("error handling get file {}", error_text);
|
println!("error handling get file {}", error_text);
|
||||||
cors_response(request, 500, &error_text)?;
|
cors_response(request, 500, &error_text)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -599,7 +599,7 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
|
|||||||
Err(err) => {
|
Err(err) => {
|
||||||
//todo set headers here for filename to be error
|
//todo set headers here for filename to be error
|
||||||
let error_text = err.to_string();
|
let error_text = err.to_string();
|
||||||
log::info!("error handling get file {}", error_text);
|
println!("error handling get file {}", error_text);
|
||||||
cors_response(request, 500, &error_text)?;
|
cors_response(request, 500, &error_text)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -697,7 +697,7 @@ fn handle_error_to500(
|
|||||||
},
|
},
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let error_text = err.to_string();
|
let error_text = err.to_string();
|
||||||
log::info!("error handling process {}", error_text);
|
println!("error handling process {}", error_text);
|
||||||
cors_response(request, 500, &error_text)?;
|
cors_response(request, 500, &error_text)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -725,6 +725,6 @@ fn read_up_to_bytes_from_request(
|
|||||||
data_store.push(actual_data.to_owned());
|
data_store.push(actual_data.to_owned());
|
||||||
}
|
}
|
||||||
let allvec = data_store.concat();
|
let allvec = data_store.concat();
|
||||||
log::info!("Raw data {}", from_utf8(&allvec)?);
|
println!("Raw data {}", from_utf8(&allvec)?);
|
||||||
Ok(allvec)
|
Ok(allvec)
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user