20 Commits
Author SHA1 Message Date
Matt SpencerandCopilot c6b1537c8c tools: install a release into the idle firmware slot
release / release (push) Successful in 1m39s
Add tools/install_release.py, a host script that takes a release from Gitea
and puts it on a board over USB the way an update would: it downloads the
release's application image and checks it against the release checksums,
writes it to the slot that is not running, and rewrites otadata to select
that slot as a new image before resetting the board.

It reads the board's own partition table and slot selection rather than
assuming a layout, refuses a board without the A/B partition table, and
writes nothing until the image has been downloaded and verified. A dry run
shows what it would do.

This lets the A/B slots be tested with real releases while there is no
over-the-air update source. The README documents it, and the full image's
install steps now clear the slot selection, so that a board which had
switched to the second slot runs the image just written.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-29 01:16:37 +00:00
Matt Spencer ae5ed848ad Merge branch 'ab_update' into main
Bring the A/B firmware slots into main, so that releases contain them.
2026-11-29 01:14:32 +00:00
Matt SpencerandCopilot 35fe7c7bf9 build: pin the Rust nightly
The toolchain file said "nightly", so every build used whatever the newest
nightly was that day. The release workflow built the same commit as a
different binary to a local build (346,464 bytes against 358,928), and a new
nightly could break the build with no change to the project.

Pin the nightly that the project has been built and tested with, 2026-10-17
(rustc 5d8fec066). Moving it forward is now a deliberate change.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-29 01:14:32 +00:00
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 Spencer 9e7d0d7d1f Merge branch 'main' into ab_update 2026-11-29 00:38:36 +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 9ea25c3aab feat: add A/B firmware slots
Split the single app partition into two slots, ota_0 and ota_1, with an
otadata partition that tells the bootloader which to run, so an update can
be written to the idle slot while the other keeps running. The Zigbee
storage partition is unchanged, so the light keeps its network. Moving from
the old table needs one USB flash.

* src/ota.rs logs the running slot and the state of its image at boot,
  marks an image valid after it has stayed up for 20 seconds, and can
  switch to the other slot and restart. The slot in use is read from the
  flash mapping, not from otadata.
* src/flash.rs shares the one flash handle: esp-storage allows only one, and
  both the Zigbee stack and the update code need it.
* The runner clears otadata on every USB flash. A USB flash always writes
  slot 0, so without this a board that had switched to slot 1 would keep
  booting the old image.
* Two development features, ota-test and ota-test-crash, exercise slot
  switching and an unconfirmed image without an update source. FW_LABEL tells
  builds apart in the log.

