From 1aa6ba3c5f63f9ec7635651feaf6588d07f74b14 Mon Sep 17 00:00:00 2001 From: Matt Spencer Date: Sun, 15 Nov 2026 23:22:20 +0000 Subject: [PATCH] feat: add Zigbee-controlled smart light --- .gitignore | 1 + .gitmodules | 4 +- Cargo.lock | 26 ++++++++++- src/bin/gpio_out_diag.rs | 30 +++++++++++++ src/bin/led_diag.rs | 54 +++++++++++++++++++++++ src/config.rs | 5 +-- src/light.rs | 89 ++++++++++++++++---------------------- src/main.rs | 32 ++++---------- src/zigbee_stack.rs | 93 +++++++++++++++++++++++++++++++++------- vendor/zigbee-rs | 2 +- 10 files changed, 237 insertions(+), 99 deletions(-) create mode 100644 src/bin/gpio_out_diag.rs create mode 100644 src/bin/led_diag.rs diff --git a/.gitignore b/.gitignore index 4e65899..cf6a67d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target /vendor/zigbee-rs/target +/nda \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index cd5d47e..adce940 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,4 @@ [submodule "vendor/zigbee-rs"] path = vendor/zigbee-rs - url = https://github.com/zigbee-rs/zigbee-rs.git - branch = smart-light + url = git@github.com:m5p3nc3r/zigbee-rs.git + branch = feature/light-control diff --git a/Cargo.lock b/Cargo.lock index ccd0b8a..8dc8444 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -382,6 +382,26 @@ dependencies = [ "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]] name = "defmt-parser" version = "1.1.0" @@ -2206,6 +2226,7 @@ dependencies = [ name = "zigbee" version = "0.1.0" dependencies = [ + "defmt-or-log", "embedded-hal-async", "log", "zigbee-base-device-behavior", @@ -2219,6 +2240,7 @@ dependencies = [ name = "zigbee-base-device-behavior" version = "0.1.0" dependencies = [ + "defmt-or-log", "embedded-hal-async", "log", "spin", @@ -2249,6 +2271,7 @@ dependencies = [ "aes", "byte", "ccm 0.5.0", + "defmt-or-log", "embedded-hal-async", "embedded-storage-async", "heapless 0.9.3", @@ -2267,6 +2290,8 @@ name = "zigbee-mac" version = "0.1.0" dependencies = [ "byte", + "defmt", + "defmt-or-log", "embassy-futures", "embassy-sync 0.8.0", "embassy-time", @@ -2294,7 +2319,6 @@ dependencies = [ "byte", "embedded-storage", "heapless 0.9.3", - "itertools", "spin", "zigbee-macros", ] diff --git a/src/bin/gpio_out_diag.rs b/src/bin/gpio_out_diag.rs new file mode 100644 index 0000000..65a853c --- /dev/null +++ b/src/bin/gpio_out_diag.rs @@ -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; + } +} \ No newline at end of file diff --git a/src/bin/led_diag.rs b/src/bin/led_diag.rs new file mode 100644 index 0000000..117a113 --- /dev/null +++ b/src/bin/led_diag.rs @@ -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::(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; + } +} \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 938384d..351bea4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,10 +3,7 @@ //! Everything that changes when the hardware changes lives here. /// Number of WS2812B pixels on the strip. -/// -/// 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; +pub const LED_COUNT: usize = 24; /// Ceiling on the duty cycle applied to every channel, as a fraction of 255. /// diff --git a/src/light.rs b/src/light.rs index 2fdc4a6..18c1426 100644 --- a/src/light.rs +++ b/src/light.rs @@ -14,27 +14,30 @@ use smart_leds::RGB8; use smart_leds::SmartLedsWriteAsync; use smart_leds::brightness as scale_brightness; use smart_leds::gamma; -use smart_leds::hsv::Hsv; -use smart_leds::hsv::hsv2rgb; use crate::config::LED_COUNT; use crate::config::MAX_DUTY; use crate::strip::Strip; -/// What a turn of the encoder adjusts. A long press moves to the next one. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum Mode { - Brightness, - Hue, - Saturation, -} +/// Colour temperature presets, warmest first, as sRGB with the brightest +/// channel at full. +/// +/// Precomputed rather than derived: a blackbody conversion needs floating +/// point the C6 has no hardware for, and a handful of presets does not +/// 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 HUE: AtomicU8 = AtomicU8::new(0); -/// Zero is white, whatever the hue; a lamp should not power on coloured. -static SATURATION: AtomicU8 = AtomicU8::new(0); -static MODE: AtomicU8 = AtomicU8::new(0); +/// Index into [`TEMPERATURES`]; 2700K is the warm white a lamp usually sits at. +static TEMPERATURE: AtomicU8 = AtomicU8::new(1); static DIRTY: Signal = Signal::new(); pub fn is_on() -> bool { @@ -64,39 +67,17 @@ pub fn adjust_brightness(delta: i16) { DIRTY.signal(()); } -pub fn hue() -> u8 { - HUE.load(Ordering::Relaxed) +/// The selected preset, as `(kelvin, colour)`. +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. -pub fn adjust_hue(delta: i16) { - let hue = hue().wrapping_add_signed(delta as i8); - HUE.store(hue, 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); +/// Steps to the next preset, wrapping back to the warmest. +pub fn next_temperature() -> (u16, RGB8) { + let next = (TEMPERATURE.load(Ordering::Relaxed) + 1) % TEMPERATURES.len() as u8; + TEMPERATURE.store(next, Ordering::Relaxed); DIRTY.signal(()); + temperature() } #[embassy_executor::task] @@ -104,11 +85,8 @@ pub async fn render_task(mut strip: Strip<'static>) { let mut frame = [RGB8::default(); LED_COUNT]; loop { - frame.fill(hsv2rgb(Hsv { - hue: hue(), - sat: saturation(), - val: 255, - })); + let (_, colour) = temperature(); + frame.fill(colour); // off is just zero brightness, so the colour survives a power cycle of // the strip output and comes back as it was @@ -118,8 +96,17 @@ pub async fn render_task(mut strip: Strip<'static>) { 0 }; - // gamma before brightness, as smart-leds requires - let pixels = scale_brightness(gamma(frame.iter().copied()), level); + // gamma is applied to the level, not the pixels: curving each channel + // 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 { log::warn!("strip write failed: {e:?}"); } diff --git a/src/main.rs b/src/main.rs index 94373d2..0c41df0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,7 +25,6 @@ use esp_hal_smartled::WS2812B_TIMING; use crate::config::STEPS_PER_BRIGHTNESS_UNIT; use crate::encoder::EVENTS; use crate::encoder::EncoderEvent; -use crate::light::Mode; use crate::strip::Strip; esp_bootloader_esp_idf::esp_app_desc!(); @@ -33,12 +32,6 @@ esp_bootloader_esp_idf::esp_app_desc!(); /// Brightness units per detent. 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] async fn main(spawner: embassy_executor::Spawner) -> ! { 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 // 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 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()); @@ -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::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")); } @@ -114,25 +107,16 @@ async fn main(spawner: embassy_executor::Spawner) -> ! { 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), - Mode::Saturation => light::adjust_saturation(steps * SATURATION_STEP), - } - log::info!( - "rotate {detents:+} -> brightness {} hue {} saturation {}", - light::brightness(), - light::hue(), - light::saturation() - ); + light::adjust_brightness(steps * BRIGHTNESS_STEP); + log::info!("rotate {detents:+} -> brightness {}", light::brightness()); } EncoderEvent::Click => { - let on = light::toggle(); - log::info!("light {}", if on { "on" } else { "off" }); + let (kelvin, _) = light::next_temperature(); + log::info!("colour temperature {kelvin}K"); } EncoderEvent::LongPress => { - let mode = light::next_mode(); - log::info!("encoder now adjusts {mode:?}"); + let on = light::toggle(); + log::info!("light {}", if on { "on" } else { "off" }); } } } diff --git a/src/zigbee_stack.rs b/src/zigbee_stack.rs index 53d4361..f6eaa6d 100644 --- a/src/zigbee_stack.rs +++ b/src/zigbee_stack.rs @@ -9,8 +9,10 @@ use core::ops::Range; use embassy_embedded_hal::adapter::BlockingAsync; use embassy_time::Duration; +use embassy_time::Instant; use embassy_time::Timer; use esp_storage::FlashStorage; +use zigbee::aps::apsde::ApsdeSapConfirmStatus; use zigbee::CurrentPowerMode; use zigbee::CurrentPowerSourceLevel; 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::OnOffServer; 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::sender::ZclReportTarget; +use zigbee_cluster_library::sender::ZclSender; use zigbee_cluster_library::server::UnsupportedClusterResponder; use zigbee_mac::esp::EspMlme; use zigbee_types::IeeeAddress; +use zigbee_types::ShortAddress; use crate::light; @@ -46,13 +53,11 @@ use crate::light; /// garbage collection. pub const FLASH_RANGE: Range = 0x3e_0000..0x3e_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; +/// Extended PAN ID of the Home Assistant Zigbee network. +const EXTENDED_PAN_ID: u64 = 0xafca_95fc_e132_eeb6; /// Channel to scan on; must match the coordinator. -const CHANNEL: u8 = 11; +const CHANNEL: u8 = 25; /// Scan duration exponent (beacon order). const SCAN_DURATION: u8 = 5; @@ -60,10 +65,9 @@ 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; +/// Mains powered and always listening: allocate address (bit 7), power source +/// (bit 2), and rx-on-when-idle (bit 3); bit 1 stays clear for an end device. +const CAPABILITY: u8 = 0x8c; static INPUT_CLUSTERS: [u16; 3] = [ basic::CLUSTER_ID, @@ -164,12 +168,11 @@ pub fn config() -> StackConfig<'static> { /// 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(); + loop { + let outcome = stack.run(embassy_time::Delay).await; + log::warn!("off the network ({outcome:?}), retrying in 5 seconds"); + Timer::after(Duration::from_secs(5)).await; + } } /// 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 /// attribute truthful after a local button press. #[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 pending_report = None; + let mut sequence_number = 0u8; + let started_at = Instant::now(); loop { Timer::after(Duration::from_millis(50)).await; let remote = ON_OFF.on_off(); if remote != last { last = remote; + pending_report = None; + log::info!("Zigbee On/Off state changed: {remote}"); light::set_on(remote); continue; } @@ -194,6 +204,57 @@ pub async fn on_off_task() { if local != last { last = 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; + } } } } diff --git a/vendor/zigbee-rs b/vendor/zigbee-rs index a086215..cc26af8 160000 --- a/vendor/zigbee-rs +++ b/vendor/zigbee-rs @@ -1 +1 @@ -Subproject commit a086215a37155d1a9dbda453db611afc519f080a +Subproject commit cc26af8cf16c54963feac40bb2337ef340acbeb7