Fix ota, use MMU to determine running partition, use RMW wrapper for ota_data partition (littelfs handles this internally, so it was no problem prior)

This commit is contained in:
2026-03-18 01:22:33 +01:00
parent 66e1fe63e0
commit 39e4e733f3
11 changed files with 220 additions and 249 deletions

View File

@@ -1,5 +1,5 @@
use esp_hal::uart::Config as UartConfig;
use lib_bms_protocol::BmsReadable;
use esp_hal::uart::{Config as UartConfig};
pub(crate) mod battery;
// mod can_api; // replaced by external canapi crate
pub mod esp;
@@ -9,7 +9,6 @@ mod shared_flash;
mod v4_hal;
mod water;
use lib_bms_protocol::ProtocolVersion;
use crate::alloc::string::ToString;
use crate::hal::rtc::{DS3231Module, RTCModuleInteraction};
use esp_hal::peripherals::Peripherals;
@@ -36,6 +35,7 @@ use esp_hal::peripherals::GPIO6;
use esp_hal::peripherals::GPIO7;
use esp_hal::peripherals::GPIO8;
use esp_hal::peripherals::TWAI0;
use lib_bms_protocol::ProtocolVersion;
use crate::{
bail,
@@ -66,19 +66,21 @@ use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::blocking_mutex::CriticalSectionMutex;
use esp_bootloader_esp_idf::partitions::{
AppPartitionSubType, DataPartitionSubType, FlashRegion, PartitionEntry,
AppPartitionSubType, DataPartitionSubType, FlashRegion, PartitionEntry, PartitionTable,
PartitionType,
};
use esp_hal::clock::CpuClock;
use esp_hal::gpio::{Input, InputConfig, Pull};
use measurements::{Current, Voltage};
use crate::fat_error::{ContextExt, FatError, FatResult};
use crate::hal::battery::{WCHI2CSlave};
use crate::hal::battery::WCHI2CSlave;
use crate::hal::little_fs2storage_adapter::LittleFs2Filesystem;
use crate::hal::water::TankSensor;
use crate::log::LOG_ACCESS;
use embassy_sync::mutex::Mutex;
use embassy_sync::once_lock::OnceLock;
use embedded_storage::nor_flash::RmwNorFlashStorage;
use embedded_storage::ReadStorage;
use esp_alloc as _;
use esp_backtrace as _;
@@ -93,8 +95,8 @@ use esp_hal::rtc_cntl::{Rtc, SocResetReason};
use esp_hal::system::reset_reason;
use esp_hal::time::Rate;
use esp_hal::timer::timg::TimerGroup;
use esp_hal::Blocking;
use esp_hal::uart::Uart;
use esp_hal::Blocking;
use esp_radio::{init, Controller};
use esp_storage::FlashStorage;
use littlefs2::fs::{Allocation, Filesystem as lfs2Filesystem};
@@ -138,12 +140,6 @@ pub struct HAL<'a> {
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
}
pub struct DetectionRequest {
pub sensorsa: [Sensor; PLANT_COUNT],
pub sensorsb: [Sensor; PLANT_COUNT],
}
#[async_trait(?Send)]
pub trait BoardInteraction<'a> {
fn get_tank_sensor(&mut self) -> Result<&mut TankSensor<'a>, FatError>;
@@ -169,7 +165,7 @@ pub trait BoardInteraction<'a> {
async fn can_power(&mut self, state: bool) -> FatResult<()>;
// Return JSON string with autodetected sensors per plant. Default: not supported.
async fn detect_sensors(&mut self, request: Detection) -> FatResult<Detection> {
async fn detect_sensors(&mut self, _request: Detection) -> FatResult<Detection> {
bail!("Autodetection is only available on v4 HAL with CAN bus");
}
@@ -333,31 +329,31 @@ impl PlantHal {
);
let ota_data = mk_static!(
FlashRegion<MutexFlashStorage>,
ota_data.as_embedded_storage(flash_storage_2)
FlashRegion<RmwNorFlashStorage<&mut MutexFlashStorage>>,
ota_data.as_embedded_storage(mk_static!(
RmwNorFlashStorage<&mut MutexFlashStorage>,
RmwNorFlashStorage::new(flash_storage_2, mk_static!([u8; 4096], [0_u8; 4096]))
))
);
let state_0 = ota_state(AppPartitionSubType::Ota0, ota_data);
let state_1 = ota_state(AppPartitionSubType::Ota1, ota_data);
let mut ota = Ota::new(ota_data, 2)?;
let running = get_current_slot_and_fix_ota_data(&mut ota, state_0, state_1)?;
let running = get_current_slot(&pt, &mut ota)?;
let target = next_partition(running)?;
info!("Currently running OTA slot: {running:?}");
info!("Updates will be stored in OTA slot: {target:?}");
info!("Slot0 state: {state_0:?}");
info!("Slot1 state: {state_1:?}");
//get current_state and next_state here!
let ota_target = match target {
AppPartitionSubType::Ota0 => pt
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::App(
AppPartitionSubType::Ota0,
))?
.find_partition(PartitionType::App(AppPartitionSubType::Ota0))?
.context("Partition table invalid no ota0")?,
AppPartitionSubType::Ota1 => pt
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::App(
AppPartitionSubType::Ota1,
))?
.find_partition(PartitionType::App(AppPartitionSubType::Ota1))?
.context("Partition table invalid no ota1")?,
_ => {
bail!("Invalid target partition");
@@ -401,8 +397,8 @@ impl PlantHal {
lfs2Filesystem::mount(alloc, lfs2filesystem).expect("Could not mount lfs2 filesystem"),
));
let uart0 = Uart::new(peripherals.UART0, UartConfig::default())
.map_err(|_| FatError::String {
let uart0 =
Uart::new(peripherals.UART0, UartConfig::default()).map_err(|_| FatError::String {
error: "Uart creation failed".to_string(),
})?;
@@ -421,7 +417,7 @@ impl PlantHal {
current: running,
slot0_state: state_0,
slot1_state: state_1,
uart0
uart0,
};
//init,reset rtc memory depending on cause
@@ -551,9 +547,9 @@ impl PlantHal {
// initial_hal::create_initial_board(free_pins, config, esp)?
//}
//BoardVersion::V4 => {
v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)
.await?;
//}
v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)
.await?;
//}
//};
HAL { board_hal }
@@ -571,9 +567,14 @@ impl PlantHal {
)
.await;
HAL {
board_hal: v4_hal::create_v4(free_pins, esp, PlantControllerConfig::default(),
Box::new(NoBatteryMonitor {}), rtc_module)
.await?
board_hal: v4_hal::create_v4(
free_pins,
esp,
PlantControllerConfig::default(),
Box::new(NoBatteryMonitor {}),
rtc_module,
)
.await?,
}
}
};
@@ -584,7 +585,7 @@ impl PlantHal {
fn ota_state(
slot: AppPartitionSubType,
ota_data: &mut FlashRegion<MutexFlashStorage>,
ota_data: &mut FlashRegion<RmwNorFlashStorage<&mut MutexFlashStorage>>,
) -> OtaImageState {
// Read and log OTA states for both slots before constructing Ota
// Each OTA select entry is 32 bytes: [seq:4][label:20][state:4][crc:4]
@@ -600,56 +601,40 @@ fn ota_state(
OtaImageState::try_from(raw_state).unwrap_or(OtaImageState::Undefined)
}
fn get_current_slot_and_fix_ota_data(
ota: &mut Ota<MutexFlashStorage>,
state0: OtaImageState,
state1: OtaImageState,
fn get_current_slot(
pt: &PartitionTable,
ota: &mut Ota<RmwNorFlashStorage<&mut MutexFlashStorage>>,
) -> Result<AppPartitionSubType, FatError> {
let state = ota.current_ota_state().unwrap_or_default();
let swap = match state {
OtaImageState::Invalid => true,
OtaImageState::Aborted => true,
OtaImageState::Undefined => {
info!("Undefined image in current slot, bootloader wrong?");
false
let booted = pt.booted_partition()?.ok_or(FatError::OTAError)?;
let booted_type = booted.partition_type();
let booted_ota_type = match booted_type {
PartitionType::App(subtype) => subtype,
_ => {
bail!("Booted partition is not an app partition");
}
_ => false,
};
let current = ota.current_app_partition()?;
if swap {
let other = match current {
AppPartitionSubType::Ota0 => state1,
AppPartitionSubType::Ota1 => state0,
_ => OtaImageState::Invalid,
};
match other {
OtaImageState::Invalid => {
bail!(
"cannot recover slot, as both slots in invalid state {:?} {:?} {:?}",
current,
state0,
state1
);
}
OtaImageState::Aborted => {
bail!(
"cannot recover slot, as both slots in invalid state {:?} {:?} {:?}",
current,
state0,
state1
);
}
_ => {}
}
info!("Current slot has state {state:?} other state has {other:?} swapping");
let next = next_partition(current)?;
ota.set_current_app_partition(next)?;
let expected_partition = ota.current_app_partition()?;
if expected_partition == booted_ota_type {
info!("Booted partition matches expected partition");
} else {
info!("Booted partition does not match expected partition, fixing ota entry");
ota.set_current_app_partition(booted_ota_type)?;
}
//we actually booted other slot, than partition table assumes
return Ok(ota.current_app_partition()?);
};
Ok(current)
let fixed = ota.current_app_partition()?;
let state = ota.current_ota_state();
info!("Expected partition: {expected_partition:?}, current partition: {booted_ota_type:?}, state: {state:?}");
if fixed != booted_ota_type {
bail!(
"Could not fix ota entry, booted partition is still not correct: {:?} != {:?}",
booted_ota_type,
fixed
);
}
Ok(booted_ota_type)
}
pub fn next_partition(current: AppPartitionSubType) -> FatResult<AppPartitionSubType> {
@@ -699,4 +684,3 @@ pub struct DetectionSensorResult {
sensor_a: bool,
sensor_b: bool,
}