feat: bootstrap esp32-c6 embassy lighting controller

This commit is contained in:
Matt Spencer committed 2026-10-17 15:21:58 +01:00
commit bb81182daa
13 files changed
+2926

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
[build]
target = "riscv32imac-unknown-none-elf"
[target.riscv32imac-unknown-none-elf]
runner = "espflash flash --monitor"
rustflags = [
"-C", "link-arg=-Tlinkall.x",
"-C", "force-frame-pointers",
]
[env]
ESP_LOG = "info"
[unstable]
build-std = ["core", "alloc"]
+2
View File
@@ -0,0 +1,2 @@
/target
/vendor/zigbee-rs/target
+4
View File
@@ -0,0 +1,4 @@
[submodule "vendor/zigbee-rs"]
path = vendor/zigbee-rs
url = https://github.com/zigbee-rs/zigbee-rs.git
branch = smart-light
Generated
+2177
View File
File diff suppressed because it is too large. Load diff
+53
View File
@@ -0,0 +1,53 @@
[package]
name = "smart-light"
version = "0.1.0"
edition = "2024"
[features]
default = ["esp32c6"]
esp32c6 = [
"esp-alloc/esp32c6",
"esp-backtrace/esp32c6",
"esp-bootloader-esp-idf/esp32c6",
"esp-hal/esp32c6",
"esp-println/esp32c6",
"esp-radio/esp32c6",
"esp-rtos/esp32c6",
"esp-storage/esp32c6",
"zigbee-mac/esp32c6",
]
[dependencies]
esp-alloc = "0.10.0"
esp-backtrace = { version = "0.19.0", features = ["panic-handler", "println"] }
esp-bootloader-esp-idf = "0.5.0"
esp-hal = { version = "1.1.0", features = ["log-04", "unstable"] }
esp-println = { version = "0.17.0", features = ["log-04"] }
esp-radio = { version = "1.0.0-beta.0", features = ["ieee802154", "unstable"] }
esp-rtos = { version = "0.3.0", features = ["embassy", "log-04"] }
esp-storage = "0.9.0"
embassy-executor = "0.10.0"
embassy-futures = "0.1"
embassy-sync = "0.8"
embassy-time = "0.5.0"
embassy-embedded-hal = "0.5.0"
static_cell = "2.1"
log = "0.4"
# vendored upstream: the lighting cluster is not implemented there yet, so the
# path dependency lets us add it in-tree and upstream it later
zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"] }
zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library" }
zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac" }
zigbee-types = { path = "vendor/zigbee-rs/zigbee-types" }
[profile.release]
debug = true
debug-assertions = false
lto = "fat"
codegen-units = 1
opt-level = "s"
[profile.dev]
opt-level = "s"
+4
View File
@@ -0,0 +1,4 @@
[toolchain]
channel = "nightly"
components = ["rust-src", "rustfmt", "clippy"]
targets = ["riscv32imac-unknown-none-elf"]
+22
View File
@@ -0,0 +1,22 @@
//! Board wiring and strip geometry.
//!
//! Everything that changes when the hardware changes lives here.
/// Number of WS2812B pixels on the strip.
pub const LED_COUNT: usize = 60;
/// Ceiling on the duty cycle applied to every channel, as a fraction of 255.
///
/// Keeps the supply current within what the dev board's regulator can source
/// when every pixel is driven white.
pub const MAX_DUTY: u8 = 200;
/// Rotary encoder detents per full revolution, used to scale a turn into a
/// brightness step.
pub const STEPS_PER_BRIGHTNESS_UNIT: i32 = 1;
/// Hold time that separates a click from a long press.
pub const LONG_PRESS_MS: u64 = 600;
/// Contact settle time for the encoder push button.
pub const DEBOUNCE_MS: u64 = 15;
+107
View File
@@ -0,0 +1,107 @@
//! Interrupt-driven rotary encoder with a push button.
//!
//! Both tasks park on GPIO edge interrupts; nothing here polls. Quadrature is
//! decoded from the transition between the previous and current A/B pair, so a
//! bounce that returns to the previous state cancels itself out instead of
//! registering a step.
use embassy_futures::select::Either;
use embassy_futures::select::select;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel;
use embassy_time::Duration;
use embassy_time::Timer;
use embassy_time::with_timeout;
use esp_hal::gpio::Input;
use crate::config::DEBOUNCE_MS;
use crate::config::LONG_PRESS_MS;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum EncoderEvent {
/// One detent; positive is clockwise.
Rotate(i8),
Click,
LongPress,
}
/// Depth 8 absorbs a fast spin while the consumer is mid-frame; overflowing
/// drops the oldest step, which is preferable to blocking the interrupt task.
pub static EVENTS: Channel<CriticalSectionRawMutex, EncoderEvent, 8> = Channel::new();
/// Valid quadrature transitions, indexed by `(previous << 2) | current` where
/// each pair is `(a << 1) | b`. Zero marks either no movement or an illegal
/// jump of two states, which means a transition was missed.
#[rustfmt::skip]
const TRANSITIONS: [i8; 16] = [
0, -1, 1, 0,
1, 0, 0, -1,
-1, 0, 0, 1,
0, 1, -1, 0,
];
#[embassy_executor::task]
pub async fn encoder_task(mut a: Input<'static>, mut b: Input<'static>) {
let mut previous = state(&a, &b);
// a full detent is four quadrature transitions; only whole detents are
// reported so a resting-point jitter never moves the light
let mut substeps: i8 = 0;
loop {
match select(a.wait_for_any_edge(), b.wait_for_any_edge()).await {
Either::First(()) | Either::Second(()) => {}
}
let current = state(&a, &b);
if current == previous {
continue;
}
let delta = TRANSITIONS[usize::from((previous << 2) | current)];
previous = current;
if delta == 0 {
continue;
}
substeps += delta;
if substeps.abs() >= 4 {
let detents = substeps / 4;
substeps -= detents * 4;
// full is fine: a dropped step during a spin is invisible
let _ = EVENTS.try_send(EncoderEvent::Rotate(detents));
}
}
}
#[embassy_executor::task]
pub async fn button_task(mut button: Input<'static>) {
loop {
// active low: the switch shorts to ground when pressed
button.wait_for_falling_edge().await;
Timer::after(Duration::from_millis(DEBOUNCE_MS)).await;
if button.is_high() {
continue;
}
let long_press = with_timeout(
Duration::from_millis(LONG_PRESS_MS),
button.wait_for_rising_edge(),
)
.await
.is_err();
if long_press {
let _ = EVENTS.try_send(EncoderEvent::LongPress);
// swallow the release so it is not read as a second press
button.wait_for_rising_edge().await;
} else {
let _ = EVENTS.try_send(EncoderEvent::Click);
}
Timer::after(Duration::from_millis(DEBOUNCE_MS)).await;
}
}
fn state(a: &Input<'static>, b: &Input<'static>) -> usize {
usize::from(a.is_high()) << 1 | usize::from(b.is_high())
}
+129
View File
@@ -0,0 +1,129 @@
//! Shared light state and the task that pushes it to the strip.
//!
//! The state is a few atomics plus a wake signal rather than a mutex, so the
//! encoder task and the Zigbee stack can both touch it without either waiting
//! on a frame to finish rendering.
use core::sync::atomic::AtomicBool;
use core::sync::atomic::AtomicU8;
use core::sync::atomic::AtomicU16;
use core::sync::atomic::Ordering;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use crate::config::LED_COUNT;
use crate::config::MAX_DUTY;
use crate::ws2812::Rgb;
use crate::ws2812::Ws2812;
/// What a turn of the encoder adjusts.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
Brightness,
Hue,
}
static ON: AtomicBool = AtomicBool::new(false);
static BRIGHTNESS: AtomicU8 = AtomicU8::new(128);
static HUE: AtomicU16 = AtomicU16::new(0);
static HUE_MODE: AtomicBool = AtomicBool::new(false);
static DIRTY: Signal<CriticalSectionRawMutex, ()> = Signal::new();
pub fn is_on() -> bool {
ON.load(Ordering::Relaxed)
}
pub fn set_on(on: bool) {
ON.store(on, Ordering::Relaxed);
DIRTY.signal(());
}
pub fn toggle() -> bool {
let on = !is_on();
set_on(on);
on
}
pub fn brightness() -> u8 {
BRIGHTNESS.load(Ordering::Relaxed)
}
/// Clamps rather than wraps: running past full should stay at full instead of
/// dropping the light to near-black.
pub fn adjust_brightness(delta: i16) {
let level = (i16::from(brightness()) + delta).clamp(1, 254) as u8;
BRIGHTNESS.store(level, Ordering::Relaxed);
DIRTY.signal(());
}
pub fn hue() -> u16 {
HUE.load(Ordering::Relaxed)
}
/// Hue is a circle, so this one wraps.
pub fn adjust_hue(delta: i16) {
let hue = (i32::from(hue()) + i32::from(delta)).rem_euclid(360) as u16;
HUE.store(hue, Ordering::Relaxed);
DIRTY.signal(());
}
pub fn mode() -> Mode {
if HUE_MODE.load(Ordering::Relaxed) {
Mode::Hue
} else {
Mode::Brightness
}
}
pub fn toggle_mode() -> Mode {
HUE_MODE.fetch_xor(true, Ordering::Relaxed);
mode()
}
#[embassy_executor::task]
pub async fn render_task(mut strip: Ws2812<'static>) {
let mut frame = [Rgb::BLACK; LED_COUNT];
loop {
let colour = if is_on() {
let level = (u16::from(brightness()) * u16::from(MAX_DUTY) / 255) as u8;
hsv_to_rgb(hue(), 255, 255).scaled(level)
} else {
Rgb::BLACK
};
frame.fill(colour);
if let Err(e) = strip.write(&frame).await {
log::warn!("strip write failed: {e:?}");
}
DIRTY.wait().await;
}
}
/// `hue` in degrees, `saturation` and `value` as 0..=255.
fn hsv_to_rgb(hue: u16, saturation: u8, value: u8) -> Rgb {
if saturation == 0 {
return Rgb::new(value, value, value);
}
let sector = u32::from(hue % 360) / 60;
let offset = u32::from(hue % 360) % 60;
let v = u32::from(value);
let s = u32::from(saturation);
let p = (v * (255 - s) / 255) as u8;
let q = (v * (255 - s * offset / 60) / 255) as u8;
let t = (v * (255 - s * (60 - offset) / 60) / 255) as u8;
let v = value;
match sector {
0 => Rgb::new(v, t, p),
1 => Rgb::new(q, v, p),
2 => Rgb::new(p, v, t),
3 => Rgb::new(p, q, v),
4 => Rgb::new(t, p, v),
_ => Rgb::new(v, p, q),
}
}
+116
View File
@@ -0,0 +1,116 @@
#![no_std]
#![no_main]
mod config;
mod encoder;
mod light;
mod ws2812;
mod zigbee_stack;
use embassy_embedded_hal::adapter::BlockingAsync;
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::gpio::Input;
use esp_hal::gpio::InputConfig;
use esp_hal::gpio::Pull;
use esp_hal::interrupt::software::SoftwareInterruptControl;
use esp_hal::rmt::Rmt;
use esp_hal::rmt::TxChannelConfig;
use esp_hal::rmt::TxChannelCreator;
use esp_hal::time::Rate;
use esp_hal::timer::timg::TimerGroup;
use esp_radio::ieee802154::Ieee802154;
use esp_storage::FlashStorage;
use static_cell::StaticCell;
use zigbee_mac::esp::EspMlme;
use crate::config::STEPS_PER_BRIGHTNESS_UNIT;
use crate::encoder::EVENTS;
use crate::encoder::EncoderEvent;
use crate::light::Mode;
use crate::ws2812::Ws2812;
use crate::zigbee_stack::Stack;
esp_bootloader_esp_idf::esp_app_desc!();
static STACK: StaticCell<Stack> = StaticCell::new();
/// Brightness units per detent.
const BRIGHTNESS_STEP: i16 = 8;
/// Degrees of hue per detent.
const HUE_STEP: i16 = 6;
#[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 sw_int = SoftwareInterruptControl::new(peripherals.SW_INTERRUPT);
let timg0 = TimerGroup::new(peripherals.TIMG0);
esp_rtos::start(timg0.timer0, sw_int.software_interrupt0);
esp_alloc::heap_allocator!(size: 32 * 1024);
// 80 MHz with a divider of 1 gives the 12.5 ns tick the WS2812B bit
// timings in `ws2812` are expressed in
let rmt = Rmt::new(peripherals.RMT, Rate::from_mhz(80))
.expect("init RMT")
.into_async();
let rmt_channel = rmt
.channel0
.configure_tx(&TxChannelConfig::default().with_clk_divider(1))
.expect("configure RMT TX")
.with_pin(peripherals.GPIO2);
let strip = Ws2812::new(rmt_channel);
// 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
let pull_up = InputConfig::default().with_pull(Pull::Up);
let encoder_a = Input::new(peripherals.GPIO4, pull_up);
let encoder_b = Input::new(peripherals.GPIO5, pull_up);
let button = Input::new(peripherals.GPIO6, pull_up);
// 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 storage = zigbee::storage::init_with_flash(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(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"));
spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task"));
spawner.spawn(zigbee_stack::on_off_task().expect("spawn on_off_task"));
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
loop {
match EVENTS.receive().await {
EncoderEvent::Rotate(detents) => {
let steps = i16::from(detents) * STEPS_PER_BRIGHTNESS_UNIT as i16;
match light::mode() {
Mode::Brightness => light::adjust_brightness(steps * BRIGHTNESS_STEP),
Mode::Hue => light::adjust_hue(steps * HUE_STEP),
}
}
EncoderEvent::Click => {
let on = light::toggle();
log::info!("light {}", if on { "on" } else { "off" });
}
EncoderEvent::LongPress => {
let mode = light::toggle_mode();
log::info!("encoder now adjusts {mode:?}");
}
}
}
}
+85
View File
@@ -0,0 +1,85 @@
//! WS2812B driver over the RMT peripheral.
//!
//! The RMT clock is divided to 12.5 ns per tick, so each of the 24 colour bits
//! becomes one `PulseCode` whose high and low durations encode a 0 or a 1.
use esp_hal::Async;
use esp_hal::gpio::Level;
use esp_hal::rmt::Channel;
use esp_hal::rmt::PulseCode;
use esp_hal::rmt::Tx;
use crate::config::LED_COUNT;
/// Bit timings in RMT ticks at 80 MHz with a divider of 1 (12.5 ns/tick).
const T0H: u16 = 32; // 0.40 us
const T0L: u16 = 68; // 0.85 us
const T1H: u16 = 64; // 0.80 us
const T1L: u16 = 36; // 0.45 us
/// Pulse codes for a whole frame, plus the terminating end marker.
const PULSE_COUNT: usize = LED_COUNT * 24 + 1;
/// A colour in the order the application thinks about it; the wire order
/// (green first) is applied when encoding.
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
pub struct Rgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Rgb {
pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b }
}
/// Scales every channel by `level / 255`, rounding so that a non-zero
/// channel at a non-zero level never collapses to off.
#[must_use]
pub const fn scaled(self, level: u8) -> Self {
const fn scale(channel: u8, level: u8) -> u8 {
((channel as u16 * level as u16 + 127) / 255) as u8
}
Self {
r: scale(self.r, level),
g: scale(self.g, level),
b: scale(self.b, level),
}
}
}
pub struct Ws2812<'d> {
channel: Channel<'d, Async, Tx>,
pulses: [PulseCode; PULSE_COUNT],
}
impl<'d> Ws2812<'d> {
pub fn new(channel: Channel<'d, Async, Tx>) -> Self {
let mut pulses = [PulseCode::default(); PULSE_COUNT];
pulses[PULSE_COUNT - 1] = PulseCode::end_marker();
Self { channel, pulses }
}
/// Encodes `pixels` and clocks the frame out.
///
/// A frame shorter than the strip leaves the remaining pixels dark.
pub async fn write(&mut self, pixels: &[Rgb]) -> Result<(), esp_hal::rmt::Error> {
for (led, slot) in self.pulses[..LED_COUNT * 24].chunks_exact_mut(24).enumerate() {
let colour = pixels.get(led).copied().unwrap_or(Rgb::BLACK);
// WS2812B latches GRB, most significant bit first
let word = u32::from(colour.g) << 16 | u32::from(colour.r) << 8 | u32::from(colour.b);
for (bit, code) in slot.iter_mut().enumerate() {
*code = if word & (1 << (23 - bit)) != 0 {
PulseCode::new(Level::High, T1H, Level::Low, T1L)
} else {
PulseCode::new(Level::High, T0H, Level::Low, T0L)
};
}
}
self.channel.transmit(&self.pulses).await
}
}
+211
View File
@@ -0,0 +1,211 @@
//! Zigbee end device: commissioning, the stack task, and the clusters served.
//!
//! The device is announced as an On/Off Light. Level Control and Color Control
//! (ZCL chapter 5) are deliberately absent: the vendored upstream does not
//! implement the lighting clusters yet, so for now brightness and hue are
//! local-only and the network sees on/off.
use core::ops::Range;
use embassy_embedded_hal::adapter::BlockingAsync;
use embassy_time::Duration;
use embassy_time::Timer;
use esp_storage::FlashStorage;
use zigbee::CurrentPowerMode;
use zigbee::CurrentPowerSourceLevel;
use zigbee::DeviceConfig;
use zigbee::LogicalType;
use zigbee::NetworkConfig;
use zigbee::PowerSource;
use zigbee::TimingConfig;
use zigbee::config::StackConfig;
use zigbee::nwk::nib::CapabilityInformation;
use zigbee::zdo::config::DiscoveryType;
use zigbee::zdo::descriptor::DeviceDescriptorConfig;
use zigbee::zdo::descriptor::EndpointDescriptor;
use zigbee::zdo::descriptor::NodeDescriptorConfig;
use zigbee::zdo::descriptor::PowerDescriptorConfig;
use zigbee_cluster_library::clusters::general::basic;
use zigbee_cluster_library::clusters::general::basic::BasicServer;
use zigbee_cluster_library::clusters::general::identify;
use zigbee_cluster_library::clusters::general::identify::IdentifyServer;
use zigbee_cluster_library::clusters::general::on_off;
use zigbee_cluster_library::clusters::general::on_off::OnOffServer;
use zigbee_cluster_library::profile;
use zigbee_cluster_library::reporting::ReportingTable;
use zigbee_cluster_library::server::UnsupportedClusterResponder;
use zigbee_mac::esp::EspMlme;
use zigbee_types::IeeeAddress;
use crate::light;
/// Flash region reserved for Zigbee persistence.
///
/// MUST match the partition table: erase-sector aligned (4 KiB) and at least
/// two sectors so sequential-storage has a spare for garbage collection. The
/// address assumes the 4 MiB flash of the ESP32-C6-DevKitC-1.
pub const FLASH_RANGE: Range<u32> = 0x3f_0000..0x3f_4000;
/// Extended PAN ID of the network to join.
///
/// Placeholder: replace with the Extended PAN ID of your own coordinator.
const EXTENDED_PAN_ID: u64 = 0xabcd_ef01_2345_6789;
/// Channel to scan on; must match the coordinator.
const CHANNEL: u8 = 11;
/// Scan duration exponent (beacon order).
const SCAN_DURATION: u8 = 5;
/// The application endpoint this light is served on.
const LIGHT_ENDPOINT: u8 = 1;
/// Mains powered and always listening: allocate address (bit 7) and
/// rx-on-when-idle (bit 3), so the coordinator can push commands at any time
/// rather than waiting for a poll.
const CAPABILITY: u8 = 0x8e;
static INPUT_CLUSTERS: [u16; 3] = [
basic::CLUSTER_ID,
identify::CLUSTER_ID,
on_off::CLUSTER_ID,
];
static OUTPUT_CLUSTERS: [u16; 0] = [];
static ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor {
endpoint: LIGHT_ENDPOINT,
profile_id: profile::HOME_AUTOMATION,
// HA device id 0x0100: On/Off Light. Becomes 0x0101 (Dimmable Light) once
// Level Control is implemented.
device_id: 0x0100,
device_version: 1,
input_clusters: &INPUT_CLUSTERS,
output_clusters: &OUTPUT_CLUSTERS,
}];
static BASIC: BasicServer = BasicServer {
zcl_version: 8,
application_version: 1,
stack_version: 0,
hw_version: 1,
manufacturer_name: "smart-light",
model_identifier: "smart-light.ws2812",
// 0x01: mains (single phase)
power_source: 0x01,
};
pub static IDENTIFY: IdentifyServer = IdentifyServer::new();
static REPORTING: ReportingTable<4> = ReportingTable::new();
static ON_OFF: OnOffServer = OnOffServer::new().with_reporting(&REPORTING);
type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>;
/// Cluster servers in the order they are offered a request. The responder is
/// last so an unclaimed cluster draws UNSUPPORTED_CLUSTER rather than silence
/// (ZCL 2.5.12.2).
type Handler = (
BasicServer<'static>,
&'static IdentifyServer,
&'static OnOffServer<'static>,
UnsupportedClusterResponder<'static>,
);
pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>;
pub fn handler() -> Handler {
(
BASIC,
&IDENTIFY,
&ON_OFF,
UnsupportedClusterResponder::new(&INPUT_CLUSTERS),
)
}
pub fn config() -> StackConfig<'static> {
StackConfig::new(
NetworkConfig {
extended_pan_id: IeeeAddress(EXTENDED_PAN_ID),
channels: CHANNEL..CHANNEL + 1,
scan_duration: SCAN_DURATION,
},
DeviceConfig {
logical_type: LogicalType::EndDevice,
capability_information: CapabilityInformation(CAPABILITY),
discovery_type: DiscoveryType::default(),
tc_link_key_exchange: true,
},
TimingConfig::default(),
DeviceDescriptorConfig {
node: NodeDescriptorConfig {
// bit 3: 2400 MHz band
frequency_band: 0x08,
manufacturer_code: 0x1037,
maximum_buffer_size: 80,
maximum_incoming_transfer_size: 128,
server_mask: 0,
maximum_outgoing_transfer_size: 128,
descriptor_capability_field: 0,
..NodeDescriptorConfig::default()
},
power: PowerDescriptorConfig {
current_power_mode: CurrentPowerMode::Synchronized,
available_power_sources: &[PowerSource::ConstantMainPower],
current_power_source: PowerSource::ConstantMainPower,
current_power_source_level: CurrentPowerSourceLevel::Full,
},
endpoints: &ENDPOINTS,
},
)
}
/// Drives the stack: commissioning, discovery, cluster reads and writes, the
/// parent link, and persistence.
#[embassy_executor::task]
pub async fn stack_task(stack: &'static Stack) {
// returns only once no rejoin can get us back: the network is gone or our
// keys are stale, so drop it and re-commission from scratch
let outcome = stack.run(embassy_time::Delay).await;
log::warn!("off the network ({outcome:?}), forgetting it and rebooting");
stack.forget_network().await;
esp_hal::system::software_reset();
}
/// Mirrors the On/Off attribute onto the strip, both ways.
///
/// The cluster server writes its attribute from the APS receive path without
/// any notification hook, so this samples it. The reverse direction keeps the
/// attribute truthful after a local button press.
#[embassy_executor::task]
pub async fn on_off_task() {
let mut last = ON_OFF.on_off();
loop {
Timer::after(Duration::from_millis(50)).await;
let remote = ON_OFF.on_off();
if remote != last {
last = remote;
light::set_on(remote);
continue;
}
let local = light::is_on();
if local != last {
last = local;
ON_OFF.set_on_off(local);
}
}
}
/// Counts the Identify state down once a second (ZCL 3.5.2.2.1).
#[embassy_executor::task]
pub async fn identify_task() {
loop {
Timer::after(Duration::from_secs(1)).await;
if IDENTIFY.is_identifying() {
let remaining = IDENTIFY.tick(1);
log::info!("identifying ({remaining}s remaining)");
}
}
}
Vendored Submodule
+1
Submodule vendor/zigbee-rs added at c2f2436e76.