Tested on the hardware: switching between two images across six reboots, each
booting the slot it had just selected, resuming its Zigbee network, and
confirming itself. Rollback is not available: the bootloader espflash installs
is not built with it, so a newly selected image reports "New" rather than
"PendingVerify", and an image that resets without confirming itself is booted
again indefinitely. Needs a rollback-enabled bootloader. Nothing delivers
updates yet. Both are recorded in TODO.md.

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

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
target = "riscv32imac-unknown-none-elf"
[target.riscv32imac-unknown-none-elf]
runner = "espflash flash --monitor"
runner = "espflash flash --monitor --partition-table partitions.csv --erase-parts otadata"
rustflags = [
"-C", "link-arg=-Tlinkall.x",
"-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
/vendor/zigbee-rs/target
/nda
__pycache__/
*.pyc
+2 -2
View File
@@ -1,4 +1,4 @@
[submodule "vendor/zigbee-rs"]
path = vendor/zigbee-rs
url = https://github.com/zigbee-rs/zigbee-rs.git
branch = smart-light
url = git@github.com:m5p3nc3r/zigbee-rs.git
branch = feature/lighting-effects-integration
Generated
+33 -1
View File
@@ -382,6 +382,26 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "defmt-or-log"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be59789d306cc1a082f53bb7c24c270d7e6078c00b7550a718219a7090156d97"
dependencies = [
"defmt-or-log-macros",
]
[[package]]
name = "defmt-or-log-macros"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d675dd299edbb7c8e01d4e9f520a0d8f22a8fe4af812c211c3fad5e9dcf41763"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "defmt-parser"
version = "1.1.0"
@@ -1399,6 +1419,12 @@ version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linked_list_allocator"
version = "0.10.6"
@@ -1820,6 +1846,7 @@ dependencies = [
"embassy-futures",
"embassy-sync 0.8.0",
"embassy-time",
"embedded-storage",
"esp-alloc",
"esp-backtrace",
"esp-bootloader-esp-idf",
@@ -1829,6 +1856,7 @@ dependencies = [
"esp-radio",
"esp-rtos",
"esp-storage",
"libm",
"log",
"smart-leds",
"smart-leds-trait",
@@ -2206,6 +2234,7 @@ dependencies = [
name = "zigbee"
version = "0.1.0"
dependencies = [
"defmt-or-log",
"embedded-hal-async",
"log",
"zigbee-base-device-behavior",
@@ -2219,6 +2248,7 @@ dependencies = [
name = "zigbee-base-device-behavior"
version = "0.1.0"
dependencies = [
"defmt-or-log",
"embedded-hal-async",
"log",
"spin",
@@ -2249,6 +2279,7 @@ dependencies = [
"aes",
"byte",
"ccm 0.5.0",
"defmt-or-log",
"embedded-hal-async",
"embedded-storage-async",
"heapless 0.9.3",
@@ -2267,6 +2298,8 @@ name = "zigbee-mac"
version = "0.1.0"
dependencies = [
"byte",
"defmt",
"defmt-or-log",
"embassy-futures",
"embassy-sync 0.8.0",
"embassy-time",
@@ -2294,7 +2327,6 @@ dependencies = [
"byte",
"embedded-storage",
"heapless 0.9.3",
"itertools",
"spin",
"zigbee-macros",
]
+20 -8
View File
@@ -2,19 +2,29 @@
name = "smart-light"
version = "0.1.0"
edition = "2024"
license = "MIT"
[features]
default = ["esp32c6"]
default = ["esp32c6", "zigbee"]
## Development only: switch to the other firmware slot 30 seconds after boot,
## and again after every boot, to exercise A/B slot switching without Zigbee.
ota-test = []
## Development only, with `ota-test`: never confirm the image, and reset 5
## seconds after boot, to see whether an unconfirmed image is rolled back.
ota-test-crash = ["ota-test"]
## Join a Zigbee network. Disable to bring up the local hardware on its own:
## the stack reboots the device when it cannot find its coordinator.
zigbee = ["dep:esp-radio", "dep:zigbee", "dep:zigbee-cluster-library", "dep:zigbee-mac", "dep:zigbee-types"]
esp32c6 = [
"esp-alloc/esp32c6",
"esp-backtrace/esp32c6",
"esp-bootloader-esp-idf/esp32c6",
"esp-hal/esp32c6",
"esp-println/esp32c6",
"esp-radio/esp32c6",
"esp-radio?/esp32c6",
"esp-rtos/esp32c6",
"esp-storage/esp32c6",
"zigbee-mac/esp32c6",
"zigbee-mac?/esp32c6",
]
[dependencies]
@@ -23,9 +33,10 @@ esp-backtrace = { version = "0.20", features = ["panic-handler", "println"] }
esp-bootloader-esp-idf = "0.6"
esp-hal = { version = "1.2", features = ["log-04", "unstable"] }
esp-println = { version = "0.18", features = ["log-04"] }
esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"] }
esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"], optional = true }
esp-rtos = { version = "0.4", features = ["embassy", "log-04"] }
esp-storage = { version = "0.10", features = ["embedded-storage"] }
embedded-storage = "0.3"
embassy-executor = "0.10.0"
embassy-futures = "0.1"
@@ -39,13 +50,14 @@ log = "0.4"
smart-leds = "0.4"
smart-leds-trait = "0.3"
esp-hal-smartled = "0.18"
libm = "0.2"
# vendored upstream: the lighting cluster is not implemented there yet, so the
# path dependency lets us add it in-tree and upstream it later
zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"] }
zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library" }
zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac" }
zigbee-types = { path = "vendor/zigbee-rs/zigbee-types" }
zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"], optional = true }
zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library", optional = true }
zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac", optional = true }
zigbee-types = { path = "vendor/zigbee-rs/zigbee-types", optional = true }
[profile.release]
debug = true
+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.
+201
View File
@@ -0,0 +1,201 @@
# 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.
### Firmware slots
The flash has two app slots, `ota_0` and `ota_1`, and an `otadata` partition
that tells the bootloader which to run, so a new image can be written to the
idle slot while the other keeps running. A USB flash always writes slot 0 and
clears `otadata`, which is why the runner passes `--erase-parts otadata`: without
it, a board that had switched to slot 1 would keep booting the old image.
Changing from the old single-slot partition table to this one needs one USB
flash. The network state is not touched.
The firmware logs which slot it is running from and the state of its image, and
marks a new image as valid once it has stayed up for 20 seconds. Switching
slots has no update source yet (see `TODO.md`). Two development features
exercise it without one: `ota-test` switches to the other slot 30 seconds after
every boot, and `ota-test-crash` resets without confirming the image. Set
`FW_LABEL` when building to tell images apart in the log, and write an image to
the idle slot with `espflash save-image` and `espflash write-bin`.
**There is no rollback yet.** The bootloader that `espflash` installs is not
built with rollback support, so an image that crashes after being selected will
keep being booted. Recover by flashing over USB.
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`, then clear the slot
selection with `espflash erase-parts otadata` so that the board runs it.
The image 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`.
### Installing a release over USB
Once a board has the A/B partition table, `tools/install_release.py` installs a
release into the slot that is not running and switches to it, without
touching the running image until the new one has been downloaded and checked:
```sh
tools/install_release.py # the latest release
tools/install_release.py 0.1.23 # a particular one
tools/install_release.py --dry-run # show what would be done, write nothing
```
It reads the board's partition table and slot selection, downloads the release's
application image and checks it against `SHA256SUMS`, writes it to the idle
slot, rewrites `otadata` to select that slot as a new image, and resets the
board. The firmware logs the version it is running, which slot it came from,
and when it confirms the image, so the log shows the update has worked. Run it
again and the board alternates to the other slot.
This is a way of testing the A/B slots with real releases, not an update
mechanism for lights in use: it needs the board on a USB cable. There is no
rollback yet (see `TODO.md`), so an image that does not start has to be fixed
by flashing over USB.
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.
+109
View File
@@ -0,0 +1,109 @@
# TODO
Things that are known to be open. None of these is being worked on yet.
## Firmware updates (OTA)
A/B firmware slots are in place and tested (see the README). What is missing:
- [ ] **Rollback.** The bootloader `espflash` installs is not built with
`CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE`: a newly selected image reports its
state as `New` rather than `PendingVerify`, and an image that resets without
confirming itself is booted again forever (checked with the `ota-test-crash`
build). Needs a bootloader built from ESP-IDF with rollback enabled and
flashed with `espflash --bootloader`. No ESP-IDF is installed here.
- [ ] **Zigbee OTA client.** zigbee-rs has no OTA Upgrade cluster (`0x0019`) and
no client-side cluster support. The generic client belongs on its own
upstream branch, writing through a trait; the flash writing and policy stay
here.
- [ ] **A real "image works" test.** The firmware currently confirms an image
after 20 seconds up. It should require that the light has rejoined its
Zigbee network, and mark the image invalid and switch back if it has not.
- [ ] **Hung images.** A panic hangs rather than resets, so a new image that
hangs would never reach the confirmation. Enable a watchdog.
- [ ] **Image tooling and Home Assistant.** A host tool to wrap the app image
in a Zigbee OTA file, and a ZHA `z2m_local` provider index for it. Choose a
version scheme and image type.
- [ ] **Flash writes versus the radio.** Writing an image while the radio is
active stalls the CPU for each sector erase; not yet measured against frame
loss.
## 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()
)
+12
View File
@@ -0,0 +1,12 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x4000,
# Which of the two app slots to boot, and whether the last update was confirmed.
otadata, data, ota, 0xd000, 0x2000,
phy_init, data, phy, 0xf000, 0x1000,
# A/B firmware slots: an update is written to whichever one is not running.
# Each must start on a 64 KiB boundary.
ota_0, app, ota_0, 0x10000, 0x1E0000,
ota_1, app, ota_1, 0x1F0000, 0x1E0000,
# Zigbee persistence: the stack writes this region directly, so it must not
# overlap the app partitions. 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, 0x4000,
3 # Which of the two app slots to boot, and whether the last update was confirmed.
4 otadata, data, ota, 0xd000, 0x2000,
5 phy_init, data, phy, 0xf000, 0x1000,
6 # A/B firmware slots: an update is written to whichever one is not running.
7 # Each must start on a 64 KiB boundary.
8 ota_0, app, ota_0, 0x10000, 0x1E0000,
9 ota_1, app, ota_1, 0x1F0000, 0x1E0000,
10 # Zigbee persistence: the stack writes this region directly, so it must not
11 # overlap the app partitions. Keep in sync with FLASH_RANGE in zigbee_stack.rs.
12 storage, data, nvs, 0x3E0000, 0x20000,
+3 -1
View File
@@ -1,4 +1,6 @@
[toolchain]
channel = "nightly"
# pinned, so that a release builds the same way every time: a floating
# "nightly" changes under the project. Move it forward deliberately.
channel = "nightly-2026-10-17"
components = ["rust-src", "rustfmt", "clippy"]
targets = ["riscv32imac-unknown-none-elf"]
+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.
/// Number of WS2812B pixels on the strip.
pub const LED_COUNT: usize = 60;
pub const LED_COUNT: usize = 24;
/// Ceiling on the duty cycle applied to every channel, as a fraction of 255.
///
/// Keeps the supply current within what the dev board's regulator can source
/// when every pixel is driven white.
/// Takes the top off peak current draw. This is a brightness cap, not a
/// current limit: a strip of this length still needs its own 5V supply.
pub const MAX_DUTY: u8 = 200;
/// Rotary encoder detents per full revolution, used to scale a turn into a
@@ -18,5 +18,18 @@ pub const STEPS_PER_BRIGHTNESS_UNIT: i32 = 1;
/// Hold time that separates a click from a long press.
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.
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)
}
}
+30 -49
View File
@@ -1,12 +1,11 @@
//! Interrupt-driven rotary encoder with a push button.
//!
//! Both tasks park on GPIO edge interrupts; nothing here polls. Quadrature is
//! decoded from the transition between the previous and current A/B pair, so a
//! bounce that returns to the previous state cancels itself out instead of
//! registering a step.
//! Both tasks park on GPIO edge interrupts; nothing here polls.
//!
//! Direction comes from sampling A on B's falling edge: one detent produces
//! exactly one such edge, and A's level there is opposite for the two
//! directions.
use embassy_futures::select::Either;
use embassy_futures::select::select;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel;
use embassy_time::Duration;
@@ -16,6 +15,7 @@ use esp_hal::gpio::Input;
use crate::config::DEBOUNCE_MS;
use crate::config::LONG_PRESS_MS;
use crate::config::RESET_HOLD_MS;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum EncoderEvent {
@@ -23,53 +23,27 @@ pub enum EncoderEvent {
Rotate(i8),
Click,
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
/// drops the oldest step, which is preferable to blocking the interrupt task.
pub static EVENTS: Channel<CriticalSectionRawMutex, EncoderEvent, 8> = Channel::new();
/// Valid quadrature transitions, indexed by `(previous << 2) | current` where
/// each pair is `(a << 1) | b`. Zero marks either no movement or an illegal
/// jump of two states, which means a transition was missed.
#[rustfmt::skip]
const TRANSITIONS: [i8; 16] = [
0, -1, 1, 0,
1, 0, 0, -1,
-1, 0, 0, 1,
0, 1, -1, 0,
];
#[embassy_executor::task]
pub async fn encoder_task(mut a: Input<'static>, mut b: Input<'static>) {
let mut previous = state(&a, &b);
// a full detent is four quadrature transitions; only whole detents are
// reported so a resting-point jitter never moves the light
let mut substeps: i8 = 0;
pub async fn encoder_task(a: Input<'static>, mut b: Input<'static>) {
loop {
match select(a.wait_for_any_edge(), b.wait_for_any_edge()).await {
Either::First(()) | Either::Second(()) => {}
}
b.wait_for_falling_edge().await;
let current = state(&a, &b);
if current == previous {
continue;
}
// A must be read here, before the rest of the detent moves it
let delta = if a.is_high() { -1 } else { 1 };
log::info!("edge on B -> A={} rotate {delta:+}", a.is_high() as u8);
let _ = EVENTS.try_send(EncoderEvent::Rotate(delta));
let delta = TRANSITIONS[(previous << 2) | current];
previous = current;
if delta == 0 {
continue;
}
substeps += delta;
if substeps.abs() >= 4 {
let detents = substeps / 4;
substeps -= detents * 4;
// full is fine: a dropped step during a spin is invisible
let _ = EVENTS.try_send(EncoderEvent::Rotate(detents));
}
// the rest of the detent returns B to rest; ignoring it stops one
// detent counting twice
b.wait_for_rising_edge().await;
}
}
@@ -92,8 +66,19 @@ pub async fn button_task(mut button: Input<'static>) {
if long_press {
let _ = EVENTS.try_send(EncoderEvent::LongPress);
// swallow the release so it is not read as a second press
button.wait_for_rising_edge().await;
// 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
button.wait_for_rising_edge().await;
}
} else {
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;
}
}
fn state(a: &Input<'static>, b: &Input<'static>) -> usize {
usize::from(a.is_high()) << 1 | usize::from(b.is_high())
}
+79
View File
@@ -0,0 +1,79 @@
//! The one flash handle, shared.
//!
//! `esp_storage::FlashStorage` can only be created once, but two things need
//! the flash: the Zigbee stack, which persists its state there, and the
//! firmware update code, which reads the partition table and the OTA data.
//!
//! Every access takes a critical section. `esp-storage` already makes each
//! flash operation atomic with respect to interrupts, so this adds no new
//! stall for a single read, erase or write; it only keeps two tasks from
//! interleaving a sequence of them.
use core::cell::RefCell;
use embassy_sync::blocking_mutex::Mutex;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embedded_storage::nor_flash::ErrorType;
use embedded_storage::nor_flash::MultiwriteNorFlash;
use embedded_storage::nor_flash::NorFlash;
use embedded_storage::nor_flash::ReadNorFlash;
pub use esp_storage::FlashStorage;
static FLASH: Mutex<CriticalSectionRawMutex, RefCell<Option<FlashStorage<'static>>>> =
Mutex::new(RefCell::new(None));
/// Hands the flash over to this module. Call once, before anything uses it.
pub fn init(flash: FlashStorage<'static>) {
FLASH.lock(|cell| *cell.borrow_mut() = Some(flash));
}
/// Runs `f` with exclusive access to the flash.
///
/// `f` must not call back into this module: the flash is already borrowed.
///
/// # Panics
///
/// If [`init`] has not been called.
pub fn with<R>(f: impl FnOnce(&mut FlashStorage<'static>) -> R) -> R {
FLASH.lock(|cell| {
let mut flash = cell.borrow_mut();
f(flash.as_mut().expect("flash not initialised"))
})
}
/// A handle to the shared flash that is itself a flash device, for code that
/// wants to own one, such as the Zigbee storage.
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
pub struct SharedFlash;
impl ErrorType for SharedFlash {
type Error = <FlashStorage<'static> as ErrorType>::Error;
}
impl ReadNorFlash for SharedFlash {
const READ_SIZE: usize = <FlashStorage<'static> as ReadNorFlash>::READ_SIZE;
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
with(|flash| flash.read(offset, bytes))
}
fn capacity(&self) -> usize {
with(|flash| flash.capacity())
}
}
impl NorFlash for SharedFlash {
const WRITE_SIZE: usize = <FlashStorage<'static> as NorFlash>::WRITE_SIZE;
const ERASE_SIZE: usize = <FlashStorage<'static> as NorFlash>::ERASE_SIZE;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
with(|flash| flash.erase(from, to))
}
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
with(|flash| flash.write(offset, bytes))
}
}
impl MultiwriteNorFlash for SharedFlash {}
+195 -34
View File
@@ -8,8 +8,10 @@ use core::sync::atomic::AtomicBool;
use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering;
use embassy_futures::select::select;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use embassy_time::Timer;
use smart_leds::RGB8;
use smart_leds::SmartLedsWriteAsync;
use smart_leds::brightness as scale_brightness;
@@ -19,19 +21,37 @@ use smart_leds::hsv::hsv2rgb;
use crate::config::LED_COUNT;
use crate::config::MAX_DUTY;
use crate::effect;
#[cfg(feature = "zigbee")]
pub use crate::effect::Effect;
use crate::scene;
use crate::strip::Strip;
/// What a turn of the encoder adjusts.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
Brightness,
Hue,
}
/// Colour temperature presets, warmest first, as sRGB with the brightest
/// channel at full.
///
/// Precomputed rather than derived: a blackbody conversion needs floating
/// point the C6 has no hardware for, and a handful of presets does not
/// justify carrying it.
pub const TEMPERATURES: [(u16, RGB8); 6] = [
(2200, RGB8 { r: 255, g: 147, b: 41 }),
(2700, RGB8 { r: 255, g: 169, b: 87 }),
(3000, RGB8 { r: 255, g: 180, b: 107 }),
(4000, RGB8 { r: 255, g: 209, b: 163 }),
(5000, RGB8 { r: 255, g: 228, b: 206 }),
(6500, RGB8 { r: 255, g: 249, b: 253 }),
];
static ON: AtomicBool = AtomicBool::new(false);
static ON: AtomicBool = AtomicBool::new(true);
static BRIGHTNESS: AtomicU8 = AtomicU8::new(128);
/// Index into [`TEMPERATURES`]; 2700K is the warm white a lamp usually sits at.
static TEMPERATURE: AtomicU8 = AtomicU8::new(1);
static COLOR_MODE: AtomicBool = AtomicBool::new(false);
static XY_MODE: AtomicBool = AtomicBool::new(false);
static HUE: AtomicU8 = AtomicU8::new(0);
static HUE_MODE: AtomicBool = AtomicBool::new(false);
static SATURATION: AtomicU8 = AtomicU8::new(0);
static X: AtomicU8 = AtomicU8::new(122);
static Y: AtomicU8 = AtomicU8::new(128);
static DIRTY: Signal<CriticalSectionRawMutex, ()> = Signal::new();
pub fn is_on() -> bool {
@@ -53,6 +73,11 @@ pub fn brightness() -> u8 {
BRIGHTNESS.load(Ordering::Relaxed)
}
pub fn set_brightness(level: u8) {
BRIGHTNESS.store(level.min(254), Ordering::Relaxed);
DIRTY.signal(());
}
/// Clamps rather than wraps: running past full should stay at full instead of
/// dropping the light to near-black.
pub fn adjust_brightness(delta: i16) {
@@ -61,28 +86,91 @@ pub fn adjust_brightness(delta: i16) {
DIRTY.signal(());
}
pub fn hue() -> u8 {
HUE.load(Ordering::Relaxed)
/// The selected preset, as `(kelvin, colour)`.
pub fn temperature() -> (u16, RGB8) {
TEMPERATURES[usize::from(TEMPERATURE.load(Ordering::Relaxed)) % TEMPERATURES.len()]
}
/// Hue is a circle, so this one wraps. `smart-leds` spans it over a full u8.
pub fn adjust_hue(delta: i16) {
let hue = hue().wrapping_add_signed(delta as i8);
HUE.store(hue, Ordering::Relaxed);
pub fn temperature_mireds() -> u16 {
(1_000_000u32 / u32::from(temperature().0)) as u16
}
pub fn is_color_mode() -> bool {
COLOR_MODE.load(Ordering::Relaxed)
}
pub fn set_hue_saturation(hue: u8, saturation: u8) {
HUE.store(hue.min(254), Ordering::Relaxed);
SATURATION.store(saturation.min(254), Ordering::Relaxed);
COLOR_MODE.store(true, Ordering::Relaxed);
XY_MODE.store(false, Ordering::Relaxed);
DIRTY.signal(());
}
pub fn mode() -> Mode {
if HUE_MODE.load(Ordering::Relaxed) {
Mode::Hue
} else {
Mode::Brightness
}
pub fn set_xy(x: u16, y: u16) {
X.store((u32::from(x) * 255 / 65_535) as u8, Ordering::Relaxed);
Y.store((u32::from(y) * 255 / 65_535) as u8, Ordering::Relaxed);
COLOR_MODE.store(true, Ordering::Relaxed);
XY_MODE.store(true, Ordering::Relaxed);
DIRTY.signal(());
}
pub fn toggle_mode() -> Mode {
HUE_MODE.fetch_xor(true, Ordering::Relaxed);
mode()
/// Select the nearest available RGB preset for a Zigbee mired request.
pub fn set_temperature_mireds(mireds: u16) -> u16 {
let target_kelvin = 1_000_000 / u32::from(mireds.max(1));
let mut closest_index = 0;
let mut closest_delta = u32::MAX;
for (index, (kelvin, _)) in TEMPERATURES.iter().enumerate() {
let delta = u32::from(*kelvin).abs_diff(target_kelvin);
if delta < closest_delta {
closest_index = index;
closest_delta = delta;
}
}
TEMPERATURE.store(closest_index as u8, Ordering::Relaxed);
COLOR_MODE.store(false, Ordering::Relaxed);
XY_MODE.store(false, Ordering::Relaxed);
DIRTY.signal(());
temperature_mireds()
}
/// Steps to the next preset, wrapping back to the warmest.
pub fn next_temperature() -> (u16, RGB8) {
let next = (TEMPERATURE.load(Ordering::Relaxed) + 1) % TEMPERATURES.len() as u8;
TEMPERATURE.store(next, Ordering::Relaxed);
COLOR_MODE.store(false, Ordering::Relaxed);
XY_MODE.store(false, Ordering::Relaxed);
DIRTY.signal(());
temperature()
}
/// Plays `effect` over the light, then returns to the state it was in.
#[cfg(feature = "zigbee")]
pub fn play_effect(effect: effect::Effect) {
effect::start(effect);
DIRTY.signal(());
}
/// Switches the continuous scene, which `Off` ends.
#[cfg(feature = "zigbee")]
pub fn set_scene(scene: scene::Scene) {
scene::set_scene(scene);
DIRTY.signal(());
}
/// Lets the effect's current cycle complete, then stops it.
#[cfg(feature = "zigbee")]
pub fn finish_effect() {
effect::finish();
DIRTY.signal(());
}
#[cfg(feature = "zigbee")]
pub fn stop_effect() {
effect::stop();
DIRTY.signal(());
}
#[embassy_executor::task]
@@ -90,26 +178,99 @@ pub async fn render_task(mut strip: Strip<'static>) {
let mut frame = [RGB8::default(); LED_COUNT];
loop {
frame.fill(hsv2rgb(Hsv {
hue: hue(),
sat: 255,
val: 255,
}));
let overlay = effect::overlay();
let colour = if let Some(colour) = overlay.and_then(|overlay| overlay.colour) {
colour
} else if is_color_mode() {
if XY_MODE.load(Ordering::Relaxed) {
xy_to_rgb(X.load(Ordering::Relaxed), Y.load(Ordering::Relaxed))
} else {
hsv2rgb(Hsv {
hue: (u16::from(HUE.load(Ordering::Relaxed)) * 255 / 254) as u8,
sat: (u16::from(SATURATION.load(Ordering::Relaxed)) * 255 / 254) as u8,
val: 255,
})
}
} else {
temperature().1
};
// an effect that names a colour takes the whole strip; otherwise a
// running scene draws it, and failing both the light shows one colour
if overlay.is_none_or(|overlay| overlay.colour.is_none()) && scene::is_active() {
scene::render(&mut frame, colour);
} else {
frame.fill(colour);
}
// off is just zero brightness, so the colour survives a power cycle of
// the strip output and comes back as it was
let level = if is_on() {
(u16::from(brightness()) * u16::from(MAX_DUTY) / 255) as u8
// the strip output and comes back as it was. an effect is drawn even
// when the light is off, or it could not be seen
let base = if is_on() {
brightness()
} else if overlay.is_some() {
effect::OFF_LEVEL
} else {
0
};
let level = (u16::from(base) * u16::from(MAX_DUTY) / 255) as u8;
let level = overlay.map_or(level, |overlay| {
(u16::from(level) * u16::from(overlay.gain) / 255) as u8
});
// gamma before brightness, as smart-leds requires
let pixels = scale_brightness(gamma(frame.iter().copied()), level);
// gamma is applied to the level, not the pixels: curving each channel
// of an already white-balanced colour would shift its temperature
let level = gamma(core::iter::once(RGB8 {
r: level,
g: level,
b: level,
}))
.next()
.map_or(0, |corrected| corrected.r);
let pixels = scale_brightness(frame.iter().copied(), level);
if let Err(e) = strip.write(pixels).await {
log::warn!("strip write failed: {e:?}");
}
DIRTY.wait().await;
if effect::is_active() || scene::is_active() {
// redraw on a timer while something animates, and still on demand
select(DIRTY.wait(), Timer::after_millis(scene::FRAME_MS)).await;
} else {
DIRTY.wait().await;
}
}
}
fn xy_to_rgb(x: u8, y: u8) -> RGB8 {
let x = f32::from(x) / 255.0;
let y = f32::from(y) / 255.0;
if y == 0.0 {
return RGB8::default();
}
let z = (1.0 - x - y) / y;
let x = x / y;
let mut red = 3.2406 * x - 1.5372 - 0.4986 * z;
let mut green = -0.9689 * x + 1.8758 + 0.0415 * z;
let mut blue = 0.0557 * x - 0.2040 + 1.0570 * z;
let max = red.max(green).max(blue).max(1.0);
red = (red / max).max(0.0);
green = (green / max).max(0.0);
blue = (blue / max).max(0.0);
fn srgb(value: f32) -> u8 {
let linear = if value <= 0.003_130_8 {
12.92 * value
} else {
1.055 * libm::powf(value, 1.0 / 2.4) - 0.055
};
(linear * 255.0 + 0.5) as u8
}
RGB8 {
r: srgb(red),
g: srgb(green),
b: srgb(blue),
}
}
+82 -41
View File
@@ -2,46 +2,50 @@
#![no_main]
mod config;
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
mod effect;
#[cfg(feature = "zigbee")]
mod effects_cluster;
mod encoder;
mod flash;
mod light;
// the crash test never confirms an image or switches slot, so those go unused
#[cfg_attr(feature = "ota-test-crash", allow(dead_code))]
mod ota;
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
mod scene;
mod status;
mod strip;
#[cfg(feature = "zigbee")]
mod zigbee_stack;
use embassy_embedded_hal::adapter::BlockingAsync;
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::gpio::Input;
use esp_hal::gpio::InputConfig;
use esp_hal::gpio::Level;
use esp_hal::gpio::Output;
use esp_hal::gpio::OutputConfig;
use esp_hal::gpio::Pull;
use esp_hal::rmt::Rmt;
use esp_hal::time::Rate;
use esp_hal::timer::timg::TimerGroup;
use esp_hal_smartled::WS2812B_TIMING;
use esp_radio::ieee802154::Ieee802154;
use esp_storage::FlashStorage;
use static_cell::StaticCell;
use zigbee_mac::esp::EspMlme;
use crate::config::STEPS_PER_BRIGHTNESS_UNIT;
use crate::encoder::EVENTS;
use crate::encoder::EncoderEvent;
use crate::light::Mode;
use crate::strip::Strip;
use crate::zigbee_stack::Stack;
esp_bootloader_esp_idf::esp_app_desc!();
static STACK: StaticCell<Stack> = StaticCell::new();
/// Brightness units per detent.
const BRIGHTNESS_STEP: i16 = 8;
/// Hue per detent, in 1/256ths of the colour circle (~5.6 degrees).
const HUE_STEP: i16 = 4;
#[esp_rtos::main]
async fn main(spawner: embassy_executor::Spawner) -> ! {
esp_println::logger::init_logger_from_env();
log::info!("smart-light {}", env!("CARGO_PKG_VERSION"));
let peripherals = esp_hal::init(esp_hal::Config::default());
let timg0 = TimerGroup::new(peripherals.TIMG0);
@@ -49,61 +53,98 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
esp_alloc::heap_allocator!(size: 32 * 1024);
// the one flash handle: the Zigbee stack keeps its state there and the
// firmware update code manages the A/B slots
flash::init(esp_storage::FlashStorage::new(peripherals.FLASH));
ota::log_boot();
// a stand-in for "the image works": long enough that a crash on startup
// is caught first
#[cfg(not(feature = "ota-test-crash"))]
spawner.spawn(ota::confirm_task().expect("spawn confirm_task"));
#[cfg(feature = "ota-test")]
spawner.spawn(ota::test_task().expect("spawn test_task"));
// the adapter derives its pulse timings from this frequency, so the same
// rate has to be handed to both calls
let rmt_freq = Rate::from_mhz(80);
let rmt = Rmt::new(peripherals.RMT, rmt_freq)
.expect("init RMT")
.into_async();
// XIAO ESP32C6 pads: D2, D3, D4, D5. GPIO4/5/6 are JTAG and are not
// broken out on this board; GPIO3 and GPIO14 drive the antenna switch.
let strip = Strip::new(WS2812B_TIMING, rmt.channel0, peripherals.GPIO2, rmt_freq)
.expect("configure WS2812B adapter");
// the encoder's common pin is grounded, so both phases and the switch idle
// high and are driven low; the pull-ups make an open contact well defined
// high and are driven low; the pull-ups make an open contact well defined.
// D10/D9/D8 sit directly under the 3V3 and GND pads, keeping the module's
// five wires on one side of the board.
let pull_up = InputConfig::default().with_pull(Pull::Up);
let encoder_a = Input::new(peripherals.GPIO4, pull_up);
let encoder_b = Input::new(peripherals.GPIO5, pull_up);
let button = Input::new(peripherals.GPIO6, pull_up);
let encoder_a = Input::new(peripherals.GPIO18, pull_up); // D10, CLK
let encoder_b = Input::new(peripherals.GPIO20, pull_up); // D9, DT
let button = Input::new(peripherals.GPIO19, pull_up); // D8, SW
// the stack owns persistence: the information bases are restored here and
// written back whenever the stack changes them
let flash = BlockingAsync::new(FlashStorage::new(peripherals.FLASH));
let storage = zigbee::storage::init_with_flash(flash, zigbee_stack::FLASH_RANGE).await;
let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default());
log::info!("device IEEE address: {:#018x}", mac.ieee_address());
let stack: &'static Stack = STACK.init(Stack::new(
mac,
zigbee_stack::config(),
zigbee_stack::handler(),
storage,
));
// on-board user LED, starting dark
let led = Output::new(peripherals.GPIO15, Level::High, OutputConfig::default());
spawner.spawn(status::heartbeat_task(led).expect("spawn heartbeat_task"));
spawner.spawn(light::render_task(strip).expect("spawn render_task"));
spawner.spawn(encoder::encoder_task(encoder_a, encoder_b).expect("spawn encoder_task"));
spawner.spawn(encoder::button_task(button).expect("spawn button_task"));
spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task"));
spawner.spawn(zigbee_stack::on_off_task().expect("spawn on_off_task"));
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
#[cfg(feature = "zigbee")]
{
use embassy_embedded_hal::adapter::BlockingAsync;
use esp_radio::ieee802154::Ieee802154;
use 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(flash::SharedFlash);
let storage = zigbee::storage::FlashStorage::new(flash, zigbee_stack::FLASH_RANGE).await;
let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default());
log::info!("device IEEE address: {:#018x}", mac.ieee_address());
let stack: &'static Stack = STACK.init(Stack::new(
mac,
zigbee_stack::config(),
zigbee_stack::handler(),
storage,
));
spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task"));
spawner.spawn(zigbee_stack::lighting_task(stack).expect("spawn lighting_task"));
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
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 {
match EVENTS.receive().await {
EncoderEvent::Rotate(detents) => {
let steps = i16::from(detents) * STEPS_PER_BRIGHTNESS_UNIT as i16;
match light::mode() {
Mode::Brightness => light::adjust_brightness(steps * BRIGHTNESS_STEP),
Mode::Hue => light::adjust_hue(steps * HUE_STEP),
}
light::adjust_brightness(steps * BRIGHTNESS_STEP);
log::info!("rotate {detents:+} -> brightness {}", light::brightness());
}
EncoderEvent::Click => {
let (kelvin, _) = light::next_temperature();
log::info!("colour temperature {kelvin}K");
}
EncoderEvent::LongPress => {
let on = light::toggle();
log::info!("light {}", if on { "on" } else { "off" });
}
EncoderEvent::LongPress => {
let mode = light::toggle_mode();
log::info!("encoder now adjusts {mode:?}");
EncoderEvent::NetworkReset => {
log::warn!("button held: resetting the Zigbee network");
#[cfg(feature = "zigbee")]
zigbee_stack::request_network_reset();
}
}
}
+164
View File
@@ -0,0 +1,164 @@
//! A/B firmware slots.
//!
//! The flash holds two app slots, `ota_0` and `ota_1`, and an `otadata`
//! partition that tells the bootloader which of them to run. An update is
//! written to the slot that is not running, which is then selected and marked
//! `New`. Once the new image has shown that it works it is marked `Valid`;
//! until then, a bootloader built with rollback support will go back to the
//! previous slot if the new one never confirms itself.
//!
//! This module only manages the slots. Getting an image into the idle slot is
//! the job of whatever delivers updates.
use core::convert::Infallible;
use embassy_time::Duration;
use embassy_time::Timer;
use esp_bootloader_esp_idf::ota::OtaImageState;
use esp_bootloader_esp_idf::ota_updater::OtaUpdater;
use esp_bootloader_esp_idf::partitions;
use esp_bootloader_esp_idf::partitions::AppPartitionSubType;
use esp_bootloader_esp_idf::partitions::Error;
use esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN;
use esp_bootloader_esp_idf::partitions::PartitionType;
use esp_hal::system::software_reset;
use crate::flash;
use crate::flash::FlashStorage;
/// Names a build in the log, so two images can be told apart while testing:
/// `FW_LABEL=B cargo build --release`.
const LABEL: &str = match option_env!("FW_LABEL") {
Some(label) => label,
None => "-",
};
/// How long a new image has to stay up before it is trusted.
pub const CONFIRM_AFTER: Duration = Duration::from_secs(20);
/// The slot the CPU is running from, read from the flash mapping, not from
/// what `otadata` says should be running.
fn running_slot(flash: &mut FlashStorage<'static>) -> Result<Option<AppPartitionSubType>, Error> {
let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN];
let table = partitions::read_partition_table(flash, &mut buffer)?;
Ok(table
.booted_partition()?
.and_then(|entry| match entry.partition_type() {
PartitionType::App(slot) => Some(slot),
_ => None,
}))
}
/// Logs which slot is running, which one the bootloader selected, and the
/// state of that image.
///
/// After a boot that followed an update, a state of `PendingVerify` means the
/// bootloader supports rollback, and `New` means it does not.
pub fn log_boot() {
let result = flash::with(|flash| {
let running = running_slot(flash)?;
let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN];
let mut updater = OtaUpdater::new(flash, &mut buffer)?;
Ok::<_, Error>((
running,
updater.selected_partition(),
updater.current_ota_state(),
))
});
match result {
Ok((running, selected, state)) => log::info!(
"firmware {LABEL}: running from {running:?}; bootloader selected {selected:?}, \
image state {state:?}"
),
Err(error) => log::warn!(
"firmware {LABEL}: no A/B slots ({error}); flash with the current partitions.csv"
),
}
}
/// Marks the running image `Valid`, if it is one the bootloader is still
/// waiting to hear about.
pub fn confirm_running_image() {
let result: Result<Option<OtaImageState>, Error> = flash::with(|flash| {
let running = running_slot(flash)?;
let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN];
let mut updater = OtaUpdater::new(flash, &mut buffer)?;
// an image flashed over USB has no selection and nothing to confirm
let Ok(selected) = updater.selected_partition() else {
return Ok(None);
};
// only the slot the bootloader chose has a state that means anything
if running != Some(selected) {
return Ok(None);
}
let Ok(state @ (OtaImageState::New | OtaImageState::PendingVerify)) =
updater.current_ota_state()
else {
return Ok(None);
};
updater.set_current_ota_state(OtaImageState::Valid)?;
Ok(Some(state))
});
match result {
Ok(Some(state)) => log::info!("firmware {LABEL}: image confirmed (it was {state:?})"),
Ok(None) => {}
Err(error) => log::warn!("firmware {LABEL}: could not confirm the image: {error}"),
}
}
/// Selects the slot that is not running, marks it `New`, and restarts into it.
///
/// Returns only if the switch could not be made.
// only the development test uses this until there is a source of updates
#[cfg_attr(not(feature = "ota-test"), allow(dead_code))]
pub fn switch_slot() -> Result<Infallible, Error> {
flash::with(|flash| {
let target = match running_slot(flash)? {
Some(AppPartitionSubType::Ota0) => AppPartitionSubType::Ota1,
Some(AppPartitionSubType::Ota1) => AppPartitionSubType::Ota0,
_ => return Err(Error::Invalid),
};
let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN];
let mut updater = OtaUpdater::new(flash, &mut buffer)?;
updater.ota_data()?.set_current_app_partition(target)?;
updater.set_current_ota_state(OtaImageState::New)?;
log::warn!("firmware {LABEL}: switching to {target:?}");
Ok(())
})?;
software_reset()
}
/// Confirms the running image once it has stayed up long enough to be trusted.
#[embassy_executor::task]
pub async fn confirm_task() {
Timer::after(CONFIRM_AFTER).await;
confirm_running_image();
}
/// Switches slot over and over, to exercise A/B switching without an update
/// source. Development only.
#[cfg(all(feature = "ota-test", not(feature = "ota-test-crash")))]
#[embassy_executor::task]
pub async fn test_task() {
// after the image has been confirmed
Timer::after(CONFIRM_AFTER + Duration::from_secs(10)).await;
// `Infallible` is uninhabited, so only the error is possible
let Err(error) = switch_slot();
log::error!("firmware {LABEL}: could not switch slot: {error}");
}
/// Resets without ever confirming the image, to see whether the bootloader
/// rolls an unconfirmed image back. Development only.
#[cfg(feature = "ota-test-crash")]
#[embassy_executor::task]
pub async fn test_task() {
Timer::after(Duration::from_secs(5)).await;
log::warn!("firmware {LABEL}: ota-test-crash: resetting without confirming this image");
software_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;
}
}
+469 -53
View File
@@ -1,16 +1,18 @@
//! Zigbee end device: commissioning, the stack task, and the clusters served.
//!
//! The device is announced as an On/Off Light. Level Control and Color Control
//! (ZCL chapter 5) are deliberately absent: the vendored upstream does not
//! implement the lighting clusters yet, so for now brightness and hue are
//! local-only and the network sees on/off.
//! The device is a single Extended Color Light: all strip pixels share the
//! same on/off state, level, and color or color-temperature setting.
use core::ops::Range;
use embassy_embedded_hal::adapter::BlockingAsync;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::signal::Signal;
use embassy_time::Duration;
use embassy_time::Instant;
use embassy_time::Timer;
use esp_storage::FlashStorage;
use embassy_time::with_timeout;
use zigbee::aps::apsde::ApsdeSapConfirmStatus;
use zigbee::CurrentPowerMode;
use zigbee::CurrentPowerSourceLevel;
use zigbee::DeviceConfig;
@@ -28,31 +30,50 @@ use zigbee::zdo::descriptor::PowerDescriptorConfig;
use zigbee_cluster_library::clusters::general::basic;
use zigbee_cluster_library::clusters::general::basic::BasicServer;
use zigbee_cluster_library::clusters::general::identify;
use zigbee_cluster_library::clusters::general::identify::Effect;
use zigbee_cluster_library::clusters::general::identify::IdentifyServer;
use zigbee_cluster_library::clusters::general::on_off;
use zigbee_cluster_library::clusters::general::on_off::OnOffServer;
use zigbee_cluster_library::clusters::lighting::color_control;
use zigbee_cluster_library::clusters::lighting::color_control::ColorMode;
use zigbee_cluster_library::clusters::lighting::color_control::ColorControlServer;
use zigbee_cluster_library::clusters::lighting::level_control;
use zigbee_cluster_library::clusters::lighting::level_control::LevelControlServer;
use zigbee_cluster_library::profile;
use zigbee_cluster_library::reporting::AttributeReportBuilder;
use zigbee_cluster_library::reporting::AttributeReporting;
use zigbee_cluster_library::reporting::ReportingTable;
use zigbee_cluster_library::sender::ZclReportTarget;
use zigbee_cluster_library::sender::ZclSender;
use zigbee_cluster_library::server::UnsupportedClusterResponder;
use zigbee_cluster_library::types::codec::ZclKind;
use zigbee_cluster_library::types::descriptors::AccessTypestate;
use zigbee_cluster_library::types::descriptors::Attribute;
use zigbee_cluster_library::types::descriptors::Reportable;
use zigbee_cluster_library::types::integers::Uint8;
use zigbee_cluster_library::types::integers::Uint16;
use zigbee_mac::esp::EspMlme;
use zigbee_types::IeeeAddress;
use zigbee_types::ShortAddress;
use crate::effects_cluster;
use crate::effects_cluster::EffectsServer;
use crate::flash::SharedFlash;
use crate::light;
use crate::status;
/// Flash region reserved for Zigbee persistence.
///
/// MUST match the partition table: erase-sector aligned (4 KiB) and at least
/// two sectors so sequential-storage has a spare for garbage collection. The
/// address assumes the 4 MiB flash of the ESP32-C6-DevKitC-1.
pub const FLASH_RANGE: Range<u32> = 0x3f_0000..0x3f_4000;
/// MUST match the `storage` partition in partitions.csv: erase-sector aligned
/// (4 KiB) and at least two sectors so sequential-storage has a spare for
/// garbage collection.
pub const FLASH_RANGE: Range<u32> = 0x3e_0000..0x3e_4000;
/// Extended PAN ID of the network to join.
///
/// Placeholder: replace with the Extended PAN ID of your own coordinator.
const EXTENDED_PAN_ID: u64 = 0xabcd_ef01_2345_6789;
/// Extended PAN ID of the Home Assistant Zigbee network.
const EXTENDED_PAN_ID: u64 = 0xafca_95fc_e132_eeb6;
/// Channel to scan on; must match the coordinator.
const CHANNEL: u8 = 11;
const CHANNEL: u8 = 25;
/// Scan duration exponent (beacon order).
const SCAN_DURATION: u8 = 5;
@@ -60,24 +81,25 @@ const SCAN_DURATION: u8 = 5;
/// The application endpoint this light is served on.
const LIGHT_ENDPOINT: u8 = 1;
/// Mains powered and always listening: allocate address (bit 7) and
/// rx-on-when-idle (bit 3), so the coordinator can push commands at any time
/// rather than waiting for a poll.
const CAPABILITY: u8 = 0x8e;
/// Mains powered and always listening: allocate address (bit 7), power source
/// (bit 2), and rx-on-when-idle (bit 3); bit 1 stays clear for an end device.
const CAPABILITY: u8 = 0x8c;
static INPUT_CLUSTERS: [u16; 3] = [
static INPUT_CLUSTERS: [u16; 6] = [
basic::CLUSTER_ID,
identify::CLUSTER_ID,
on_off::CLUSTER_ID,
level_control::CLUSTER_ID,
color_control::CLUSTER_ID,
effects_cluster::CLUSTER_ID,
];
static OUTPUT_CLUSTERS: [u16; 0] = [];
static ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor {
endpoint: LIGHT_ENDPOINT,
profile_id: profile::HOME_AUTOMATION,
// HA device id 0x0100: On/Off Light. Becomes 0x0101 (Dimmable Light) once
// Level Control is implemented.
device_id: 0x0100,
// HA device id 0x010d: Extended Color Light.
device_id: 0x010d,
device_version: 1,
input_clusters: &INPUT_CLUSTERS,
output_clusters: &OUTPUT_CLUSTERS,
@@ -96,20 +118,35 @@ static BASIC: BasicServer = BasicServer {
pub static IDENTIFY: IdentifyServer = IdentifyServer::new();
static REPORTING: ReportingTable<4> = ReportingTable::new();
static REPORTING: ReportingTable<7> = ReportingTable::new();
static ON_OFF: OnOffServer = OnOffServer::new().with_reporting(&REPORTING);
static LEVEL_CONTROL: LevelControlServer<'static> =
LevelControlServer::new(128).with_reporting(&REPORTING);
static COLOR_CONTROL: ColorControlServer<'static> =
ColorControlServer::new(370).with_reporting(&REPORTING);
static EFFECTS: EffectsServer = EffectsServer;
type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>;
type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<SharedFlash>>;
/// Cluster servers in the order they are offered a request. The responder is
/// last so an unclaimed cluster draws UNSUPPORTED_CLUSTER rather than silence
/// (ZCL 2.5.12.2).
type Handler = (
BasicServer<'static>,
&'static IdentifyServer,
&'static OnOffServer<'static>,
UnsupportedClusterResponder<'static>,
(
&'static IdentifyServer,
(
&'static OnOffServer<'static>,
(
&'static LevelControlServer<'static>,
(
&'static ColorControlServer<'static>,
(&'static EffectsServer, UnsupportedClusterResponder<'static>),
),
),
),
),
);
pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>;
@@ -117,9 +154,22 @@ pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>;
pub fn handler() -> Handler {
(
BASIC,
&IDENTIFY,
&ON_OFF,
UnsupportedClusterResponder::new(&INPUT_CLUSTERS),
(
&IDENTIFY,
(
&ON_OFF,
(
&LEVEL_CONTROL,
(
&COLOR_CONTROL,
(
&EFFECTS,
UnsupportedClusterResponder::new(&INPUT_CLUSTERS),
),
),
),
),
),
)
}
@@ -141,7 +191,7 @@ pub fn config() -> StackConfig<'static> {
node: NodeDescriptorConfig {
// bit 3: 2400 MHz band
frequency_band: 0x08,
manufacturer_code: 0x1037,
manufacturer_code: effects_cluster::MANUFACTURER_CODE,
maximum_buffer_size: 80,
maximum_incoming_transfer_size: 128,
server_mask: 0,
@@ -164,36 +214,346 @@ pub fn config() -> StackConfig<'static> {
/// parent link, and persistence.
#[embassy_executor::task]
pub async fn stack_task(stack: &'static Stack) {
// returns only once no rejoin can get us back: the network is gone or our
// keys are stale, so drop it and re-commission from scratch
let outcome = stack.run(embassy_time::Delay).await;
log::warn!("off the network ({outcome:?}), forgetting it and rebooting");
stack.forget_network().await;
esp_hal::system::software_reset();
loop {
let outcome = stack.run(embassy_time::Delay).await;
log::warn!("off the network ({outcome:?}), retrying in 5 seconds");
Timer::after(Duration::from_secs(5)).await;
}
}
/// Mirrors the On/Off attribute onto the strip, both ways.
///
/// The cluster server writes its attribute from the APS receive path without
/// any notification hook, so this samples it. The reverse direction keeps the
/// attribute truthful after a local button press.
async fn report_attribute<T, A>(
stack: &'static Stack,
attribute: &Attribute<T, A, Reportable>,
value: T::Value<'_>,
sequence_number: &mut u8,
) -> bool
where
T: ZclKind,
A: AccessTypestate,
{
*sequence_number = sequence_number.wrapping_add(1);
let mut buffer = [0u8; 32];
let report = AttributeReportBuilder::new(&mut buffer, *sequence_number)
.and_then(|frame| frame.push(attribute, value))
.and_then(AttributeReportBuilder::finish);
let Ok(report) = report else {
log::warn!("failed to encode lighting attribute report");
return false;
};
match stack
.device()
.send_attribute_report(
ZclReportTarget {
dst_short: ShortAddress::COORDINATOR.0,
src_endpoint: LIGHT_ENDPOINT,
dst_endpoint: 1,
profile_id: profile::HOME_AUTOMATION,
},
report,
&mut embassy_time::Delay,
)
.await
{
Ok(confirm) if confirm.status == ApsdeSapConfirmStatus::Success => true,
Ok(confirm) => {
log::warn!("lighting attribute report failed: {:?}", confirm.status);
false
}
Err(error) => {
log::warn!("lighting attribute report encoding failed: {:?}", error);
false
}
}
}
/// Keeps the single strip synchronized with Zigbee On/Off, level and color.
#[embassy_executor::task]
pub async fn on_off_task() {
let mut last = ON_OFF.on_off();
pub async fn lighting_task(stack: &'static Stack) {
stack.wait_until_joined().await;
let mut last_on = ON_OFF.on_off();
let mut last_level = LEVEL_CONTROL.current_level();
let mut last_mireds = COLOR_CONTROL.color_temperature_mireds();
let mut last_color = COLOR_CONTROL.color();
let mut last_xy = COLOR_CONTROL.xy();
let mut pending_on = None;
let mut pending_level = None;
let mut pending_mireds = None;
let mut pending_hue = None;
let mut pending_saturation = None;
let mut pending_x = None;
let mut pending_y = None;
let mut sequence_number = 0u8;
let started_at = Instant::now();
loop {
Timer::after(Duration::from_millis(50)).await;
let remote = ON_OFF.on_off();
if remote != last {
last = remote;
light::set_on(remote);
continue;
if let Some(effect) = IDENTIFY.take_effect() {
log::info!("Zigbee Trigger Effect: {effect:?}");
match effect {
Effect::Blink => light::play_effect(light::Effect::Blink),
Effect::Breathe => light::play_effect(light::Effect::Breathe),
Effect::Okay => light::play_effect(light::Effect::Okay),
Effect::ChannelChange => light::play_effect(light::Effect::ChannelChange),
Effect::FinishEffect => light::finish_effect(),
Effect::StopEffect => light::stop_effect(),
}
}
let local = light::is_on();
if local != last {
last = local;
ON_OFF.set_on_off(local);
if let Some(on) = LEVEL_CONTROL.take_on_off_change() {
ON_OFF.set_on_off(on);
}
let remote_on = ON_OFF.on_off();
if remote_on != last_on {
last_on = remote_on;
if light::is_on() != remote_on {
log::info!("Zigbee On/Off state changed: {remote_on}");
light::set_on(remote_on);
}
pending_on = None;
}
let local_on = light::is_on();
if local_on != last_on {
last_on = local_on;
ON_OFF.set_on_off(local_on);
pending_on = Some(local_on);
}
let remote_level = LEVEL_CONTROL.current_level();
if remote_level != last_level {
last_level = remote_level;
if light::brightness() != remote_level {
light::set_brightness(remote_level);
}
pending_level = None;
}
let local_level = light::brightness();
if local_level != last_level {
last_level = local_level;
LEVEL_CONTROL.set_current_level(local_level);
pending_level = Some(local_level);
}
let remote_color = COLOR_CONTROL.color();
let color_changed = remote_color != last_color;
let remote_xy = COLOR_CONTROL.xy();
let xy_changed = remote_xy != last_xy;
if color_changed {
last_color = remote_color;
if remote_color.0 == ColorMode::HueSaturation {
light::set_hue_saturation(remote_color.1, remote_color.2);
pending_mireds = None;
pending_hue = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_HUE.id(),
)
.map(|_| remote_color.1);
pending_saturation = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_SATURATION.id(),
)
.map(|_| remote_color.2);
} else if remote_color.0 == ColorMode::Xy {
light::set_xy(remote_xy.0, remote_xy.1);
pending_mireds = None;
pending_hue = None;
pending_saturation = None;
pending_x = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_X.id(),
)
.map(|_| remote_xy.0);
pending_y = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_Y.id(),
)
.map(|_| remote_xy.1);
} else {
pending_hue = None;
pending_saturation = None;
}
}
if remote_color.0 == ColorMode::Xy && xy_changed {
last_xy = remote_xy;
pending_x = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_X.id(),
)
.map(|_| remote_xy.0);
pending_y = REPORTING
.configuration(
color_control::CLUSTER.id(),
color_control::CURRENT_Y.id(),
)
.map(|_| remote_xy.1);
if !color_changed {
light::set_xy(remote_xy.0, remote_xy.1);
}
}
let remote_mireds = COLOR_CONTROL.color_temperature_mireds();
if remote_color.0 == ColorMode::ColorTemperature
&& (remote_mireds != last_mireds || color_changed)
{
let actual_mireds = light::set_temperature_mireds(remote_mireds);
last_mireds = actual_mireds;
if actual_mireds != remote_mireds {
COLOR_CONTROL.set_color_temperature_mireds(actual_mireds);
pending_mireds = Some(actual_mireds);
} else {
pending_mireds = None;
}
}
let local_mireds = light::temperature_mireds();
if !light::is_color_mode()
&& (local_mireds != last_mireds || last_color.0 != ColorMode::ColorTemperature)
{
last_mireds = local_mireds;
COLOR_CONTROL.set_color_temperature_mireds(local_mireds);
last_color = COLOR_CONTROL.color();
pending_mireds = Some(local_mireds);
pending_hue = None;
pending_saturation = None;
pending_x = None;
pending_y = None;
}
let now_secs = started_at.elapsed().as_secs().min(u64::from(u32::MAX)) as u32;
if let Some(value) = pending_on {
let cluster = on_off::CLUSTER.id();
let attribute = on_off::ON_OFF.id();
let due = REPORTING.configuration(cluster, attribute).is_none()
|| REPORTING.should_report(cluster, attribute, now_secs, i64::from(value));
if due && report_attribute(stack, &on_off::ON_OFF, value, &mut sequence_number).await {
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_on = None;
log::info!("reported local Zigbee On/Off state: {value}");
}
}
if let Some(value) = pending_level {
let cluster = level_control::CLUSTER.id();
let attribute = level_control::CURRENT_LEVEL.id();
let due = REPORTING.configuration(cluster, attribute).is_none()
|| REPORTING.should_report(cluster, attribute, now_secs, i64::from(value));
if due
&& report_attribute(
stack,
&level_control::CURRENT_LEVEL,
Uint8(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_level = None;
log::info!("reported local Zigbee level: {value}");
}
}
if let Some(value) = pending_mireds {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::COLOR_TEMPERATURE_MIREDS.id();
let due = REPORTING.configuration(cluster, attribute).is_none()
|| REPORTING.should_report(cluster, attribute, now_secs, i64::from(value));
if due
&& report_attribute(
stack,
&color_control::COLOR_TEMPERATURE_MIREDS,
Uint16(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_mireds = None;
log::info!("reported local color temperature: {value} mireds");
}
}
if let Some(value) = pending_hue {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::CURRENT_HUE.id();
let due = REPORTING.configuration(cluster, attribute).is_none()
|| REPORTING.should_report(cluster, attribute, now_secs, i64::from(value));
if due
&& report_attribute(
stack,
&color_control::CURRENT_HUE,
Uint8(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_hue = None;
}
}
if let Some(value) = pending_saturation {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::CURRENT_SATURATION.id();
let due = REPORTING.configuration(cluster, attribute).is_none()
|| REPORTING.should_report(cluster, attribute, now_secs, i64::from(value));
if due
&& report_attribute(
stack,
&color_control::CURRENT_SATURATION,
Uint8(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_saturation = None;
}
}
if let Some(value) = pending_x {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::CURRENT_X.id();
let due = REPORTING.configuration(cluster, attribute).is_none()
|| REPORTING.should_report(cluster, attribute, now_secs, i64::from(value));
if due
&& report_attribute(
stack,
&color_control::CURRENT_X,
Uint16(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_x = None;
}
}
if let Some(value) = pending_y {
let cluster = color_control::CLUSTER.id();
let attribute = color_control::CURRENT_Y.id();
let due = REPORTING.configuration(cluster, attribute).is_none()
|| REPORTING.should_report(cluster, attribute, now_secs, i64::from(value));
if due
&& report_attribute(
stack,
&color_control::CURRENT_Y,
Uint16(value),
&mut sequence_number,
)
.await
{
REPORTING.reported(cluster, attribute, now_secs, i64::from(value));
pending_y = None;
}
}
}
}
@@ -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;
}
}
+275
View File
@@ -0,0 +1,275 @@
#!/usr/bin/env python3
"""Install a release into the idle firmware slot of a connected board, and
switch the board to it.
tools/install_release.py # the latest release
tools/install_release.py 0.1.23 # a particular one
tools/install_release.py --dry-run # only show what would be done
The release's application image is downloaded, checked against the release's
checksums, and written to the slot that is not running. The board's `otadata`
partition is then rewritten to select that slot, marked as a new image, and the
board is reset. The firmware logs the version it is running and which slot it
came from, and confirms the new image once it has stayed up for a while.
Needs `espflash` and a board with the A/B partition table, connected over USB.
Nothing is written to the board until the image has been downloaded and checked.
"""
import argparse
import hashlib
import json
import shutil
import struct
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
import zlib
from pathlib import Path
SERVER = "https://gitea.m5p3nc3r.co.uk"
REPO = "m5p3nc3r/smart_lights"
PARTITION_TABLE_OFFSET = 0x8000
PARTITION_TABLE_SIZE = 0xC00
# partition types and subtypes, as the bootloader numbers them
TYPE_APP, TYPE_DATA = 0x00, 0x01
SUBTYPE_OTA_FIRST, SUBTYPE_OTA_LAST = 0x10, 0x1F
SUBTYPE_OTA_DATA = 0x00
# otadata is two sectors, each holding one 32-byte selection record
SECTOR = 0x1000
UNINITIALISED = 0xFFFFFFFF
STATE_NEW = 0x0
STATE_NAMES = {
0x0: "New",
0x1: "PendingVerify",
0x2: "Valid",
0x3: "Invalid",
0x4: "Aborted",
UNINITIALISED: "Undefined",
}
APP_IMAGE_MAGIC = 0xE9
class Error(Exception):
"""Something the user needs to know about, without a traceback."""
def espflash(args, port):
command = ["espflash", *args]
if port:
command += ["--port", port]
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
raise Error(f"`{' '.join(command)}` failed:\n{result.stdout}{result.stderr}")
def read_flash(offset, size, port, directory):
path = directory / f"read-{offset:#x}.bin"
espflash(["read-flash", f"{offset:#x}", f"{size:#x}", str(path)], port)
return path.read_bytes()
def write_flash(offset, data, port, directory):
path = directory / f"write-{offset:#x}.bin"
path.write_bytes(data)
espflash(["write-bin", f"{offset:#x}", str(path)], port)
def parse_partition_table(data):
"""Maps each partition's label to (type, subtype, offset, size)."""
partitions = {}
for start in range(0, len(data) - 31, 32):
entry = data[start : start + 32]
if entry[:2] != b"\xaa\x50":
break # the end marker, or the table's checksum entry
kind, subtype, offset, size = struct.unpack_from("<BBII", entry, 2)
label = entry[12:28].split(b"\0")[0].decode(errors="replace")
partitions[label] = (kind, subtype, offset, size)
return partitions
def find_layout(partitions):
otadata = next(
(
p
for p in partitions.values()
if p[0] == TYPE_DATA and p[1] == SUBTYPE_OTA_DATA
),
None,
)
slots = sorted(
(
p
for p in partitions.values()
if p[0] == TYPE_APP and SUBTYPE_OTA_FIRST <= p[1] <= SUBTYPE_OTA_LAST
),
key=lambda p: p[1],
)
if otadata is None or len(slots) < 2:
raise Error(
"the board does not have the A/B partition table (an otadata partition "
"and two OTA app slots). Flash a release's full image first; see the README."
)
return otadata, slots
def checksum(sequence):
"""The checksum the bootloader keeps with a selection record: CRC-32 of the
sequence number alone, started from all ones."""
return zlib.crc32(struct.pack("<I", sequence), 0xFFFFFFFF)
def parse_record(sector):
"""The (sequence, state) of a selection record, or None if there is no valid
one in the sector."""
sequence, = struct.unpack_from("<I", sector, 0)
state, stored = struct.unpack_from("<II", sector, 24)
if sequence == UNINITIALISED or state not in STATE_NAMES:
return None
return (sequence, state) if stored == checksum(sequence) else None
def current_selection(otadata, slot_count):
"""Returns (slot, state, record index, sequence) for the slot the bootloader
will run, or None if nothing has been selected yet."""
records = [
parse_record(otadata[i * SECTOR : (i + 1) * SECTOR]) for i in range(2)
]
valid = [(record[0], i, record[1]) for i, record in enumerate(records) if record]
if not valid:
return None
sequence, index, state = max(valid)
return ((sequence - 1) % slot_count, state, index, sequence)
def new_record(sequence):
"""A selection record for a new image, padded to a whole sector."""
record = struct.pack("<I20sII", sequence, b"\xff" * 20, STATE_NEW, checksum(sequence))
return record + b"\xff" * (SECTOR - len(record))
def next_sequence(selection, target, slot_count):
"""The lowest sequence number above the current one that selects `target`.
The slot is the sequence number, minus one, modulo the number of slots."""
sequence = (selection[3] if selection else 0) + 1
while (sequence - 1) % slot_count != target:
sequence += 1
return sequence
def fetch(url):
try:
with urllib.request.urlopen(url, timeout=60) as response:
return response.read()
except urllib.error.URLError as error:
raise Error(f"could not fetch {url}: {error}") from error
def latest_version():
release = json.loads(fetch(f"{SERVER}/api/v1/repos/{REPO}/releases/latest"))
return release["tag_name"].lstrip("v")
def download_image(version, slot_size):
base = f"{SERVER}/{REPO}/releases/download/v{version}"
name = f"smart-light-{version}.bin"
image = fetch(f"{base}/{name}")
sums = fetch(f"{base}/SHA256SUMS").decode()
expected = {}
for line in sums.splitlines():
if line.strip():
digest, filename = line.split(None, 1)
expected[filename.strip().lstrip("*")] = digest
if name not in expected:
raise Error(f"{name} is not in the release's SHA256SUMS")
if hashlib.sha256(image).hexdigest() != expected[name]:
raise Error(f"{name} does not match the release's checksum")
if image[0] != APP_IMAGE_MAGIC:
raise Error(f"{name} is not an application image")
if len(image) > slot_size:
raise Error(f"{name} is {len(image)} bytes and the slot holds {slot_size}")
return image
def describe(selection):
if selection is None:
return "nothing selected yet (the bootloader runs the first slot)"
slot, state, _, sequence = selection
return f"slot {slot} (sequence {sequence}), image state {STATE_NAMES[state]}"
def main():
parser = argparse.ArgumentParser(
description="Install a release into the idle firmware slot and switch to it."
)
parser.add_argument(
"version", nargs="?", default="latest", help="e.g. 0.1.23 (default: the latest)"
)
parser.add_argument("--port", help="serial port of the board, if there are several")
parser.add_argument(
"--slot", type=int, help="write to this slot instead of the idle one"
)
parser.add_argument(
"--dry-run", action="store_true", help="show what would be done; write nothing"
)
parser.add_argument(
"--no-reset", action="store_true", help="do not reset the board afterwards"
)
args = parser.parse_args()
if shutil.which("espflash") is None:
raise Error("espflash is not installed (cargo install espflash)")
with tempfile.TemporaryDirectory() as temporary:
directory = Path(temporary)
print("Reading the board's partition table and slot selection...")
table = read_flash(PARTITION_TABLE_OFFSET, PARTITION_TABLE_SIZE, args.port, directory)
otadata_partition, slots = find_layout(parse_partition_table(table))
otadata_offset = otadata_partition[2]
otadata = read_flash(otadata_offset, 2 * SECTOR, args.port, directory)
selection = current_selection(otadata, len(slots))
running = selection[0] if selection else 0
target = args.slot if args.slot is not None else 1 - running
if not 0 <= target < len(slots):
raise Error(f"there is no slot {target}")
print(f" the board will run {describe(selection)}")
print(f" the image goes into slot {target} at {slots[target][2]:#x}")
version = latest_version() if args.version == "latest" else args.version.lstrip("v")
print(f"Downloading release {version}...")
image = download_image(version, slots[target][3])
print(f" {len(image)} bytes, checksum verified")
if args.dry_run:
print("Dry run: nothing written.")
return
print(f"Writing slot {target}...")
write_flash(slots[target][2], image, args.port, directory)
sequence = next_sequence(selection, target, len(slots))
sector = 0 if selection is None else 1 - selection[2]
print(f"Selecting slot {target} (sequence {sequence}, record {sector})...")
write_flash(otadata_offset + sector * SECTOR, new_record(sequence), args.port, directory)
if args.no_reset:
print("Done. Reset the board to run it.")
else:
espflash(["reset"], args.port)
print(f"Done. The board is restarting into {version}.")
if __name__ == "__main__":
try:
main()
except Error as error:
sys.exit(f"error: {error}")