15 Commits
Author SHA1 Message Date
Matt SpencerandCopilot bf031b55b7 ci: publish a release for every commit to main
release / release (push) Successful in 3m2s
Add a Gitea Actions workflow that builds the firmware and publishes a
release whenever main changes.

The version is MAJOR.MINOR from the version in Cargo.toml plus the number of
commits on main as the patch number, so it only ever goes up and can be worked
out again from any commit. The workflow stamps it into Cargo.toml for the
build, which puts it in the app descriptor, and the firmware now logs it at
boot. The release is tagged v plus the version.

Each release carries a full image (bootloader, partition table and
application, stopping short of the storage partition so flashing it keeps the
Zigbee network), the application image alone, the unstripped build for
backtraces, and checksums.

The submodule is declared with an SSH address, so the workflow rewrites it to
HTTPS for the runner, which has no key. The README documents the scheme.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-29 01:04:33 +00:00
Matt SpencerandCopilot c92adaed01 docs: license the project under the MIT License
Add the LICENSE file, declare the license in Cargo.toml, and say so in the
README. The Zigbee stack in vendor/zigbee-rs is a separate project and keeps
its own licenses (MIT or Apache-2.0).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-29 00:38:36 +00:00
Matt SpencerandCopilot 2f5f457ffc docs: add a TODO of the known open work
Record what is known to be open but not being worked on: the Zigbee stack
forgetting its network after a short coordinator outage, the hardcoded
network ID and channel, state not kept across reboots, the upstream zigbee-rs
PRs and the spec questions to raise in them, what has not been tried on the
hardware, and some housekeeping.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-29 00:32:10 +00:00
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
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
24 changed files with 1980 additions and 170 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
target = "riscv32imac-unknown-none-elf" target = "riscv32imac-unknown-none-elf"
[target.riscv32imac-unknown-none-elf] [target.riscv32imac-unknown-none-elf]
runner = "espflash flash --monitor" runner = "espflash flash --monitor --partition-table partitions.csv"
rustflags = [ rustflags = [
"-C", "link-arg=-Tlinkall.x", "-C", "link-arg=-Tlinkall.x",
"-C", "force-frame-pointers", "-C", "force-frame-pointers",
+128
View File
@@ -0,0 +1,128 @@
name: release
# Every commit to main builds the firmware and publishes a release.
#
# The version is MAJOR.MINOR from the version in Cargo.toml, with the number
# of commits on main as the patch number, so it only ever goes up and can be
# worked out again from any commit: Cargo.toml saying 0.1.0 gives 0.1.57 for
# the 57th commit. Change MAJOR or MINOR in Cargo.toml to start a new series.
on:
push:
branches:
- main
jobs:
release:
# Must match a label of the Gitea runner.
runs-on: ubuntu-latest
env:
ESPFLASH_VERSION: v4.6.0
steps:
- name: Check out the repository
uses: actions/checkout@v4
with:
# the commit count and the previous release tag need the history
fetch-depth: 0
- name: Fetch the Zigbee stack
run: |
# the submodule is declared with an SSH address; a runner has no key
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init
- name: Work out the version
id: version
run: |
base=$(sed -n 's/^version = "\([0-9]*\.[0-9]*\)\..*"/\1/p' Cargo.toml | head -n 1)
count=$(git rev-list --count HEAD)
version="$base.$count"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "Releasing $version"
# the firmware reads its version from the package, so this is what
# ends up in the app descriptor and the boot log
sed -i '0,/^version = ".*"/s//version = "'"$version"'"/' Cargo.toml
- name: Install Rust
run: |
if ! command -v rustup > /dev/null; then
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
fi
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
export PATH="$HOME/.cargo/bin:$PATH"
# installs the toolchain, components and target that
# rust-toolchain.toml asks for
rustup toolchain install || true
cargo --version
- name: Install espflash
run: |
curl -fsSL -o espflash.zip \
"https://github.com/esp-rs/espflash/releases/download/${ESPFLASH_VERSION}/espflash-x86_64-unknown-linux-musl.zip"
python3 -m zipfile -e espflash.zip "$HOME/espflash-bin"
chmod +x "$HOME/espflash-bin/espflash"
echo "$HOME/espflash-bin" >> "$GITHUB_PATH"
- name: Build the firmware
run: cargo build --release
- name: Package the images
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
elf=target/riscv32imac-unknown-none-elf/release/smart-light
mkdir dist
# the application on its own: what goes into a firmware slot
espflash save-image --chip esp32c6 --flash-size 4mb "$elf" "dist/smart-light-$VERSION.bin"
# bootloader, partition table and application, to be written at
# address 0. Without padding it stops short of the storage
# partition, so flashing it keeps the light's Zigbee network.
espflash save-image --chip esp32c6 --flash-size 4mb --merge --skip-padding \
--partition-table partitions.csv "$elf" "dist/smart-light-$VERSION-full.bin"
# for decoding backtraces
gzip -9 -c "$elf" > "dist/smart-light-$VERSION.elf.gz"
(cd dist && sha256sum * > SHA256SUMS)
ls -l dist
- name: Publish the release
env:
VERSION: ${{ steps.version.outputs.version }}
# the job's own token if it may create releases, otherwise a token
# kept in the RELEASE_TOKEN secret
TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITHUB_TOKEN }}
API: ${{ github.server_url }}/api/v1
REPO: ${{ github.repository }}
run: |
previous=$(git describe --tags --abbrev=0 --match 'v*' 2> /dev/null || true)
notes=$(git log --no-merges --pretty='- %s (%h)' -n 50 ${previous:+"$previous..HEAD"})
payload=$(python3 -c '
import json, sys
version, sha, notes = sys.argv[1:4]
body = "Built from " + sha[:7] + ".\n\n" + notes
print(json.dumps({
"tag_name": "v" + version,
"target_commitish": sha,
"name": "smart-light " + version,
"body": body,
"draft": False,
"prerelease": False,
}))' "$VERSION" "$GITHUB_SHA" "$notes")
response=$(curl -fsS -X POST \
-H "Authorization: token $TOKEN" \
-H "Content-Type: application/json" \
-d "$payload" "$API/repos/$REPO/releases")
id=$(printf '%s' "$response" | python3 -c 'import json, sys; print(json.load(sys.stdin)["id"])')
for file in dist/*; do
curl -fsS -X POST \
-H "Authorization: token $TOKEN" \
-F "attachment=@$file" \
"$API/repos/$REPO/releases/$id/assets?name=$(basename "$file")" > /dev/null
echo "uploaded $(basename "$file")"
done
+3
View File
@@ -1,2 +1,5 @@
/target /target
/vendor/zigbee-rs/target /vendor/zigbee-rs/target
/nda
__pycache__/
*.pyc
+2 -2
View File
@@ -1,4 +1,4 @@
[submodule "vendor/zigbee-rs"] [submodule "vendor/zigbee-rs"]
path = vendor/zigbee-rs path = vendor/zigbee-rs
url = https://github.com/zigbee-rs/zigbee-rs.git url = git@github.com:m5p3nc3r/zigbee-rs.git
branch = smart-light branch = feature/lighting-effects-integration
Generated
+32 -1
View File
@@ -382,6 +382,26 @@ dependencies = [
"syn 3.0.9", "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]] [[package]]
name = "defmt-parser" name = "defmt-parser"
version = "1.1.0" version = "1.1.0"
@@ -1399,6 +1419,12 @@ version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]] [[package]]
name = "linked_list_allocator" name = "linked_list_allocator"
version = "0.10.6" version = "0.10.6"
@@ -1829,6 +1855,7 @@ dependencies = [
"esp-radio", "esp-radio",
"esp-rtos", "esp-rtos",
"esp-storage", "esp-storage",
"libm",
"log", "log",
"smart-leds", "smart-leds",
"smart-leds-trait", "smart-leds-trait",
@@ -2206,6 +2233,7 @@ dependencies = [
name = "zigbee" name = "zigbee"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"defmt-or-log",
"embedded-hal-async", "embedded-hal-async",
"log", "log",
"zigbee-base-device-behavior", "zigbee-base-device-behavior",
@@ -2219,6 +2247,7 @@ dependencies = [
name = "zigbee-base-device-behavior" name = "zigbee-base-device-behavior"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"defmt-or-log",
"embedded-hal-async", "embedded-hal-async",
"log", "log",
"spin", "spin",
@@ -2249,6 +2278,7 @@ dependencies = [
"aes", "aes",
"byte", "byte",
"ccm 0.5.0", "ccm 0.5.0",
"defmt-or-log",
"embedded-hal-async", "embedded-hal-async",
"embedded-storage-async", "embedded-storage-async",
"heapless 0.9.3", "heapless 0.9.3",
@@ -2267,6 +2297,8 @@ name = "zigbee-mac"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"byte", "byte",
"defmt",
"defmt-or-log",
"embassy-futures", "embassy-futures",
"embassy-sync 0.8.0", "embassy-sync 0.8.0",
"embassy-time", "embassy-time",
@@ -2294,7 +2326,6 @@ dependencies = [
"byte", "byte",
"embedded-storage", "embedded-storage",
"heapless 0.9.3", "heapless 0.9.3",
"itertools",
"spin", "spin",
"zigbee-macros", "zigbee-macros",
] ]
+13 -8
View File
@@ -2,19 +2,23 @@
name = "smart-light" name = "smart-light"
version = "0.1.0" version = "0.1.0"
edition = "2024" edition = "2024"
license = "MIT"
[features] [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 = [ esp32c6 = [
"esp-alloc/esp32c6", "esp-alloc/esp32c6",
"esp-backtrace/esp32c6", "esp-backtrace/esp32c6",
"esp-bootloader-esp-idf/esp32c6", "esp-bootloader-esp-idf/esp32c6",
"esp-hal/esp32c6", "esp-hal/esp32c6",
"esp-println/esp32c6", "esp-println/esp32c6",
"esp-radio/esp32c6", "esp-radio?/esp32c6",
"esp-rtos/esp32c6", "esp-rtos/esp32c6",
"esp-storage/esp32c6", "esp-storage/esp32c6",
"zigbee-mac/esp32c6", "zigbee-mac?/esp32c6",
] ]
[dependencies] [dependencies]
@@ -23,7 +27,7 @@ esp-backtrace = { version = "0.20", features = ["panic-handler", "println"] }
esp-bootloader-esp-idf = "0.6" esp-bootloader-esp-idf = "0.6"
esp-hal = { version = "1.2", features = ["log-04", "unstable"] } esp-hal = { version = "1.2", features = ["log-04", "unstable"] }
esp-println = { version = "0.18", features = ["log-04"] } 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-rtos = { version = "0.4", features = ["embassy", "log-04"] }
esp-storage = { version = "0.10", features = ["embedded-storage"] } esp-storage = { version = "0.10", features = ["embedded-storage"] }
@@ -39,13 +43,14 @@ log = "0.4"
smart-leds = "0.4" smart-leds = "0.4"
smart-leds-trait = "0.3" smart-leds-trait = "0.3"
esp-hal-smartled = "0.18" esp-hal-smartled = "0.18"
libm = "0.2"
# vendored upstream: the lighting cluster is not implemented there yet, so the # vendored upstream: the lighting cluster is not implemented there yet, so the
# path dependency lets us add it in-tree and upstream it later # path dependency lets us add it in-tree and upstream it later
zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"] } zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"], optional = true }
zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library" } zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library", optional = true }
zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac" } zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac", optional = true }
zigbee-types = { path = "vendor/zigbee-rs/zigbee-types" } zigbee-types = { path = "vendor/zigbee-rs/zigbee-types", optional = true }
[profile.release] [profile.release]
debug = true debug = true
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Matt Spencer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+152
View File
@@ -0,0 +1,152 @@
# 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.
## Releases
Every commit to `main` builds the firmware on the Gitea runner and publishes a
release (`.gitea/workflows/release.yml`).
The version is the `MAJOR.MINOR` of the version in `Cargo.toml` followed by the
number of commits on `main`, so with `0.1.0` in `Cargo.toml` the 57th commit
becomes `0.1.57`. It only goes up, and can be worked out again from any commit.
To start a new series, change the major or minor number in `Cargo.toml`. The
build writes the version into the firmware, which logs it at boot, and the
release is tagged `v` plus the version.
Each release has:
- `smart-light-<version>-full.bin`: bootloader, partition table and
application. Write it at address 0 with
`espflash write-bin 0x0 smart-light-<version>-full.bin`. It stops short of
the `storage` partition, so the light keeps its Zigbee network.
- `smart-light-<version>.bin`: the application alone, for a firmware slot.
- `smart-light-<version>.elf.gz`: the unstripped build, for decoding backtraces.
- `SHA256SUMS`.
The workflow's `runs-on` must match a label of your Gitea runner. If the job's
own token is not allowed to create releases, add a token with write access to
the repository as a secret named `RELEASE_TOKEN`.
## License
Released under the [MIT License](LICENSE). The Zigbee stack in
`vendor/zigbee-rs` is a separate project with its own licenses.
+83
View File
@@ -0,0 +1,83 @@
# TODO
Things that are known to be open. None of these is being worked on yet.
## Reliability
- [ ] **The Zigbee stack forgets its network after a short coordinator outage.**
A failed rejoin is followed by a second attempt that, if it also fails,
wipes the network keys and falls back to a fresh join, which needs the
coordinator's pairing window to be open. This took the light off the network
when the server rebooted (18 Nov) and, most likely, again when Home Assistant
restarted (24 Nov; inferred, the failure itself was not captured). Each time
it needed re-pairing.
- Where: `commission` and `link_maintenance` in
`vendor/zigbee-rs/zigbee/src/stack.rs`, and the retry loop in
`stack_task` (`src/zigbee_stack.rs`).
- Idea: keep the saved network and keep retrying the rejoin with a back-off,
and only forget it after a long failure (say 30 minutes), an explicit
leave, or a network mismatch.
- It is a library change, so it belongs on its own branch off upstream
`main`, separate from the effects work.
- The 10-second button hold makes recovery easy, but does not prevent it.
## Configuration
- [ ] **The Zigbee network ID and channel are hardcoded** in
`src/zigbee_stack.rs` (`EXTENDED_PAN_ID`, `CHANNEL`). The ID is broadcast by
the network and is not a secret, but it means a light only pairs with one
network.
- Why it is pinned: the stack takes both from its configuration. Resuming
after a reboot tunes to the first configured channel rather than the
channel that was joined, and rejoin looks for the configured network ID.
A wildcard ID or a range of channels would therefore break resume.
- Options: change the library to use the channel and ID it remembers, or have
the app save the network it joined in its own flash and build the
configuration from that.
- [ ] **Light and effect state is not saved across reboots.** On/off, level,
colour and the selected effect all start from their defaults.
- [ ] **The effects cluster uses development identifiers.** Manufacturer code
`0xC0DE` is not assigned to anyone, and the cluster ID is `0xFD00`. Decide on
proper values and change them together in `src/effects_cluster.rs` and
`ha/zha_quirks/smart_light.py`.
- [ ] **The effect attributes are not reportable**, so Home Assistant only
knows what it last wrote. Fine while nothing else changes them; revisit if
effects can be changed locally.
## Upstream zigbee-rs
- [ ] **Open PRs for the two branches already pushed to the fork**, each as its
own PR off upstream `main`:
- `feature/identify-trigger-effect`
- `feature/manufacturer-specific-clusters`
- [ ] **PR #109 (RGB colour control)** is open and has had review comments
applied. Squash-merge when approved.
- [ ] **Spec questions to raise in review.** Neither PR can say what ZCL
requires, so both pick an answer and flag it:
- Trigger Effect with an undefined effect or variant answers `INVALID_FIELD`.
- A frame for a manufacturer-specific cluster with the wrong manufacturer
code answers `UNSUP_COMMAND`.
- [ ] **After the PRs merge**, point the submodule at upstream (or the fork's
`main`) instead of `feature/lighting-effects-integration`, and delete the
integration branch.
## Testing gaps
Not yet tried on the hardware (the commit messages say so too):
- [ ] Trigger Effect: Okay, Channel change, Finish effect and Stop effect sent
from a coordinator. Only blink and breathe (ZHA's `flash`) were tried.
- [ ] Manufacturer-specific attribute reports.
- [ ] Rejection of a frame that carries the wrong manufacturer code.
## Housekeeping
- [ ] **`.gitmodules` uses an SSH URL** for the submodule
(`git@github.com:m5p3nc3r/zigbee-rs.git`). Switch to HTTPS if cloning from a
network that blocks SSH.
- [ ] **Older commits point at submodule commits that no longer exist on any
branch**, because the integration branch was rebased. The tip works, but
checking out an old commit and updating the submodule can fail.
- [ ] **Pre-existing `rustfmt` differences**: 1 in `src/light.rs` and 7 in
`src/zigbee_stack.rs`. Cosmetic; fix in a commit of their own.
- [ ] **No licence file.** Decide on one.
+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;
}
}
}
}
}
}
+16 -3
View File
@@ -3,12 +3,12 @@
//! Everything that changes when the hardware changes lives here. //! Everything that changes when the hardware changes lives here.
/// Number of WS2812B pixels on the strip. /// 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. /// 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 /// Takes the top off peak current draw. This is a brightness cap, not a
/// when every pixel is driven white. /// current limit: a strip of this length still needs its own 5V supply.
pub const MAX_DUTY: u8 = 200; pub const MAX_DUTY: u8 = 200;
/// Rotary encoder detents per full revolution, used to scale a turn into a /// Rotary encoder detents per full revolution, used to scale a turn into a
@@ -18,5 +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.
pub const HEARTBEAT_ON_MS: u64 = 50;
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;
+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)
}
}
+28 -47
View File
@@ -1,12 +1,11 @@
//! Interrupt-driven rotary encoder with a push button. //! Interrupt-driven rotary encoder with a push button.
//! //!
//! Both tasks park on GPIO edge interrupts; nothing here polls. Quadrature is //! Both tasks park on GPIO edge interrupts; nothing here polls.
//! 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 //! Direction comes from sampling A on B's falling edge: one detent produces
//! registering a step. //! 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::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel; use embassy_sync::channel::Channel;
use embassy_time::Duration; use embassy_time::Duration;
@@ -16,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 {
@@ -23,53 +23,27 @@ 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
/// drops the oldest step, which is preferable to blocking the interrupt task. /// drops the oldest step, which is preferable to blocking the interrupt task.
pub static EVENTS: Channel<CriticalSectionRawMutex, EncoderEvent, 8> = Channel::new(); 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] #[embassy_executor::task]
pub async fn encoder_task(mut a: Input<'static>, mut b: Input<'static>) { pub async fn encoder_task(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;
loop { loop {
match select(a.wait_for_any_edge(), b.wait_for_any_edge()).await { b.wait_for_falling_edge().await;
Either::First(()) | Either::Second(()) => {}
}
let current = state(&a, &b); // A must be read here, before the rest of the detent moves it
if current == previous { let delta = if a.is_high() { -1 } else { 1 };
continue; 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]; // the rest of the detent returns B to rest; ignoring it stops one
previous = current; // detent counting twice
if delta == 0 { b.wait_for_rising_edge().await;
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));
}
} }
} }
@@ -92,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);
} }
@@ -101,7 +86,3 @@ pub async fn button_task(mut button: Input<'static>) {
Timer::after(Duration::from_millis(DEBOUNCE_MS)).await; 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())
}
+193 -32
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,19 +21,37 @@ 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;
/// What a turn of the encoder adjusts. /// Colour temperature presets, warmest first, as sRGB with the brightest
#[derive(Clone, Copy, PartialEq, Eq, Debug)] /// channel at full.
pub enum Mode { ///
Brightness, /// Precomputed rather than derived: a blackbody conversion needs floating
Hue, /// 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); 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: 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(); static DIRTY: Signal<CriticalSectionRawMutex, ()> = Signal::new();
pub fn is_on() -> bool { pub fn is_on() -> bool {
@@ -53,6 +73,11 @@ pub fn brightness() -> u8 {
BRIGHTNESS.load(Ordering::Relaxed) BRIGHTNESS.load(Ordering::Relaxed)
} }
pub fn set_brightness(level: u8) {
BRIGHTNESS.store(level.min(254), Ordering::Relaxed);
DIRTY.signal(());
}
/// Clamps rather than wraps: running past full should stay at full instead of /// Clamps rather than wraps: running past full should stay at full instead of
/// dropping the light to near-black. /// dropping the light to near-black.
pub fn adjust_brightness(delta: i16) { pub fn adjust_brightness(delta: i16) {
@@ -61,28 +86,91 @@ pub fn adjust_brightness(delta: i16) {
DIRTY.signal(()); DIRTY.signal(());
} }
pub fn hue() -> u8 { /// The selected preset, as `(kelvin, colour)`.
HUE.load(Ordering::Relaxed) 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 temperature_mireds() -> u16 {
pub fn adjust_hue(delta: i16) { (1_000_000u32 / u32::from(temperature().0)) as u16
let hue = hue().wrapping_add_signed(delta as i8); }
HUE.store(hue, Ordering::Relaxed);
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(()); DIRTY.signal(());
} }
pub fn mode() -> Mode { pub fn set_xy(x: u16, y: u16) {
if HUE_MODE.load(Ordering::Relaxed) { X.store((u32::from(x) * 255 / 65_535) as u8, Ordering::Relaxed);
Mode::Hue Y.store((u32::from(y) * 255 / 65_535) as u8, Ordering::Relaxed);
} else { COLOR_MODE.store(true, Ordering::Relaxed);
Mode::Brightness XY_MODE.store(true, Ordering::Relaxed);
} DIRTY.signal(());
} }
pub fn toggle_mode() -> Mode { /// Select the nearest available RGB preset for a Zigbee mired request.
HUE_MODE.fetch_xor(true, Ordering::Relaxed); pub fn set_temperature_mireds(mireds: u16) -> u16 {
mode() 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] #[embassy_executor::task]
@@ -90,26 +178,99 @@ 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 {
frame.fill(hsv2rgb(Hsv { let overlay = effect::overlay();
hue: hue(),
sat: 255, 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, 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 // 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 before brightness, as smart-leds requires // gamma is applied to the level, not the pixels: curving each channel
let pixels = scale_brightness(gamma(frame.iter().copied()), level); // 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 { if let Err(e) = strip.write(pixels).await {
log::warn!("strip write failed: {e:?}"); log::warn!("strip write failed: {e:?}");
} }
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; 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),
}
} }
+57 -30
View File
@@ -2,46 +2,46 @@
#![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 strip; mod strip;
#[cfg(feature = "zigbee")]
mod zigbee_stack; mod zigbee_stack;
use embassy_embedded_hal::adapter::BlockingAsync;
use esp_alloc as _; use esp_alloc as _;
use esp_backtrace as _; use esp_backtrace as _;
use esp_hal::gpio::Input; use esp_hal::gpio::Input;
use esp_hal::gpio::InputConfig; 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::gpio::Pull;
use esp_hal::rmt::Rmt; use esp_hal::rmt::Rmt;
use esp_hal::time::Rate; use esp_hal::time::Rate;
use esp_hal::timer::timg::TimerGroup; use esp_hal::timer::timg::TimerGroup;
use esp_hal_smartled::WS2812B_TIMING; 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::config::STEPS_PER_BRIGHTNESS_UNIT;
use crate::encoder::EVENTS; use crate::encoder::EVENTS;
use crate::encoder::EncoderEvent; use crate::encoder::EncoderEvent;
use crate::light::Mode;
use crate::strip::Strip; use crate::strip::Strip;
use crate::zigbee_stack::Stack;
esp_bootloader_esp_idf::esp_app_desc!(); esp_bootloader_esp_idf::esp_app_desc!();
static STACK: StaticCell<Stack> = StaticCell::new();
/// Brightness units per detent. /// Brightness units per detent.
const BRIGHTNESS_STEP: i16 = 8; 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] #[esp_rtos::main]
async fn main(spawner: embassy_executor::Spawner) -> ! { async fn main(spawner: embassy_executor::Spawner) -> ! {
esp_println::logger::init_logger_from_env(); esp_println::logger::init_logger_from_env();
log::info!("smart-light {}", env!("CARGO_PKG_VERSION"));
let peripherals = esp_hal::init(esp_hal::Config::default()); let peripherals = esp_hal::init(esp_hal::Config::default());
let timg0 = TimerGroup::new(peripherals.TIMG0); let timg0 = TimerGroup::new(peripherals.TIMG0);
@@ -55,20 +55,44 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
let rmt = Rmt::new(peripherals.RMT, rmt_freq) let rmt = Rmt::new(peripherals.RMT, rmt_freq)
.expect("init RMT") .expect("init RMT")
.into_async(); .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) let strip = Strip::new(WS2812B_TIMING, rmt.channel0, peripherals.GPIO2, rmt_freq)
.expect("configure WS2812B adapter"); .expect("configure WS2812B adapter");
// the encoder's common pin is grounded, so both phases and the switch idle // 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 pull_up = InputConfig::default().with_pull(Pull::Up);
let encoder_a = Input::new(peripherals.GPIO4, pull_up); let encoder_a = Input::new(peripherals.GPIO18, pull_up); // D10, CLK
let encoder_b = Input::new(peripherals.GPIO5, pull_up); let encoder_b = Input::new(peripherals.GPIO20, pull_up); // D9, DT
let button = Input::new(peripherals.GPIO6, pull_up); let button = Input::new(peripherals.GPIO19, pull_up); // D8, SW
// the stack owns persistence: the information bases are restored here and // on-board user LED, starting dark
// written back whenever the stack changes them 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"));
#[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 flash = BlockingAsync::new(FlashStorage::new(peripherals.FLASH));
let storage = zigbee::storage::init_with_flash(flash, zigbee_stack::FLASH_RANGE).await; let storage = zigbee::storage::FlashStorage::new(flash, zigbee_stack::FLASH_RANGE).await;
let ieee802154 = Ieee802154::new(peripherals.IEEE802154); let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default()); let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default());
@@ -81,29 +105,32 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
storage, storage,
)); ));
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::stack_task(stack).expect("spawn stack_task"));
spawner.spawn(zigbee_stack::on_off_task().expect("spawn on_off_task")); spawner.spawn(zigbee_stack::lighting_task(stack).expect("spawn lighting_task"));
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task")); spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
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 {
match EVENTS.receive().await { match EVENTS.receive().await {
EncoderEvent::Rotate(detents) => { EncoderEvent::Rotate(detents) => {
let steps = i16::from(detents) * STEPS_PER_BRIGHTNESS_UNIT as i16; let steps = i16::from(detents) * STEPS_PER_BRIGHTNESS_UNIT as i16;
match light::mode() { light::adjust_brightness(steps * BRIGHTNESS_STEP);
Mode::Brightness => light::adjust_brightness(steps * BRIGHTNESS_STEP), log::info!("rotate {detents:+} -> brightness {}", light::brightness());
Mode::Hue => light::adjust_hue(steps * HUE_STEP),
}
} }
EncoderEvent::Click => { EncoderEvent::Click => {
let (kelvin, _) = light::next_temperature();
log::info!("colour temperature {kelvin}K");
}
EncoderEvent::LongPress => {
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::LongPress => { EncoderEvent::NetworkReset => {
let mode = light::toggle_mode(); log::warn!("button held: resetting the Zigbee network");
log::info!("encoder now adjusts {mode:?}"); #[cfg(feature = "zigbee")]
zigbee_stack::request_network_reset();
} }
} }
} }
+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),
}
}
+43
View File
@@ -0,0 +1,43 @@
//! Status blinks on the XIAO's on-board user LED.
//!
//! A short pulse once a second means the firmware is running: if it stops, the
//! 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::Timer;
use esp_hal::gpio::Output;
use crate::config::HEARTBEAT_ON_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]
pub async fn heartbeat_task(mut led: Output<'static>) {
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
led.set_low();
Timer::after(Duration::from_millis(on_ms)).await;
led.set_high();
Timer::after(Duration::from_millis(period_ms - on_ms)).await;
}
}
+461 -45
View File
@@ -1,16 +1,19 @@
//! Zigbee end device: commissioning, the stack task, and the clusters served. //! Zigbee end device: commissioning, the stack task, and the clusters served.
//! //!
//! The device is announced as an On/Off Light. Level Control and Color Control //! The device is a single Extended Color Light: all strip pixels share the
//! (ZCL chapter 5) are deliberately absent: the vendored upstream does not //! same on/off state, level, and color or color-temperature setting.
//! implement the lighting clusters yet, so for now brightness and hue are
//! local-only and the network sees on/off.
use core::ops::Range; use core::ops::Range;
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::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::CurrentPowerMode; use zigbee::CurrentPowerMode;
use zigbee::CurrentPowerSourceLevel; use zigbee::CurrentPowerSourceLevel;
use zigbee::DeviceConfig; use zigbee::DeviceConfig;
@@ -28,31 +31,49 @@ 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;
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::profile;
use zigbee_cluster_library::reporting::AttributeReportBuilder;
use zigbee_cluster_library::reporting::AttributeReporting;
use zigbee_cluster_library::reporting::ReportingTable; 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::server::UnsupportedClusterResponder;
use zigbee_cluster_library::types::codec::ZclKind;
use zigbee_cluster_library::types::descriptors::AccessTypestate;
use zigbee_cluster_library::types::descriptors::Attribute;
use zigbee_cluster_library::types::descriptors::Reportable;
use zigbee_cluster_library::types::integers::Uint8;
use zigbee_cluster_library::types::integers::Uint16;
use zigbee_mac::esp::EspMlme; use zigbee_mac::esp::EspMlme;
use zigbee_types::IeeeAddress; use zigbee_types::IeeeAddress;
use zigbee_types::ShortAddress;
use crate::effects_cluster;
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.
/// ///
/// MUST match the partition table: erase-sector aligned (4 KiB) and at least /// MUST match the `storage` partition in partitions.csv: erase-sector aligned
/// two sectors so sequential-storage has a spare for garbage collection. The /// (4 KiB) and at least two sectors so sequential-storage has a spare for
/// address assumes the 4 MiB flash of the ESP32-C6-DevKitC-1. /// garbage collection.
pub const FLASH_RANGE: Range<u32> = 0x3f_0000..0x3f_4000; pub const FLASH_RANGE: Range<u32> = 0x3e_0000..0x3e_4000;
/// Extended PAN ID of the network to join. /// Extended PAN ID of the Home Assistant Zigbee network.
/// const EXTENDED_PAN_ID: u64 = 0xafca_95fc_e132_eeb6;
/// Placeholder: replace with the Extended PAN ID of your own coordinator.
const EXTENDED_PAN_ID: u64 = 0xabcd_ef01_2345_6789;
/// Channel to scan on; must match the coordinator. /// Channel to scan on; must match the coordinator.
const CHANNEL: u8 = 11; const CHANNEL: u8 = 25;
/// Scan duration exponent (beacon order). /// Scan duration exponent (beacon order).
const SCAN_DURATION: u8 = 5; const SCAN_DURATION: u8 = 5;
@@ -60,24 +81,25 @@ const SCAN_DURATION: u8 = 5;
/// The application endpoint this light is served on. /// The application endpoint this light is served on.
const LIGHT_ENDPOINT: u8 = 1; const LIGHT_ENDPOINT: u8 = 1;
/// Mains powered and always listening: allocate address (bit 7) and /// Mains powered and always listening: allocate address (bit 7), power source
/// rx-on-when-idle (bit 3), so the coordinator can push commands at any time /// (bit 2), and rx-on-when-idle (bit 3); bit 1 stays clear for an end device.
/// rather than waiting for a poll. const CAPABILITY: u8 = 0x8c;
const CAPABILITY: u8 = 0x8e;
static INPUT_CLUSTERS: [u16; 3] = [ 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,
color_control::CLUSTER_ID,
effects_cluster::CLUSTER_ID,
]; ];
static OUTPUT_CLUSTERS: [u16; 0] = []; static OUTPUT_CLUSTERS: [u16; 0] = [];
static ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor { static ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor {
endpoint: LIGHT_ENDPOINT, endpoint: LIGHT_ENDPOINT,
profile_id: profile::HOME_AUTOMATION, profile_id: profile::HOME_AUTOMATION,
// HA device id 0x0100: On/Off Light. Becomes 0x0101 (Dimmable Light) once // HA device id 0x010d: Extended Color Light.
// Level Control is implemented. device_id: 0x010d,
device_id: 0x0100,
device_version: 1, device_version: 1,
input_clusters: &INPUT_CLUSTERS, input_clusters: &INPUT_CLUSTERS,
output_clusters: &OUTPUT_CLUSTERS, output_clusters: &OUTPUT_CLUSTERS,
@@ -96,9 +118,14 @@ static BASIC: BasicServer = BasicServer {
pub static IDENTIFY: IdentifyServer = IdentifyServer::new(); 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 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>>>; type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>;
@@ -107,9 +134,19 @@ type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'sta
/// (ZCL 2.5.12.2). /// (ZCL 2.5.12.2).
type Handler = ( type Handler = (
BasicServer<'static>, BasicServer<'static>,
(
&'static IdentifyServer, &'static IdentifyServer,
(
&'static OnOffServer<'static>, &'static OnOffServer<'static>,
UnsupportedClusterResponder<'static>, (
&'static LevelControlServer<'static>,
(
&'static ColorControlServer<'static>,
(&'static EffectsServer, UnsupportedClusterResponder<'static>),
),
),
),
),
); );
pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>; pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>;
@@ -117,9 +154,22 @@ pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>;
pub fn handler() -> Handler { pub fn handler() -> Handler {
( (
BASIC, BASIC,
(
&IDENTIFY, &IDENTIFY,
(
&ON_OFF, &ON_OFF,
(
&LEVEL_CONTROL,
(
&COLOR_CONTROL,
(
&EFFECTS,
UnsupportedClusterResponder::new(&INPUT_CLUSTERS), UnsupportedClusterResponder::new(&INPUT_CLUSTERS),
),
),
),
),
),
) )
} }
@@ -141,7 +191,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,
@@ -164,36 +214,346 @@ pub fn config() -> StackConfig<'static> {
/// parent link, and persistence. /// parent link, and persistence.
#[embassy_executor::task] #[embassy_executor::task]
pub async fn stack_task(stack: &'static Stack) { pub async fn stack_task(stack: &'static Stack) {
// returns only once no rejoin can get us back: the network is gone or our loop {
// keys are stale, so drop it and re-commission from scratch
let outcome = stack.run(embassy_time::Delay).await; let outcome = stack.run(embassy_time::Delay).await;
log::warn!("off the network ({outcome:?}), forgetting it and rebooting"); log::warn!("off the network ({outcome:?}), retrying in 5 seconds");
stack.forget_network().await; Timer::after(Duration::from_secs(5)).await;
esp_hal::system::software_reset(); }
} }
/// Mirrors the On/Off attribute onto the strip, both ways. async fn report_attribute<T, A>(
/// stack: &'static Stack,
/// The cluster server writes its attribute from the APS receive path without attribute: &Attribute<T, A, Reportable>,
/// any notification hook, so this samples it. The reverse direction keeps the value: T::Value<'_>,
/// attribute truthful after a local button press. sequence_number: &mut u8,
) -> 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] #[embassy_executor::task]
pub async fn on_off_task() { pub async fn lighting_task(stack: &'static Stack) {
let mut last = ON_OFF.on_off(); 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 { loop {
Timer::after(Duration::from_millis(50)).await; Timer::after(Duration::from_millis(50)).await;
let remote = ON_OFF.on_off(); if let Some(effect) = IDENTIFY.take_effect() {
if remote != last { log::info!("Zigbee Trigger Effect: {effect:?}");
last = remote; match effect {
light::set_on(remote); Effect::Blink => light::play_effect(light::Effect::Blink),
continue; 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 let Some(on) = LEVEL_CONTROL.take_on_off_change() {
if local != last { ON_OFF.set_on_off(on);
last = local; }
ON_OFF.set_on_off(local);
let remote_on = ON_OFF.on_off();
if remote_on != last_on {
last_on = remote_on;
if light::is_on() != remote_on {
log::info!("Zigbee On/Off state changed: {remote_on}");
light::set_on(remote_on);
}
pending_on = None;
}
let local_on = light::is_on();
if local_on != last_on {
last_on = local_on;
ON_OFF.set_on_off(local_on);
pending_on = Some(local_on);
}
let 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;
}
} }
} }
} }
@@ -209,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;
}
}