Files
smart_lights/src/main.rs
T
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

151 lines
5.8 KiB
Rust

#![no_std]
#![no_main]
mod config;
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
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;
mod strip;
#[cfg(feature = "zigbee")]
mod zigbee_stack;
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::gpio::Input;
use esp_hal::gpio::InputConfig;
use esp_hal::gpio::Level;
use esp_hal::gpio::Output;
use esp_hal::gpio::OutputConfig;
use esp_hal::gpio::Pull;
use esp_hal::rmt::Rmt;
use esp_hal::time::Rate;
use esp_hal::timer::timg::TimerGroup;
use esp_hal_smartled::WS2812B_TIMING;
use crate::config::STEPS_PER_BRIGHTNESS_UNIT;
use crate::encoder::EVENTS;
use crate::encoder::EncoderEvent;
use crate::strip::Strip;
esp_bootloader_esp_idf::esp_app_desc!();
/// Brightness units per detent.
const BRIGHTNESS_STEP: i16 = 8;
#[esp_rtos::main]
async fn main(spawner: embassy_executor::Spawner) -> ! {
esp_println::logger::init_logger_from_env();
let peripherals = esp_hal::init(esp_hal::Config::default());
let timg0 = TimerGroup::new(peripherals.TIMG0);
esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0);
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);
let rmt = Rmt::new(peripherals.RMT, rmt_freq)
.expect("init RMT")
.into_async();
// XIAO ESP32C6 pads: D2, D3, D4, D5. GPIO4/5/6 are JTAG and are not
// broken out on this board; GPIO3 and GPIO14 drive the antenna switch.
let strip = Strip::new(WS2812B_TIMING, rmt.channel0, peripherals.GPIO2, rmt_freq)
.expect("configure WS2812B adapter");
// the encoder's common pin is grounded, so both phases and the switch idle
// high and are driven low; the pull-ups make an open contact well defined.
// D10/D9/D8 sit directly under the 3V3 and GND pads, keeping the module's
// five wires on one side of the board.
let pull_up = InputConfig::default().with_pull(Pull::Up);
let encoder_a = Input::new(peripherals.GPIO18, pull_up); // D10, CLK
let encoder_b = Input::new(peripherals.GPIO20, pull_up); // D9, DT
let button = Input::new(peripherals.GPIO19, pull_up); // D8, SW
// on-board user LED, starting dark
let led = Output::new(peripherals.GPIO15, Level::High, OutputConfig::default());
spawner.spawn(status::heartbeat_task(led).expect("spawn heartbeat_task"));
spawner.spawn(light::render_task(strip).expect("spawn render_task"));
spawner.spawn(encoder::encoder_task(encoder_a, encoder_b).expect("spawn encoder_task"));
spawner.spawn(encoder::button_task(button).expect("spawn button_task"));
#[cfg(feature = "zigbee")]
{
use embassy_embedded_hal::adapter::BlockingAsync;
use esp_radio::ieee802154::Ieee802154;
use static_cell::StaticCell;
use zigbee_mac::esp::EspMlme;
use crate::zigbee_stack::Stack;
static STACK: StaticCell<Stack> = StaticCell::new();
// the stack owns persistence: the information bases are restored here
// and written back whenever the stack changes them
let flash = BlockingAsync::new(flash::SharedFlash);
let storage = zigbee::storage::FlashStorage::new(flash, zigbee_stack::FLASH_RANGE).await;
let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default());
log::info!("device IEEE address: {:#018x}", mac.ieee_address());
let stack: &'static Stack = STACK.init(Stack::new(
mac,
zigbee_stack::config(),
zigbee_stack::handler(),
storage,
));
spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task"));
spawner.spawn(zigbee_stack::lighting_task(stack).expect("spawn lighting_task"));
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
spawner.spawn(zigbee_stack::network_reset_task(stack).expect("spawn network_reset_task"));
spawner.spawn(zigbee_stack::pairing_status_task(stack).expect("spawn pairing_status_task"));
}
loop {
match EVENTS.receive().await {
EncoderEvent::Rotate(detents) => {
let steps = i16::from(detents) * STEPS_PER_BRIGHTNESS_UNIT as i16;
light::adjust_brightness(steps * BRIGHTNESS_STEP);
log::info!("rotate {detents:+} -> brightness {}", light::brightness());
}
EncoderEvent::Click => {
let (kelvin, _) = light::next_temperature();
log::info!("colour temperature {kelvin}K");
}
EncoderEvent::LongPress => {
let on = light::toggle();
log::info!("light {}", if on { "on" } else { "off" });
}
EncoderEvent::NetworkReset => {
log::warn!("button held: resetting the Zigbee network");
#[cfg(feature = "zigbee")]
zigbee_stack::request_network_reset();
}
}
}
}