feat: add Zigbee brightness and color temperature

This commit is contained in:
Matt Spencer committed 2026-11-16 00:33:54 +00:00
1 parent 1aa6ba3c5f
commit 65f951b890
5 files changed
+221 -75

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
[submodule "vendor/zigbee-rs"] [submodule "vendor/zigbee-rs"]
path = vendor/zigbee-rs path = vendor/zigbee-rs
url = git@github.com:m5p3nc3r/zigbee-rs.git url = git@github.com:m5p3nc3r/zigbee-rs.git
branch = feature/light-control branch = feature/brightness-color-temp
+28
View File
@@ -59,6 +59,11 @@ pub fn brightness() -> u8 {
BRIGHTNESS.load(Ordering::Relaxed) 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 /// Clamps rather than wraps: running past full should stay at full instead of
/// dropping the light to near-black. /// dropping the light to near-black.
pub fn adjust_brightness(delta: i16) { pub fn adjust_brightness(delta: i16) {
@@ -72,6 +77,29 @@ pub fn temperature() -> (u16, RGB8) {
TEMPERATURES[usize::from(TEMPERATURE.load(Ordering::Relaxed)) % TEMPERATURES.len()] 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. /// Steps to the next preset, wrapping back to the warmest.
pub fn next_temperature() -> (u16, RGB8) { pub fn next_temperature() -> (u16, RGB8) {
let next = (TEMPERATURE.load(Ordering::Relaxed) + 1) % TEMPERATURES.len() as u8; let next = (TEMPERATURE.load(Ordering::Relaxed) + 1) % TEMPERATURES.len() as u8;
+1 -1
View File
@@ -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::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")); spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
} }
+190 -72
View File
@@ -1,9 +1,7 @@
//! Zigbee end device: commissioning, the stack task, and the clusters served. //! 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 //! The device is a single Color Temperature Light: all strip pixels share the
//! (ZCL chapter 5) are deliberately absent: the vendored upstream does not //! same on/off state, level, and color-temperature preset.
//! 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 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::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::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::profile;
use zigbee_cluster_library::reporting::AttributeReportBuilder; use zigbee_cluster_library::reporting::AttributeReportBuilder;
use zigbee_cluster_library::reporting::AttributeReporting; 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::ZclReportTarget;
use zigbee_cluster_library::sender::ZclSender; use zigbee_cluster_library::sender::ZclSender;
use zigbee_cluster_library::server::UnsupportedClusterResponder; 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_mac::esp::EspMlme;
use zigbee_types::IeeeAddress; use zigbee_types::IeeeAddress;
use zigbee_types::ShortAddress; 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. /// (bit 2), and rx-on-when-idle (bit 3); bit 1 stays clear for an end device.
const CAPABILITY: u8 = 0x8c; const CAPABILITY: u8 = 0x8c;
static INPUT_CLUSTERS: [u16; 3] = [ static INPUT_CLUSTERS: [u16; 5] = [
basic::CLUSTER_ID, basic::CLUSTER_ID,
identify::CLUSTER_ID, identify::CLUSTER_ID,
on_off::CLUSTER_ID, on_off::CLUSTER_ID,
level_control::CLUSTER_ID,
color_control::CLUSTER_ID,
]; ];
static OUTPUT_CLUSTERS: [u16; 0] = []; static OUTPUT_CLUSTERS: [u16; 0] = [];
static ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor { static ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor {
endpoint: LIGHT_ENDPOINT, endpoint: LIGHT_ENDPOINT,
profile_id: profile::HOME_AUTOMATION, profile_id: profile::HOME_AUTOMATION,
// HA device id 0x0100: On/Off Light. Becomes 0x0101 (Dimmable Light) once // HA device id 0x010c: Color Temperature Light.
// Level Control is implemented. device_id: 0x010c,
device_id: 0x0100,
device_version: 1, device_version: 1,
input_clusters: &INPUT_CLUSTERS, input_clusters: &INPUT_CLUSTERS,
output_clusters: &OUTPUT_CLUSTERS, output_clusters: &OUTPUT_CLUSTERS,
@@ -103,6 +112,10 @@ pub static IDENTIFY: IdentifyServer = IdentifyServer::new();
static REPORTING: ReportingTable<4> = ReportingTable::new(); static REPORTING: ReportingTable<4> = ReportingTable::new();
static ON_OFF: OnOffServer = OnOffServer::new().with_reporting(&REPORTING); 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<BlockingAsync<FlashStorage<'static>>>; type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>;
@@ -111,9 +124,16 @@ type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'sta
/// (ZCL 2.5.12.2). /// (ZCL 2.5.12.2).
type Handler = ( type Handler = (
BasicServer<'static>, BasicServer<'static>,
(
&'static IdentifyServer, &'static IdentifyServer,
(
&'static OnOffServer<'static>, &'static OnOffServer<'static>,
UnsupportedClusterResponder<'static>, (
&'static LevelControlServer<'static>,
(&'static ColorControlServer<'static>, UnsupportedClusterResponder<'static>),
),
),
),
); );
pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>; 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 { pub fn handler() -> Handler {
( (
BASIC, BASIC,
(
&IDENTIFY, &IDENTIFY,
(
&ON_OFF, &ON_OFF,
(
&LEVEL_CONTROL,
(
&COLOR_CONTROL,
UnsupportedClusterResponder::new(&INPUT_CLUSTERS), UnsupportedClusterResponder::new(&INPUT_CLUSTERS),
),
),
),
),
) )
} }
@@ -175,59 +205,27 @@ pub async fn stack_task(stack: &'static Stack) {
} }
} }
/// Mirrors the On/Off attribute onto the strip, both ways. async fn report_attribute<T, A>(
/// stack: &'static Stack,
/// The cluster server writes its attribute from the APS receive path without attribute: &Attribute<T, A, Reportable>,
/// any notification hook, so this samples it. The reverse direction keeps the value: T::Value<'_>,
/// attribute truthful after a local button press. sequence_number: &mut u8,
#[embassy_executor::task] ) -> bool
pub async fn on_off_task(stack: &'static Stack) { where
stack.wait_until_joined().await; T: ZclKind,
A: AccessTypestate,
let mut last = ON_OFF.on_off(); {
let mut pending_report = None; *sequence_number = sequence_number.wrapping_add(1);
let mut sequence_number = 0u8; let mut buffer = [0u8; 32];
let started_at = Instant::now(); let report = AttributeReportBuilder::new(&mut buffer, *sequence_number)
loop { .and_then(|frame| frame.push(attribute, value))
Timer::after(Duration::from_millis(50)).await; .and_then(AttributeReportBuilder::finish);
let Ok(report) = report else {
let remote = ON_OFF.on_off(); log::warn!("failed to encode lighting attribute report");
if remote != last { return false;
last = remote;
pending_report = None;
log::info!("Zigbee On/Off state changed: {remote}");
light::set_on(remote);
continue;
}
let local = light::is_on();
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(); match stack
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() .device()
.send_attribute_report( .send_attribute_report(
ZclReportTarget { ZclReportTarget {
@@ -239,21 +237,141 @@ pub async fn on_off_task(stack: &'static Stack) {
report, report,
&mut embassy_time::Delay, &mut embassy_time::Delay,
) )
.await; .await
{
match result { Ok(confirm) if confirm.status == ApsdeSapConfirmStatus::Success => true,
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) => { Ok(confirm) => {
log::warn!("On/Off report failed: {:?}", confirm.status); log::warn!("lighting attribute report failed: {:?}", confirm.status);
Timer::after(Duration::from_secs(1)).await; false
} }
Err(error) => { Err(error) => {
log::warn!("On/Off report encoding failed: {:?}", error); log::warn!("lighting attribute report encoding failed: {:?}", error);
Timer::after(Duration::from_secs(1)).await; false
}
}
}
/// Keeps the single strip synchronized with Zigbee On/Off, level and color temperature.
#[embassy_executor::task]
pub async fn lighting_task(stack: &'static Stack) {
stack.wait_until_joined().await;
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;
if let Some(on) = LEVEL_CONTROL.take_on_off_change() {
ON_OFF.set_on_off(on);
}
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 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 now_secs = started_at.elapsed().as_secs().min(u64::from(u32::MAX)) as u32;
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_on = None;
log::info!("reported local Zigbee On/Off state: {value}");
}
}
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}");
}
}
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");
} }
} }
} }