5 Commits
Author SHA1 Message Date
Matt SpencerandCopilot c6b1537c8c tools: install a release into the idle firmware slot
release / release (push) Successful in 1m39s
Add tools/install_release.py, a host script that takes a release from Gitea
and puts it on a board over USB the way an update would: it downloads the
release's application image and checks it against the release checksums,
writes it to the slot that is not running, and rewrites otadata to select
that slot as a new image before resetting the board.

It reads the board's own partition table and slot selection rather than
assuming a layout, refuses a board without the A/B partition table, and
writes nothing until the image has been downloaded and verified. A dry run
shows what it would do.

This lets the A/B slots be tested with real releases while there is no
over-the-air update source. The README documents it, and the full image's
install steps now clear the slot selection, so that a board which had
switched to the second slot runs the image just written.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-29 01:16:37 +00:00
Matt Spencer ae5ed848ad Merge branch 'ab_update' into main
Bring the A/B firmware slots into main, so that releases contain them.
2026-11-29 01:14:32 +00:00
Matt SpencerandCopilot 35fe7c7bf9 build: pin the Rust nightly
The toolchain file said "nightly", so every build used whatever the newest
nightly was that day. The release workflow built the same commit as a
different binary to a local build (346,464 bytes against 358,928), and a new
nightly could break the build with no change to the project.

