feat: add light effects driven over Zigbee

Add animated effects to the light, controlled from Home Assistant.

* Identify Trigger Effect (ZCL 3.5.2.3.3): the light plays Blink, Breathe,
  Okay and Channel change as overlays on its current state, and returns to
  exactly what it was showing (src/effect.rs). Home Assistant's flash
  option uses this.
* Scenes: Rainbow, Pulse and Comet run continuously and use the light's own
  colour and brightness, so on/off, level and colour keep working while one
  plays (src/scene.rs). The strip is redrawn every 20 ms while anything
  animates.
* A manufacturer-specific effects cluster (0xfd00) selects the scene and
  tunes its speed and intensity (src/effects_cluster.rs). It uses 0xc0de as
  a development manufacturer code, which is also what the node descriptor
  now reports instead of the NXP code it had borrowed.
* A ZHA quirk exposes the cluster as a select and two number entities
  (ha/zha_quirks/smart_light.py). Copy it to a folder set as ZHA's
  custom_quirks_path.
* Ignore Python bytecode.

vendor/zigbee-rs is not vendored here: it stays a submodule, now tracking
feature/lighting-effects-integration on the fork. That branch adds the
manufacturer-specific cluster support and Identify Trigger Effect on top of
the RGB colour control work, each of which is also on its own branch for
upstream.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Matt SpencerandCopilot committed 2026-11-28 22:22:08 +00:00
1 parent cb4b38fc01
commit 115f245484
10 files changed
+665 -13

No files matched your search

