10 Commits
Author SHA1 Message Date
Matt SpencerandCopilot 115f245484 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>
2026-11-28 22:22:08 +00:00
Matt SpencerandCopilot cb4b38fc01 chore: rebase zigbee-rs integration onto upstream main
The level and color temperature work was merged upstream, so the RGB
integration branch now sits directly on main. Track that branch.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 15:48:04 +00:00
Matt Spencer e8e7d78714 chore: update zigbee-rs RGB integration 2026-11-17 23:47:57 +00:00
Matt Spencer 3e5ef7570f feat: add RGB color picker support 2026-11-17 23:26:50 +00:00
Matt Spencer f7f97e8685 chore: track lighting integration branch 2026-11-16 00:45:33 +00:00
Matt Spencer 65f951b890 feat: add Zigbee brightness and color temperature 2026-11-16 00:33:54 +00:00
Matt Spencer 1aa6ba3c5f feat: add Zigbee-controlled smart light 2026-11-15 23:22:20 +00:00
Matt Spencer 9793bc62af feat(encoder): trigger on B and sample A
Waiting on both phases via select drops the pending future each time the
other fires, so B's edges were being lost and a later sample of B always
read it back at rest. Triggering on B's falling edge and sampling A there
is stable on this encoder.

Also moves the encoder to D10/D9/D8 next to the power pads, drops the
strip to a single LED for bring-up, and makes saturation an adjustable
axis so the light defaults to white.
2026-10-17 18:22:09 +01:00
Matt Spencer b0e3b6f4a0 fix(flash): give zigbee persistence its own partition
The default espflash layout hands the whole 0x10000..0x400000 span to the
app partition, so the storage range sat inside it. Shrink the app and
reserve a dedicated storage partition above it.
2026-10-17 16:13:47 +01:00
Matt Spencer 74b3a4a06b feat(status): blink the on-board LED as a heartbeat
Also moves the encoder and button onto XIAO ESP32C6 pads: GPIO4/5/6 are
JTAG pins and are not broken out on this board.
2026-10-17 16:08:30 +01:00
20 changed files with 1503 additions and 190 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
target = "riscv32imac-unknown-none-elf"
[target.riscv32imac-unknown-none-elf]
runner = "espflash flash --monitor"
runner = "espflash flash --monitor --partition-table partitions.csv"
rustflags = [
"-C", "link-arg=-Tlinkall.x",
"-C", "force-frame-pointers",
+3
View File
@@ -1,2 +1,5 @@
/target
/vendor/zigbee-rs/target
/nda
__pycache__/
*.pyc
+2 -2
View File
@@ -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/lighting-effects-integration
Generated
+32 -1
View File
@@ -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"
@@ -1399,6 +1419,12 @@ version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linked_list_allocator"
version = "0.10.6"
@@ -1829,6 +1855,7 @@ dependencies = [
"esp-radio",
"esp-rtos",
"esp-storage",
"libm",
"log",
"smart-leds",
"smart-leds-trait",
@@ -2206,6 +2233,7 @@ dependencies = [
name = "zigbee"
version = "0.1.0"
dependencies = [
"defmt-or-log",
"embedded-hal-async",
"log",
"zigbee-base-device-behavior",
@@ -2219,6 +2247,7 @@ dependencies = [
name = "zigbee-base-device-behavior"
version = "0.1.0"
dependencies = [
"defmt-or-log",
"embedded-hal-async",
"log",
"spin",
@@ -2249,6 +2278,7 @@ dependencies = [
"aes",
"byte",
"ccm 0.5.0",
"defmt-or-log",
"embedded-hal-async",
"embedded-storage-async",
"heapless 0.9.3",
@@ -2267,6 +2297,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 +2326,6 @@ dependencies = [
"byte",
"embedded-storage",
"heapless 0.9.3",
"itertools",
"spin",
"zigbee-macros",
]
+12 -8
View File
@@ -4,17 +4,20 @@ version = "0.1.0"
edition = "2024"
[features]
default = ["esp32c6"]
default = ["esp32c6", "zigbee"]
## Join a Zigbee network. Disable to bring up the local hardware on its own:
## the stack reboots the device when it cannot find its coordinator.
zigbee = ["dep:esp-radio", "dep:zigbee", "dep:zigbee-cluster-library", "dep:zigbee-mac", "dep:zigbee-types"]
esp32c6 = [
"esp-alloc/esp32c6",
"esp-backtrace/esp32c6",
"esp-bootloader-esp-idf/esp32c6",
"esp-hal/esp32c6",
"esp-println/esp32c6",
"esp-radio/esp32c6",
"esp-radio?/esp32c6",
"esp-rtos/esp32c6",
"esp-storage/esp32c6",
"zigbee-mac/esp32c6",
"zigbee-mac?/esp32c6",
]
[dependencies]
@@ -23,7 +26,7 @@ esp-backtrace = { version = "0.20", features = ["panic-handler", "println"] }
esp-bootloader-esp-idf = "0.6"
esp-hal = { version = "1.2", features = ["log-04", "unstable"] }
esp-println = { version = "0.18", features = ["log-04"] }
esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"] }
esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"], optional = true }
esp-rtos = { version = "0.4", features = ["embassy", "log-04"] }
esp-storage = { version = "0.10", features = ["embedded-storage"] }
@@ -39,13 +42,14 @@ log = "0.4"
smart-leds = "0.4"
smart-leds-trait = "0.3"
esp-hal-smartled = "0.18"
libm = "0.2"
# vendored upstream: the lighting cluster is not implemented there yet, so the
# path dependency lets us add it in-tree and upstream it later
zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"] }
zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library" }
zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac" }
zigbee-types = { path = "vendor/zigbee-rs/zigbee-types" }
zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"], optional = true }
zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library", optional = true }
zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac", optional = true }
zigbee-types = { path = "vendor/zigbee-rs/zigbee-types", optional = true }
[profile.release]
debug = true
+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()
)
+7
View File
@@ -0,0 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x6000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 0x3D0000,
# Zigbee persistence: the stack writes this region directly, so it must not
# overlap the app partition. Keep in sync with FLASH_RANGE in zigbee_stack.rs.
storage, data, nvs, 0x3E0000, 0x20000,
1 # Name, Type, SubType, Offset, Size, Flags
2 nvs, data, nvs, 0x9000, 0x6000,
3 phy_init, data, phy, 0xf000, 0x1000,
4 factory, app, factory, 0x10000, 0x3D0000,
5 # Zigbee persistence: the stack writes this region directly, so it must not
6 # overlap the app partition. Keep in sync with FLASH_RANGE in zigbee_stack.rs.
7 storage, data, nvs, 0x3E0000, 0x20000,
+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;
}
}
+89
View File
@@ -0,0 +1,89 @@
//! Pin-level diagnostic: polls every XIAO pad, alternating pull-up and
//! pull-down, and logs whichever pads change.
//!
//! Deliberately avoids interrupts, so a wiring fault (nothing ever changes) is
//! distinguishable from an interrupt fault (levels move but `encoder_task`
//! stays silent).
//!
//! Scanning every pad catches wires landing somewhere unexpected, and
//! alternating the pull settles whether the encoder's common pin is tied to
//! GND (active low, needs pull-up) or to + (active high, needs pull-down).
//!
//! Run with:
//! cargo run --release --no-default-features --features esp32c6 --bin pin_diag
#![no_std]
#![no_main]
use embassy_time::Duration;
use embassy_time::Timer;
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::gpio::Input;
use esp_hal::gpio::InputConfig;
use esp_hal::gpio::Pull;
use esp_hal::timer::timg::TimerGroup;
esp_bootloader_esp_idf::esp_app_desc!();
/// How long to watch in each pull configuration.
const PHASE_SECS: u32 = 8;
#[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 timg0 = TimerGroup::new(peripherals.TIMG0);
esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0);
let up = InputConfig::default().with_pull(Pull::Up);
// every pad broken out on the XIAO ESP32C6, in silkscreen order
let mut pads = [
("D0/GPIO0", Input::new(peripherals.GPIO0, up)),
("D1/GPIO1", Input::new(peripherals.GPIO1, up)),
("D2/GPIO2", Input::new(peripherals.GPIO2, up)),
("D3/GPIO21", Input::new(peripherals.GPIO21, up)),
("D4/GPIO22", Input::new(peripherals.GPIO22, up)),
("D5/GPIO23", Input::new(peripherals.GPIO23, up)),
("D6/GPIO16", Input::new(peripherals.GPIO16, up)),
("D7/GPIO17", Input::new(peripherals.GPIO17, up)),
("D8/GPIO19", Input::new(peripherals.GPIO19, up)),
("D9/GPIO20", Input::new(peripherals.GPIO20, up)),
("D10/GPIO18", Input::new(peripherals.GPIO18, up)),
];
log::info!("pin_diag: scanning every pad, alternating pull-up and pull-down");
log::info!("keep turning the knob and pressing it through both phases");
let mut previous = [false; 11];
loop {
for pull in [Pull::Up, Pull::Down] {
let config = InputConfig::default().with_pull(pull);
for (_, pin) in pads.iter_mut() {
pin.apply_config(&config);
}
// let the pull charge the pin before sampling the baseline
Timer::after(Duration::from_millis(10)).await;
log::info!("--- pull {pull:?} for {PHASE_SECS}s ---");
for (index, (name, pin)) in pads.iter().enumerate() {
previous[index] = pin.is_high();
log::info!(" baseline {name} = {}", previous[index] as u8);
}
for _ in 0..(PHASE_SECS * 500) {
Timer::after(Duration::from_millis(2)).await;
for (index, (name, pin)) in pads.iter().enumerate() {
let level = pin.is_high();
if level != previous[index] {
log::info!(" {name} -> {}", level as u8);
previous[index] = level;
}
}
}
}
}
}
+7 -3
View File
@@ -3,12 +3,12 @@
//! Everything that changes when the hardware changes lives here.
/// Number of WS2812B pixels on the strip.
pub const LED_COUNT: usize = 60;
pub const LED_COUNT: usize = 24;
/// Ceiling on the duty cycle applied to every channel, as a fraction of 255.
///
/// Keeps the supply current within what the dev board's regulator can source
/// when every pixel is driven white.
/// Takes the top off peak current draw. This is a brightness cap, not a
/// current limit: a strip of this length still needs its own 5V supply.
pub const MAX_DUTY: u8 = 200;
/// Rotary encoder detents per full revolution, used to scale a turn into a
@@ -20,3 +20,7 @@ pub const LONG_PRESS_MS: u64 = 600;
/// Contact settle time for the encoder push button.
pub const DEBOUNCE_MS: u64 = 15;
/// Heartbeat blink: a brief pulse, repeated once a second.
pub const HEARTBEAT_ON_MS: u64 = 50;
pub const HEARTBEAT_PERIOD_MS: u64 = 1000;
+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)
}
}
+14 -47
View File
@@ -1,12 +1,11 @@
//! Interrupt-driven rotary encoder with a push button.
//!
//! Both tasks park on GPIO edge interrupts; nothing here polls. Quadrature is
//! decoded from the transition between the previous and current A/B pair, so a
//! bounce that returns to the previous state cancels itself out instead of
//! registering a step.
//! Both tasks park on GPIO edge interrupts; nothing here polls.
//!
//! Direction comes from sampling A on B's falling edge: one detent produces
//! exactly one such edge, and A's level there is opposite for the two
//! directions.
use embassy_futures::select::Either;
use embassy_futures::select::select;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel;
use embassy_time::Duration;
@@ -29,47 +28,19 @@ pub enum EncoderEvent {
/// drops the oldest step, which is preferable to blocking the interrupt task.
pub static EVENTS: Channel<CriticalSectionRawMutex, EncoderEvent, 8> = Channel::new();
/// Valid quadrature transitions, indexed by `(previous << 2) | current` where
/// each pair is `(a << 1) | b`. Zero marks either no movement or an illegal
/// jump of two states, which means a transition was missed.
#[rustfmt::skip]
const TRANSITIONS: [i8; 16] = [
0, -1, 1, 0,
1, 0, 0, -1,
-1, 0, 0, 1,
0, 1, -1, 0,
];
#[embassy_executor::task]
pub async fn encoder_task(mut a: Input<'static>, mut b: Input<'static>) {
let mut previous = state(&a, &b);
// a full detent is four quadrature transitions; only whole detents are
// reported so a resting-point jitter never moves the light
let mut substeps: i8 = 0;
pub async fn encoder_task(a: Input<'static>, mut b: Input<'static>) {
loop {
match select(a.wait_for_any_edge(), b.wait_for_any_edge()).await {
Either::First(()) | Either::Second(()) => {}
}
b.wait_for_falling_edge().await;
let current = state(&a, &b);
if current == previous {
continue;
}
// A must be read here, before the rest of the detent moves it
let delta = if a.is_high() { -1 } else { 1 };
log::info!("edge on B -> A={} rotate {delta:+}", a.is_high() as u8);
let _ = EVENTS.try_send(EncoderEvent::Rotate(delta));
let delta = TRANSITIONS[(previous << 2) | current];
previous = current;
if delta == 0 {
continue;
}
substeps += delta;
if substeps.abs() >= 4 {
let detents = substeps / 4;
substeps -= detents * 4;
// full is fine: a dropped step during a spin is invisible
let _ = EVENTS.try_send(EncoderEvent::Rotate(detents));
}
// the rest of the detent returns B to rest; ignoring it stops one
// detent counting twice
b.wait_for_rising_edge().await;
}
}
@@ -101,7 +72,3 @@ pub async fn button_task(mut button: Input<'static>) {
Timer::after(Duration::from_millis(DEBOUNCE_MS)).await;
}
}
fn state(a: &Input<'static>, b: &Input<'static>) -> usize {
usize::from(a.is_high()) << 1 | usize::from(b.is_high())
}
+195 -34
View File
@@ -8,8 +8,10 @@ use core::sync::atomic::AtomicBool;
use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering;
use embassy_futures::select::select;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use embassy_time::Timer;
use smart_leds::RGB8;
use smart_leds::SmartLedsWriteAsync;
use smart_leds::brightness as scale_brightness;
@@ -19,19 +21,37 @@ use smart_leds::hsv::hsv2rgb;
use crate::config::LED_COUNT;
use crate::config::MAX_DUTY;
use crate::effect;
#[cfg(feature = "zigbee")]
pub use crate::effect::Effect;
use crate::scene;
use crate::strip::Strip;
/// What a turn of the encoder adjusts.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
Brightness,
Hue,
}
/// 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);
/// Index into [`TEMPERATURES`]; 2700K is the warm white a lamp usually sits at.
static TEMPERATURE: AtomicU8 = AtomicU8::new(1);
static COLOR_MODE: AtomicBool = AtomicBool::new(false);
static XY_MODE: AtomicBool = AtomicBool::new(false);
static HUE: AtomicU8 = AtomicU8::new(0);
static HUE_MODE: AtomicBool = AtomicBool::new(false);
static SATURATION: AtomicU8 = AtomicU8::new(0);
static X: AtomicU8 = AtomicU8::new(122);
static Y: AtomicU8 = AtomicU8::new(128);
static DIRTY: Signal<CriticalSectionRawMutex, ()> = Signal::new();
pub fn is_on() -> bool {
@@ -53,6 +73,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) {
@@ -61,28 +86,91 @@ 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);
pub fn temperature_mireds() -> u16 {
(1_000_000u32 / u32::from(temperature().0)) as u16
}
pub fn is_color_mode() -> bool {
COLOR_MODE.load(Ordering::Relaxed)
}
pub fn set_hue_saturation(hue: u8, saturation: u8) {
HUE.store(hue.min(254), Ordering::Relaxed);
SATURATION.store(saturation.min(254), Ordering::Relaxed);
COLOR_MODE.store(true, Ordering::Relaxed);
XY_MODE.store(false, Ordering::Relaxed);
DIRTY.signal(());
}
pub fn mode() -> Mode {
if HUE_MODE.load(Ordering::Relaxed) {
Mode::Hue
} else {
Mode::Brightness
}
pub fn set_xy(x: u16, y: u16) {
X.store((u32::from(x) * 255 / 65_535) as u8, Ordering::Relaxed);
Y.store((u32::from(y) * 255 / 65_535) as u8, Ordering::Relaxed);
COLOR_MODE.store(true, Ordering::Relaxed);
XY_MODE.store(true, Ordering::Relaxed);
DIRTY.signal(());
}
pub fn toggle_mode() -> Mode {
HUE_MODE.fetch_xor(true, Ordering::Relaxed);
mode()
/// 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);
COLOR_MODE.store(false, Ordering::Relaxed);
XY_MODE.store(false, 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;
TEMPERATURE.store(next, Ordering::Relaxed);
COLOR_MODE.store(false, Ordering::Relaxed);
XY_MODE.store(false, Ordering::Relaxed);
DIRTY.signal(());
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]
@@ -90,26 +178,99 @@ pub async fn render_task(mut strip: Strip<'static>) {
let mut frame = [RGB8::default(); LED_COUNT];
loop {
frame.fill(hsv2rgb(Hsv {
hue: hue(),
sat: 255,
val: 255,
}));
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) {
xy_to_rgb(X.load(Ordering::Relaxed), Y.load(Ordering::Relaxed))
} else {
hsv2rgb(Hsv {
hue: (u16::from(HUE.load(Ordering::Relaxed)) * 255 / 254) as u8,
sat: (u16::from(SATURATION.load(Ordering::Relaxed)) * 255 / 254) as u8,
val: 255,
})
}
} else {
temperature().1
};
// 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
// the strip output and comes back as it was
let level = if is_on() {
(u16::from(brightness()) * u16::from(MAX_DUTY) / 255) as u8
// the strip output and comes back as it was. an effect is drawn even
// when the light is off, or it could not be seen
let base = if is_on() {
brightness()
} else if overlay.is_some() {
effect::OFF_LEVEL
} else {
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 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:?}");
}
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;
}
}
}
fn xy_to_rgb(x: u8, y: u8) -> RGB8 {
let x = f32::from(x) / 255.0;
let y = f32::from(y) / 255.0;
if y == 0.0 {
return RGB8::default();
}
let z = (1.0 - x - y) / y;
let x = x / y;
let mut red = 3.2406 * x - 1.5372 - 0.4986 * z;
let mut green = -0.9689 * x + 1.8758 + 0.0415 * z;
let mut blue = 0.0557 * x - 0.2040 + 1.0570 * z;
let max = red.max(green).max(blue).max(1.0);
red = (red / max).max(0.0);
green = (green / max).max(0.0);
blue = (blue / max).max(0.0);
fn srgb(value: f32) -> u8 {
let linear = if value <= 0.003_130_8 {
12.92 * value
} else {
1.055 * libm::powf(value, 1.0 / 2.4) - 0.055
};
(linear * 255.0 + 0.5) as u8
}
RGB8 {
r: srgb(red),
g: srgb(green),
b: srgb(blue),
}
}
+61 -42
View File
@@ -2,43 +2,42 @@
#![no_main]
mod config;
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
mod effect;
#[cfg(feature = "zigbee")]
mod effects_cluster;
mod encoder;
mod light;
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
mod scene;
mod status;
mod strip;
#[cfg(feature = "zigbee")]
mod zigbee_stack;
use embassy_embedded_hal::adapter::BlockingAsync;
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::gpio::Input;
use esp_hal::gpio::InputConfig;
use esp_hal::gpio::Level;
use esp_hal::gpio::Output;
use esp_hal::gpio::OutputConfig;
use esp_hal::gpio::Pull;
use esp_hal::rmt::Rmt;
use esp_hal::time::Rate;
use esp_hal::timer::timg::TimerGroup;
use esp_hal_smartled::WS2812B_TIMING;
use esp_radio::ieee802154::Ieee802154;
use esp_storage::FlashStorage;
use static_cell::StaticCell;
use zigbee_mac::esp::EspMlme;
use crate::config::STEPS_PER_BRIGHTNESS_UNIT;
use crate::encoder::EVENTS;
use crate::encoder::EncoderEvent;
use crate::light::Mode;
use crate::strip::Strip;
use crate::zigbee_stack::Stack;
esp_bootloader_esp_idf::esp_app_desc!();
static STACK: StaticCell<Stack> = StaticCell::new();
/// 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;
#[esp_rtos::main]
async fn main(spawner: embassy_executor::Spawner) -> ! {
esp_println::logger::init_logger_from_env();
@@ -55,55 +54,75 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
let rmt = Rmt::new(peripherals.RMT, rmt_freq)
.expect("init RMT")
.into_async();
// XIAO ESP32C6 pads: D2, D3, D4, D5. GPIO4/5/6 are JTAG and are not
// broken out on this board; GPIO3 and GPIO14 drive the antenna switch.
let strip = Strip::new(WS2812B_TIMING, rmt.channel0, peripherals.GPIO2, rmt_freq)
.expect("configure WS2812B adapter");
// the encoder's common pin is grounded, so both phases and the switch idle
// high and are driven low; the pull-ups make an open contact well defined
// high and are driven low; the pull-ups make an open contact well defined.
// D10/D9/D8 sit directly under the 3V3 and GND pads, keeping the module's
// five wires on one side of the board.
let pull_up = InputConfig::default().with_pull(Pull::Up);
let encoder_a = Input::new(peripherals.GPIO4, pull_up);
let encoder_b = Input::new(peripherals.GPIO5, pull_up);
let button = Input::new(peripherals.GPIO6, pull_up);
let encoder_a = Input::new(peripherals.GPIO18, pull_up); // D10, CLK
let encoder_b = Input::new(peripherals.GPIO20, pull_up); // D9, DT
let button = Input::new(peripherals.GPIO19, pull_up); // D8, SW
// 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 ieee802154 = Ieee802154::new(peripherals.IEEE802154);
let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default());
log::info!("device IEEE address: {:#018x}", mac.ieee_address());
let stack: &'static Stack = STACK.init(Stack::new(
mac,
zigbee_stack::config(),
zigbee_stack::handler(),
storage,
));
// on-board user LED, starting dark
let led = Output::new(peripherals.GPIO15, Level::High, OutputConfig::default());
spawner.spawn(status::heartbeat_task(led).expect("spawn heartbeat_task"));
spawner.spawn(light::render_task(strip).expect("spawn render_task"));
spawner.spawn(encoder::encoder_task(encoder_a, encoder_b).expect("spawn encoder_task"));
spawner.spawn(encoder::button_task(button).expect("spawn button_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::identify_task().expect("spawn identify_task"));
#[cfg(feature = "zigbee")]
{
use embassy_embedded_hal::adapter::BlockingAsync;
use esp_radio::ieee802154::Ieee802154;
use esp_storage::FlashStorage;
use static_cell::StaticCell;
use zigbee_mac::esp::EspMlme;
use crate::zigbee_stack::Stack;
static STACK: StaticCell<Stack> = StaticCell::new();
// 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::FlashStorage::new(flash, zigbee_stack::FLASH_RANGE).await;
let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default());
log::info!("device IEEE address: {:#018x}", mac.ieee_address());
let stack: &'static Stack = STACK.init(Stack::new(
mac,
zigbee_stack::config(),
zigbee_stack::handler(),
storage,
));
spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task"));
spawner.spawn(zigbee_stack::lighting_task(stack).expect("spawn lighting_task"));
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
}
loop {
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),
}
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::toggle_mode();
log::info!("encoder now adjusts {mode:?}");
let on = light::toggle();
log::info!("light {}", if on { "on" } else { "off" });
}
}
}
+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),
}
}
+22
View File
@@ -0,0 +1,22 @@
//! Heartbeat on the XIAO's on-board user LED.
//!
//! A short pulse once a second: if it stops, the executor has stalled or a
//! task has panicked, which is otherwise invisible without a serial console.
use embassy_time::Duration;
use embassy_time::Timer;
use esp_hal::gpio::Output;
use crate::config::HEARTBEAT_ON_MS;
use crate::config::HEARTBEAT_PERIOD_MS;
#[embassy_executor::task]
pub async fn heartbeat_task(mut led: Output<'static>) {
loop {
// the LED's anode sits on 3V3, so a low level lights it
led.set_low();
Timer::after(Duration::from_millis(HEARTBEAT_ON_MS)).await;
led.set_high();
Timer::after(Duration::from_millis(HEARTBEAT_PERIOD_MS - HEARTBEAT_ON_MS)).await;
}
}
+407 -51
View File
@@ -1,16 +1,16 @@
//! 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 Extended Color Light: all strip pixels share the
//! same on/off state, level, and color or color-temperature setting.
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;
@@ -28,31 +28,48 @@ use zigbee::zdo::descriptor::PowerDescriptorConfig;
use zigbee_cluster_library::clusters::general::basic;
use zigbee_cluster_library::clusters::general::basic::BasicServer;
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::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::ColorMode;
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;
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;
use crate::effects_cluster;
use crate::effects_cluster::EffectsServer;
use crate::light;
/// Flash region reserved for Zigbee persistence.
///
/// MUST match the partition table: erase-sector aligned (4 KiB) and at least
/// two sectors so sequential-storage has a spare for garbage collection. The
/// address assumes the 4 MiB flash of the ESP32-C6-DevKitC-1.
pub const FLASH_RANGE: Range<u32> = 0x3f_0000..0x3f_4000;
/// MUST match the `storage` partition in partitions.csv: erase-sector aligned
/// (4 KiB) and at least two sectors so sequential-storage has a spare for
/// garbage collection.
pub const FLASH_RANGE: Range<u32> = 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,24 +77,25 @@ 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] = [
static INPUT_CLUSTERS: [u16; 6] = [
basic::CLUSTER_ID,
identify::CLUSTER_ID,
on_off::CLUSTER_ID,
level_control::CLUSTER_ID,
color_control::CLUSTER_ID,
effects_cluster::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 0x010d: Extended Color Light.
device_id: 0x010d,
device_version: 1,
input_clusters: &INPUT_CLUSTERS,
output_clusters: &OUTPUT_CLUSTERS,
@@ -96,9 +114,14 @@ static BASIC: BasicServer = BasicServer {
pub static IDENTIFY: IdentifyServer = IdentifyServer::new();
static REPORTING: ReportingTable<4> = ReportingTable::new();
static REPORTING: ReportingTable<7> = 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);
static EFFECTS: EffectsServer = EffectsServer;
type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>;
@@ -107,9 +130,19 @@ type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'sta
/// (ZCL 2.5.12.2).
type Handler = (
BasicServer<'static>,
&'static IdentifyServer,
&'static OnOffServer<'static>,
UnsupportedClusterResponder<'static>,
(
&'static IdentifyServer,
(
&'static OnOffServer<'static>,
(
&'static LevelControlServer<'static>,
(
&'static ColorControlServer<'static>,
(&'static EffectsServer, UnsupportedClusterResponder<'static>),
),
),
),
),
);
pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>;
@@ -117,9 +150,22 @@ 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,
(
&EFFECTS,
UnsupportedClusterResponder::new(&INPUT_CLUSTERS),
),
),
),
),
),
)
}
@@ -141,7 +187,7 @@ pub fn config() -> StackConfig<'static> {
node: NodeDescriptorConfig {
// bit 3: 2400 MHz band
frequency_band: 0x08,
manufacturer_code: 0x1037,
manufacturer_code: effects_cluster::MANUFACTURER_CODE,
maximum_buffer_size: 80,
maximum_incoming_transfer_size: 128,
server_mask: 0,
@@ -164,36 +210,346 @@ 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.
///
/// 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<T, A>(
stack: &'static Stack,
attribute: &Attribute<T, A, Reportable>,
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.
#[embassy_executor::task]
pub async fn on_off_task() {
let mut last = ON_OFF.on_off();
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 last_color = COLOR_CONTROL.color();
let mut last_xy = COLOR_CONTROL.xy();
let mut pending_on = None;
let mut pending_level = None;
let mut pending_mireds = None;
let mut pending_hue = None;
let mut pending_saturation = None;
let mut pending_x = None;
let mut pending_y = 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;
light::set_on(remote);
continue;
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(),
}
}
let local = light::is_on();
if local != last {
last = local;
ON_OFF.set_on_off(local);
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_color = COLOR_CONTROL.color();
let color_changed = remote_color != last_color;
let remote_xy = COLOR_CONTROL.xy();
let xy_changed = remote_xy != last_xy;
if color_changed {
last_color = remote_color;
if remote_color.0 == ColorMode::HueSaturation {
light::set_hue_saturation(remote_color.1, remote_color.2);
pending_mireds = None;
pending_hue = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_HUE.id(),
)
.map(|_| remote_color.1);
pending_saturation = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_SATURATION.id(),
)
.map(|_| remote_color.2);
} else if remote_color.0 == ColorMode::Xy {
light::set_xy(remote_xy.0, remote_xy.1);
pending_mireds = None;
pending_hue = None;
pending_saturation = None;
pending_x = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_X.id(),
)
.map(|_| remote_xy.0);
pending_y = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_Y.id(),
)
.map(|_| remote_xy.1);
} else {
pending_hue = None;
pending_saturation = None;
}
}
if remote_color.0 == ColorMode::Xy && xy_changed {
last_xy = remote_xy;
pending_x = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_X.id(),
)
.map(|_| remote_xy.0);
pending_y = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_Y.id(),
)
.map(|_| remote_xy.1);
if !color_changed {
light::set_xy(remote_xy.0, remote_xy.1);
}
}
let remote_mireds = COLOR_CONTROL.color_temperature_mireds();
if remote_color.0 == ColorMode::ColorTemperature
&& (remote_mireds != last_mireds || color_changed)
{
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 !light::is_color_mode()
&& (local_mireds != last_mireds || last_color.0 != ColorMode::ColorTemperature)
{
last_mireds = local_mireds;
COLOR_CONTROL.set_color_temperature_mireds(local_mireds);
last_color = COLOR_CONTROL.color();
pending_mireds = Some(local_mireds);
pending_hue = None;
pending_saturation = None;
pending_x = None;
pending_y = None;
}
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");
}
}
if let Some(value) = pending_hue {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::CURRENT_HUE.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::CURRENT_HUE,
Uint8(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_hue = None;
}
}
if let Some(value) = pending_saturation {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::CURRENT_SATURATION.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::CURRENT_SATURATION,
Uint8(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_saturation = None;
}
}
if let Some(value) = pending_x {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::CURRENT_X.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::CURRENT_X,
Uint16(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_x = None;
}
}
if let Some(value) = pending_y {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::CURRENT_Y.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::CURRENT_Y,
Uint16(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_y = None;
}
}
}
}