feat: add Zigbee-controlled smart light

This commit is contained in:
Matt Spencer committed 2026-11-15 23:22:20 +00:00
1 parent 9793bc62af
commit 1aa6ba3c5f
10 files changed
+236 -98

No files matched your search

+1
View File
@@ -1,2 +1,3 @@
/target /target
/vendor/zigbee-rs/target /vendor/zigbee-rs/target
/nda
+2 -2
View File
@@ -1,4 +1,4 @@
[submodule "vendor/zigbee-rs"] [submodule "vendor/zigbee-rs"]
path = vendor/zigbee-rs path = vendor/zigbee-rs
url = https://github.com/zigbee-rs/zigbee-rs.git url = git@github.com:m5p3nc3r/zigbee-rs.git
branch = smart-light branch = feature/light-control
Generated
+25 -1
View File
@@ -382,6 +382,26 @@ dependencies = [
"syn 3.0.9", "syn 3.0.9",
] ]
[[package]]
name = "defmt-or-log"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be59789d306cc1a082f53bb7c24c270d7e6078c00b7550a718219a7090156d97"
dependencies = [
"defmt-or-log-macros",
]
[[package]]
name = "defmt-or-log-macros"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d675dd299edbb7c8e01d4e9f520a0d8f22a8fe4af812c211c3fad5e9dcf41763"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "defmt-parser" name = "defmt-parser"
version = "1.1.0" version = "1.1.0"
@@ -2206,6 +2226,7 @@ dependencies = [
name = "zigbee" name = "zigbee"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"defmt-or-log",
"embedded-hal-async", "embedded-hal-async",
"log", "log",
"zigbee-base-device-behavior", "zigbee-base-device-behavior",
@@ -2219,6 +2240,7 @@ dependencies = [
name = "zigbee-base-device-behavior" name = "zigbee-base-device-behavior"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"defmt-or-log",
"embedded-hal-async", "embedded-hal-async",
"log", "log",
"spin", "spin",
@@ -2249,6 +2271,7 @@ dependencies = [
"aes", "aes",
"byte", "byte",
"ccm 0.5.0", "ccm 0.5.0",
"defmt-or-log",
"embedded-hal-async", "embedded-hal-async",
"embedded-storage-async", "embedded-storage-async",
"heapless 0.9.3", "heapless 0.9.3",
@@ -2267,6 +2290,8 @@ name = "zigbee-mac"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"byte", "byte",
"defmt",
"defmt-or-log",
"embassy-futures", "embassy-futures",
"embassy-sync 0.8.0", "embassy-sync 0.8.0",
"embassy-time", "embassy-time",
@@ -2294,7 +2319,6 @@ dependencies = [
"byte", "byte",
"embedded-storage", "embedded-storage",
"heapless 0.9.3", "heapless 0.9.3",
"itertools",
"spin", "spin",
"zigbee-macros", "zigbee-macros",
] ]
+30
View File
@@ -0,0 +1,30 @@
#![no_std]
#![no_main]
use embassy_time::Duration;
use embassy_time::Timer;
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::gpio::Level;
use esp_hal::gpio::Output;
use esp_hal::gpio::OutputConfig;
use esp_hal::timer::timg::TimerGroup;
esp_bootloader_esp_idf::esp_app_desc!();
#[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 timers = TimerGroup::new(peripherals.TIMG0);
esp_rtos::start(timers.timer0, peripherals.FROM_CPU_INTR0);
esp_alloc::heap_allocator!(size: 8 * 1024);
let _pin = Output::new(peripherals.GPIO2, Level::High, OutputConfig::default());
log::info!("GPIO diagnostic: holding GPIO2/D2 high");
loop {
Timer::after(Duration::from_secs(1)).await;
}
}
+54
View File
@@ -0,0 +1,54 @@
#![no_std]
#![no_main]
use embassy_time::Duration;
use embassy_time::Timer;
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::Async;
use esp_hal::rmt::Rmt;
use esp_hal::time::Rate;
use esp_hal::timer::timg::TimerGroup;
use esp_hal_smartled::RmtSmartLeds;
use esp_hal_smartled::WS2812B_TIMING;
use esp_hal_smartled::buffer_size;
use esp_hal_smartled::color_order::Grb;
use smart_leds::RGB8;
use smart_leds::SmartLedsWriteAsync;
esp_bootloader_esp_idf::esp_app_desc!();
const LED_COUNT: usize = 24;
const BUFFER_SIZE: usize = buffer_size::<RGB8>(LED_COUNT);
const FRAME: [RGB8; LED_COUNT] = [RGB8 {
r: 32,
g: 32,
b: 32,
}; LED_COUNT];
type Strip<'d> = RmtSmartLeds<'d, BUFFER_SIZE, Async, RGB8, Grb>;
#[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 timers = TimerGroup::new(peripherals.TIMG0);
esp_rtos::start(timers.timer0, peripherals.FROM_CPU_INTR0);
esp_alloc::heap_allocator!(size: 8 * 1024);
let rate = Rate::from_mhz(80);
let rmt = Rmt::new(peripherals.RMT, rate)
.expect("init RMT")
.into_async();
let mut strip = Strip::new(WS2812B_TIMING, rmt.channel0, peripherals.GPIO2, rate)
.expect("configure WS2812B adapter");
log::info!("LED diagnostic: sending dim white on GPIO2/D2");
loop {
if let Err(error) = strip.write(FRAME).await {
log::error!("LED diagnostic write failed: {error:?}");
}
Timer::after(Duration::from_millis(100)).await;
}
}
+1 -4
View File
@@ -3,10 +3,7 @@
//! Everything that changes when the hardware changes lives here. //! Everything that changes when the hardware changes lives here.
/// Number of WS2812B pixels on the strip. /// Number of WS2812B pixels on the strip.
/// pub const LED_COUNT: usize = 24;
/// Held at 1 during bring-up to keep the current draw within what the board
/// can supply; a full strip needs its own 5V supply.
pub const LED_COUNT: usize = 1;
/// Ceiling on the duty cycle applied to every channel, as a fraction of 255. /// Ceiling on the duty cycle applied to every channel, as a fraction of 255.
/// ///
+38 -51
View File
@@ -14,27 +14,30 @@ use smart_leds::RGB8;
use smart_leds::SmartLedsWriteAsync; use smart_leds::SmartLedsWriteAsync;
use smart_leds::brightness as scale_brightness; use smart_leds::brightness as scale_brightness;
use smart_leds::gamma; use smart_leds::gamma;
use smart_leds::hsv::Hsv;
use smart_leds::hsv::hsv2rgb;
use crate::config::LED_COUNT; use crate::config::LED_COUNT;
use crate::config::MAX_DUTY; use crate::config::MAX_DUTY;
use crate::strip::Strip; use crate::strip::Strip;
/// What a turn of the encoder adjusts. A long press moves to the next one. /// Colour temperature presets, warmest first, as sRGB with the brightest
#[derive(Clone, Copy, PartialEq, Eq, Debug)] /// channel at full.
pub enum Mode { ///
Brightness, /// Precomputed rather than derived: a blackbody conversion needs floating
Hue, /// point the C6 has no hardware for, and a handful of presets does not
Saturation, /// justify carrying it.
} pub const TEMPERATURES: [(u16, RGB8); 6] = [
(2200, RGB8 { r: 255, g: 147, b: 41 }),
(2700, RGB8 { r: 255, g: 169, b: 87 }),
(3000, RGB8 { r: 255, g: 180, b: 107 }),
(4000, RGB8 { r: 255, g: 209, b: 163 }),
(5000, RGB8 { r: 255, g: 228, b: 206 }),
(6500, RGB8 { r: 255, g: 249, b: 253 }),
];
static ON: AtomicBool = AtomicBool::new(false); static ON: AtomicBool = AtomicBool::new(true);
static BRIGHTNESS: AtomicU8 = AtomicU8::new(128); static BRIGHTNESS: AtomicU8 = AtomicU8::new(128);
static HUE: AtomicU8 = AtomicU8::new(0); /// Index into [`TEMPERATURES`]; 2700K is the warm white a lamp usually sits at.
/// Zero is white, whatever the hue; a lamp should not power on coloured. static TEMPERATURE: AtomicU8 = AtomicU8::new(1);
static SATURATION: AtomicU8 = AtomicU8::new(0);
static MODE: AtomicU8 = AtomicU8::new(0);
static DIRTY: Signal<CriticalSectionRawMutex, ()> = Signal::new(); static DIRTY: Signal<CriticalSectionRawMutex, ()> = Signal::new();
pub fn is_on() -> bool { pub fn is_on() -> bool {
@@ -64,39 +67,17 @@ pub fn adjust_brightness(delta: i16) {
DIRTY.signal(()); DIRTY.signal(());
} }
pub fn hue() -> u8 { /// The selected preset, as `(kelvin, colour)`.
HUE.load(Ordering::Relaxed) pub fn temperature() -> (u16, RGB8) {
TEMPERATURES[usize::from(TEMPERATURE.load(Ordering::Relaxed)) % TEMPERATURES.len()]
} }
/// Hue is a circle, so this one wraps. `smart-leds` spans it over a full u8. /// Steps to the next preset, wrapping back to the warmest.
pub fn adjust_hue(delta: i16) { pub fn next_temperature() -> (u16, RGB8) {
let hue = hue().wrapping_add_signed(delta as i8); let next = (TEMPERATURE.load(Ordering::Relaxed) + 1) % TEMPERATURES.len() as u8;
HUE.store(hue, Ordering::Relaxed); TEMPERATURE.store(next, Ordering::Relaxed);
DIRTY.signal(());
}
pub fn mode() -> Mode {
match MODE.load(Ordering::Relaxed) {
1 => Mode::Hue,
2 => Mode::Saturation,
_ => Mode::Brightness,
}
}
pub fn next_mode() -> Mode {
MODE.store((MODE.load(Ordering::Relaxed) + 1) % 3, Ordering::Relaxed);
mode()
}
pub fn saturation() -> u8 {
SATURATION.load(Ordering::Relaxed)
}
/// Clamps, so the ends of the travel are pure white and fully saturated.
pub fn adjust_saturation(delta: i16) {
let level = (i16::from(saturation()) + delta).clamp(0, 255) as u8;
SATURATION.store(level, Ordering::Relaxed);
DIRTY.signal(()); DIRTY.signal(());
temperature()
} }
#[embassy_executor::task] #[embassy_executor::task]
@@ -104,11 +85,8 @@ pub async fn render_task(mut strip: Strip<'static>) {
let mut frame = [RGB8::default(); LED_COUNT]; let mut frame = [RGB8::default(); LED_COUNT];
loop { loop {
frame.fill(hsv2rgb(Hsv { let (_, colour) = temperature();
hue: hue(), frame.fill(colour);
sat: saturation(),
val: 255,
}));
// off is just zero brightness, so the colour survives a power cycle of // off is just zero brightness, so the colour survives a power cycle of
// the strip output and comes back as it was // the strip output and comes back as it was
@@ -118,8 +96,17 @@ pub async fn render_task(mut strip: Strip<'static>) {
0 0
}; };
// gamma before brightness, as smart-leds requires // gamma is applied to the level, not the pixels: curving each channel
let pixels = scale_brightness(gamma(frame.iter().copied()), level); // of an already white-balanced colour would shift its temperature
let level = gamma(core::iter::once(RGB8 {
r: level,
g: level,
b: level,
}))
.next()
.map_or(0, |corrected| corrected.r);
let pixels = scale_brightness(frame.iter().copied(), level);
if let Err(e) = strip.write(pixels).await { if let Err(e) = strip.write(pixels).await {
log::warn!("strip write failed: {e:?}"); log::warn!("strip write failed: {e:?}");
} }
+8 -24
View File
@@ -25,7 +25,6 @@ use esp_hal_smartled::WS2812B_TIMING;
use crate::config::STEPS_PER_BRIGHTNESS_UNIT; use crate::config::STEPS_PER_BRIGHTNESS_UNIT;
use crate::encoder::EVENTS; use crate::encoder::EVENTS;
use crate::encoder::EncoderEvent; use crate::encoder::EncoderEvent;
use crate::light::Mode;
use crate::strip::Strip; use crate::strip::Strip;
esp_bootloader_esp_idf::esp_app_desc!(); esp_bootloader_esp_idf::esp_app_desc!();
@@ -33,12 +32,6 @@ esp_bootloader_esp_idf::esp_app_desc!();
/// Brightness units per detent. /// Brightness units per detent.
const BRIGHTNESS_STEP: i16 = 8; const BRIGHTNESS_STEP: i16 = 8;
/// Hue per detent, in 1/256ths of the colour circle (~5.6 degrees).
const HUE_STEP: i16 = 4;
/// Saturation units per detent; 0 is white, 255 fully coloured.
const SATURATION_STEP: i16 = 16;
#[esp_rtos::main] #[esp_rtos::main]
async fn main(spawner: embassy_executor::Spawner) -> ! { async fn main(spawner: embassy_executor::Spawner) -> ! {
esp_println::logger::init_logger_from_env(); esp_println::logger::init_logger_from_env();
@@ -92,7 +85,7 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
// the stack owns persistence: the information bases are restored here // the stack owns persistence: the information bases are restored here
// and written back whenever the stack changes them // and written back whenever the stack changes them
let flash = BlockingAsync::new(FlashStorage::new(peripherals.FLASH)); let flash = BlockingAsync::new(FlashStorage::new(peripherals.FLASH));
let storage = zigbee::storage::init_with_flash(flash, zigbee_stack::FLASH_RANGE).await; let storage = zigbee::storage::FlashStorage::new(flash, zigbee_stack::FLASH_RANGE).await;
let ieee802154 = Ieee802154::new(peripherals.IEEE802154); let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default()); let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default());
@@ -106,7 +99,7 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
)); ));
spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_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::on_off_task(stack).expect("spawn on_off_task"));
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task")); spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
} }
@@ -114,26 +107,17 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
match EVENTS.receive().await { match EVENTS.receive().await {
EncoderEvent::Rotate(detents) => { EncoderEvent::Rotate(detents) => {
let steps = i16::from(detents) * STEPS_PER_BRIGHTNESS_UNIT as i16; let steps = i16::from(detents) * STEPS_PER_BRIGHTNESS_UNIT as i16;
match light::mode() { light::adjust_brightness(steps * BRIGHTNESS_STEP);
Mode::Brightness => light::adjust_brightness(steps * BRIGHTNESS_STEP), log::info!("rotate {detents:+} -> brightness {}", light::brightness());
Mode::Hue => light::adjust_hue(steps * HUE_STEP),
Mode::Saturation => light::adjust_saturation(steps * SATURATION_STEP),
}
log::info!(
"rotate {detents:+} -> brightness {} hue {} saturation {}",
light::brightness(),
light::hue(),
light::saturation()
);
} }
EncoderEvent::Click => { EncoderEvent::Click => {
let (kelvin, _) = light::next_temperature();
log::info!("colour temperature {kelvin}K");
}
EncoderEvent::LongPress => {
let on = light::toggle(); let on = light::toggle();
log::info!("light {}", if on { "on" } else { "off" }); log::info!("light {}", if on { "on" } else { "off" });
} }
EncoderEvent::LongPress => {
let mode = light::next_mode();
log::info!("encoder now adjusts {mode:?}");
}
} }
} }
} }
+76 -15
View File
@@ -9,8 +9,10 @@ use core::ops::Range;
use embassy_embedded_hal::adapter::BlockingAsync; use embassy_embedded_hal::adapter::BlockingAsync;
use embassy_time::Duration; use embassy_time::Duration;
use embassy_time::Instant;
use embassy_time::Timer; use embassy_time::Timer;
use esp_storage::FlashStorage; use esp_storage::FlashStorage;
use zigbee::aps::apsde::ApsdeSapConfirmStatus;
use zigbee::CurrentPowerMode; use zigbee::CurrentPowerMode;
use zigbee::CurrentPowerSourceLevel; use zigbee::CurrentPowerSourceLevel;
use zigbee::DeviceConfig; use zigbee::DeviceConfig;
@@ -32,10 +34,15 @@ use zigbee_cluster_library::clusters::general::identify::IdentifyServer;
use zigbee_cluster_library::clusters::general::on_off; use zigbee_cluster_library::clusters::general::on_off;
use zigbee_cluster_library::clusters::general::on_off::OnOffServer; use zigbee_cluster_library::clusters::general::on_off::OnOffServer;
use zigbee_cluster_library::profile; use zigbee_cluster_library::profile;
use zigbee_cluster_library::reporting::AttributeReportBuilder;
use zigbee_cluster_library::reporting::AttributeReporting;
use zigbee_cluster_library::reporting::ReportingTable; use zigbee_cluster_library::reporting::ReportingTable;
use zigbee_cluster_library::sender::ZclReportTarget;
use zigbee_cluster_library::sender::ZclSender;
use zigbee_cluster_library::server::UnsupportedClusterResponder; use zigbee_cluster_library::server::UnsupportedClusterResponder;
use zigbee_mac::esp::EspMlme; use zigbee_mac::esp::EspMlme;
use zigbee_types::IeeeAddress; use zigbee_types::IeeeAddress;
use zigbee_types::ShortAddress;
use crate::light; use crate::light;
@@ -46,13 +53,11 @@ use crate::light;
/// garbage collection. /// garbage collection.
pub const FLASH_RANGE: Range<u32> = 0x3e_0000..0x3e_4000; pub const FLASH_RANGE: Range<u32> = 0x3e_0000..0x3e_4000;
/// Extended PAN ID of the network to join. /// Extended PAN ID of the Home Assistant Zigbee network.
/// const EXTENDED_PAN_ID: u64 = 0xafca_95fc_e132_eeb6;
/// 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. /// Channel to scan on; must match the coordinator.
const CHANNEL: u8 = 11; const CHANNEL: u8 = 25;
/// Scan duration exponent (beacon order). /// Scan duration exponent (beacon order).
const SCAN_DURATION: u8 = 5; const SCAN_DURATION: u8 = 5;
@@ -60,10 +65,9 @@ const SCAN_DURATION: u8 = 5;
/// The application endpoint this light is served on. /// The application endpoint this light is served on.
const LIGHT_ENDPOINT: u8 = 1; const LIGHT_ENDPOINT: u8 = 1;
/// Mains powered and always listening: allocate address (bit 7) and /// Mains powered and always listening: allocate address (bit 7), power source
/// rx-on-when-idle (bit 3), so the coordinator can push commands at any time /// (bit 2), and rx-on-when-idle (bit 3); bit 1 stays clear for an end device.
/// rather than waiting for a poll. const CAPABILITY: u8 = 0x8c;
const CAPABILITY: u8 = 0x8e;
static INPUT_CLUSTERS: [u16; 3] = [ static INPUT_CLUSTERS: [u16; 3] = [
basic::CLUSTER_ID, basic::CLUSTER_ID,
@@ -164,12 +168,11 @@ pub fn config() -> StackConfig<'static> {
/// parent link, and persistence. /// parent link, and persistence.
#[embassy_executor::task] #[embassy_executor::task]
pub async fn stack_task(stack: &'static Stack) { pub async fn stack_task(stack: &'static Stack) {
// returns only once no rejoin can get us back: the network is gone or our loop {
// keys are stale, so drop it and re-commission from scratch
let outcome = stack.run(embassy_time::Delay).await; let outcome = stack.run(embassy_time::Delay).await;
log::warn!("off the network ({outcome:?}), forgetting it and rebooting"); log::warn!("off the network ({outcome:?}), retrying in 5 seconds");
stack.forget_network().await; Timer::after(Duration::from_secs(5)).await;
esp_hal::system::software_reset(); }
} }
/// Mirrors the On/Off attribute onto the strip, both ways. /// Mirrors the On/Off attribute onto the strip, both ways.
@@ -178,14 +181,21 @@ pub async fn stack_task(stack: &'static Stack) {
/// any notification hook, so this samples it. The reverse direction keeps the /// any notification hook, so this samples it. The reverse direction keeps the
/// attribute truthful after a local button press. /// attribute truthful after a local button press.
#[embassy_executor::task] #[embassy_executor::task]
pub async fn on_off_task() { pub async fn on_off_task(stack: &'static Stack) {
stack.wait_until_joined().await;
let mut last = ON_OFF.on_off(); let mut last = ON_OFF.on_off();
let mut pending_report = None;
let mut sequence_number = 0u8;
let started_at = Instant::now();
loop { loop {
Timer::after(Duration::from_millis(50)).await; Timer::after(Duration::from_millis(50)).await;
let remote = ON_OFF.on_off(); let remote = ON_OFF.on_off();
if remote != last { if remote != last {
last = remote; last = remote;
pending_report = None;
log::info!("Zigbee On/Off state changed: {remote}");
light::set_on(remote); light::set_on(remote);
continue; continue;
} }
@@ -194,6 +204,57 @@ pub async fn on_off_task() {
if local != last { if local != last {
last = local; last = local;
ON_OFF.set_on_off(local); ON_OFF.set_on_off(local);
pending_report = Some(local);
}
let Some(value) = pending_report else {
continue;
};
let cluster = on_off::CLUSTER.id();
let attribute = on_off::ON_OFF.id();
let now_secs = started_at.elapsed().as_secs().min(u64::from(u32::MAX)) as u32;
let configured = REPORTING.configuration(cluster, attribute).is_some();
let due = !configured
|| REPORTING.should_report(cluster, attribute, now_secs, i64::from(value));
if !due {
continue;
}
sequence_number = sequence_number.wrapping_add(1);
let mut buffer = [0u8; 32];
let report = AttributeReportBuilder::new(&mut buffer, sequence_number)
.and_then(|frame| frame.push(&on_off::ON_OFF, value))
.and_then(AttributeReportBuilder::finish)
.expect("encode On/Off report");
let result = stack
.device()
.send_attribute_report(
ZclReportTarget {
dst_short: ShortAddress::COORDINATOR.0,
src_endpoint: LIGHT_ENDPOINT,
dst_endpoint: 1,
profile_id: profile::HOME_AUTOMATION,
},
report,
&mut embassy_time::Delay,
)
.await;
match result {
Ok(confirm) if confirm.status == ApsdeSapConfirmStatus::Success => {
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_report = None;
log::info!("reported local Zigbee On/Off state: {value}");
}
Ok(confirm) => {
log::warn!("On/Off report failed: {:?}", confirm.status);
Timer::after(Duration::from_secs(1)).await;
}
Err(error) => {
log::warn!("On/Off report encoding failed: {:?}", error);
Timer::after(Duration::from_secs(1)).await;
}
} }
} }
} }