diff --git a/.gitmodules b/.gitmodules index adce940..9b5422e 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,4 @@ [submodule "vendor/zigbee-rs"] path = vendor/zigbee-rs url = git@github.com:m5p3nc3r/zigbee-rs.git - branch = feature/light-control + branch = feature/brightness-color-temp diff --git a/src/light.rs b/src/light.rs index 18c1426..fe49086 100644 --- a/src/light.rs +++ b/src/light.rs @@ -59,6 +59,11 @@ pub fn brightness() -> u8 { BRIGHTNESS.load(Ordering::Relaxed) } +pub fn set_brightness(level: u8) { + BRIGHTNESS.store(level.min(254), Ordering::Relaxed); + DIRTY.signal(()); +} + /// 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) { @@ -72,6 +77,29 @@ pub fn temperature() -> (u16, RGB8) { TEMPERATURES[usize::from(TEMPERATURE.load(Ordering::Relaxed)) % TEMPERATURES.len()] } +pub fn temperature_mireds() -> u16 { + (1_000_000u32 / u32::from(temperature().0)) as u16 +} + +/// Select the nearest available RGB preset for a Zigbee mired request. +pub fn set_temperature_mireds(mireds: u16) -> u16 { + let target_kelvin = 1_000_000 / u32::from(mireds.max(1)); + let mut closest_index = 0; + let mut closest_delta = u32::MAX; + + for (index, (kelvin, _)) in TEMPERATURES.iter().enumerate() { + let delta = u32::from(*kelvin).abs_diff(target_kelvin); + if delta < closest_delta { + closest_index = index; + closest_delta = delta; + } + } + + TEMPERATURE.store(closest_index as u8, Ordering::Relaxed); + DIRTY.signal(()); + temperature_mireds() +} + /// 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; diff --git a/src/main.rs b/src/main.rs index 0c41df0..cb9b7e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -99,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(stack).expect("spawn on_off_task")); + spawner.spawn(zigbee_stack::lighting_task(stack).expect("spawn lighting_task")); spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task")); } diff --git a/src/zigbee_stack.rs b/src/zigbee_stack.rs index f6eaa6d..2d0817d 100644 --- a/src/zigbee_stack.rs +++ b/src/zigbee_stack.rs @@ -1,9 +1,7 @@ //! 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. +//! The device is a single Color Temperature Light: all strip pixels share the +//! same on/off state, level, and color-temperature preset. use core::ops::Range; @@ -33,6 +31,10 @@ 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::clusters::lighting::color_control; +use zigbee_cluster_library::clusters::lighting::color_control::ColorControlServer; +use zigbee_cluster_library::clusters::lighting::level_control; +use zigbee_cluster_library::clusters::lighting::level_control::LevelControlServer; use zigbee_cluster_library::profile; use zigbee_cluster_library::reporting::AttributeReportBuilder; use zigbee_cluster_library::reporting::AttributeReporting; @@ -40,6 +42,12 @@ 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::types::codec::ZclKind; +use zigbee_cluster_library::types::descriptors::AccessTypestate; +use zigbee_cluster_library::types::descriptors::Attribute; +use zigbee_cluster_library::types::descriptors::Reportable; +use zigbee_cluster_library::types::integers::Uint8; +use zigbee_cluster_library::types::integers::Uint16; use zigbee_mac::esp::EspMlme; use zigbee_types::IeeeAddress; use zigbee_types::ShortAddress; @@ -69,19 +77,20 @@ const LIGHT_ENDPOINT: u8 = 1; /// (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] = [ +static INPUT_CLUSTERS: [u16; 5] = [ basic::CLUSTER_ID, identify::CLUSTER_ID, on_off::CLUSTER_ID, + level_control::CLUSTER_ID, + color_control::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, + // HA device id 0x010c: Color Temperature Light. + device_id: 0x010c, device_version: 1, input_clusters: &INPUT_CLUSTERS, output_clusters: &OUTPUT_CLUSTERS, @@ -103,6 +112,10 @@ pub static IDENTIFY: IdentifyServer = IdentifyServer::new(); static REPORTING: ReportingTable<4> = ReportingTable::new(); static ON_OFF: OnOffServer = OnOffServer::new().with_reporting(&REPORTING); +static LEVEL_CONTROL: LevelControlServer<'static> = + LevelControlServer::new(128).with_reporting(&REPORTING); +static COLOR_CONTROL: ColorControlServer<'static> = + ColorControlServer::new(370).with_reporting(&REPORTING); type ZigbeeFlash = zigbee::storage::FlashStorage>>; @@ -111,9 +124,16 @@ type ZigbeeFlash = zigbee::storage::FlashStorage, - &'static IdentifyServer, - &'static OnOffServer<'static>, - UnsupportedClusterResponder<'static>, + ( + &'static IdentifyServer, + ( + &'static OnOffServer<'static>, + ( + &'static LevelControlServer<'static>, + (&'static ColorControlServer<'static>, UnsupportedClusterResponder<'static>), + ), + ), + ), ); pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>; @@ -121,9 +141,19 @@ pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>; pub fn handler() -> Handler { ( BASIC, - &IDENTIFY, - &ON_OFF, - UnsupportedClusterResponder::new(&INPUT_CLUSTERS), + ( + &IDENTIFY, + ( + &ON_OFF, + ( + &LEVEL_CONTROL, + ( + &COLOR_CONTROL, + UnsupportedClusterResponder::new(&INPUT_CLUSTERS), + ), + ), + ), + ), ) } @@ -175,85 +205,173 @@ pub async fn stack_task(stack: &'static Stack) { } } -/// 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. +async fn report_attribute( + stack: &'static Stack, + attribute: &Attribute, + value: T::Value<'_>, + sequence_number: &mut u8, +) -> bool +where + T: ZclKind, + A: AccessTypestate, +{ + *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(attribute, value)) + .and_then(AttributeReportBuilder::finish); + let Ok(report) = report else { + log::warn!("failed to encode lighting attribute report"); + return false; + }; + + match 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 + { + Ok(confirm) if confirm.status == ApsdeSapConfirmStatus::Success => true, + Ok(confirm) => { + log::warn!("lighting attribute report failed: {:?}", confirm.status); + false + } + Err(error) => { + log::warn!("lighting attribute report encoding failed: {:?}", error); + false + } + } +} + +/// Keeps the single strip synchronized with Zigbee On/Off, level and color temperature. #[embassy_executor::task] -pub async fn on_off_task(stack: &'static Stack) { +pub async fn lighting_task(stack: &'static Stack) { stack.wait_until_joined().await; - let mut last = ON_OFF.on_off(); - let mut pending_report = None; + let mut last_on = ON_OFF.on_off(); + let mut last_level = LEVEL_CONTROL.current_level(); + let mut last_mireds = COLOR_CONTROL.color_temperature_mireds(); + let mut pending_on = None; + let mut pending_level = None; + let mut pending_mireds = 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; + if let Some(on) = LEVEL_CONTROL.take_on_off_change() { + ON_OFF.set_on_off(on); } - let local = light::is_on(); - if local != last { - last = local; - ON_OFF.set_on_off(local); - pending_report = Some(local); + let remote_on = ON_OFF.on_off(); + if remote_on != last_on { + last_on = remote_on; + if light::is_on() != remote_on { + log::info!("Zigbee On/Off state changed: {remote_on}"); + light::set_on(remote_on); + } + pending_on = None; + } + let local_on = light::is_on(); + if local_on != last_on { + last_on = local_on; + ON_OFF.set_on_off(local_on); + pending_on = Some(local_on); } - let Some(value) = pending_report else { - continue; - }; + let remote_level = LEVEL_CONTROL.current_level(); + if remote_level != last_level { + last_level = remote_level; + if light::brightness() != remote_level { + light::set_brightness(remote_level); + } + pending_level = None; + } + let local_level = light::brightness(); + if local_level != last_level { + last_level = local_level; + LEVEL_CONTROL.set_current_level(local_level); + pending_level = Some(local_level); + } + + let remote_mireds = COLOR_CONTROL.color_temperature_mireds(); + if remote_mireds != last_mireds { + let actual_mireds = light::set_temperature_mireds(remote_mireds); + last_mireds = actual_mireds; + if actual_mireds != remote_mireds { + COLOR_CONTROL.set_color_temperature_mireds(actual_mireds); + pending_mireds = Some(actual_mireds); + } else { + pending_mireds = None; + } + } + let local_mireds = light::temperature_mireds(); + if local_mireds != last_mireds { + last_mireds = local_mireds; + COLOR_CONTROL.set_color_temperature_mireds(local_mireds); + pending_mireds = Some(local_mireds); + } - 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 => { + if let Some(value) = pending_on { + let cluster = on_off::CLUSTER.id(); + let attribute = on_off::ON_OFF.id(); + let due = REPORTING.configuration(cluster, attribute).is_none() + || REPORTING.should_report(cluster, attribute, now_secs, i64::from(value)); + if due && report_attribute(stack, &on_off::ON_OFF, value, &mut sequence_number).await { REPORTING.reported(cluster, attribute, now_secs, i64::from(value)); - pending_report = None; + pending_on = 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; + } + + if let Some(value) = pending_level { + let cluster = level_control::CLUSTER.id(); + let attribute = level_control::CURRENT_LEVEL.id(); + let due = REPORTING.configuration(cluster, attribute).is_none() + || REPORTING.should_report(cluster, attribute, now_secs, i64::from(value)); + if due + && report_attribute( + stack, + &level_control::CURRENT_LEVEL, + Uint8(value), + &mut sequence_number, + ) + .await + { + REPORTING.reported(cluster, attribute, now_secs, i64::from(value)); + pending_level = None; + log::info!("reported local Zigbee level: {value}"); } - Err(error) => { - log::warn!("On/Off report encoding failed: {:?}", error); - Timer::after(Duration::from_secs(1)).await; + } + + if let Some(value) = pending_mireds { + let cluster = color_control::CLUSTER.id(); + let attribute = color_control::COLOR_TEMPERATURE_MIREDS.id(); + let due = REPORTING.configuration(cluster, attribute).is_none() + || REPORTING.should_report(cluster, attribute, now_secs, i64::from(value)); + if due + && report_attribute( + stack, + &color_control::COLOR_TEMPERATURE_MIREDS, + Uint16(value), + &mut sequence_number, + ) + .await + { + REPORTING.reported(cluster, attribute, now_secs, i64::from(value)); + pending_mireds = None; + log::info!("reported local color temperature: {value} mireds"); } } } diff --git a/vendor/zigbee-rs b/vendor/zigbee-rs index cc26af8..1b4d9b9 160000 --- a/vendor/zigbee-rs +++ b/vendor/zigbee-rs @@ -1 +1 @@ -Subproject commit cc26af8cf16c54963feac40bb2337ef340acbeb7 +Subproject commit 1b4d9b972d1e4ef60de58dd7d5326208b159408d