Compare commits
No commits in common. "goodby-espidf" and "develop" have entirely different histories.
goodby-esp
...
develop
@ -1,28 +1,26 @@
|
||||
[build]
|
||||
rustflags = [
|
||||
# Required to obtain backtraces (e.g. when using the "esp-backtrace" crate.)
|
||||
# NOTE: May negatively impact performance of produced code
|
||||
"-C", "force-frame-pointers",
|
||||
"-Z", "stack-protector=all",
|
||||
]
|
||||
#target = "xtensa-esp32-espidf"
|
||||
target = "riscv32imac-esp-espidf"
|
||||
|
||||
target = "riscv32imac-unknown-none-elf"
|
||||
|
||||
[target.riscv32imac-unknown-none-elf]
|
||||
runner = "espflash flash --monitor --chip esp32c6"
|
||||
[target.riscv32imac-esp-espidf]
|
||||
linker = "ldproxy"
|
||||
#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 = "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
|
||||
|
||||
[env]
|
||||
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"
|
||||
rustflags = ["--cfg", "espidf_time64"] # Extending time_t for ESP IDF 5: https://github.com/esp-rs/rust/issues/110
|
||||
|
||||
[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"
|
100
rust/Cargo.toml
100
rust/Cargo.toml
@ -44,103 +44,59 @@ command = [
|
||||
[package.metadata.espflash]
|
||||
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]
|
||||
#ESP stuff
|
||||
esp-bootloader-esp-idf = { version = "0.2.0", features = ["esp32c6"] }
|
||||
esp-hal = { version = "=1.0.0-rc.0", features = [
|
||||
"esp32c6",
|
||||
"log-04",
|
||||
"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-svc = { version = "0.28.1", features = ["experimental"] }
|
||||
esp-idf-hal = "0.45.2"
|
||||
esp-idf-sys = { version = "0.36.1", features = ["binstart", "native"] }
|
||||
esp-idf-svc = { version = "0.51.0", default-features = false }
|
||||
embedded-hal = "1.0.0"
|
||||
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
|
||||
#ds18b20 = "0.1.1"
|
||||
#bq34z100 = { version = "0.3.0", default-features = false }
|
||||
ds18b20 = "0.1.1"
|
||||
bq34z100 = { version = "0.3.0", features = ["flashstream"] }
|
||||
one-wire-bus = "0.1.1"
|
||||
ds323x = "0.6.0"
|
||||
|
||||
#pure code dependencies
|
||||
#once_cell = "1.19.0"
|
||||
anyhow = { version = "1.0.75", default-features = false }
|
||||
#strum = { version = "0.27.0", default-feature = false, features = ["derive"] }
|
||||
once_cell = "1.19.0"
|
||||
anyhow = { version = "1.0.75", features = ["std", "backtrace"] }
|
||||
strum = { version = "0.27.0", features = ["derive"] }
|
||||
measurements = "0.11.0"
|
||||
|
||||
#json
|
||||
serde = { version = "1.0.219", features = ["derive", "alloc"], default-features = false }
|
||||
serde_json = { version = "1.0.143", default-features = false, features = ["alloc"] }
|
||||
serde = { version = "1.0.192", features = ["derive"] }
|
||||
serde_json = "1.0.108"
|
||||
|
||||
#timezone
|
||||
|
||||
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"] }
|
||||
eeprom24x = "0.7.2"
|
||||
#url = "2.5.3"
|
||||
url = "2.5.3"
|
||||
crc = "3.2.1"
|
||||
bincode = {version = "2.0.1", default-features = false, features = ["alloc", "serde"] }
|
||||
bincode = "2.0.1"
|
||||
ringbuffer = "0.15.0"
|
||||
#text-template = "0.1.0"
|
||||
text-template = "0.1.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"
|
||||
pca9535 = { version = "2.0.0" }
|
||||
ina219 = { version = "0.2.0" }
|
||||
pca9535 = { version = "2.0.0", features = ["std"] }
|
||||
ina219 = { version = "0.2.0", features = ["std"] }
|
||||
embedded-storage = "=0.3.1"
|
||||
ekv = "1.0.0"
|
||||
embedded-can = "0.4.1"
|
||||
critical-section = "1.2.0"
|
||||
portable-atomic = "1.11.1"
|
||||
embassy-sync = { version = "0.7.2", features = ["log"] }
|
||||
|
||||
|
||||
[patch.crates-io]
|
||||
@ -152,4 +108,6 @@ embassy-sync = { version = "0.7.2", features = ["log"] }
|
||||
#bq34z100 = { path = "../../bq34z100_rust" }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "=1.1.30"
|
||||
embuild = { version = "0.32.0", features = ["espidf"] }
|
||||
vergen = { version = "8.2.6", features = ["build", "git", "gitcl"] }
|
||||
|
@ -1,54 +1,6 @@
|
||||
use std::process::Command;
|
||||
|
||||
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() {
|
||||
println!("cargo:rerun-if-changed=./src/src_webpack");
|
||||
Command::new("rm")
|
||||
@ -112,6 +64,7 @@ fn main() {
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
linker_be_nice();
|
||||
|
||||
embuild::espidf::sysenv::output();
|
||||
let _ = EmitBuilder::builder().all_git().all_build().emit();
|
||||
}
|
||||
|
@ -158,56 +158,56 @@ impl BatteryInteraction for BQ34Z100G1<'_> {
|
||||
pub fn print_battery_bq34z100(
|
||||
battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
|
||||
) -> 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| {
|
||||
log::info!("Firmware {:?}", e);
|
||||
println!("Firmware {:?}", e);
|
||||
0
|
||||
});
|
||||
log::info!("fw version is {}", fwversion);
|
||||
println!("fw version is {}", fwversion);
|
||||
|
||||
let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
|
||||
log::info!("Design capacity {:?}", e);
|
||||
println!("Design capacity {:?}", e);
|
||||
0
|
||||
});
|
||||
log::info!("Design Capacity {}", design_capacity);
|
||||
println!("Design Capacity {}", design_capacity);
|
||||
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()?;
|
||||
log::info!("Flags {:?}", flags);
|
||||
println!("Flags {:?}", flags);
|
||||
|
||||
let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
|
||||
log::info!("Chemid {:?}", e);
|
||||
println!("Chemid {:?}", e);
|
||||
0
|
||||
});
|
||||
|
||||
let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
|
||||
log::info!("Bat Temp {:?}", e);
|
||||
println!("Bat Temp {:?}", e);
|
||||
0
|
||||
});
|
||||
let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
|
||||
let voltage = battery_driver.voltage().unwrap_or_else(|e| {
|
||||
log::info!("Bat volt {:?}", e);
|
||||
println!("Bat volt {:?}", e);
|
||||
0
|
||||
});
|
||||
let current = battery_driver.current().unwrap_or_else(|e| {
|
||||
log::info!("Bat current {:?}", e);
|
||||
println!("Bat current {:?}", e);
|
||||
0
|
||||
});
|
||||
let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
|
||||
log::info!("Bat Soc {:?}", e);
|
||||
println!("Bat Soc {:?}", e);
|
||||
0
|
||||
});
|
||||
let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
|
||||
log::info!("Bat Charge Volt {:?}", e);
|
||||
println!("Bat Charge Volt {:?}", e);
|
||||
0
|
||||
});
|
||||
let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
|
||||
log::info!("Bat Charge Current {:?}", e);
|
||||
println!("Bat Charge Current {:?}", e);
|
||||
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.it_enable();
|
||||
anyhow::Result::Ok(())
|
||||
|
@ -4,9 +4,30 @@ use crate::log::{log, LogMessage};
|
||||
use crate::STAY_ALIVE;
|
||||
use anyhow::{anyhow, bail, Context};
|
||||
use chrono::{DateTime, Utc};
|
||||
use embedded_svc::ipv4::IpInfo;
|
||||
use embedded_svc::mqtt::client::QoS::{AtLeastOnce, ExactlyOnce};
|
||||
use embedded_svc::wifi::{
|
||||
AccessPointConfiguration, AccessPointInfo, AuthMethod, ClientConfiguration, Configuration,
|
||||
};
|
||||
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 alloc::{vec::Vec, string::{String, ToString}};
|
||||
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"]
|
||||
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
|
||||
@ -191,7 +212,7 @@ impl Esp<'_> {
|
||||
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()? {
|
||||
delay.delay_ms(250);
|
||||
@ -216,26 +237,23 @@ impl Esp<'_> {
|
||||
pub(crate) fn save_config(&mut self, config: &PlantControllerConfig) -> anyhow::Result<()> {
|
||||
let mut cfg = File::create(Self::CONFIG_FILE)?;
|
||||
serde_json::to_writer(&mut cfg, &config)?;
|
||||
log::info!("Wrote config config {:?}", config);
|
||||
println!("Wrote config config {:?}", config);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
pub(crate) fn mount_file_system(&mut self) -> anyhow::Result<()> {
|
||||
log(LogMessage::MountingFilesystem, 0, 0, "", "");
|
||||
let base_path = String::try_from("/spiffs")?;
|
||||
let storage = String::try_from(Self::SPIFFS_PARTITION_NAME)?;
|
||||
let conf = todo!();
|
||||
let base_path = CString::new("/spiffs")?;
|
||||
let storage = CString::new(Self::SPIFFS_PARTITION_NAME)?;
|
||||
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 {
|
||||
//base_path: base_path.as_ptr(),
|
||||
//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))?;
|
||||
//}
|
||||
unsafe {
|
||||
esp_idf_sys::esp!(esp_idf_sys::esp_vfs_spiffs_register(&conf))?;
|
||||
}
|
||||
|
||||
let free_space = self.file_system_size()?;
|
||||
log(
|
||||
@ -359,13 +377,13 @@ impl Esp<'_> {
|
||||
"",
|
||||
);
|
||||
for i in 0..PLANT_COUNT {
|
||||
log::info!(
|
||||
println!(
|
||||
"LAST_WATERING_TIMESTAMP[{}] = UTC {}",
|
||||
i, LAST_WATERING_TIMESTAMP[i]
|
||||
);
|
||||
}
|
||||
for i in 0..PLANT_COUNT {
|
||||
log::info!(
|
||||
println!(
|
||||
"CONSECUTIVE_WATERING_PLANT[{}] = {}",
|
||||
i, CONSECUTIVE_WATERING_PLANT[i]
|
||||
);
|
||||
@ -450,35 +468,35 @@ impl Esp<'_> {
|
||||
mqtt_connected_event_received_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 => {
|
||||
mqtt_connected_event_received_copy
|
||||
.store(true, 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) => {
|
||||
log::info!("EspMqttError reported {:?}", esp_error);
|
||||
println!("EspMqttError reported {:?}", esp_error);
|
||||
mqtt_connected_event_received_copy
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
|
||||
log::info!("Mqtt error");
|
||||
println!("Mqtt error");
|
||||
}
|
||||
esp_idf_svc::mqtt::client::EventPayload::BeforeConnect => {
|
||||
log::info!("Mqtt before connect")
|
||||
println!("Mqtt before connect")
|
||||
}
|
||||
esp_idf_svc::mqtt::client::EventPayload::Subscribed(_) => {
|
||||
log::info!("Mqtt subscribed")
|
||||
println!("Mqtt subscribed")
|
||||
}
|
||||
esp_idf_svc::mqtt::client::EventPayload::Unsubscribed(_) => {
|
||||
log::info!("Mqtt unsubscribed")
|
||||
println!("Mqtt unsubscribed")
|
||||
}
|
||||
esp_idf_svc::mqtt::client::EventPayload::Published(_) => {
|
||||
log::info!("Mqtt published")
|
||||
println!("Mqtt published")
|
||||
}
|
||||
esp_idf_svc::mqtt::client::EventPayload::Deleted(_) => {
|
||||
log::info!("Mqtt deleted")
|
||||
println!("Mqtt deleted")
|
||||
}
|
||||
}
|
||||
})?;
|
||||
@ -488,10 +506,10 @@ impl Esp<'_> {
|
||||
wait_for_connections_event += 1;
|
||||
match mqtt_connected_event_received.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
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) {
|
||||
true => {
|
||||
log::info!("Mqtt did callback as connected, testing with roundtrip now");
|
||||
println!("Mqtt did callback as connected, testing with roundtrip now");
|
||||
//subscribe to roundtrip
|
||||
client.subscribe(round_trip_topic.as_str(), ExactlyOnce)?;
|
||||
client.subscribe(stay_alive_topic.as_str(), ExactlyOnce)?;
|
||||
@ -508,7 +526,7 @@ impl Esp<'_> {
|
||||
wait_for_roundtrip += 1;
|
||||
match round_trip_ok.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
true => {
|
||||
log::info!("Round trip registered, proceeding");
|
||||
println!("Round trip registered, proceeding");
|
||||
self.mqtt_client = Some(MqttClient {
|
||||
mqtt_client: client,
|
||||
base_topic: base_topic_copy,
|
||||
@ -539,21 +557,21 @@ impl Esp<'_> {
|
||||
return anyhow::Ok(());
|
||||
}
|
||||
if !subtopic.starts_with("/") {
|
||||
log::info!("Subtopic without / at start {}", subtopic);
|
||||
println!("Subtopic without / at start {}", subtopic);
|
||||
bail!("Subtopic without / at start {}", subtopic);
|
||||
}
|
||||
if subtopic.len() > 192 {
|
||||
log::info!("Subtopic exceeds 192 chars {}", subtopic);
|
||||
println!("Subtopic exceeds 192 chars {}", subtopic);
|
||||
bail!("Subtopic exceeds 192 chars {}", subtopic);
|
||||
}
|
||||
let client = self.mqtt_client.as_mut().unwrap();
|
||||
let mut full_topic: heapless::String<256> = heapless::String::new();
|
||||
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")
|
||||
};
|
||||
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")
|
||||
};
|
||||
let publish = client
|
||||
@ -562,7 +580,7 @@ impl Esp<'_> {
|
||||
Delay::new(10).delay_ms(50);
|
||||
match publish {
|
||||
OkStd(message_id) => {
|
||||
log::info!(
|
||||
println!(
|
||||
"Published mqtt topic {} with message {:#?} msgid is {:?}",
|
||||
full_topic,
|
||||
String::from_utf8_lossy(message),
|
||||
@ -571,7 +589,7 @@ impl Esp<'_> {
|
||||
anyhow::Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!(
|
||||
println!(
|
||||
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
|
||||
full_topic,
|
||||
String::from_utf8_lossy(message),
|
||||
|
@ -9,8 +9,9 @@ use crate::{
|
||||
use anyhow::{bail, Result};
|
||||
use chrono::{DateTime, Utc};
|
||||
use embedded_hal::digital::OutputPin;
|
||||
use esp_idf_hal::gpio::{IOPin, Pull};
|
||||
use esp_idf_hal::gpio::{InputOutput, PinDriver};
|
||||
use measurements::{Current, Voltage};
|
||||
use crate::alloc::boxed::Box;
|
||||
|
||||
pub struct Initial<'a> {
|
||||
pub(crate) general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
@ -50,7 +51,7 @@ pub(crate) fn create_initial_board(
|
||||
config: PlantControllerConfig,
|
||||
esp: Esp<'static>,
|
||||
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
||||
log::info!("Start initial");
|
||||
println!("Start initial");
|
||||
let mut general_fault = PinDriver::input_output(free_pins.gpio6.downgrade())?;
|
||||
general_fault.set_pull(Pull::Floating)?;
|
||||
general_fault.set_low()?;
|
||||
|
@ -17,7 +17,6 @@ use crate::{
|
||||
},
|
||||
log::{log, LogMessage},
|
||||
};
|
||||
use alloc::boxed::Box;
|
||||
use anyhow::{Ok, Result};
|
||||
use battery::BQ34Z100G1;
|
||||
use bq34z100::Bq34z100g1Driver;
|
||||
@ -46,16 +45,18 @@ use esp_idf_sys::{
|
||||
};
|
||||
use esp_ota::mark_app_valid;
|
||||
use measurements::{Current, Voltage};
|
||||
use embassy_sync::{Mutex, LazyLock};
|
||||
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;
|
||||
use crate::alloc::string::ToString;
|
||||
|
||||
//Only support for 8 right now!
|
||||
pub const PLANT_COUNT: usize = 8;
|
||||
|
||||
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) -> ! {
|
||||
unsafe {
|
||||
@ -265,10 +266,10 @@ impl PlantHal {
|
||||
|
||||
let config = esp.load_config();
|
||||
|
||||
log::info!("Init rtc driver");
|
||||
println!("Init rtc driver");
|
||||
let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
|
||||
|
||||
log::info!("Init rtc eeprom driver");
|
||||
println!("Init rtc eeprom driver");
|
||||
let eeprom = {
|
||||
Eeprom24x::new_24x32(
|
||||
MutexDevice::new(&I2C_DRIVER),
|
||||
@ -278,10 +279,10 @@ impl PlantHal {
|
||||
let rtc_time = rtc.datetime();
|
||||
match rtc_time {
|
||||
OkStd(tt) => {
|
||||
log::info!("Rtc Module reports time at UTC {}", tt);
|
||||
println!("Rtc Module reports time at UTC {}", tt);
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Rtc Module could not be read {:?}", err);
|
||||
println!("Rtc Module could not be read {:?}", err);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -52,7 +52,7 @@ impl RTCModuleInteraction for DS3231Module<'_> {
|
||||
let (header, len): (BackupHeader, usize) =
|
||||
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)
|
||||
}
|
||||
|
||||
@ -95,7 +95,7 @@ impl RTCModuleInteraction for DS3231Module<'_> {
|
||||
};
|
||||
let config = config::standard();
|
||||
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
|
||||
log::info!(
|
||||
println!(
|
||||
"Raw header is {:?} with size {}",
|
||||
header_page_buffer, encoded
|
||||
);
|
||||
|
@ -10,12 +10,14 @@ use crate::{
|
||||
};
|
||||
use anyhow::{bail, Ok, Result};
|
||||
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 plant_ctrl2::sipo::ShiftRegister40;
|
||||
use core::result::Result::Ok as OkStd;
|
||||
use alloc::string::ToString;
|
||||
use alloc::boxed::Box;
|
||||
use esp_hall::gpio::Pull;
|
||||
use std::result::Result::Ok as OkStd;
|
||||
|
||||
const PUMP8_BIT: usize = 0;
|
||||
const PUMP1_BIT: usize = 1;
|
||||
@ -92,7 +94,7 @@ pub(crate) fn create_v3(
|
||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
||||
log::info!("Start v3");
|
||||
println!("Start v3");
|
||||
let mut clock = PinDriver::input_output(peripherals.gpio15.downgrade())?;
|
||||
clock.set_pull(Pull::Floating)?;
|
||||
let mut latch = PinDriver::input_output(peripherals.gpio3.downgrade())?;
|
||||
|
@ -12,6 +12,12 @@ use crate::log::{log, LogMessage};
|
||||
use anyhow::bail;
|
||||
use embedded_hal::digital::OutputPin;
|
||||
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::calibration::UnCalibrated;
|
||||
use ina219::configuration::{Configuration, OperatingMode};
|
||||
@ -21,9 +27,7 @@ use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
||||
use std::result::Result::Ok as OkStd;
|
||||
use embedded_can::Frame;
|
||||
use embedded_can::StandardId;
|
||||
use alloc::string::ToString;
|
||||
use alloc::boxed::Box;
|
||||
use esp_hal::gpio::Pull;
|
||||
use esp_idf_hal::can;
|
||||
|
||||
pub enum Charger<'a> {
|
||||
SolarMpptV1 {
|
||||
@ -48,7 +52,7 @@ impl Charger<'_> {
|
||||
operating_mode: OperatingMode::PowerDown,
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::info!(
|
||||
println!(
|
||||
"Error setting ina mppt configuration during deep sleep preparation{:?}",
|
||||
e
|
||||
);
|
||||
@ -129,7 +133,7 @@ pub(crate) fn create_v4(
|
||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||
) -> anyhow::Result<Box<dyn BoardInteraction<'static> + Send + 'static>> {
|
||||
log::info!("Start v4");
|
||||
println!("Start v4");
|
||||
let mut awake = PinDriver::output(peripherals.gpio21.downgrade())?;
|
||||
awake.set_high()?;
|
||||
|
||||
@ -159,7 +163,7 @@ pub(crate) fn create_v4(
|
||||
let mut sensor_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 34);
|
||||
let sensor = match sensor_expander.pin_into_output(GPIOBank::Bank0, 0) {
|
||||
Ok(_) => {
|
||||
log::info!("SensorExpander answered");
|
||||
println!("SensorExpander answered");
|
||||
//pulse counter version
|
||||
let mut signal_counter = PcntDriver::new(
|
||||
peripherals.pcnt0,
|
||||
@ -196,7 +200,7 @@ pub(crate) fn create_v4(
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
log::info!("Can bus mode ");
|
||||
println!("Can bus mode ");
|
||||
let timing = can::config::Timing::B25K;
|
||||
let config = can::config::Config::new().timing(timing);
|
||||
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();
|
||||
|
||||
if let Ok(rx_frame) = can.receive(1000) {
|
||||
log::info!("rx {:}:", rx_frame);
|
||||
println!("rx {:}:", rx_frame);
|
||||
}
|
||||
//can bus version
|
||||
SensorImpl::CanBus {
|
||||
@ -270,7 +274,7 @@ pub(crate) fn create_v4(
|
||||
) {
|
||||
Ok(pump_ina) => Some(pump_ina),
|
||||
Err(err) => {
|
||||
log::info!("Error creating pump ina: {:?}", err);
|
||||
println!("Error creating pump ina: {:?}", err);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
@ -1,4 +1,3 @@
|
||||
use alloc::string::ToString;
|
||||
use embedded_hal_bus::i2c::MutexDevice;
|
||||
use esp_idf_hal::can::CanDriver;
|
||||
use esp_idf_hal::delay::Delay;
|
||||
|
@ -109,11 +109,11 @@ impl<'a> TankSensor<'a> {
|
||||
let temp = self.single_temperature_c();
|
||||
match &temp {
|
||||
Ok(res) => {
|
||||
log::info!("Water temp is {}", res);
|
||||
println!("Water temp is {}", res);
|
||||
break temp;
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Could not get water temp {} attempt {}", err, attempt)
|
||||
println!("Could not get water temp {} attempt {}", err, attempt)
|
||||
}
|
||||
}
|
||||
if attempt == 5 {
|
||||
|
@ -1,5 +1,4 @@
|
||||
#![allow(dead_code)]
|
||||
#![no_std]
|
||||
extern crate embedded_hal as hal;
|
||||
|
||||
pub mod sipo;
|
||||
|
@ -1,5 +1,3 @@
|
||||
use alloc::string::ToString;
|
||||
use alloc::vec::Vec;
|
||||
use serde::Serialize;
|
||||
use std::{collections::HashMap, sync::Mutex};
|
||||
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 serial_entry = template.fill_in(&values);
|
||||
|
||||
log::info!("{serial_entry}");
|
||||
println!("{serial_entry}");
|
||||
//TODO push to mqtt?
|
||||
|
||||
let entry = LogEntry {
|
||||
|
208
rust/src/main.rs
208
rust/src/main.rs
@ -1,45 +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::BoardVersion::INITIAL,
|
||||
hal::{PlantHal, HAL, PLANT_COUNT},
|
||||
//webserver::httpd,
|
||||
webserver::httpd,
|
||||
};
|
||||
use core::sync::atomic::Ordering;
|
||||
use alloc::borrow::ToOwned;
|
||||
use alloc::sync::Arc;
|
||||
use alloc::fmt::format;
|
||||
use alloc::string::{String, ToString};
|
||||
use anyhow::{bail, Context};
|
||||
use chrono::{DateTime, Datelike, Timelike, Utc};
|
||||
use chrono_tz::Tz::{self, UTC};
|
||||
use embassy_executor::Spawner;
|
||||
use esp_idf_hal::delay::Delay;
|
||||
use esp_idf_sys::{
|
||||
esp_ota_get_app_partition_count, esp_ota_get_running_partition, esp_ota_get_state_partition,
|
||||
esp_ota_img_states_t, esp_ota_img_states_t_ESP_OTA_IMG_ABORTED,
|
||||
esp_ota_img_states_t_ESP_OTA_IMG_INVALID, esp_ota_img_states_t_ESP_OTA_IMG_NEW,
|
||||
esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY, esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED,
|
||||
esp_ota_img_states_t_ESP_OTA_IMG_VALID,
|
||||
};
|
||||
use esp_ota::{mark_app_valid, rollback_and_reboot};
|
||||
use hal::battery::BatteryState;
|
||||
use esp_hal::{timer::systimer::SystemTimer, clock::CpuClock, delay::Delay};
|
||||
use esp_println::logger;
|
||||
use log::{log, LogMessage};
|
||||
use once_cell::sync::Lazy;
|
||||
use plant_state::PlantState;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use embassy_sync::{Mutex, LazyLock, mutex::MutexGuard};
|
||||
use portable_atomic::AtomicBool;
|
||||
use std::sync::{atomic::AtomicBool, Arc, Mutex, MutexGuard};
|
||||
use tank::*;
|
||||
|
||||
mod config;
|
||||
mod hal;
|
||||
mod log;
|
||||
mod plant_state;
|
||||
mod tank;
|
||||
mod webserver;
|
||||
|
||||
extern crate alloc;
|
||||
//mod webserver;
|
||||
|
||||
pub static BOARD_ACCESS: LazyLock<Mutex<HAL>> = LazyLock::new(|| PlantHal::create().unwrap());
|
||||
pub static STAY_ALIVE: LazyLock<AtomicBool> = LazyLock::new(|| AtomicBool::new(false));
|
||||
pub static BOARD_ACCESS: Lazy<Mutex<HAL>> = Lazy::new(|| PlantHal::create().unwrap());
|
||||
pub static STAY_ALIVE: Lazy<AtomicBool> = Lazy::new(|| AtomicBool::new(false));
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||
enum WaitType {
|
||||
@ -117,45 +110,55 @@ enum NetworkMode {
|
||||
}
|
||||
|
||||
fn safe_main() -> anyhow::Result<()> {
|
||||
// It is necessary to call this function once. Otherwise, some patches to the runtime
|
||||
// implemented by esp-idf-sys might not link properly. See https://github.com/esp-rs/esp-idf-template/issues/71
|
||||
esp_idf_svc::sys::link_patches();
|
||||
|
||||
log::info!("Startup Rust");
|
||||
// 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 version = get_version();
|
||||
log::info!(
|
||||
println!(
|
||||
"Version using git has {} build on {}",
|
||||
version.git_hash, version.build_time
|
||||
);
|
||||
|
||||
//TODO
|
||||
//let count = unsafe { esp_ota_get_app_partition_count() };
|
||||
//log::info!("Partition count is {}", count);
|
||||
//let mut ota_state: esp_ota_img_states_t = 0;
|
||||
//let running_partition = unsafe { esp_ota_get_running_partition() };
|
||||
//let address = unsafe { (*running_partition).address };
|
||||
//log::info!("Partition address is {}", address);
|
||||
let count = unsafe { esp_ota_get_app_partition_count() };
|
||||
println!("Partition count is {}", count);
|
||||
let mut ota_state: esp_ota_img_states_t = 0;
|
||||
let running_partition = unsafe { esp_ota_get_running_partition() };
|
||||
let address = unsafe { (*running_partition).address };
|
||||
println!("Partition address is {}", address);
|
||||
|
||||
// TODO
|
||||
//let ota_state_string = unsafe {
|
||||
//esp_ota_get_state_partition(running_partition, &mut ota_state);
|
||||
//if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_NEW {
|
||||
//"ESP_OTA_IMG_NEW"
|
||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY {
|
||||
//"ESP_OTA_IMG_PENDING_VERIFY"
|
||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_VALID {
|
||||
//"ESP_OTA_IMG_VALID"
|
||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_INVALID {
|
||||
//"ESP_OTA_IMG_INVALID"
|
||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_ABORTED {
|
||||
//"ESP_OTA_IMG_ABORTED"
|
||||
//} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED {
|
||||
//"ESP_OTA_IMG_UNDEFINED"
|
||||
//} else {
|
||||
//&format!("unknown {ota_state}")
|
||||
//}
|
||||
//};
|
||||
//log(LogMessage::PartitionState, 0, 0, "", ota_state_string);
|
||||
let ota_state_string = unsafe {
|
||||
esp_ota_get_state_partition(running_partition, &mut ota_state);
|
||||
if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_NEW {
|
||||
"ESP_OTA_IMG_NEW"
|
||||
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY {
|
||||
"ESP_OTA_IMG_PENDING_VERIFY"
|
||||
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_VALID {
|
||||
"ESP_OTA_IMG_VALID"
|
||||
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_INVALID {
|
||||
"ESP_OTA_IMG_INVALID"
|
||||
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_ABORTED {
|
||||
"ESP_OTA_IMG_ABORTED"
|
||||
} else if ota_state == esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED {
|
||||
"ESP_OTA_IMG_UNDEFINED"
|
||||
} else {
|
||||
&format!("unknown {ota_state}")
|
||||
}
|
||||
};
|
||||
log(LogMessage::PartitionState, 0, 0, "", ota_state_string);
|
||||
|
||||
let mut board = BOARD_ACCESS
|
||||
.lock()
|
||||
@ -167,7 +170,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
.get_rtc_module()
|
||||
.get_rtc_time()
|
||||
.or_else(|err| {
|
||||
log::info!("rtc module error: {:?}", err);
|
||||
println!("rtc module error: {:?}", err);
|
||||
board.board_hal.general_fault(true);
|
||||
board.board_hal.get_esp().time()
|
||||
})
|
||||
@ -182,7 +185,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
log(LogMessage::YearInplausibleForceConfig, 0, 0, "", "");
|
||||
}
|
||||
|
||||
log::info!("cur is {}", cur);
|
||||
println!("cur is {}", cur);
|
||||
update_charge_indicator(&mut board);
|
||||
|
||||
if board.board_hal.get_esp().get_restart_to_conf() {
|
||||
@ -220,41 +223,40 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
let _ = board.board_hal.get_esp().wifi_ap();
|
||||
drop(board);
|
||||
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());
|
||||
}
|
||||
|
||||
log::info!("attempting to connect wifi");
|
||||
println!("attempting to connect wifi");
|
||||
let network_mode = if board.board_hal.get_config().network.ssid.is_some() {
|
||||
try_connect_wifi_sntp_mqtt(&mut board)
|
||||
} else {
|
||||
log::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;
|
||||
board.board_hal.get_esp().delay.delay_ms(100);
|
||||
NetworkMode::OFFLINE
|
||||
};
|
||||
|
||||
if matches!(network_mode, NetworkMode::OFFLINE) && to_config {
|
||||
log::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() {
|
||||
Ok(_) => {
|
||||
log::info!("Started ap, continuing")
|
||||
println!("Started ap, continuing")
|
||||
}
|
||||
Err(err) => log::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 {
|
||||
Some(tz_str) => tz_str.parse::<Tz>().unwrap_or_else(|_| {
|
||||
log::info!("Invalid timezone '{}', falling back to UTC", tz_str);
|
||||
println!("Invalid timezone '{}', falling back to UTC", tz_str);
|
||||
UTC
|
||||
}),
|
||||
None => UTC, // Fallback to UTC if no timezone is set
|
||||
};
|
||||
|
||||
let timezone_time = cur.with_timezone(&timezone);
|
||||
log::info!(
|
||||
println!(
|
||||
"Running logic at utc {} and {} {}",
|
||||
cur,
|
||||
timezone.name(),
|
||||
@ -292,12 +294,11 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
|
||||
if to_config {
|
||||
//check if client or ap mode and init Wi-Fi
|
||||
log::info!("executing config mode override");
|
||||
println!("executing config mode override");
|
||||
//config upload will trigger reboot!
|
||||
drop(board);
|
||||
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());
|
||||
} else {
|
||||
log(LogMessage::NormalRun, 0, 0, "", "");
|
||||
@ -505,7 +506,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
board.board_hal.light(false)?;
|
||||
}
|
||||
|
||||
log::info!("Lightstate is {:?}", light_state);
|
||||
println!("Lightstate is {:?}", light_state);
|
||||
}
|
||||
|
||||
match serde_json::to_string(&light_state) {
|
||||
@ -516,7 +517,7 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
.mqtt_publish("/light", state.as_bytes());
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error publishing lightstate {}", err);
|
||||
println!("Error publishing lightstate {}", err);
|
||||
}
|
||||
};
|
||||
|
||||
@ -550,27 +551,24 @@ fn safe_main() -> anyhow::Result<()> {
|
||||
//is light out of work trigger soon?
|
||||
//is battery low ??
|
||||
//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;
|
||||
log::info!("Check stay alive, current state is {}", stay_alive);
|
||||
println!("Check stay alive, current state is {}", stay_alive);
|
||||
|
||||
if stay_alive {
|
||||
log::info!("Go to stay alive move");
|
||||
println!("Go to stay alive move");
|
||||
drop(board);
|
||||
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());
|
||||
}
|
||||
board.board_hal.get_esp().set_restart_to_conf(false);
|
||||
board
|
||||
.board_hal
|
||||
.deep_sleep(1000 * 1000 * 60 * deep_sleep_duration_minutes as u64);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
pub fn do_secure_pump(
|
||||
@ -606,12 +604,12 @@ pub fn do_secure_pump(
|
||||
flow_collector[step] = flow_value;
|
||||
let flow_value_ml = flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
|
||||
|
||||
log::info!(
|
||||
println!(
|
||||
"Flow value is {} ml, limit is {} ml raw sensor {}",
|
||||
flow_value_ml, plant_config.pump_limit_ml, flow_value
|
||||
);
|
||||
if flow_value_ml > plant_config.pump_limit_ml as f32 {
|
||||
log::info!("Flow value is reached, stopping");
|
||||
println!("Flow value is reached, stopping");
|
||||
break;
|
||||
}
|
||||
|
||||
@ -661,7 +659,7 @@ pub fn do_secure_pump(
|
||||
}
|
||||
Err(err) => {
|
||||
if !plant_config.ignore_current_error {
|
||||
log::info!("Error getting pump current: {}", err);
|
||||
println!("Error getting pump current: {}", err);
|
||||
log(
|
||||
LogMessage::PumpMissingSensorCurrent,
|
||||
plant_id as u32,
|
||||
@ -687,7 +685,7 @@ pub fn do_secure_pump(
|
||||
.unwrap()
|
||||
.get_flow_meter_value();
|
||||
let flow_value_ml = final_flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
|
||||
log::info!(
|
||||
println!(
|
||||
"Final flow value is {} with {} ml",
|
||||
final_flow_value, flow_value_ml
|
||||
);
|
||||
@ -738,7 +736,7 @@ fn publish_tank_state(
|
||||
.mqtt_publish("/water", state.as_bytes());
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error publishing tankstate {}", err);
|
||||
println!("Error publishing tankstate {}", err);
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -764,7 +762,7 @@ fn publish_plant_states(
|
||||
board.board_hal.get_esp().delay.delay_ms(200);
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error publishing plant state {}", err);
|
||||
println!("Error publishing plant state {}", err);
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -814,12 +812,12 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode {
|
||||
Ok(ip_info) => {
|
||||
let sntp_mode: SntpMode = match board.board_hal.get_esp().sntp(1000 * 10) {
|
||||
Ok(new_time) => {
|
||||
log::info!("Using time from sntp");
|
||||
println!("Using time from sntp");
|
||||
let _ = board.board_hal.get_rtc_module().set_rtc_time(&new_time);
|
||||
SntpMode::SYNC { current: new_time }
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("sntp error: {}", err);
|
||||
println!("sntp error: {}", err);
|
||||
board.board_hal.general_fault(true);
|
||||
SntpMode::OFFLINE
|
||||
}
|
||||
@ -828,11 +826,11 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode {
|
||||
let nw_config = &board.board_hal.get_config().network.clone();
|
||||
match board.board_hal.get_esp().mqtt(nw_config) {
|
||||
Ok(_) => {
|
||||
log::info!("Mqtt connection ready");
|
||||
println!("Mqtt connection ready");
|
||||
true
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Could not connect mqtt due to {}", err);
|
||||
println!("Could not connect mqtt due to {}", err);
|
||||
false
|
||||
}
|
||||
}
|
||||
@ -846,7 +844,7 @@ fn try_connect_wifi_sntp_mqtt(board: &mut MutexGuard<HAL>) -> NetworkMode {
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
log::info!("Offline mode");
|
||||
println!("Offline mode");
|
||||
board.board_hal.general_fault(true);
|
||||
NetworkMode::OFFLINE
|
||||
}
|
||||
@ -881,7 +879,7 @@ fn pump_info(
|
||||
Delay::new_default().delay_ms(200);
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error publishing pump state {}", err);
|
||||
println!("Error publishing pump state {}", err);
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -965,11 +963,11 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
||||
delay_handle.delay_ms(delay);
|
||||
|
||||
if wait_type == WaitType::MqttConfig
|
||||
&& !STAY_ALIVE.load(Ordering::Relaxed)
|
||||
&& !STAY_ALIVE.load(std::sync::atomic::Ordering::Relaxed)
|
||||
{
|
||||
reboot_now.store(true, 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
|
||||
Delay::new_default().delay_ms(500);
|
||||
BOARD_ACCESS.lock().unwrap().board_hal.deep_sleep(1);
|
||||
@ -977,26 +975,13 @@ fn wait_infinity(wait_type: WaitType, reboot_now: Arc<AtomicBool>) -> ! {
|
||||
}
|
||||
}
|
||||
|
||||
#[esp_hal_embassy::main]
|
||||
async fn main(spawner: Spawner) {
|
||||
// intialize embassy
|
||||
esp_log::info::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!");
|
||||
|
||||
fn main() {
|
||||
let result = safe_main();
|
||||
match result {
|
||||
// this should not get triggered, safe_main should not return but go into deep sleep with sensible
|
||||
// timeout, this is just a fallback
|
||||
Ok(_) => {
|
||||
log::info!("Main app finished, restarting");
|
||||
println!("Main app finished, restarting");
|
||||
BOARD_ACCESS
|
||||
.lock()
|
||||
.unwrap()
|
||||
@ -1007,9 +992,8 @@ async fn main(spawner: Spawner) {
|
||||
}
|
||||
// if safe_main exists with an error, rollback to a known good ota version
|
||||
Err(err) => {
|
||||
log::info!("Failed main {}", err);
|
||||
//TODO
|
||||
//let _rollback_successful = rollback_and_reboot();
|
||||
println!("Failed main {}", err);
|
||||
let _rollback_successful = rollback_and_reboot();
|
||||
panic!("Failed to rollback :(");
|
||||
}
|
||||
}
|
||||
@ -1030,10 +1014,8 @@ fn get_version() -> VersionInfo {
|
||||
let branch = env!("VERGEN_GIT_BRANCH").to_owned();
|
||||
let hash = &env!("VERGEN_GIT_SHA")[0..8];
|
||||
|
||||
//TODO
|
||||
//let running_partition = unsafe { esp_ota_get_running_partition() };
|
||||
let address = 0;
|
||||
//let address = unsafe { (*running_partition).address };
|
||||
let running_partition = unsafe { esp_ota_get_running_partition() };
|
||||
let address = unsafe { (*running_partition).address };
|
||||
let partition = if address > 100000 {
|
||||
"ota_1 @ "
|
||||
} else {
|
||||
|
@ -3,7 +3,6 @@ use crate::{
|
||||
hal::{Sensor, HAL},
|
||||
in_time_range,
|
||||
};
|
||||
use alloc::string::String;
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use chrono_tz::Tz;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
@ -2,9 +2,7 @@
|
||||
|
||||
use core::cell::RefCell;
|
||||
use core::mem::{self, MaybeUninit};
|
||||
use core::convert::Infallible;
|
||||
use core::result::{Result, Result::Ok};
|
||||
use core::iter::Iterator;
|
||||
use std::convert::Infallible;
|
||||
|
||||
use hal::digital::OutputPin;
|
||||
|
||||
|
@ -1,6 +1,5 @@
|
||||
use crate::{config::TankConfig, hal::HAL};
|
||||
use anyhow::Context;
|
||||
use crate::alloc::string::{String, ToString};
|
||||
use serde::Serialize;
|
||||
|
||||
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() {
|
||||
Ok(config) => from_utf8(&config)?.to_owned(),
|
||||
Err(err) => {
|
||||
log::info!("Error get backup config {:?}", err);
|
||||
println!("Error get backup config {:?}", err);
|
||||
err.to_string()
|
||||
}
|
||||
};
|
||||
@ -318,7 +318,7 @@ fn wifi_scan(
|
||||
let mut ssids: Vec<&String<32>> = Vec::new();
|
||||
scan_result.iter().for_each(|s| ssids.push(&s.ssid));
|
||||
let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
|
||||
log::info!("Sending ssid list {}", &ssid_json);
|
||||
println!("Sending ssid list {}", &ssid_json);
|
||||
anyhow::Ok(Some(ssid_json))
|
||||
}
|
||||
|
||||
@ -338,7 +338,7 @@ fn ota(
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
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 ;)
|
||||
const BUFFER_SIZE: usize = 512;
|
||||
@ -366,13 +366,13 @@ fn ota(
|
||||
break;
|
||||
}
|
||||
}
|
||||
log::info!("wrote bytes ota {total_read}");
|
||||
log::info!("finish ota");
|
||||
println!("wrote bytes ota {total_read}");
|
||||
println!("finish ota");
|
||||
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()?;
|
||||
log::info!("changing boot partition");
|
||||
println!("changing boot partition");
|
||||
board.board_hal.get_esp().set_restart_to_conf(true);
|
||||
drop(board);
|
||||
finalizer.set_as_boot_partition()?;
|
||||
@ -380,7 +380,7 @@ fn ota(
|
||||
}
|
||||
|
||||
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 value = parsed.query_pairs().find(|it| it.0 == param_name);
|
||||
match value {
|
||||
@ -551,14 +551,14 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
log::info!("wrote {total_read} for file {filename}");
|
||||
println!("wrote {total_read} for file {filename}");
|
||||
drop(file_handle);
|
||||
response.flush()?;
|
||||
}
|
||||
Err(err) => {
|
||||
//todo set headers here for filename to be error
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
@ -599,7 +599,7 @@ pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
|
||||
Err(err) => {
|
||||
//todo set headers here for filename to be error
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
@ -697,7 +697,7 @@ fn handle_error_to500(
|
||||
},
|
||||
Err(err) => {
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
@ -725,6 +725,6 @@ fn read_up_to_bytes_from_request(
|
||||
data_store.push(actual_data.to_owned());
|
||||
}
|
||||
let allvec = data_store.concat();
|
||||
log::info!("Raw data {}", from_utf8(&allvec)?);
|
||||
println!("Raw data {}", from_utf8(&allvec)?);
|
||||
Ok(allvec)
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user