feat: add A/B firmware slots

Split the single app partition into two slots, ota_0 and ota_1, with an
otadata partition that tells the bootloader which to run, so an update can
be written to the idle slot while the other keeps running. The Zigbee
storage partition is unchanged, so the light keeps its network. Moving from
the old table needs one USB flash.

* src/ota.rs logs the running slot and the state of its image at boot,
  marks an image valid after it has stayed up for 20 seconds, and can
  switch to the other slot and restart. The slot in use is read from the
  flash mapping, not from otadata.
* src/flash.rs shares the one flash handle: esp-storage allows only one, and
  both the Zigbee stack and the update code need it.
* The runner clears otadata on every USB flash. A USB flash always writes
  slot 0, so without this a board that had switched to slot 1 would keep
  booting the old image.
* Two development features, ota-test and ota-test-crash, exercise slot
  switching and an unconfirmed image without an update source. FW_LABEL tells
  builds apart in the log.

Tested on the hardware: switching between two images across six reboots, each
booting the slot it had just selected, resuming its Zigbee network, and
confirming itself. Rollback is not available: the bootloader espflash installs
is not built with it, so a newly selected image reports "New" rather than
"PendingVerify", and an image that resets without confirming itself is booted
again indefinitely. Needs a rollback-enabled bootloader. Nothing delivers
updates yet. Both are recorded in TODO.md.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Matt SpencerandCopilot committed 2026-11-29 00:32:40 +00:00
1 parent 2f5f457ffc
commit 9ea25c3aab
10 files changed
+327 -8

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
//! The one flash handle, shared.
//!
//! `esp_storage::FlashStorage` can only be created once, but two things need
//! the flash: the Zigbee stack, which persists its state there, and the
//! firmware update code, which reads the partition table and the OTA data.
//!
//! Every access takes a critical section. `esp-storage` already makes each
//! flash operation atomic with respect to interrupts, so this adds no new
//! stall for a single read, erase or write; it only keeps two tasks from
//! interleaving a sequence of them.
use core::cell::RefCell;
use embassy_sync::blocking_mutex::Mutex;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embedded_storage::nor_flash::ErrorType;
use embedded_storage::nor_flash::MultiwriteNorFlash;
use embedded_storage::nor_flash::NorFlash;
use embedded_storage::nor_flash::ReadNorFlash;
pub use esp_storage::FlashStorage;
static FLASH: Mutex<CriticalSectionRawMutex, RefCell<Option<FlashStorage<'static>>>> =
Mutex::new(RefCell::new(None));
/// Hands the flash over to this module. Call once, before anything uses it.
pub fn init(flash: FlashStorage<'static>) {
FLASH.lock(|cell| *cell.borrow_mut() = Some(flash));
}
/// Runs `f` with exclusive access to the flash.
///
/// `f` must not call back into this module: the flash is already borrowed.
///
/// # Panics
///
/// If [`init`] has not been called.
pub fn with<R>(f: impl FnOnce(&mut FlashStorage<'static>) -> R) -> R {
FLASH.lock(|cell| {
let mut flash = cell.borrow_mut();
f(flash.as_mut().expect("flash not initialised"))
})
}
/// A handle to the shared flash that is itself a flash device, for code that
/// wants to own one, such as the Zigbee storage.
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
pub struct SharedFlash;
impl ErrorType for SharedFlash {
type Error = <FlashStorage<'static> as ErrorType>::Error;
}
impl ReadNorFlash for SharedFlash {
const READ_SIZE: usize = <FlashStorage<'static> as ReadNorFlash>::READ_SIZE;
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
with(|flash| flash.read(offset, bytes))
}
fn capacity(&self) -> usize {
with(|flash| flash.capacity())
}
}
impl NorFlash for SharedFlash {
const WRITE_SIZE: usize = <FlashStorage<'static> as NorFlash>::WRITE_SIZE;
const ERASE_SIZE: usize = <FlashStorage<'static> as NorFlash>::ERASE_SIZE;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
with(|flash| flash.erase(from, to))
}
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
with(|flash| flash.write(offset, bytes))
}
}
impl MultiwriteNorFlash for SharedFlash {}
+16 -2
View File
@@ -7,7 +7,11 @@ mod effect;
#[cfg(feature = "zigbee")]
mod effects_cluster;
mod encoder;
mod flash;
mod light;
// the crash test never confirms an image or switches slot, so those go unused
#[cfg_attr(feature = "ota-test-crash", allow(dead_code))]
mod ota;
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
mod scene;
mod status;
@@ -48,6 +52,17 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
esp_alloc::heap_allocator!(size: 32 * 1024);
// the one flash handle: the Zigbee stack keeps its state there and the
// firmware update code manages the A/B slots
flash::init(esp_storage::FlashStorage::new(peripherals.FLASH));
ota::log_boot();
// a stand-in for "the image works": long enough that a crash on startup
// is caught first
#[cfg(not(feature = "ota-test-crash"))]
spawner.spawn(ota::confirm_task().expect("spawn confirm_task"));
#[cfg(feature = "ota-test")]
spawner.spawn(ota::test_task().expect("spawn test_task"));
// the adapter derives its pulse timings from this frequency, so the same
// rate has to be handed to both calls
let rmt_freq = Rate::from_mhz(80);
@@ -80,7 +95,6 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
{
use embassy_embedded_hal::adapter::BlockingAsync;
use esp_radio::ieee802154::Ieee802154;
use esp_storage::FlashStorage;
use static_cell::StaticCell;
use zigbee_mac::esp::EspMlme;
@@ -90,7 +104,7 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
// the stack owns persistence: the information bases are restored here
// and written back whenever the stack changes them
let flash = BlockingAsync::new(FlashStorage::new(peripherals.FLASH));
let flash = BlockingAsync::new(flash::SharedFlash);
let storage = zigbee::storage::FlashStorage::new(flash, zigbee_stack::FLASH_RANGE).await;
let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
+164
View File
@@ -0,0 +1,164 @@
//! A/B firmware slots.
//!
//! The flash holds two app slots, `ota_0` and `ota_1`, and an `otadata`
//! partition that tells the bootloader which of them to run. An update is
//! written to the slot that is not running, which is then selected and marked
//! `New`. Once the new image has shown that it works it is marked `Valid`;
//! until then, a bootloader built with rollback support will go back to the
//! previous slot if the new one never confirms itself.
//!
//! This module only manages the slots. Getting an image into the idle slot is
//! the job of whatever delivers updates.
use core::convert::Infallible;
use embassy_time::Duration;
use embassy_time::Timer;
use esp_bootloader_esp_idf::ota::OtaImageState;
use esp_bootloader_esp_idf::ota_updater::OtaUpdater;
use esp_bootloader_esp_idf::partitions;
use esp_bootloader_esp_idf::partitions::AppPartitionSubType;
use esp_bootloader_esp_idf::partitions::Error;
use esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN;
use esp_bootloader_esp_idf::partitions::PartitionType;
use esp_hal::system::software_reset;
use crate::flash;
use crate::flash::FlashStorage;
/// Names a build in the log, so two images can be told apart while testing:
/// `FW_LABEL=B cargo build --release`.
const LABEL: &str = match option_env!("FW_LABEL") {
Some(label) => label,
None => "-",
};
/// How long a new image has to stay up before it is trusted.
pub const CONFIRM_AFTER: Duration = Duration::from_secs(20);
/// The slot the CPU is running from, read from the flash mapping, not from
/// what `otadata` says should be running.
fn running_slot(flash: &mut FlashStorage<'static>) -> Result<Option<AppPartitionSubType>, Error> {
let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN];
let table = partitions::read_partition_table(flash, &mut buffer)?;
Ok(table
.booted_partition()?
.and_then(|entry| match entry.partition_type() {
PartitionType::App(slot) => Some(slot),
_ => None,
}))
}
/// Logs which slot is running, which one the bootloader selected, and the
/// state of that image.
///
/// After a boot that followed an update, a state of `PendingVerify` means the
/// bootloader supports rollback, and `New` means it does not.
pub fn log_boot() {
let result = flash::with(|flash| {
let running = running_slot(flash)?;
let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN];
let mut updater = OtaUpdater::new(flash, &mut buffer)?;
Ok::<_, Error>((
running,
updater.selected_partition(),
updater.current_ota_state(),
))
});
match result {
Ok((running, selected, state)) => log::info!(
"firmware {LABEL}: running from {running:?}; bootloader selected {selected:?}, \
image state {state:?}"
),
Err(error) => log::warn!(
"firmware {LABEL}: no A/B slots ({error}); flash with the current partitions.csv"
),
}
}
/// Marks the running image `Valid`, if it is one the bootloader is still
/// waiting to hear about.
pub fn confirm_running_image() {
let result: Result<Option<OtaImageState>, Error> = flash::with(|flash| {
let running = running_slot(flash)?;
let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN];
let mut updater = OtaUpdater::new(flash, &mut buffer)?;
// an image flashed over USB has no selection and nothing to confirm
let Ok(selected) = updater.selected_partition() else {
return Ok(None);
};
// only the slot the bootloader chose has a state that means anything
if running != Some(selected) {
return Ok(None);
}
let Ok(state @ (OtaImageState::New | OtaImageState::PendingVerify)) =
updater.current_ota_state()
else {
return Ok(None);
};
updater.set_current_ota_state(OtaImageState::Valid)?;
Ok(Some(state))
});
match result {
Ok(Some(state)) => log::info!("firmware {LABEL}: image confirmed (it was {state:?})"),
Ok(None) => {}
Err(error) => log::warn!("firmware {LABEL}: could not confirm the image: {error}"),
}
}
/// Selects the slot that is not running, marks it `New`, and restarts into it.
///
/// Returns only if the switch could not be made.
// only the development test uses this until there is a source of updates
#[cfg_attr(not(feature = "ota-test"), allow(dead_code))]
pub fn switch_slot() -> Result<Infallible, Error> {
flash::with(|flash| {
let target = match running_slot(flash)? {
Some(AppPartitionSubType::Ota0) => AppPartitionSubType::Ota1,
Some(AppPartitionSubType::Ota1) => AppPartitionSubType::Ota0,
_ => return Err(Error::Invalid),
};
let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN];
let mut updater = OtaUpdater::new(flash, &mut buffer)?;
updater.ota_data()?.set_current_app_partition(target)?;
updater.set_current_ota_state(OtaImageState::New)?;
log::warn!("firmware {LABEL}: switching to {target:?}");
Ok(())
})?;
software_reset()
}
/// Confirms the running image once it has stayed up long enough to be trusted.
#[embassy_executor::task]
pub async fn confirm_task() {
Timer::after(CONFIRM_AFTER).await;
confirm_running_image();
}
/// Switches slot over and over, to exercise A/B switching without an update
/// source. Development only.
#[cfg(all(feature = "ota-test", not(feature = "ota-test-crash")))]
#[embassy_executor::task]
pub async fn test_task() {
// after the image has been confirmed
Timer::after(CONFIRM_AFTER + Duration::from_secs(10)).await;
// `Infallible` is uninhabited, so only the error is possible
let Err(error) = switch_slot();
log::error!("firmware {LABEL}: could not switch slot: {error}");
}
/// Resets without ever confirming the image, to see whether the bootloader
/// rolls an unconfirmed image back. Development only.
#[cfg(feature = "ota-test-crash")]
#[embassy_executor::task]
pub async fn test_task() {
Timer::after(Duration::from_secs(5)).await;
log::warn!("firmware {LABEL}: ota-test-crash: resetting without confirming this image");
software_reset()
}
+2 -2
View File
@@ -12,7 +12,6 @@ use embassy_time::Duration;
use embassy_time::Instant;
use embassy_time::Timer;
use embassy_time::with_timeout;
use esp_storage::FlashStorage;
use zigbee::aps::apsde::ApsdeSapConfirmStatus;
use zigbee::CurrentPowerMode;
use zigbee::CurrentPowerSourceLevel;
@@ -59,6 +58,7 @@ use zigbee_types::ShortAddress;
use crate::effects_cluster;
use crate::effects_cluster::EffectsServer;
use crate::flash::SharedFlash;
use crate::light;
use crate::status;
@@ -127,7 +127,7 @@ static COLOR_CONTROL: ColorControlServer<'static> =
ColorControlServer::new(370).with_reporting(&REPORTING);
static EFFECTS: EffectsServer = EffectsServer;
type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>;
type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<SharedFlash>>;
/// Cluster servers in the order they are offered a request. The responder is
/// last so an unclaimed cluster draws UNSUPPORTED_CLUSTER rather than silence