Author SHA1 Message Date
Matt SpencerandCopilot 575cd8896f feat: add a button gesture to return to pairing mode
A light that has a network only ever rejoins that one, so there was no way
to re-pair it or move it to another coordinator without reflashing.

Holding the encoder button for 10 seconds now makes the light flash green
twice, forget its Zigbee network (saved to flash) and restart, after which
it looks for a network with an open pairing window, in ZHA with Add device.
The coordinator is not told, so Home Assistant keeps the device and
recognises it by its IEEE address when it joins again.

While the light is looking for a network the on-board LED blinks fast
instead of once a second, so a waiting pairing window can be seen to be
picked up, and the change between joined and searching is logged.

The README documents the gesture and how pairing works, and notes that the
extended PAN ID is broadcast by the network and is not a secret.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-28 23:26:29 +00:00
Matt SpencerandCopilot 90af6197c6 docs: add a README
Describe what the project is, the hardware and controls, how to build and
flash it from source, how to join a Zigbee network, and how to install the
ZHA quirk for the effects cluster.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-28 22:33:38 +00:00
6 changed files with 237 additions and 5 deletions

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
# smart_light
Firmware for a Zigbee-controlled LED strip light, written in Rust for the
ESP32-C6. It joins a Zigbee network as an Extended Color Light, so it shows up
in Home Assistant (ZHA) as a normal light with on/off, brightness, colour
temperature and colour. It can also be controlled locally with a rotary
encoder, and can play animated effects.
## Hardware
- Seeed Studio XIAO ESP32-C6
- WS2812B LED strip (24 LEDs by default), data on D2 (GPIO2)
- Rotary encoder with push button: CLK on D10, DT on D9, SW on D8
(GPIO18, GPIO20, GPIO19)
The on-board user LED (GPIO15) blinks as a heartbeat.
## Controls
| Input | Action |
|---|---|
| Turn the encoder | Brightness up or down |
| Click | Next colour temperature preset |
| Long press | Turn on or off |
| Hold for 10 seconds | Forget the Zigbee network and go back to pairing mode |
From Home Assistant you get on/off, brightness, colour temperature and colour.
Blink and breathe effects are available through the light's `flash` option, and
the animated scenes (rainbow, pulse, comet) are described under
[Effects](#effects).
## Building from source
You need [rustup](https://rustup.rs). The repository pins a nightly toolchain
in `rust-toolchain.toml`, so the right compiler, components and the
`riscv32imac-unknown-none-elf` target are installed on the first build.
The Zigbee stack is a git submodule (`vendor/zigbee-rs`), so clone with
submodules:
```sh
git clone --recurse-submodules https://gitea.m5p3nc3r.co.uk/m5p3nc3r/smart_lights.git
cd smart_lights
```
If you already cloned without them, run `git submodule update --init`. The
submodule URL is an SSH address on GitHub; if you have no SSH key set up, switch
it to HTTPS first with
`git config submodule.vendor/zigbee-rs.url https://github.com/m5p3nc3r/zigbee-rs.git`.
Build:
```sh
cargo build --release
```
To flash a board connected over USB and open the serial log, install
[espflash](https://github.com/esp-rs/espflash) and run:
```sh
cargo install espflash
cargo run --release
```
`cargo run` uses the runner in `.cargo/config.toml`, which flashes the app with
the partition table in `partitions.csv` and then starts the monitor. The Zigbee
network state is kept in the `storage` partition, so reflashing keeps the
light on its network.
To build without Zigbee, for example to test the strip and encoder on their own:
```sh
cargo build --release --no-default-features --features esp32c6
```
The `led_diag`, `pin_diag` and `gpio_out_diag` binaries in `src/bin` are small
hardware checks, run with `cargo run --release --bin led_diag`.
## Configuration
- `src/config.rs`: number of LEDs, maximum brightness, encoder timing.
- `src/zigbee_stack.rs`: the Zigbee network to join. The extended PAN ID and
channel (25) are set in the code and must match your coordinator.
## Joining the network
A light that is not on a network is always in pairing mode: it scans every few
seconds, and the on-board LED blinks quickly while it does. To join, open a
pairing window on your coordinator (in ZHA, **Add device**) and the light joins
as soon as it sees it. After that it rejoins by itself when it restarts.
To pair a light that is already on a network, for example to re-pair it or move
it to another coordinator, hold the encoder button for 10 seconds. The strip
flashes green twice, the light forgets its network and restarts, and it is then
in pairing mode as above. The coordinator is not told, so Home Assistant keeps
the device and recognises it when it joins again.
The same applies if it has lost its network keys, for example after a long
coordinator outage: open the pairing window and it will join again.
The network it looks for is fixed in the firmware (see Configuration), so a
light only pairs with a coordinator whose extended PAN ID and channel match.
The extended PAN ID is broadcast by the network and is not a secret.
## Effects
Beyond the standard controls, the light has a manufacturer-specific effects
cluster (`0xFD00`) that selects an animated scene (rainbow, pulse or comet) and
sets its speed and intensity. Home Assistant needs a quirk to talk to it:
1. Copy `ha/zha_quirks/smart_light.py` into a folder in your Home Assistant
config, for example `custom_zha_quirks/`.
2. Point ZHA at it in `configuration.yaml`:
```yaml
zha:
custom_quirks_path: /config/custom_zha_quirks/
```
3. Restart Home Assistant. The light then has an Effect select and Effect speed
and Effect intensity sliders.
+9
View File
@@ -18,9 +18,18 @@ pub const STEPS_PER_BRIGHTNESS_UNIT: i32 = 1;
/// Hold time that separates a click from a long press. /// Hold time that separates a click from a long press.
pub const LONG_PRESS_MS: u64 = 600; pub const LONG_PRESS_MS: u64 = 600;
/// Hold time that makes the light forget its Zigbee network and go back to
/// pairing mode.
pub const RESET_HOLD_MS: u64 = 10_000;
/// Contact settle time for the encoder push button. /// Contact settle time for the encoder push button.
pub const DEBOUNCE_MS: u64 = 15; pub const DEBOUNCE_MS: u64 = 15;
/// Heartbeat blink: a brief pulse, repeated once a second. /// Heartbeat blink: a brief pulse, repeated once a second.
pub const HEARTBEAT_ON_MS: u64 = 50; pub const HEARTBEAT_ON_MS: u64 = 50;
pub const HEARTBEAT_PERIOD_MS: u64 = 1000; pub const HEARTBEAT_PERIOD_MS: u64 = 1000;
/// The faster blink that shows the light is looking for a Zigbee network to
/// join, so a pairing window can be seen to be waiting for it.
pub const SEARCHING_ON_MS: u64 = 100;
pub const SEARCHING_PERIOD_MS: u64 = 300;
+14
View File
@@ -15,6 +15,7 @@ use esp_hal::gpio::Input;
use crate::config::DEBOUNCE_MS; use crate::config::DEBOUNCE_MS;
use crate::config::LONG_PRESS_MS; use crate::config::LONG_PRESS_MS;
use crate::config::RESET_HOLD_MS;
#[derive(Clone, Copy, PartialEq, Eq, Debug)] #[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum EncoderEvent { pub enum EncoderEvent {
@@ -22,6 +23,8 @@ pub enum EncoderEvent {
Rotate(i8), Rotate(i8),
Click, Click,
LongPress, LongPress,
/// The button was held long enough to forget the Zigbee network.
NetworkReset,
} }
/// Depth 8 absorbs a fast spin while the consumer is mid-frame; overflowing /// Depth 8 absorbs a fast spin while the consumer is mid-frame; overflowing
@@ -63,8 +66,19 @@ pub async fn button_task(mut button: Input<'static>) {
if long_press { if long_press {
let _ = EVENTS.try_send(EncoderEvent::LongPress); let _ = EVENTS.try_send(EncoderEvent::LongPress);
// still held past the reset time: ask for a network reset while
// the button is down, so the light can react before it is let go
let released = with_timeout(
Duration::from_millis(RESET_HOLD_MS - LONG_PRESS_MS),
button.wait_for_rising_edge(),
)
.await
.is_ok();
if !released {
let _ = EVENTS.try_send(EncoderEvent::NetworkReset);
// swallow the release so it is not read as a second press // swallow the release so it is not read as a second press
button.wait_for_rising_edge().await; button.wait_for_rising_edge().await;
}
} else { } else {
let _ = EVENTS.try_send(EncoderEvent::Click); let _ = EVENTS.try_send(EncoderEvent::Click);
} }
+7
View File
@@ -107,6 +107,8 @@ 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::lighting_task(stack).expect("spawn lighting_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"));
spawner.spawn(zigbee_stack::network_reset_task(stack).expect("spawn network_reset_task"));
spawner.spawn(zigbee_stack::pairing_status_task(stack).expect("spawn pairing_status_task"));
} }
loop { loop {
@@ -124,6 +126,11 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
let on = light::toggle(); let on = light::toggle();
log::info!("light {}", if on { "on" } else { "off" }); log::info!("light {}", if on { "on" } else { "off" });
} }
EncoderEvent::NetworkReset => {
log::warn!("button held: resetting the Zigbee network");
#[cfg(feature = "zigbee")]
zigbee_stack::request_network_reset();
}
} }
} }
} }
+26 -5
View File
@@ -1,7 +1,12 @@
//! Heartbeat on the XIAO's on-board user LED. //! Status blinks on the XIAO's on-board user LED.
//! //!
//! A short pulse once a second: if it stops, the executor has stalled or a //! A short pulse once a second means the firmware is running: if it stops, the
//! task has panicked, which is otherwise invisible without a serial console. //! executor has stalled or a task has panicked, which is otherwise invisible
//! without a serial console. While the light is looking for a Zigbee network to
//! join the pulse is faster, so a pairing window can be seen to be waiting.
use core::sync::atomic::AtomicBool;
use core::sync::atomic::Ordering;
use embassy_time::Duration; use embassy_time::Duration;
use embassy_time::Timer; use embassy_time::Timer;
@@ -9,14 +14,30 @@ use esp_hal::gpio::Output;
use crate::config::HEARTBEAT_ON_MS; use crate::config::HEARTBEAT_ON_MS;
use crate::config::HEARTBEAT_PERIOD_MS; use crate::config::HEARTBEAT_PERIOD_MS;
use crate::config::SEARCHING_ON_MS;
use crate::config::SEARCHING_PERIOD_MS;
/// Set while the light is not on a Zigbee network and is looking for one.
static SEARCHING: AtomicBool = AtomicBool::new(false);
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
pub fn set_searching(searching: bool) {
SEARCHING.store(searching, Ordering::Relaxed);
}
#[embassy_executor::task] #[embassy_executor::task]
pub async fn heartbeat_task(mut led: Output<'static>) { pub async fn heartbeat_task(mut led: Output<'static>) {
loop { loop {
let (on_ms, period_ms) = if SEARCHING.load(Ordering::Relaxed) {
(SEARCHING_ON_MS, SEARCHING_PERIOD_MS)
} else {
(HEARTBEAT_ON_MS, HEARTBEAT_PERIOD_MS)
};
// the LED's anode sits on 3V3, so a low level lights it // the LED's anode sits on 3V3, so a low level lights it
led.set_low(); led.set_low();
Timer::after(Duration::from_millis(HEARTBEAT_ON_MS)).await; Timer::after(Duration::from_millis(on_ms)).await;
led.set_high(); led.set_high();
Timer::after(Duration::from_millis(HEARTBEAT_PERIOD_MS - HEARTBEAT_ON_MS)).await; Timer::after(Duration::from_millis(period_ms - on_ms)).await;
} }
} }
+60
View File
@@ -6,9 +6,12 @@
use core::ops::Range; use core::ops::Range;
use embassy_embedded_hal::adapter::BlockingAsync; use embassy_embedded_hal::adapter::BlockingAsync;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use embassy_time::Duration; use embassy_time::Duration;
use embassy_time::Instant; use embassy_time::Instant;
use embassy_time::Timer; use embassy_time::Timer;
use embassy_time::with_timeout;
use esp_storage::FlashStorage; use esp_storage::FlashStorage;
use zigbee::aps::apsde::ApsdeSapConfirmStatus; use zigbee::aps::apsde::ApsdeSapConfirmStatus;
use zigbee::CurrentPowerMode; use zigbee::CurrentPowerMode;
@@ -57,6 +60,7 @@ use zigbee_types::ShortAddress;
use crate::effects_cluster; use crate::effects_cluster;
use crate::effects_cluster::EffectsServer; use crate::effects_cluster::EffectsServer;
use crate::light; use crate::light;
use crate::status;
/// Flash region reserved for Zigbee persistence. /// Flash region reserved for Zigbee persistence.
/// ///
@@ -565,3 +569,59 @@ pub async fn identify_task() {
} }
} }
} }
static NETWORK_RESET: Signal<CriticalSectionRawMutex, ()> = Signal::new();
/// Asks for the Zigbee network to be forgotten, which [`network_reset_task`]
/// then does.
pub fn request_network_reset() {
NETWORK_RESET.signal(());
}
/// Puts the light back into pairing mode on request.
///
/// A light that has a network only ever rejoins that one, so this is how it is
/// moved to another or re-paired from scratch: it forgets the network, then
/// restarts and goes looking for one with an open pairing window (in ZHA,
/// **Add device**).
///
/// The coordinator is not told. Home Assistant keeps the device, and recognises
/// it by its IEEE address when it joins again.
#[embassy_executor::task]
pub async fn network_reset_task(stack: &'static Stack) {
NETWORK_RESET.wait().await;
log::warn!("network reset: forgetting the Zigbee network");
// two green flashes, so the reset can be seen before the light restarts
light::play_effect(light::Effect::Okay);
Timer::after(Duration::from_millis(1500)).await;
// forgets the network and writes that to flash, so the next boot starts
// commissioning from scratch rather than resuming
stack.forget_network().await;
log::warn!("network reset: network forgotten and saved, restarting");
esp_hal::system::software_reset()
}
/// Shows on the status LED whether the light is looking for a network.
#[embassy_executor::task]
pub async fn pairing_status_task(stack: &'static Stack) {
let mut was_joined = None;
loop {
// the join gate stays open once joined, so this returns at once when
// the light is on a network and times out when it is not
let joined = with_timeout(Duration::from_millis(1), stack.wait_until_joined())
.await
.is_ok();
status::set_searching(!joined);
if was_joined != Some(joined) {
if joined {
log::info!("on a Zigbee network");
} else {
log::info!("not on a Zigbee network: looking for one to join");
}
was_joined = Some(joined);
}
Timer::after(Duration::from_millis(250)).await;
}
}