get log to work, make time accessible

This commit is contained in:
2025-09-20 11:31:51 +02:00
parent 584d6df2d0
commit c94f5bdb45
6 changed files with 334 additions and 212 deletions

View File

@@ -1,9 +1,9 @@
use crate::config::{NetworkConfig, PlantControllerConfig};
use crate::hal::{GW_IP_ADDR_ENV, PLANT_COUNT};
use crate::log::{log, LogMessage};
use crate::hal::{GW_IP_ADDR_ENV, PLANT_COUNT, TIME_ACCESS};
use crate::log::{ LogArray, LogMessage, LOG_ACCESS};
use crate::STAY_ALIVE;
use anyhow::{anyhow, bail, Context};
use chrono::{DateTime, Utc};
use chrono::{DateTime, FixedOffset, Utc};
use serde::Serialize;
use crate::hal::little_fs2storage_adapter::LittleFs2Filesystem;
@@ -13,12 +13,10 @@ use alloc::{format, string::String, vec::Vec};
use core::marker::PhantomData;
use core::net::{IpAddr, Ipv4Addr};
use core::str::FromStr;
use embassy_executor::{SendSpawner, Spawner};
use embassy_net::tcp::TcpSocket;
use embassy_net::{IpListenEndpoint, Ipv4Cidr, Runner, Stack, StackResources, StaticConfigV4};
use embassy_executor::{Spawner};
use embassy_net::{Ipv4Cidr, Runner, Stack, StackResources, StaticConfigV4};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::Mutex;
use embassy_sync::rwlock::TryLockError;
use embassy_time::{Duration, Instant, Timer};
use embedded_storage::nor_flash::ReadNorFlash;
use embedded_storage::Storage;
@@ -26,25 +24,27 @@ use esp_bootloader_esp_idf::ota::{Ota, OtaImageState, Slot};
use esp_bootloader_esp_idf::partitions::{Error, FlashRegion, PartitionEntry, PartitionTable};
use esp_hal::gpio::Input;
use esp_hal::rng::Rng;
use esp_hal::rtc_cntl::Rtc;
use esp_hal::rtc_cntl::sleep::RtcSleepConfig;
use esp_println::{print, println};
use esp_hal::system::software_reset;
use esp_println::{println};
use esp_storage::FlashStorage;
use esp_wifi::wifi::{
AccessPointConfiguration, AccessPointInfo, Configuration, Interfaces, ScanConfig,
ScanTypeConfig, WifiController, WifiDevice, WifiEvent, WifiState,
ScanTypeConfig, WifiController, WifiDevice,
};
use littlefs2::fs::Filesystem;
use littlefs2_core::{DynFile, FileType, OpenSeekFrom, Path, PathBuf, SeekFrom};
use log::{info, warn};
use littlefs2_core::{DynFile, FileType, PathBuf, SeekFrom};
use log::{info};
#[link_section = ".rtc.data"]
#[esp_hal::ram(rtc_fast, persistent)]
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
#[link_section = ".rtc.data"]
#[esp_hal::ram(rtc_fast, persistent)]
static mut CONSECUTIVE_WATERING_PLANT: [u32; PLANT_COUNT] = [0; PLANT_COUNT];
#[link_section = ".rtc.data"]
static mut LOW_VOLTAGE_DETECTED: bool = false;
#[link_section = ".rtc.data"]
static mut RESTART_TO_CONF: bool = false;
#[esp_hal::ram(rtc_fast, persistent)]
static mut LOW_VOLTAGE_DETECTED: i8 = 0;
#[esp_hal::ram(rtc_fast, persistent)]
static mut RESTART_TO_CONF: i8 = 0;
static CONFIG_FILE: &str = "config.json";
@@ -239,10 +239,6 @@ impl Esp<'_> {
bail!("not implemented")
}
pub(crate) fn time(&mut self) -> DateTime<Utc> {
let wall_clock = Instant::now().as_millis() + self.wall_clock_offset;
DateTime::from_timestamp_millis(wall_clock as i64).unwrap()
}
pub(crate) async fn wifi_scan(&mut self) -> anyhow::Result<Vec<AccessPointInfo>> {
info!("start wifi scan");
@@ -277,17 +273,17 @@ impl Esp<'_> {
}
pub(crate) fn set_low_voltage_in_cycle(&mut self) {
unsafe {
LOW_VOLTAGE_DETECTED = true;
LOW_VOLTAGE_DETECTED = 1;
}
}
pub(crate) fn clear_low_voltage_in_cycle(&mut self) {
unsafe {
LOW_VOLTAGE_DETECTED = false;
LOW_VOLTAGE_DETECTED = 1;
}
}
pub(crate) fn low_voltage_in_cycle(&mut self) -> bool {
unsafe { LOW_VOLTAGE_DETECTED }
unsafe { LOW_VOLTAGE_DETECTED == 1 }
}
pub(crate) fn store_consecutive_pump_count(&mut self, plant: usize, count: u32) {
unsafe {
@@ -298,11 +294,15 @@ impl Esp<'_> {
unsafe { CONSECUTIVE_WATERING_PLANT[plant] }
}
pub(crate) fn get_restart_to_conf(&mut self) -> bool {
unsafe { RESTART_TO_CONF }
unsafe { RESTART_TO_CONF == 1}
}
pub(crate) fn set_restart_to_conf(&mut self, to_conf: bool) {
unsafe {
RESTART_TO_CONF = to_conf;
if to_conf {
RESTART_TO_CONF = 1;
} else {
RESTART_TO_CONF = 0;
}
}
}
@@ -374,10 +374,9 @@ impl Esp<'_> {
//unsafe {
// //allow early wakeup by pressing the boot button
if duration_in_ms == 0 {
loop {
info!("todo reboot")
}
software_reset();
} else {
loop {
info!("todo deepsleep")
}
@@ -547,31 +546,34 @@ impl Esp<'_> {
unsafe {
LAST_WATERING_TIMESTAMP = [0; PLANT_COUNT];
CONSECUTIVE_WATERING_PLANT = [0; PLANT_COUNT];
LOW_VOLTAGE_DETECTED = false;
crate::log::init().await;
RESTART_TO_CONF = to_config_mode;
LOW_VOLTAGE_DETECTED = 0;
if to_config_mode {
RESTART_TO_CONF = 1
} else {
RESTART_TO_CONF = 0;
}
};
} else {
unsafe {
if to_config_mode {
RESTART_TO_CONF = true;
RESTART_TO_CONF = 1;
}
log(
LOG_ACCESS.lock().await.log(
LogMessage::RestartToConfig,
RESTART_TO_CONF as u32,
0,
"",
"",
)
.await;
log(
).await
;
LOG_ACCESS.lock().await.log(
LogMessage::LowVoltage,
LOW_VOLTAGE_DETECTED as u32,
0,
"",
"",
)
.await;
).await
;
for i in 0..PLANT_COUNT {
log::info!(
"LAST_WATERING_TIMESTAMP[{}] = UTC {}",

View File

@@ -18,13 +18,15 @@ use crate::{
battery::{BatteryInteraction, NoBatteryMonitor},
esp::Esp,
},
log::{log, LogMessage},
log::{LogMessage},
};
use alloc::boxed::Box;
use alloc::format;
use alloc::sync::Arc;
use core::cell::OnceCell;
use anyhow::{bail, Ok, Result};
use async_trait::async_trait;
use chrono::{DateTime, FixedOffset, Utc};
use embassy_executor::Spawner;
//use battery::BQ34Z100G1;
//use bq34z100::Bq34z100g1Driver;
@@ -38,16 +40,22 @@ use measurements::{Current, Voltage};
use crate::hal::little_fs2storage_adapter::LittleFs2Filesystem;
use embassy_sync::mutex::Mutex;
use embassy_sync::once_lock::OnceLock;
use esp_alloc as _;
use esp_backtrace as _;
use esp_bootloader_esp_idf::ota::Slot;
use esp_hal::rng::Rng;
use esp_hal::rtc_cntl::{Rtc, SocResetReason};
use esp_hal::system::reset_reason;
use esp_hal::timer::timg::TimerGroup;
use esp_storage::FlashStorage;
use esp_wifi::{init, EspWifiController};
use littlefs2::fs::{Allocation, Filesystem as lfs2Filesystem};
use littlefs2::object_safe::DynStorage;
use log::{info, warn};
use crate::log::{LogArray, LOG_ACCESS};
pub static TIME_ACCESS: OnceLock<Rtc> = OnceLock::new();
//Only support for 8 right now!
pub const PLANT_COUNT: usize = 8;
@@ -181,6 +189,13 @@ impl PlantHal {
esp_alloc::heap_allocator!(size: 64 * 1024);
esp_alloc::heap_allocator!(#[link_section = ".dram2_uninit"] size: 64000);
let rtc: Rtc = Rtc::new(peripherals.LPWR);
match(TIME_ACCESS.init(rtc)){
Result::Ok(_) => {}
Err(_) => {}
}
let systimer = SystemTimer::new(peripherals.SYSTIMER);
let boot_button = Input::new(
@@ -335,36 +350,78 @@ impl PlantHal {
//init,reset rtc memory depending on cause
let mut init_rtc_store: bool = false;
let mut to_config_mode: bool = false;
let reasons = "";
// let reasons = ResetReason::get();
// match reasons {
// ResetReason::Software => {}
// ResetReason::ExternalPin => {}
// ResetReason::Watchdog => {
// init_rtc_store = true;
// }
// ResetReason::Sdio => init_rtc_store = true,
// ResetReason::Panic => init_rtc_store = true,
// ResetReason::InterruptWatchdog => init_rtc_store = true,
// ResetReason::PowerOn => init_rtc_store = true,
// ResetReason::Unknown => init_rtc_store = true,
// ResetReason::Brownout => init_rtc_store = true,
// ResetReason::TaskWatchdog => init_rtc_store = true,
// ResetReason::DeepSleep => {}
// ResetReason::USBPeripheral => {
// init_rtc_store = true;
// to_config_mode = true;
// }
// ResetReason::JTAG => init_rtc_store = true,
// };
log(
let reasons = match reset_reason() {
None => {
"unknown"
}
Some(reason) => {
match reason {
SocResetReason::ChipPowerOn => {
"power on"
}
SocResetReason::CoreSw => {
"software reset"
}
SocResetReason::CoreDeepSleep => {
"deep sleep"
}
SocResetReason::CoreSDIO => {
"sdio reset"
}
SocResetReason::CoreMwdt0 => {
"Watchdog Main"
}
SocResetReason::CoreMwdt1 => {
"Watchdog 1"
}
SocResetReason::CoreRtcWdt => {
"Watchdog RTC"
}
SocResetReason::Cpu0Mwdt0 => {
"Watchdog MCpu0"
}
SocResetReason::Cpu0Sw => {
"software reset cpu0"
}
SocResetReason::Cpu0RtcWdt => {
init_rtc_store = true;
"Watchdog RTC cpu0"
}
SocResetReason::SysBrownOut => {
"sys brown out"
}
SocResetReason::SysRtcWdt => {
"Watchdog Sys rtc"
}
SocResetReason::Cpu0Mwdt1 => {
"cpu0 mwdt1"
}
SocResetReason::SysSuperWdt => {
"Watchdog Super"
}
SocResetReason::CoreEfuseCrc => {
"core efuse crc"
}
SocResetReason::CoreUsbUart => {
to_config_mode = true;
"core usb uart"
}
SocResetReason::CoreUsbJtag => {
"core usb jtag"
}
SocResetReason::Cpu0JtagCpu => {
"cpu0 jtag cpu"
}
}
}
};
LOG_ACCESS.lock().await.log(
LogMessage::ResetReason,
init_rtc_store as u32,
to_config_mode as u32,
"",
&format!("{reasons:?}"),
)
.await;
).await;
esp.init_rtc_deepsleep_memory(init_rtc_store, to_config_mode)
.await;
@@ -430,32 +487,32 @@ impl PlantHal {
}
};
let board_hal: Box<dyn BoardInteraction + Send> = match config.hardware.board {
BoardVersion::INITIAL => {
let board_hal: Box<dyn BoardInteraction + Send> = //match config.hardware.board {
//BoardVersion::INITIAL => {
initial_hal::create_initial_board(free_pins, config, esp)?
}
;
//}
// BoardVersion::V3 => {
// v3_hal::create_v3(free_pins, esp, config, battery_interaction, rtc_module)?
// }
// BoardVersion::V4 => {
// v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)?
// }
_ => {
todo!()
}
};
//BoardVersion::V4 => {
// v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)?
//}
//_ => {
// todo!()
//}
//};
HAL { board_hal }
}
Err(err) => {
log(
LOG_ACCESS.lock().await.log(
LogMessage::ConfigModeMissingConfig,
0,
0,
"",
&err.to_string(),
)
.await;
).await;
HAL {
board_hal: initial_hal::create_initial_board(
free_pins,
@@ -469,3 +526,12 @@ impl PlantHal {
Ok(Mutex::new(hal))
}
}
pub async fn esp_time() -> DateTime<Utc> {
DateTime::from_timestamp_micros(TIME_ACCESS.get().await.current_time_us() as i64).unwrap()
}
pub async fn esp_set_time(time: DateTime<FixedOffset>) {
TIME_ACCESS.get().await.set_current_time_us(time.timestamp_micros() as u64);
}