Pin the nightly that the project has been built and tested with, 2026-10-17
(rustc 5d8fec066). Moving it forward is now a deliberate change.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-29 01:14:32 +00:00
Matt Spencer 9e7d0d7d1f Merge branch 'main' into ab_update 2026-11-29 00:38:36 +00:00
Matt SpencerandCopilot 9ea25c3aab 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>
2026-11-29 00:32:40 +00:00
12 changed files with 633 additions and 11 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
target = "riscv32imac-unknown-none-elf"
[target.riscv32imac-unknown-none-elf]
runner = "espflash flash --monitor --partition-table partitions.csv"
runner = "espflash flash --monitor --partition-table partitions.csv --erase-parts otadata"
rustflags = [
"-C", "link-arg=-Tlinkall.x",
"-C", "force-frame-pointers",
Generated
+1
View File
@@ -1846,6 +1846,7 @@ dependencies = [
"embassy-futures",
"embassy-sync 0.8.0",
"embassy-time",
"embedded-storage",
"esp-alloc",
"esp-backtrace",
"esp-bootloader-esp-idf",
+7
View File
@@ -6,6 +6,12 @@ license = "MIT"
[features]
default = ["esp32c6", "zigbee"]
## Development only: switch to the other firmware slot 30 seconds after boot,
## and again after every boot, to exercise A/B slot switching without Zigbee.
ota-test = []
## Development only, with `ota-test`: never confirm the image, and reset 5
## seconds after boot, to see whether an unconfirmed image is rolled back.
ota-test-crash = ["ota-test"]
## Join a Zigbee network. Disable to bring up the local hardware on its own:
## the stack reboots the device when it cannot find its coordinator.
zigbee = ["dep:esp-radio", "dep:zigbee", "dep:zigbee-cluster-library", "dep:zigbee-mac", "dep:zigbee-types"]
@@ -30,6 +36,7 @@ esp-println = { version = "0.18", features = ["log-04"] }
esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"], optional = true }
esp-rtos = { version = "0.4", features = ["embassy", "log-04"] }
esp-storage = { version = "0.10", features = ["embedded-storage"] }
embedded-storage = "0.3"
embassy-executor = "0.10.0"
embassy-futures = "0.1"
+51 -2
View File
@@ -67,6 +67,29 @@ the partition table in `partitions.csv` and then starts the monitor. The Zigbee
network state is kept in the `storage` partition, so reflashing keeps the
light on its network.
### Firmware slots
The flash has two app slots, `ota_0` and `ota_1`, and an `otadata` partition
that tells the bootloader which to run, so a new image can be written to the
idle slot while the other keeps running. A USB flash always writes slot 0 and
clears `otadata`, which is why the runner passes `--erase-parts otadata`: without
it, a board that had switched to slot 1 would keep booting the old image.
Changing from the old single-slot partition table to this one needs one USB
flash. The network state is not touched.
The firmware logs which slot it is running from and the state of its image, and
marks a new image as valid once it has stayed up for 20 seconds. Switching
slots has no update source yet (see `TODO.md`). Two development features
exercise it without one: `ota-test` switches to the other slot 30 seconds after
every boot, and `ota-test-crash` resets without confirming the image. Set
`FW_LABEL` when building to tell images apart in the log, and write an image to
the idle slot with `espflash save-image` and `espflash write-bin`.
**There is no rollback yet.** The bootloader that `espflash` installs is not
built with rollback support, so an image that crashes after being selected will
keep being booted. Recover by flashing over USB.
To build without Zigbee, for example to test the strip and encoder on their own:
```sh
@@ -136,12 +159,38 @@ Each release has:
- `smart-light-<version>-full.bin`: bootloader, partition table and
application. Write it at address 0 with
`espflash write-bin 0x0 smart-light-<version>-full.bin`. It stops short of
the `storage` partition, so the light keeps its Zigbee network.
`espflash write-bin 0x0 smart-light-<version>-full.bin`, then clear the slot
selection with `espflash erase-parts otadata` so that the board runs it.
The image stops short of the `storage` partition, so the light keeps its
Zigbee network.
- `smart-light-<version>.bin`: the application alone, for a firmware slot.
- `smart-light-<version>.elf.gz`: the unstripped build, for decoding backtraces.
- `SHA256SUMS`.
### Installing a release over USB
Once a board has the A/B partition table, `tools/install_release.py` installs a
release into the slot that is not running and switches to it, without
touching the running image until the new one has been downloaded and checked:
```sh
tools/install_release.py # the latest release
tools/install_release.py 0.1.23 # a particular one
tools/install_release.py --dry-run # show what would be done, write nothing
```
It reads the board's partition table and slot selection, downloads the release's
application image and checks it against `SHA256SUMS`, writes it to the idle
slot, rewrites `otadata` to select that slot as a new image, and resets the
board. The firmware logs the version it is running, which slot it came from,
and when it confirms the image, so the log shows the update has worked. Run it
again and the board alternates to the other slot.
This is a way of testing the A/B slots with real releases, not an update
mechanism for lights in use: it needs the board on a USB cable. There is no
rollback yet (see `TODO.md`), so an image that does not start has to be fixed
by flashing over USB.
The workflow's `runs-on` must match a label of your Gitea runner. If the job's
own token is not allowed to create releases, add a token with write access to
the repository as a secret named `RELEASE_TOKEN`.
+26
View File
@@ -2,6 +2,32 @@
Things that are known to be open. None of these is being worked on yet.
## Firmware updates (OTA)
A/B firmware slots are in place and tested (see the README). What is missing:
- [ ] **Rollback.** The bootloader `espflash` installs is not built with
`CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE`: a newly selected image reports its
state as `New` rather than `PendingVerify`, and an image that resets without
confirming itself is booted again forever (checked with the `ota-test-crash`
build). Needs a bootloader built from ESP-IDF with rollback enabled and
flashed with `espflash --bootloader`. No ESP-IDF is installed here.
- [ ] **Zigbee OTA client.** zigbee-rs has no OTA Upgrade cluster (`0x0019`) and
no client-side cluster support. The generic client belongs on its own
upstream branch, writing through a trait; the flash writing and policy stay
here.
- [ ] **A real "image works" test.** The firmware currently confirms an image
after 20 seconds up. It should require that the light has rejoined its
Zigbee network, and mark the image invalid and switch back if it has not.
- [ ] **Hung images.** A panic hangs rather than resets, so a new image that
hangs would never reach the confirmation. Enable a watchdog.
- [ ] **Image tooling and Home Assistant.** A host tool to wrap the app image
in a Zigbee OTA file, and a ZHA `z2m_local` provider index for it. Choose a
version scheme and image type.
- [ ] **Flash writes versus the radio.** Writing an image while the radio is
active stalls the CPU for each sector erase; not yet measured against frame
loss.
## Reliability
- [ ] **The Zigbee stack forgets its network after a short coordinator outage.**
+8 -3
View File
@@ -1,7 +1,12 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x6000,
nvs, data, nvs, 0x9000, 0x4000,
# Which of the two app slots to boot, and whether the last update was confirmed.
otadata, data, ota, 0xd000, 0x2000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 0x3D0000,
# A/B firmware slots: an update is written to whichever one is not running.
# Each must start on a 64 KiB boundary.
ota_0, app, ota_0, 0x10000, 0x1E0000,
ota_1, app, ota_1, 0x1F0000, 0x1E0000,
# Zigbee persistence: the stack writes this region directly, so it must not
# overlap the app partition. Keep in sync with FLASH_RANGE in zigbee_stack.rs.
# overlap the app partitions. Keep in sync with FLASH_RANGE in zigbee_stack.rs.
storage, data, nvs, 0x3E0000, 0x20000,
1 # Name, Type, SubType, Offset, Size, Flags
2 nvs, data, nvs, 0x9000, 0x6000, nvs, data, nvs, 0x9000, 0x4000,
3 # Which of the two app slots to boot, and whether the last update was confirmed.
4 otadata, data, ota, 0xd000, 0x2000,
5 phy_init, data, phy, 0xf000, 0x1000,
6 factory, app, factory, 0x10000, 0x3D0000, # A/B firmware slots: an update is written to whichever one is not running.
7 # Each must start on a 64 KiB boundary.
8 ota_0, app, ota_0, 0x10000, 0x1E0000,
9 ota_1, app, ota_1, 0x1F0000, 0x1E0000,
10 # Zigbee persistence: the stack writes this region directly, so it must not
11 # overlap the app partition. Keep in sync with FLASH_RANGE in zigbee_stack.rs. # overlap the app partitions. Keep in sync with FLASH_RANGE in zigbee_stack.rs.
12 storage, data, nvs, 0x3E0000, 0x20000,
+3 -1
View File
@@ -1,4 +1,6 @@
[toolchain]
channel = "nightly"
# pinned, so that a release builds the same way every time: a floating
# "nightly" changes under the project. Move it forward deliberately.
channel = "nightly-2026-10-17"
components = ["rust-src", "rustfmt", "clippy"]
targets = ["riscv32imac-unknown-none-elf"]
+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;
@@ -49,6 +53,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);
@@ -81,7 +96,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;
@@ -91,7 +105,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
+275
View File
@@ -0,0 +1,275 @@
#!/usr/bin/env python3
"""Install a release into the idle firmware slot of a connected board, and
switch the board to it.
tools/install_release.py # the latest release
tools/install_release.py 0.1.23 # a particular one
tools/install_release.py --dry-run # only show what would be done
The release's application image is downloaded, checked against the release's
checksums, and written to the slot that is not running. The board's `otadata`
partition is then rewritten to select that slot, marked as a new image, and the
board is reset. The firmware logs the version it is running and which slot it
came from, and confirms the new image once it has stayed up for a while.
Needs `espflash` and a board with the A/B partition table, connected over USB.
Nothing is written to the board until the image has been downloaded and checked.
"""
import argparse
import hashlib
import json
import shutil
import struct
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
import zlib
from pathlib import Path
SERVER = "https://gitea.m5p3nc3r.co.uk"
REPO = "m5p3nc3r/smart_lights"
PARTITION_TABLE_OFFSET = 0x8000
PARTITION_TABLE_SIZE = 0xC00
# partition types and subtypes, as the bootloader numbers them
TYPE_APP, TYPE_DATA = 0x00, 0x01
SUBTYPE_OTA_FIRST, SUBTYPE_OTA_LAST = 0x10, 0x1F
SUBTYPE_OTA_DATA = 0x00
# otadata is two sectors, each holding one 32-byte selection record
SECTOR = 0x1000
UNINITIALISED = 0xFFFFFFFF
STATE_NEW = 0x0
STATE_NAMES = {
0x0: "New",
0x1: "PendingVerify",
0x2: "Valid",
0x3: "Invalid",
0x4: "Aborted",
UNINITIALISED: "Undefined",
}
APP_IMAGE_MAGIC = 0xE9
class Error(Exception):
"""Something the user needs to know about, without a traceback."""
def espflash(args, port):
command = ["espflash", *args]
if port:
command += ["--port", port]
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
raise Error(f"`{' '.join(command)}` failed:\n{result.stdout}{result.stderr}")
def read_flash(offset, size, port, directory):
path = directory / f"read-{offset:#x}.bin"
espflash(["read-flash", f"{offset:#x}", f"{size:#x}", str(path)], port)
return path.read_bytes()
def write_flash(offset, data, port, directory):
path = directory / f"write-{offset:#x}.bin"
path.write_bytes(data)
espflash(["write-bin", f"{offset:#x}", str(path)], port)
def parse_partition_table(data):
"""Maps each partition's label to (type, subtype, offset, size)."""
partitions = {}
for start in range(0, len(data) - 31, 32):
entry = data[start : start + 32]
if entry[:2] != b"\xaa\x50":
break # the end marker, or the table's checksum entry
kind, subtype, offset, size = struct.unpack_from("<BBII", entry, 2)
label = entry[12:28].split(b"\0")[0].decode(errors="replace")
partitions[label] = (kind, subtype, offset, size)
return partitions
def find_layout(partitions):
otadata = next(
(
p
for p in partitions.values()
if p[0] == TYPE_DATA and p[1] == SUBTYPE_OTA_DATA
),
None,
)
slots = sorted(
(
p
for p in partitions.values()
if p[0] == TYPE_APP and SUBTYPE_OTA_FIRST <= p[1] <= SUBTYPE_OTA_LAST
),
key=lambda p: p[1],
)
if otadata is None or len(slots) < 2:
raise Error(
"the board does not have the A/B partition table (an otadata partition "
"and two OTA app slots). Flash a release's full image first; see the README."
)
return otadata, slots
def checksum(sequence):
"""The checksum the bootloader keeps with a selection record: CRC-32 of the
sequence number alone, started from all ones."""
return zlib.crc32(struct.pack("<I", sequence), 0xFFFFFFFF)
def parse_record(sector):
"""The (sequence, state) of a selection record, or None if there is no valid
one in the sector."""
sequence, = struct.unpack_from("<I", sector, 0)
state, stored = struct.unpack_from("<II", sector, 24)
if sequence == UNINITIALISED or state not in STATE_NAMES:
return None
return (sequence, state) if stored == checksum(sequence) else None
def current_selection(otadata, slot_count):
"""Returns (slot, state, record index, sequence) for the slot the bootloader
will run, or None if nothing has been selected yet."""
records = [
parse_record(otadata[i * SECTOR : (i + 1) * SECTOR]) for i in range(2)
]
valid = [(record[0], i, record[1]) for i, record in enumerate(records) if record]
if not valid:
return None
sequence, index, state = max(valid)
return ((sequence - 1) % slot_count, state, index, sequence)
def new_record(sequence):
"""A selection record for a new image, padded to a whole sector."""
record = struct.pack("<I20sII", sequence, b"\xff" * 20, STATE_NEW, checksum(sequence))
return record + b"\xff" * (SECTOR - len(record))
def next_sequence(selection, target, slot_count):
"""The lowest sequence number above the current one that selects `target`.
The slot is the sequence number, minus one, modulo the number of slots."""
sequence = (selection[3] if selection else 0) + 1
while (sequence - 1) % slot_count != target:
sequence += 1
return sequence
def fetch(url):
try:
with urllib.request.urlopen(url, timeout=60) as response:
return response.read()
except urllib.error.URLError as error:
raise Error(f"could not fetch {url}: {error}") from error
def latest_version():
release = json.loads(fetch(f"{SERVER}/api/v1/repos/{REPO}/releases/latest"))
return release["tag_name"].lstrip("v")
def download_image(version, slot_size):
base = f"{SERVER}/{REPO}/releases/download/v{version}"
name = f"smart-light-{version}.bin"
image = fetch(f"{base}/{name}")
sums = fetch(f"{base}/SHA256SUMS").decode()
expected = {}
for line in sums.splitlines():
if line.strip():
digest, filename = line.split(None, 1)
expected[filename.strip().lstrip("*")] = digest
if name not in expected:
raise Error(f"{name} is not in the release's SHA256SUMS")
if hashlib.sha256(image).hexdigest() != expected[name]:
raise Error(f"{name} does not match the release's checksum")
if image[0] != APP_IMAGE_MAGIC:
raise Error(f"{name} is not an application image")
if len(image) > slot_size:
raise Error(f"{name} is {len(image)} bytes and the slot holds {slot_size}")
return image
def describe(selection):
if selection is None:
return "nothing selected yet (the bootloader runs the first slot)"
slot, state, _, sequence = selection
return f"slot {slot} (sequence {sequence}), image state {STATE_NAMES[state]}"
def main():
parser = argparse.ArgumentParser(
description="Install a release into the idle firmware slot and switch to it."
)
parser.add_argument(
"version", nargs="?", default="latest", help="e.g. 0.1.23 (default: the latest)"
)
parser.add_argument("--port", help="serial port of the board, if there are several")
parser.add_argument(
"--slot", type=int, help="write to this slot instead of the idle one"
)
parser.add_argument(
"--dry-run", action="store_true", help="show what would be done; write nothing"
)
parser.add_argument(
"--no-reset", action="store_true", help="do not reset the board afterwards"
)
args = parser.parse_args()
if shutil.which("espflash") is None:
raise Error("espflash is not installed (cargo install espflash)")
with tempfile.TemporaryDirectory() as temporary:
directory = Path(temporary)
print("Reading the board's partition table and slot selection...")
table = read_flash(PARTITION_TABLE_OFFSET, PARTITION_TABLE_SIZE, args.port, directory)
otadata_partition, slots = find_layout(parse_partition_table(table))
otadata_offset = otadata_partition[2]
otadata = read_flash(otadata_offset, 2 * SECTOR, args.port, directory)
selection = current_selection(otadata, len(slots))
running = selection[0] if selection else 0
target = args.slot if args.slot is not None else 1 - running
if not 0 <= target < len(slots):
raise Error(f"there is no slot {target}")
print(f" the board will run {describe(selection)}")
print(f" the image goes into slot {target} at {slots[target][2]:#x}")
version = latest_version() if args.version == "latest" else args.version.lstrip("v")
print(f"Downloading release {version}...")
image = download_image(version, slots[target][3])
print(f" {len(image)} bytes, checksum verified")
if args.dry_run:
print("Dry run: nothing written.")
return
print(f"Writing slot {target}...")
write_flash(slots[target][2], image, args.port, directory)
sequence = next_sequence(selection, target, len(slots))
sector = 0 if selection is None else 1 - selection[2]
print(f"Selecting slot {target} (sequence {sequence}, record {sector})...")
write_flash(otadata_offset + sector * SECTOR, new_record(sequence), args.port, directory)
if args.no_reset:
print("Done. Reset the board to run it.")
else:
espflash(["reset"], args.port)
print(f"Done. The board is restarting into {version}.")
if __name__ == "__main__":
try:
main()
except Error as error:
sys.exit(f"error: {error}")