+3 -1
View File
@@ -1,3 +1,5 @@
/target /target
/vendor/zigbee-rs/target /vendor/zigbee-rs/target
/nda /nda
__pycache__/
*.pyc
+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/rgb-color-control-integration branch = feature/lighting-effects-integration
+116
View File
@@ -0,0 +1,116 @@
"""ZHA quirk for the smart-light effects cluster.
The light serves a manufacturer-specific cluster (0xFD00, manufacturer code
0xC0DE) through which Home Assistant picks an animated scene and tunes it. ZHA
cannot talk to a cluster it has no definition for, so this quirk supplies one
and turns its attributes into entities:
* a select for the effect (Off, Rainbow, Pulse, Comet)
* a number for the speed, and one for the intensity
The scene plays in the light's own colour and brightness, so the light's
on/off, brightness and colour controls keep working while one runs.
The identifiers here have to match the firmware: src/effects_cluster.rs.
Install: copy this file into a folder under the Home Assistant config
directory, point ZHA at it in configuration.yaml, and restart Home Assistant:
zha:
custom_quirks_path: /config/custom_zha_quirks/
The Zigbee device is then listed with the extra entities.
Untested against a running ZHA: the import fallbacks below are there because
the quirk authoring API has moved between releases.
"""
import zigpy.types as t
from zigpy.zcl.foundation import BaseAttributeDefs, ZCLAttributeDef
try:
from zhaquirks.clusters import CustomCluster
except ImportError: # older zha-quirks
from zhaquirks import CustomCluster
try:
from zhaquirks.builder import EntityType, QuirkBuilder
except ImportError: # older zha-quirks
from zigpy.quirks.v2 import QuirkBuilder
from zigpy.quirks.v2.homeassistant import EntityType
CLUSTER_ID = 0xFD00
# a development code: the device has no manufacturer code of its own
MANUFACTURER_CODE = 0xC0DE
class SmartLightEffect(t.enum8):
"""The scene playing."""
Off = 0x00
Rainbow = 0x01
Pulse = 0x02
Comet = 0x03
class SmartLightEffectsCluster(CustomCluster):
"""The light's effects cluster."""
cluster_id = CLUSTER_ID
ep_attribute = "smart_light_effects"
# without this, ZHA would use the device's node descriptor code
manufacturer_id_override = MANUFACTURER_CODE
class AttributeDefs(BaseAttributeDefs):
"""Attribute definitions."""
effect = ZCLAttributeDef(
id=0x0000,
type=SmartLightEffect,
is_manufacturer_specific=True,
)
speed = ZCLAttributeDef(
id=0x0001,
type=t.uint8_t,
is_manufacturer_specific=True,
)
intensity = ZCLAttributeDef(
id=0x0002,
type=t.uint8_t,
is_manufacturer_specific=True,
)
(
QuirkBuilder("smart-light", "smart-light.ws2812")
.adds(SmartLightEffectsCluster)
.enum(
SmartLightEffectsCluster.AttributeDefs.effect.name,
SmartLightEffect,
SmartLightEffectsCluster.cluster_id,
entity_type=EntityType.STANDARD,
translation_key="effect",
fallback_name="Effect",
)
.number(
SmartLightEffectsCluster.AttributeDefs.speed.name,
SmartLightEffectsCluster.cluster_id,
min_value=0,
max_value=255,
step=1,
entity_type=EntityType.STANDARD,
translation_key="effect_speed",
fallback_name="Effect speed",
)
.number(
SmartLightEffectsCluster.AttributeDefs.intensity.name,
SmartLightEffectsCluster.cluster_id,
min_value=0,
max_value=255,
step=1,
entity_type=EntityType.STANDARD,
translation_key="effect_intensity",
fallback_name="Effect intensity",
)
.add_to_registry()
)
+162
View File
@@ -0,0 +1,162 @@
//! Short visual effects played over the light's normal state.
//!
//! An effect only changes what is drawn: the stored on/off state, level and
//! colour are untouched, so the light returns to exactly what it was showing
//! when the effect ends.
use core::cell::Cell;
use embassy_sync::blocking_mutex::Mutex;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_time::Instant;
use smart_leds::RGB8;
const GREEN: RGB8 = RGB8 { r: 0, g: 255, b: 0 };
const ORANGE: RGB8 = RGB8 {
r: 255,
g: 100,
b: 0,
};
/// Level an effect is drawn at when the light is off, so it can still be seen.
pub const OFF_LEVEL: u8 = 128;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Effect {
/// One flash.
Blink,
/// A one second fade up and down, repeated 15 times.
Breathe,
/// Two flashes in green.
Okay,
/// Orange for 8 seconds.
ChannelChange,
}
impl Effect {
const fn cycle_ms(self) -> u32 {
match self {
Self::Blink | Self::Breathe => 1000,
Self::Okay => 600,
Self::ChannelChange => 8000,
}
}
const fn cycles(self) -> u32 {
match self {
Self::Blink | Self::ChannelChange => 1,
Self::Breathe => 15,
Self::Okay => 2,
}
}
/// Colour drawn in place of the light's own, if the effect has one.
const fn colour(self) -> Option<RGB8> {
match self {
Self::Okay => Some(GREEN),
Self::ChannelChange => Some(ORANGE),
Self::Blink | Self::Breathe => None,
}
}
/// Brightness scale, 0..=255, `phase_ms` into one cycle.
const fn gain(self, phase_ms: u32) -> u8 {
match self {
Self::Blink => {
if phase_ms < 500 {
255
} else {
0
}
}
Self::Okay => {
if phase_ms < 300 {
255
} else {
0
}
}
// a triangle: up for the first half, down for the second
Self::Breathe => {
let rising = if phase_ms < 500 {
phase_ms
} else {
1000 - phase_ms
};
(rising * 255 / 500) as u8
}
Self::ChannelChange => 255,
}
}
}
#[derive(Clone, Copy)]
struct Active {
effect: Effect,
started: Instant,
duration_ms: u32,
}
static ACTIVE: Mutex<CriticalSectionRawMutex, Cell<Option<Active>>> = Mutex::new(Cell::new(None));
/// What to draw for the current frame of an effect.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Overlay {
pub colour: Option<RGB8>,
pub gain: u8,
}
/// Play `effect`, replacing any already playing.
pub fn start(effect: Effect) {
ACTIVE.lock(|active| {
active.set(Some(Active {
effect,
started: Instant::now(),
duration_ms: effect.cycle_ms() * effect.cycles(),
}));
});
}
/// Let the cycle in progress complete, then stop.
pub fn finish() {
ACTIVE.lock(|cell| {
if let Some(mut active) = cell.get() {
let cycle = active.effect.cycle_ms();
let elapsed = elapsed_ms(active.started);
active.duration_ms = active.duration_ms.min((elapsed / cycle + 1) * cycle);
cell.set(Some(active));
}
});
}
/// Stop as soon as possible.
pub fn stop() {
ACTIVE.lock(|active| active.set(None));
}
pub fn is_active() -> bool {
ACTIVE.lock(|active| active.get().is_some())
}
/// The overlay for this instant, or `None` once the effect is over (which also
/// retires it).
pub fn overlay() -> Option<Overlay> {
ACTIVE.lock(|cell| {
let active = cell.get()?;
let elapsed = elapsed_ms(active.started);
if elapsed >= active.duration_ms {
cell.set(None);
return None;
}
let effect = active.effect;
Some(Overlay {
colour: effect.colour(),
gain: effect.gain(elapsed % effect.cycle_ms()),
})
})
}
fn elapsed_ms(since: Instant) -> u32 {
u32::try_from(since.elapsed().as_millis()).unwrap_or(u32::MAX)
}
+133
View File
@@ -0,0 +1,133 @@
//! The light's own effects cluster: a manufacturer-specific cluster through
//! which a coordinator selects a scene and tunes it.
//!
//! The cluster is not part of the Zigbee Cluster Library, so nothing speaks it
//! without help: Home Assistant needs the quirk in `ha/zha_quirks`, which
//! defines the same identifiers.
//!
//! Scenes are not an on/off thing. They play in the light's own colour and
//! brightness, so the standard controls keep working while one runs.
use zigbee::zcl::frame::Status;
use zigbee::zcl::server::ClusterServer;
use zigbee::zcl::types::descriptors::AttrInfo;
use zigbee::zcl::types::descriptors::Attribute;
use zigbee::zcl::types::descriptors::Cluster;
use zigbee::zcl::types::descriptors::ReadWrite;
use zigbee::zcl::types::enums::Enum8;
use zigbee::zcl::types::enums::ZclEnum8;
use zigbee::zcl::types::ids::AttributeId;
use zigbee::zcl::types::ids::ClusterId;
use zigbee::zcl::types::ids::ManufacturerCode;
use zigbee::zcl::types::ids::TypeId;
use zigbee::zcl::types::integers::Uint8;
use zigbee::zdo::ClusterReply;
use zigbee::zdo::ClusterRequest;
use zigbee::zdo::ClusterRequestHandler;
use crate::light;
use crate::scene;
use crate::scene::Scene;
/// A development code: this device has no manufacturer code of its own. Not
/// assigned to anyone in zigbee-herdsman's list of known codes, but unregistered.
pub const MANUFACTURER_CODE: u16 = 0xc0de;
/// Manufacturer-specific cluster identifiers run from 0xfc00 to 0xffff.
const CLUSTER_ID_VALUE: u16 = 0xfd00;
pub const CLUSTER: Cluster = Cluster::manufacturer_specific(
ClusterId(CLUSTER_ID_VALUE),
ManufacturerCode(MANUFACTURER_CODE),
"SmartLightEffects",
);
/// Cluster identifier, for the endpoint's cluster list.
pub const CLUSTER_ID: u16 = CLUSTER.id().0;
/// The scene playing: 0 none, 1 rainbow, 2 pulse, 3 comet.
pub const EFFECT: Attribute<Enum8<Scene>, ReadWrite> =
CLUSTER.attribute(AttributeId(0x0000), "Effect");
/// How fast the scene moves, 0 slowest to 255 fastest.
pub const SPEED: Attribute<Uint8, ReadWrite> = CLUSTER.attribute(AttributeId(0x0001), "Speed");
/// How pronounced the scene is: rainbow repeats, pulse depth, comet tail.
pub const INTENSITY: Attribute<Uint8, ReadWrite> =
CLUSTER.attribute(AttributeId(0x0002), "Intensity");
const ATTRIBUTES: &[AttrInfo] = &[EFFECT.attr_info(), SPEED.attr_info(), INTENSITY.attr_info()];
impl ZclEnum8 for Scene {
fn from_raw(raw: u8) -> Option<Self> {
Scene::from_raw(raw)
}
fn into_raw(self) -> u8 {
self as u8
}
}
/// Serves the effects cluster; the state lives in [`crate::scene`].
pub struct EffectsServer;
impl ClusterServer for EffectsServer {
fn cluster(&self) -> Cluster {
CLUSTER
}
fn attributes(&self) -> &'static [AttrInfo] {
ATTRIBUTES
}
fn encode_value(&self, id: AttributeId, out: &mut [u8], offset: &mut usize) -> Status {
let encoded = match id.0 {
0x0000 => EFFECT.encode(scene::scene(), out, offset),
0x0001 => SPEED.encode(Uint8(scene::speed()), out, offset),
0x0002 => INTENSITY.encode(Uint8(scene::intensity()), out, offset),
_ => return Status::UnsupportedAttribute,
};
encoded.map_or(Status::InsufficientSpace, |()| Status::Success)
}
fn decode_value(
&self,
id: AttributeId,
type_id: TypeId,
bytes: &[u8],
offset: &mut usize,
) -> Status {
match id.0 {
0x0000 => match EFFECT.decode(type_id, bytes, offset) {
Ok(scene) => {
light::set_scene(scene);
Status::Success
}
// the right type but not one of the scenes, or the wrong type
Err(_) if type_id == EFFECT.type_id() => Status::InvalidValue,
Err(_) => Status::InvalidDataType,
},
0x0001 => match SPEED.decode(type_id, bytes, offset) {
Ok(Uint8(speed)) => {
scene::set_speed(speed);
Status::Success
}
Err(_) => Status::InvalidDataType,
},
0x0002 => match INTENSITY.decode(type_id, bytes, offset) {
Ok(Uint8(intensity)) => {
scene::set_intensity(intensity);
Status::Success
}
Err(_) => Status::InvalidDataType,
},
_ => Status::UnsupportedAttribute,
}
}
}
impl ClusterRequestHandler for EffectsServer {
fn handle(&self, request: &ClusterRequest<'_>, out: &mut [u8]) -> Option<ClusterReply> {
self.handle_request(request, out)
}
}
+61 -6
View File
@@ -8,8 +8,10 @@ use core::sync::atomic::AtomicBool;
use core::sync::atomic::AtomicU8; use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering; use core::sync::atomic::Ordering;
use embassy_futures::select::select;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal; use embassy_sync::signal::Signal;
use embassy_time::Timer;
use smart_leds::RGB8; 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;
@@ -19,6 +21,10 @@ 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::effect;
#[cfg(feature = "zigbee")]
pub use crate::effect::Effect;
use crate::scene;
use crate::strip::Strip; use crate::strip::Strip;
/// Colour temperature presets, warmest first, as sRGB with the brightest /// Colour temperature presets, warmest first, as sRGB with the brightest
@@ -140,12 +146,43 @@ pub fn next_temperature() -> (u16, RGB8) {
temperature() temperature()
} }
/// Plays `effect` over the light, then returns to the state it was in.
#[cfg(feature = "zigbee")]
pub fn play_effect(effect: effect::Effect) {
effect::start(effect);
DIRTY.signal(());
}
/// Switches the continuous scene, which `Off` ends.
#[cfg(feature = "zigbee")]
pub fn set_scene(scene: scene::Scene) {
scene::set_scene(scene);
DIRTY.signal(());
}
/// Lets the effect's current cycle complete, then stops it.
#[cfg(feature = "zigbee")]
pub fn finish_effect() {
effect::finish();
DIRTY.signal(());
}
#[cfg(feature = "zigbee")]
pub fn stop_effect() {
effect::stop();
DIRTY.signal(());
}
#[embassy_executor::task] #[embassy_executor::task]
pub async fn render_task(mut strip: Strip<'static>) { 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 {
let colour = if is_color_mode() { let overlay = effect::overlay();
let colour = if let Some(colour) = overlay.and_then(|overlay| overlay.colour) {
colour
} else if is_color_mode() {
if XY_MODE.load(Ordering::Relaxed) { if XY_MODE.load(Ordering::Relaxed) {
xy_to_rgb(X.load(Ordering::Relaxed), Y.load(Ordering::Relaxed)) xy_to_rgb(X.load(Ordering::Relaxed), Y.load(Ordering::Relaxed))
} else { } else {
@@ -158,15 +195,28 @@ pub async fn render_task(mut strip: Strip<'static>) {
} else { } else {
temperature().1 temperature().1
}; };
frame.fill(colour); // an effect that names a colour takes the whole strip; otherwise a
// running scene draws it, and failing both the light shows one colour
if overlay.is_none_or(|overlay| overlay.colour.is_none()) && scene::is_active() {
scene::render(&mut frame, colour);
} else {
frame.fill(colour);
}
// 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. an effect is drawn even
let level = if is_on() { // when the light is off, or it could not be seen
(u16::from(brightness()) * u16::from(MAX_DUTY) / 255) as u8 let base = if is_on() {
brightness()
} else if overlay.is_some() {
effect::OFF_LEVEL
} else { } else {
0 0
}; };
let level = (u16::from(base) * u16::from(MAX_DUTY) / 255) as u8;
let level = overlay.map_or(level, |overlay| {
(u16::from(level) * u16::from(overlay.gain) / 255) as u8
});
// gamma is applied to the level, not the pixels: curving each channel // gamma is applied to the level, not the pixels: curving each channel
// of an already white-balanced colour would shift its temperature // of an already white-balanced colour would shift its temperature
@@ -183,7 +233,12 @@ pub async fn render_task(mut strip: Strip<'static>) {
log::warn!("strip write failed: {e:?}"); log::warn!("strip write failed: {e:?}");
} }
DIRTY.wait().await; if effect::is_active() || scene::is_active() {
// redraw on a timer while something animates, and still on demand
select(DIRTY.wait(), Timer::after_millis(scene::FRAME_MS)).await;
} else {
DIRTY.wait().await;
}
} }
} }
+6
View File
@@ -2,8 +2,14 @@
#![no_main] #![no_main]
mod config; mod config;
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
mod effect;
#[cfg(feature = "zigbee")]
mod effects_cluster;
mod encoder; mod encoder;
mod light; mod light;
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
mod scene;
mod status; mod status;
mod strip; mod strip;
#[cfg(feature = "zigbee")] #[cfg(feature = "zigbee")]
+155
View File
@@ -0,0 +1,155 @@
//! Continuous scenes: animations that run on the strip until switched off.
//!
//! A scene draws the whole frame, using the light's own colour where it has
//! one, so the normal brightness and on/off controls keep working while it
//! plays. Everything is integer arithmetic: the strip is redrawn many times a
//! second on a chip with no floating point hardware.
use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering;
use embassy_time::Instant;
use smart_leds::RGB8;
use smart_leds::hsv::Hsv;
use smart_leds::hsv::hsv2rgb;
/// How often a frame is redrawn while a scene plays.
pub const FRAME_MS: u64 = 20;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Scene {
/// The normal light: no animation.
Off = 0,
/// Hue rotating along the strip, in the scene's own colours.
Rainbow = 1,
/// The whole strip fades up and down in the light's colour.
Pulse = 2,
/// A bright head chasing around the strip, trailing off behind it.
Comet = 3,
}
impl Scene {
pub const fn from_raw(raw: u8) -> Option<Self> {
match raw {
0 => Some(Self::Off),
1 => Some(Self::Rainbow),
2 => Some(Self::Pulse),
3 => Some(Self::Comet),
_ => None,
}
}
}
static SCENE: AtomicU8 = AtomicU8::new(Scene::Off as u8);
static SPEED: AtomicU8 = AtomicU8::new(128);
static INTENSITY: AtomicU8 = AtomicU8::new(128);
pub fn scene() -> Scene {
Scene::from_raw(SCENE.load(Ordering::Relaxed)).unwrap_or(Scene::Off)
}
pub fn set_scene(scene: Scene) {
SCENE.store(scene as u8, Ordering::Relaxed);
}
pub fn speed() -> u8 {
SPEED.load(Ordering::Relaxed)
}
pub fn set_speed(speed: u8) {
SPEED.store(speed, Ordering::Relaxed);
}
pub fn intensity() -> u8 {
INTENSITY.load(Ordering::Relaxed)
}
pub fn set_intensity(intensity: u8) {
INTENSITY.store(intensity, Ordering::Relaxed);
}
pub fn is_active() -> bool {
scene() != Scene::Off
}
/// Draws the current scene into `frame`, with `colour` as the light's own
/// colour. Leaves the frame alone when no scene is active.
pub fn render(frame: &mut [RGB8], colour: RGB8) {
let now = u32::try_from(Instant::now().as_millis() % u64::from(u32::MAX)).unwrap_or(0);
draw(scene(), speed(), intensity(), frame, colour, now);
}
fn draw(scene: Scene, speed: u8, intensity: u8, frame: &mut [RGB8], colour: RGB8, now_ms: u32) {
match scene {
Scene::Off => {}
Scene::Rainbow => rainbow(frame, speed, intensity, now_ms),
Scene::Pulse => frame.fill(scale(colour, pulse_gain(speed, intensity, now_ms))),
Scene::Comet => comet(frame, colour, speed, intensity, now_ms),
}
}
/// Hue turns once along the strip per repeat; intensity sets 1 to 4 repeats,
/// and speed how fast the pattern turns (about 12 s per turn down to 0.5 s).
fn rainbow(frame: &mut [RGB8], speed: u8, intensity: u8, now_ms: u32) {
let period = 12_000u32.saturating_sub(45 * u32::from(speed)).max(500);
let repeats = 1 + u32::from(intensity) / 64;
let count = frame.len().max(1) as u32;
let turn = (now_ms % period) * 256 / period;
for (index, pixel) in frame.iter_mut().enumerate() {
let along = index as u32 * 256 * repeats / count;
*pixel = hsv2rgb(Hsv {
hue: ((along + turn) % 256) as u8,
sat: 255,
val: 255,
});
}
}
/// A triangle wave, `intensity` deep: at full depth the trough is dark, at
/// zero the strip does not move. Speed sets the period (about 4 s down to
/// 0.4 s).
fn pulse_gain(speed: u8, intensity: u8, now_ms: u32) -> u8 {
let period = 4_000u32.saturating_sub(14 * u32::from(speed)).max(400);
let phase = now_ms % period;
let rising = if phase * 2 < period {
phase * 2
} else {
period * 2 - phase * 2
};
let triangle = rising * 255 / period;
let depth = u32::from(intensity);
(255 - depth * (255 - triangle) / 255) as u8
}
/// A head that advances one pixel every 15 to 250 ms, with a tail from 2
/// pixels to the whole strip as intensity rises.
fn comet(frame: &mut [RGB8], colour: RGB8, speed: u8, intensity: u8, now_ms: u32) {
let count = frame.len() as u32;
if count == 0 {
return;
}
let step_ms = 250u32.saturating_sub(u32::from(speed)).max(15);
let head = (now_ms / step_ms) % count;
let tail = (2 + u32::from(intensity) * count.saturating_sub(2) / 255).min(count);
for (index, pixel) in frame.iter_mut().enumerate() {
// pixels behind the head, counting back from it
let behind = (head + count - index as u32) % count;
*pixel = if behind < tail {
scale(colour, (255 - behind * 255 / tail) as u8)
} else {
RGB8::default()
};
}
}
fn scale(colour: RGB8, gain: u8) -> RGB8 {
let scale = |channel: u8| (u16::from(channel) * u16::from(gain) / 255) as u8;
RGB8 {
r: scale(colour.r),
g: scale(colour.g),
b: scale(colour.b),
}
}
+27 -4
View File
@@ -28,6 +28,7 @@ use zigbee::zdo::descriptor::PowerDescriptorConfig;
use zigbee_cluster_library::clusters::general::basic; use zigbee_cluster_library::clusters::general::basic;
use zigbee_cluster_library::clusters::general::basic::BasicServer; use zigbee_cluster_library::clusters::general::basic::BasicServer;
use zigbee_cluster_library::clusters::general::identify; use zigbee_cluster_library::clusters::general::identify;
use zigbee_cluster_library::clusters::general::identify::Effect;
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;
@@ -53,6 +54,8 @@ use zigbee_mac::esp::EspMlme;
use zigbee_types::IeeeAddress; use zigbee_types::IeeeAddress;
use zigbee_types::ShortAddress; use zigbee_types::ShortAddress;
use crate::effects_cluster;
use crate::effects_cluster::EffectsServer;
use crate::light; use crate::light;
/// Flash region reserved for Zigbee persistence. /// Flash region reserved for Zigbee persistence.
@@ -78,12 +81,13 @@ 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; 5] = [ static INPUT_CLUSTERS: [u16; 6] = [
basic::CLUSTER_ID, basic::CLUSTER_ID,
identify::CLUSTER_ID, identify::CLUSTER_ID,
on_off::CLUSTER_ID, on_off::CLUSTER_ID,
level_control::CLUSTER_ID, level_control::CLUSTER_ID,
color_control::CLUSTER_ID, color_control::CLUSTER_ID,
effects_cluster::CLUSTER_ID,
]; ];
static OUTPUT_CLUSTERS: [u16; 0] = []; static OUTPUT_CLUSTERS: [u16; 0] = [];
@@ -117,6 +121,7 @@ static LEVEL_CONTROL: LevelControlServer<'static> =
LevelControlServer::new(128).with_reporting(&REPORTING); LevelControlServer::new(128).with_reporting(&REPORTING);
static COLOR_CONTROL: ColorControlServer<'static> = static COLOR_CONTROL: ColorControlServer<'static> =
ColorControlServer::new(370).with_reporting(&REPORTING); ColorControlServer::new(370).with_reporting(&REPORTING);
static EFFECTS: EffectsServer = EffectsServer;
type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>; type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>;
@@ -131,7 +136,10 @@ type Handler = (
&'static OnOffServer<'static>, &'static OnOffServer<'static>,
( (
&'static LevelControlServer<'static>, &'static LevelControlServer<'static>,
(&'static ColorControlServer<'static>, UnsupportedClusterResponder<'static>), (
&'static ColorControlServer<'static>,
(&'static EffectsServer, UnsupportedClusterResponder<'static>),
),
), ),
), ),
), ),
@@ -150,7 +158,10 @@ pub fn handler() -> Handler {
&LEVEL_CONTROL, &LEVEL_CONTROL,
( (
&COLOR_CONTROL, &COLOR_CONTROL,
UnsupportedClusterResponder::new(&INPUT_CLUSTERS), (
&EFFECTS,
UnsupportedClusterResponder::new(&INPUT_CLUSTERS),
),
), ),
), ),
), ),
@@ -176,7 +187,7 @@ pub fn config() -> StackConfig<'static> {
node: NodeDescriptorConfig { node: NodeDescriptorConfig {
// bit 3: 2400 MHz band // bit 3: 2400 MHz band
frequency_band: 0x08, frequency_band: 0x08,
manufacturer_code: 0x1037, manufacturer_code: effects_cluster::MANUFACTURER_CODE,
maximum_buffer_size: 80, maximum_buffer_size: 80,
maximum_incoming_transfer_size: 128, maximum_incoming_transfer_size: 128,
server_mask: 0, server_mask: 0,
@@ -275,6 +286,18 @@ pub async fn lighting_task(stack: &'static Stack) {
loop { loop {
Timer::after(Duration::from_millis(50)).await; Timer::after(Duration::from_millis(50)).await;
if let Some(effect) = IDENTIFY.take_effect() {
log::info!("Zigbee Trigger Effect: {effect:?}");
match effect {
Effect::Blink => light::play_effect(light::Effect::Blink),
Effect::Breathe => light::play_effect(light::Effect::Breathe),
Effect::Okay => light::play_effect(light::Effect::Okay),
Effect::ChannelChange => light::play_effect(light::Effect::ChannelChange),
Effect::FinishEffect => light::finish_effect(),
Effect::StopEffect => light::stop_effect(),
}
}
if let Some(on) = LEVEL_CONTROL.take_on_off_change() { if let Some(on) = LEVEL_CONTROL.take_on_off_change() {
ON_OFF.set_on_off(on); ON_OFF.set_on_off(on);
} }