Compare commits
5
Commits
115f245484
...
v0.1.19
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf031b55b7 | ||
|
|
c92adaed01 | ||
|
|
2f5f457ffc | ||
|
|
575cd8896f | ||
|
|
90af6197c6 |
No files matched your search
@@ -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
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
name = "smart-light"
|
name = "smart-light"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
license = "MIT"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["esp32c6", "zigbee"]
|
default = ["esp32c6", "zigbee"]
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
# smart_light
|
||||||
|
|
||||||
|
Firmware for a Zigbee-controlled LED strip light, written in Rust for the
|
||||||
|
ESP32-C6. It joins a Zigbee network as an Extended Color Light, so it shows up
|
||||||
|
in Home Assistant (ZHA) as a normal light with on/off, brightness, colour
|
||||||
|
temperature and colour. It can also be controlled locally with a rotary
|
||||||
|
encoder, and can play animated effects.
|
||||||
|
|
||||||
|
## Hardware
|
||||||
|
|
||||||
|
- Seeed Studio XIAO ESP32-C6
|
||||||
|
- WS2812B LED strip (24 LEDs by default), data on D2 (GPIO2)
|
||||||
|
- Rotary encoder with push button: CLK on D10, DT on D9, SW on D8
|
||||||
|
(GPIO18, GPIO20, GPIO19)
|
||||||
|
|
||||||
|
The on-board user LED (GPIO15) blinks as a heartbeat.
|
||||||
|
|
||||||
|
## Controls
|
||||||
|
|
||||||
|
| Input | Action |
|
||||||
|
|---|---|
|
||||||
|
| Turn the encoder | Brightness up or down |
|
||||||
|
| Click | Next colour temperature preset |
|
||||||
|
| Long press | Turn on or off |
|
||||||
|
| Hold for 10 seconds | Forget the Zigbee network and go back to pairing mode |
|
||||||
|
|
||||||
|
From Home Assistant you get on/off, brightness, colour temperature and colour.
|
||||||
|
Blink and breathe effects are available through the light's `flash` option, and
|
||||||
|
the animated scenes (rainbow, pulse, comet) are described under
|
||||||
|
[Effects](#effects).
|
||||||
|
|
||||||
|
## Building from source
|
||||||
|
|
||||||
|
You need [rustup](https://rustup.rs). The repository pins a nightly toolchain
|
||||||
|
in `rust-toolchain.toml`, so the right compiler, components and the
|
||||||
|
`riscv32imac-unknown-none-elf` target are installed on the first build.
|
||||||
|
|
||||||
|
The Zigbee stack is a git submodule (`vendor/zigbee-rs`), so clone with
|
||||||
|
submodules:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone --recurse-submodules https://gitea.m5p3nc3r.co.uk/m5p3nc3r/smart_lights.git
|
||||||
|
cd smart_lights
|
||||||
|
```
|
||||||
|
|
||||||
|
If you already cloned without them, run `git submodule update --init`. The
|
||||||
|
submodule URL is an SSH address on GitHub; if you have no SSH key set up, switch
|
||||||
|
it to HTTPS first with
|
||||||
|
`git config submodule.vendor/zigbee-rs.url https://github.com/m5p3nc3r/zigbee-rs.git`.
|
||||||
|
|
||||||
|
Build:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build --release
|
||||||
|
```
|
||||||
|
|
||||||
|
To flash a board connected over USB and open the serial log, install
|
||||||
|
[espflash](https://github.com/esp-rs/espflash) and run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo install espflash
|
||||||
|
cargo run --release
|
||||||
|
```
|
||||||
|
|
||||||
|
`cargo run` uses the runner in `.cargo/config.toml`, which flashes the app with
|
||||||
|
the partition table in `partitions.csv` and then starts the monitor. The Zigbee
|
||||||
|
network state is kept in the `storage` partition, so reflashing keeps the
|
||||||
|
light on its network.
|
||||||
|
|
||||||
|
To build without Zigbee, for example to test the strip and encoder on their own:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build --release --no-default-features --features esp32c6
|
||||||
|
```
|
||||||
|
|
||||||
|
The `led_diag`, `pin_diag` and `gpio_out_diag` binaries in `src/bin` are small
|
||||||
|
hardware checks, run with `cargo run --release --bin led_diag`.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
- `src/config.rs`: number of LEDs, maximum brightness, encoder timing.
|
||||||
|
- `src/zigbee_stack.rs`: the Zigbee network to join. The extended PAN ID and
|
||||||
|
channel (25) are set in the code and must match your coordinator.
|
||||||
|
|
||||||
|
## Joining the network
|
||||||
|
|
||||||
|
A light that is not on a network is always in pairing mode: it scans every few
|
||||||
|
seconds, and the on-board LED blinks quickly while it does. To join, open a
|
||||||
|
pairing window on your coordinator (in ZHA, **Add device**) and the light joins
|
||||||
|
as soon as it sees it. After that it rejoins by itself when it restarts.
|
||||||
|
|
||||||
|
To pair a light that is already on a network, for example to re-pair it or move
|
||||||
|
it to another coordinator, hold the encoder button for 10 seconds. The strip
|
||||||
|
flashes green twice, the light forgets its network and restarts, and it is then
|
||||||
|
in pairing mode as above. The coordinator is not told, so Home Assistant keeps
|
||||||
|
the device and recognises it when it joins again.
|
||||||
|
|
||||||
|
The same applies if it has lost its network keys, for example after a long
|
||||||
|
coordinator outage: open the pairing window and it will join again.
|
||||||
|
|
||||||
|
The network it looks for is fixed in the firmware (see Configuration), so a
|
||||||
|
light only pairs with a coordinator whose extended PAN ID and channel match.
|
||||||
|
The extended PAN ID is broadcast by the network and is not a secret.
|
||||||
|
|
||||||
|
## Effects
|
||||||
|
|
||||||
|
Beyond the standard controls, the light has a manufacturer-specific effects
|
||||||
|
cluster (`0xFD00`) that selects an animated scene (rainbow, pulse or comet) and
|
||||||
|
sets its speed and intensity. Home Assistant needs a quirk to talk to it:
|
||||||
|
|
||||||
|
1. Copy `ha/zha_quirks/smart_light.py` into a folder in your Home Assistant
|
||||||
|
config, for example `custom_zha_quirks/`.
|
||||||
|
2. Point ZHA at it in `configuration.yaml`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
zha:
|
||||||
|
custom_quirks_path: /config/custom_zha_quirks/
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Restart Home Assistant. The light then has an Effect select and Effect speed
|
||||||
|
and Effect intensity sliders.
|
||||||
|
|
||||||
|
## Releases
|
||||||
|
|
||||||
|
Every commit to `main` builds the firmware on the Gitea runner and publishes a
|
||||||
|
release (`.gitea/workflows/release.yml`).
|
||||||
|
|
||||||
|
The version is the `MAJOR.MINOR` of the version in `Cargo.toml` followed by the
|
||||||
|
number of commits on `main`, so with `0.1.0` in `Cargo.toml` the 57th commit
|
||||||
|
becomes `0.1.57`. It only goes up, and can be worked out again from any commit.
|
||||||
|
To start a new series, change the major or minor number in `Cargo.toml`. The
|
||||||
|
build writes the version into the firmware, which logs it at boot, and the
|
||||||
|
release is tagged `v` plus the version.
|
||||||
|
|
||||||
|
Each release has:
|
||||||
|
|
||||||
|
- `smart-light-<version>-full.bin`: bootloader, partition table and
|
||||||
|
application. Write it at address 0 with
|
||||||
|
`espflash write-bin 0x0 smart-light-<version>-full.bin`. It stops short of
|
||||||
|
the `storage` partition, so the light keeps its Zigbee network.
|
||||||
|
- `smart-light-<version>.bin`: the application alone, for a firmware slot.
|
||||||
|
- `smart-light-<version>.elf.gz`: the unstripped build, for decoding backtraces.
|
||||||
|
- `SHA256SUMS`.
|
||||||
|
|
||||||
|
The workflow's `runs-on` must match a label of your Gitea runner. If the job's
|
||||||
|
own token is not allowed to create releases, add a token with write access to
|
||||||
|
the repository as a secret named `RELEASE_TOKEN`.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Released under the [MIT License](LICENSE). The Zigbee stack in
|
||||||
|
`vendor/zigbee-rs` is a separate project with its own licenses.
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# TODO
|
||||||
|
|
||||||
|
Things that are known to be open. None of these is being worked on yet.
|
||||||
|
|
||||||
|
## Reliability
|
||||||
|
|
||||||
|
- [ ] **The Zigbee stack forgets its network after a short coordinator outage.**
|
||||||
|
A failed rejoin is followed by a second attempt that, if it also fails,
|
||||||
|
wipes the network keys and falls back to a fresh join, which needs the
|
||||||
|
coordinator's pairing window to be open. This took the light off the network
|
||||||
|
when the server rebooted (18 Nov) and, most likely, again when Home Assistant
|
||||||
|
restarted (24 Nov; inferred, the failure itself was not captured). Each time
|
||||||
|
it needed re-pairing.
|
||||||
|
- Where: `commission` and `link_maintenance` in
|
||||||
|
`vendor/zigbee-rs/zigbee/src/stack.rs`, and the retry loop in
|
||||||
|
`stack_task` (`src/zigbee_stack.rs`).
|
||||||
|
- Idea: keep the saved network and keep retrying the rejoin with a back-off,
|
||||||
|
and only forget it after a long failure (say 30 minutes), an explicit
|
||||||
|
leave, or a network mismatch.
|
||||||
|
- It is a library change, so it belongs on its own branch off upstream
|
||||||
|
`main`, separate from the effects work.
|
||||||
|
- The 10-second button hold makes recovery easy, but does not prevent it.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
- [ ] **The Zigbee network ID and channel are hardcoded** in
|
||||||
|
`src/zigbee_stack.rs` (`EXTENDED_PAN_ID`, `CHANNEL`). The ID is broadcast by
|
||||||
|
the network and is not a secret, but it means a light only pairs with one
|
||||||
|
network.
|
||||||
|
- Why it is pinned: the stack takes both from its configuration. Resuming
|
||||||
|
after a reboot tunes to the first configured channel rather than the
|
||||||
|
channel that was joined, and rejoin looks for the configured network ID.
|
||||||
|
A wildcard ID or a range of channels would therefore break resume.
|
||||||
|
- Options: change the library to use the channel and ID it remembers, or have
|
||||||
|
the app save the network it joined in its own flash and build the
|
||||||
|
configuration from that.
|
||||||
|
- [ ] **Light and effect state is not saved across reboots.** On/off, level,
|
||||||
|
colour and the selected effect all start from their defaults.
|
||||||
|
- [ ] **The effects cluster uses development identifiers.** Manufacturer code
|
||||||
|
`0xC0DE` is not assigned to anyone, and the cluster ID is `0xFD00`. Decide on
|
||||||
|
proper values and change them together in `src/effects_cluster.rs` and
|
||||||
|
`ha/zha_quirks/smart_light.py`.
|
||||||
|
- [ ] **The effect attributes are not reportable**, so Home Assistant only
|
||||||
|
knows what it last wrote. Fine while nothing else changes them; revisit if
|
||||||
|
effects can be changed locally.
|
||||||
|
|
||||||
|
## Upstream zigbee-rs
|
||||||
|
|
||||||
|
- [ ] **Open PRs for the two branches already pushed to the fork**, each as its
|
||||||
|
own PR off upstream `main`:
|
||||||
|
- `feature/identify-trigger-effect`
|
||||||
|
- `feature/manufacturer-specific-clusters`
|
||||||
|
- [ ] **PR #109 (RGB colour control)** is open and has had review comments
|
||||||
|
applied. Squash-merge when approved.
|
||||||
|
- [ ] **Spec questions to raise in review.** Neither PR can say what ZCL
|
||||||
|
requires, so both pick an answer and flag it:
|
||||||
|
- Trigger Effect with an undefined effect or variant answers `INVALID_FIELD`.
|
||||||
|
- A frame for a manufacturer-specific cluster with the wrong manufacturer
|
||||||
|
code answers `UNSUP_COMMAND`.
|
||||||
|
- [ ] **After the PRs merge**, point the submodule at upstream (or the fork's
|
||||||
|
`main`) instead of `feature/lighting-effects-integration`, and delete the
|
||||||
|
integration branch.
|
||||||
|
|
||||||
|
## Testing gaps
|
||||||
|
|
||||||
|
Not yet tried on the hardware (the commit messages say so too):
|
||||||
|
|
||||||
|
- [ ] Trigger Effect: Okay, Channel change, Finish effect and Stop effect sent
|
||||||
|
from a coordinator. Only blink and breathe (ZHA's `flash`) were tried.
|
||||||
|
- [ ] Manufacturer-specific attribute reports.
|
||||||
|
- [ ] Rejection of a frame that carries the wrong manufacturer code.
|
||||||
|
|
||||||
|
## Housekeeping
|
||||||
|
|
||||||
|
- [ ] **`.gitmodules` uses an SSH URL** for the submodule
|
||||||
|
(`git@github.com:m5p3nc3r/zigbee-rs.git`). Switch to HTTPS if cloning from a
|
||||||
|
network that blocks SSH.
|
||||||
|
- [ ] **Older commits point at submodule commits that no longer exist on any
|
||||||
|
branch**, because the integration branch was rebased. The tip works, but
|
||||||
|
checking out an old commit and updating the submodule can fail.
|
||||||
|
- [ ] **Pre-existing `rustfmt` differences**: 1 in `src/light.rs` and 7 in
|
||||||
|
`src/zigbee_stack.rs`. Cosmetic; fix in a commit of their own.
|
||||||
|
- [ ] **No licence file.** Decide on one.
|
||||||
@@ -18,9 +18,18 @@ pub const STEPS_PER_BRIGHTNESS_UNIT: i32 = 1;
|
|||||||
/// Hold time that separates a click from a long press.
|
/// Hold time that separates a click from a long press.
|
||||||
pub const LONG_PRESS_MS: u64 = 600;
|
pub const LONG_PRESS_MS: u64 = 600;
|
||||||
|
|
||||||
|
/// Hold time that makes the light forget its Zigbee network and go back to
|
||||||
|
/// pairing mode.
|
||||||
|
pub const RESET_HOLD_MS: u64 = 10_000;
|
||||||
|
|
||||||
/// Contact settle time for the encoder push button.
|
/// Contact settle time for the encoder push button.
|
||||||
pub const DEBOUNCE_MS: u64 = 15;
|
pub const DEBOUNCE_MS: u64 = 15;
|
||||||
|
|
||||||
/// Heartbeat blink: a brief pulse, repeated once a second.
|
/// Heartbeat blink: a brief pulse, repeated once a second.
|
||||||
pub const HEARTBEAT_ON_MS: u64 = 50;
|
pub const HEARTBEAT_ON_MS: u64 = 50;
|
||||||
pub const HEARTBEAT_PERIOD_MS: u64 = 1000;
|
pub const HEARTBEAT_PERIOD_MS: u64 = 1000;
|
||||||
|
|
||||||
|
/// The faster blink that shows the light is looking for a Zigbee network to
|
||||||
|
/// join, so a pairing window can be seen to be waiting for it.
|
||||||
|
pub const SEARCHING_ON_MS: u64 = 100;
|
||||||
|
pub const SEARCHING_PERIOD_MS: u64 = 300;
|
||||||
+16
-2
@@ -15,6 +15,7 @@ use esp_hal::gpio::Input;
|
|||||||
|
|
||||||
use crate::config::DEBOUNCE_MS;
|
use crate::config::DEBOUNCE_MS;
|
||||||
use crate::config::LONG_PRESS_MS;
|
use crate::config::LONG_PRESS_MS;
|
||||||
|
use crate::config::RESET_HOLD_MS;
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
pub enum EncoderEvent {
|
pub enum EncoderEvent {
|
||||||
@@ -22,6 +23,8 @@ pub enum EncoderEvent {
|
|||||||
Rotate(i8),
|
Rotate(i8),
|
||||||
Click,
|
Click,
|
||||||
LongPress,
|
LongPress,
|
||||||
|
/// The button was held long enough to forget the Zigbee network.
|
||||||
|
NetworkReset,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Depth 8 absorbs a fast spin while the consumer is mid-frame; overflowing
|
/// Depth 8 absorbs a fast spin while the consumer is mid-frame; overflowing
|
||||||
@@ -63,8 +66,19 @@ pub async fn button_task(mut button: Input<'static>) {
|
|||||||
|
|
||||||
if long_press {
|
if long_press {
|
||||||
let _ = EVENTS.try_send(EncoderEvent::LongPress);
|
let _ = EVENTS.try_send(EncoderEvent::LongPress);
|
||||||
// swallow the release so it is not read as a second press
|
// still held past the reset time: ask for a network reset while
|
||||||
button.wait_for_rising_edge().await;
|
// 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 {
|
} else {
|
||||||
let _ = EVENTS.try_send(EncoderEvent::Click);
|
let _ = EVENTS.try_send(EncoderEvent::Click);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ const BRIGHTNESS_STEP: i16 = 8;
|
|||||||
#[esp_rtos::main]
|
#[esp_rtos::main]
|
||||||
async fn main(spawner: embassy_executor::Spawner) -> ! {
|
async fn main(spawner: embassy_executor::Spawner) -> ! {
|
||||||
esp_println::logger::init_logger_from_env();
|
esp_println::logger::init_logger_from_env();
|
||||||
|
log::info!("smart-light {}", env!("CARGO_PKG_VERSION"));
|
||||||
let peripherals = esp_hal::init(esp_hal::Config::default());
|
let peripherals = esp_hal::init(esp_hal::Config::default());
|
||||||
|
|
||||||
let timg0 = TimerGroup::new(peripherals.TIMG0);
|
let timg0 = TimerGroup::new(peripherals.TIMG0);
|
||||||
@@ -107,6 +108,8 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
|
|||||||
spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task"));
|
spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task"));
|
||||||
spawner.spawn(zigbee_stack::lighting_task(stack).expect("spawn lighting_task"));
|
spawner.spawn(zigbee_stack::lighting_task(stack).expect("spawn lighting_task"));
|
||||||
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
|
spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task"));
|
||||||
|
spawner.spawn(zigbee_stack::network_reset_task(stack).expect("spawn network_reset_task"));
|
||||||
|
spawner.spawn(zigbee_stack::pairing_status_task(stack).expect("spawn pairing_status_task"));
|
||||||
}
|
}
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
@@ -124,6 +127,11 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
|
|||||||
let on = light::toggle();
|
let on = light::toggle();
|
||||||
log::info!("light {}", if on { "on" } else { "off" });
|
log::info!("light {}", if on { "on" } else { "off" });
|
||||||
}
|
}
|
||||||
|
EncoderEvent::NetworkReset => {
|
||||||
|
log::warn!("button held: resetting the Zigbee network");
|
||||||
|
#[cfg(feature = "zigbee")]
|
||||||
|
zigbee_stack::request_network_reset();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+26
-5
@@ -1,7 +1,12 @@
|
|||||||
//! Heartbeat on the XIAO's on-board user LED.
|
//! Status blinks on the XIAO's on-board user LED.
|
||||||
//!
|
//!
|
||||||
//! A short pulse once a second: if it stops, the executor has stalled or a
|
//! A short pulse once a second means the firmware is running: if it stops, the
|
||||||
//! task has panicked, which is otherwise invisible without a serial console.
|
//! executor has stalled or a task has panicked, which is otherwise invisible
|
||||||
|
//! without a serial console. While the light is looking for a Zigbee network to
|
||||||
|
//! join the pulse is faster, so a pairing window can be seen to be waiting.
|
||||||
|
|
||||||
|
use core::sync::atomic::AtomicBool;
|
||||||
|
use core::sync::atomic::Ordering;
|
||||||
|
|
||||||
use embassy_time::Duration;
|
use embassy_time::Duration;
|
||||||
use embassy_time::Timer;
|
use embassy_time::Timer;
|
||||||
@@ -9,14 +14,30 @@ use esp_hal::gpio::Output;
|
|||||||
|
|
||||||
use crate::config::HEARTBEAT_ON_MS;
|
use crate::config::HEARTBEAT_ON_MS;
|
||||||
use crate::config::HEARTBEAT_PERIOD_MS;
|
use crate::config::HEARTBEAT_PERIOD_MS;
|
||||||
|
use crate::config::SEARCHING_ON_MS;
|
||||||
|
use crate::config::SEARCHING_PERIOD_MS;
|
||||||
|
|
||||||
|
/// Set while the light is not on a Zigbee network and is looking for one.
|
||||||
|
static SEARCHING: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
|
||||||
|
pub fn set_searching(searching: bool) {
|
||||||
|
SEARCHING.store(searching, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
pub async fn heartbeat_task(mut led: Output<'static>) {
|
pub async fn heartbeat_task(mut led: Output<'static>) {
|
||||||
loop {
|
loop {
|
||||||
|
let (on_ms, period_ms) = if SEARCHING.load(Ordering::Relaxed) {
|
||||||
|
(SEARCHING_ON_MS, SEARCHING_PERIOD_MS)
|
||||||
|
} else {
|
||||||
|
(HEARTBEAT_ON_MS, HEARTBEAT_PERIOD_MS)
|
||||||
|
};
|
||||||
|
|
||||||
// the LED's anode sits on 3V3, so a low level lights it
|
// the LED's anode sits on 3V3, so a low level lights it
|
||||||
led.set_low();
|
led.set_low();
|
||||||
Timer::after(Duration::from_millis(HEARTBEAT_ON_MS)).await;
|
Timer::after(Duration::from_millis(on_ms)).await;
|
||||||
led.set_high();
|
led.set_high();
|
||||||
Timer::after(Duration::from_millis(HEARTBEAT_PERIOD_MS - HEARTBEAT_ON_MS)).await;
|
Timer::after(Duration::from_millis(period_ms - on_ms)).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,9 +6,12 @@
|
|||||||
use core::ops::Range;
|
use core::ops::Range;
|
||||||
|
|
||||||
use embassy_embedded_hal::adapter::BlockingAsync;
|
use embassy_embedded_hal::adapter::BlockingAsync;
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::signal::Signal;
|
||||||
use embassy_time::Duration;
|
use embassy_time::Duration;
|
||||||
use embassy_time::Instant;
|
use embassy_time::Instant;
|
||||||
use embassy_time::Timer;
|
use embassy_time::Timer;
|
||||||
|
use embassy_time::with_timeout;
|
||||||
use esp_storage::FlashStorage;
|
use esp_storage::FlashStorage;
|
||||||
use zigbee::aps::apsde::ApsdeSapConfirmStatus;
|
use zigbee::aps::apsde::ApsdeSapConfirmStatus;
|
||||||
use zigbee::CurrentPowerMode;
|
use zigbee::CurrentPowerMode;
|
||||||
@@ -57,6 +60,7 @@ use zigbee_types::ShortAddress;
|
|||||||
use crate::effects_cluster;
|
use crate::effects_cluster;
|
||||||
use crate::effects_cluster::EffectsServer;
|
use crate::effects_cluster::EffectsServer;
|
||||||
use crate::light;
|
use crate::light;
|
||||||
|
use crate::status;
|
||||||
|
|
||||||
/// Flash region reserved for Zigbee persistence.
|
/// Flash region reserved for Zigbee persistence.
|
||||||
///
|
///
|
||||||
@@ -565,3 +569,59 @@ pub async fn identify_task() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static NETWORK_RESET: Signal<CriticalSectionRawMutex, ()> = Signal::new();
|
||||||
|
|
||||||
|
/// Asks for the Zigbee network to be forgotten, which [`network_reset_task`]
|
||||||
|
/// then does.
|
||||||
|
pub fn request_network_reset() {
|
||||||
|
NETWORK_RESET.signal(());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the light back into pairing mode on request.
|
||||||
|
///
|
||||||
|
/// A light that has a network only ever rejoins that one, so this is how it is
|
||||||
|
/// moved to another or re-paired from scratch: it forgets the network, then
|
||||||
|
/// restarts and goes looking for one with an open pairing window (in ZHA,
|
||||||
|
/// **Add device**).
|
||||||
|
///
|
||||||
|
/// The coordinator is not told. Home Assistant keeps the device, and recognises
|
||||||
|
/// it by its IEEE address when it joins again.
|
||||||
|
#[embassy_executor::task]
|
||||||
|
pub async fn network_reset_task(stack: &'static Stack) {
|
||||||
|
NETWORK_RESET.wait().await;
|
||||||
|
log::warn!("network reset: forgetting the Zigbee network");
|
||||||
|
|
||||||
|
// two green flashes, so the reset can be seen before the light restarts
|
||||||
|
light::play_effect(light::Effect::Okay);
|
||||||
|
Timer::after(Duration::from_millis(1500)).await;
|
||||||
|
|
||||||
|
// forgets the network and writes that to flash, so the next boot starts
|
||||||
|
// commissioning from scratch rather than resuming
|
||||||
|
stack.forget_network().await;
|
||||||
|
log::warn!("network reset: network forgotten and saved, restarting");
|
||||||
|
esp_hal::system::software_reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows on the status LED whether the light is looking for a network.
|
||||||
|
#[embassy_executor::task]
|
||||||
|
pub async fn pairing_status_task(stack: &'static Stack) {
|
||||||
|
let mut was_joined = None;
|
||||||
|
loop {
|
||||||
|
// the join gate stays open once joined, so this returns at once when
|
||||||
|
// the light is on a network and times out when it is not
|
||||||
|
let joined = with_timeout(Duration::from_millis(1), stack.wait_until_joined())
|
||||||
|
.await
|
||||||
|
.is_ok();
|
||||||
|
status::set_searching(!joined);
|
||||||
|
if was_joined != Some(joined) {
|
||||||
|
if joined {
|
||||||
|
log::info!("on a Zigbee network");
|
||||||
|
} else {
|
||||||
|
log::info!("not on a Zigbee network: looking for one to join");
|
||||||
|
}
|
||||||
|
was_joined = Some(joined);
|
||||||
|
}
|
||||||
|
Timer::after(Duration::from_millis(250)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user