Compare commits
6
Commits
115f245484
...
ab_update
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e7d0d7d1f | ||
|
|
c92adaed01 | ||
|
|
9ea25c3aab | ||
|
|
2f5f457ffc | ||
|
|
575cd8896f | ||
|
|
90af6197c6 |
No files matched your search
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
target = "riscv32imac-unknown-none-elf"
|
target = "riscv32imac-unknown-none-elf"
|
||||||
|
|
||||||
[target.riscv32imac-unknown-none-elf]
|
[target.riscv32imac-unknown-none-elf]
|
||||||
runner = "espflash flash --monitor --partition-table partitions.csv"
|
runner = "espflash flash --monitor --partition-table partitions.csv --erase-parts otadata"
|
||||||
rustflags = [
|
rustflags = [
|
||||||
"-C", "link-arg=-Tlinkall.x",
|
"-C", "link-arg=-Tlinkall.x",
|
||||||
"-C", "force-frame-pointers",
|
"-C", "force-frame-pointers",
|
||||||
|
|||||||
Generated
+1
@@ -1846,6 +1846,7 @@ dependencies = [
|
|||||||
"embassy-futures",
|
"embassy-futures",
|
||||||
"embassy-sync 0.8.0",
|
"embassy-sync 0.8.0",
|
||||||
"embassy-time",
|
"embassy-time",
|
||||||
|
"embedded-storage",
|
||||||
"esp-alloc",
|
"esp-alloc",
|
||||||
"esp-backtrace",
|
"esp-backtrace",
|
||||||
"esp-bootloader-esp-idf",
|
"esp-bootloader-esp-idf",
|
||||||
|
|||||||
@@ -2,9 +2,16 @@
|
|||||||
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"]
|
||||||
|
## 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:
|
## 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.
|
## 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"]
|
zigbee = ["dep:esp-radio", "dep:zigbee", "dep:zigbee-cluster-library", "dep:zigbee-mac", "dep:zigbee-types"]
|
||||||
@@ -29,6 +36,7 @@ esp-println = { version = "0.18", features = ["log-04"] }
|
|||||||
esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"], optional = true }
|
esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"], optional = true }
|
||||||
esp-rtos = { version = "0.4", features = ["embassy", "log-04"] }
|
esp-rtos = { version = "0.4", features = ["embassy", "log-04"] }
|
||||||
esp-storage = { version = "0.10", features = ["embedded-storage"] }
|
esp-storage = { version = "0.10", features = ["embedded-storage"] }
|
||||||
|
embedded-storage = "0.3"
|
||||||
|
|
||||||
embassy-executor = "0.10.0"
|
embassy-executor = "0.10.0"
|
||||||
embassy-futures = "0.1"
|
embassy-futures = "0.1"
|
||||||
|
|||||||
@@ -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,149 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
## 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,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.
|
||||||
+8
-3
@@ -1,7 +1,12 @@
|
|||||||
# Name, Type, SubType, Offset, Size, Flags
|
# Name, Type, SubType, Offset, Size, Flags
|
||||||
nvs, data, nvs, 0x9000, 0x6000,
|
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,
|
phy_init, data, phy, 0xf000, 0x1000,
|
||||||
factory, app, factory, 0x10000, 0x3D0000,
|
# 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
|
# Zigbee persistence: the stack writes this region directly, so it must not
|
||||||
# overlap the app partition. Keep in sync with FLASH_RANGE in zigbee_stack.rs.
|
# overlap the app partitions. Keep in sync with FLASH_RANGE in zigbee_stack.rs.
|
||||||
storage, data, nvs, 0x3E0000, 0x20000,
|
storage, data, nvs, 0x3E0000, 0x20000,
|
||||||
|
@@ -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;
|
||||||
@@ -15,6 +15,7 @@ use esp_hal::gpio::Input;
|
|||||||
|
|
||||||
use crate::config::DEBOUNCE_MS;
|
use crate::config::DEBOUNCE_MS;
|
||||||
use crate::config::LONG_PRESS_MS;
|
use crate::config::LONG_PRESS_MS;
|
||||||
|
use crate::config::RESET_HOLD_MS;
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
pub enum EncoderEvent {
|
pub enum EncoderEvent {
|
||||||
@@ -22,6 +23,8 @@ pub enum EncoderEvent {
|
|||||||
Rotate(i8),
|
Rotate(i8),
|
||||||
Click,
|
Click,
|
||||||
LongPress,
|
LongPress,
|
||||||
|
/// The button was held long enough to forget the Zigbee network.
|
||||||
|
NetworkReset,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Depth 8 absorbs a fast spin while the consumer is mid-frame; overflowing
|
/// Depth 8 absorbs a fast spin while the consumer is mid-frame; overflowing
|
||||||
@@ -63,8 +66,19 @@ pub async fn button_task(mut button: Input<'static>) {
|
|||||||
|
|
||||||
if long_press {
|
if long_press {
|
||||||
let _ = EVENTS.try_send(EncoderEvent::LongPress);
|
let _ = EVENTS.try_send(EncoderEvent::LongPress);
|
||||||
|
// still held past the reset time: ask for a network reset while
|
||||||
|
// the button is down, so the light can react before it is let go
|
||||||
|
let released = with_timeout(
|
||||||
|
Duration::from_millis(RESET_HOLD_MS - LONG_PRESS_MS),
|
||||||
|
button.wait_for_rising_edge(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_ok();
|
||||||
|
if !released {
|
||||||
|
let _ = EVENTS.try_send(EncoderEvent::NetworkReset);
|
||||||
// swallow the release so it is not read as a second press
|
// swallow the release so it is not read as a second press
|
||||||
button.wait_for_rising_edge().await;
|
button.wait_for_rising_edge().await;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
let _ = EVENTS.try_send(EncoderEvent::Click);
|
let _ = EVENTS.try_send(EncoderEvent::Click);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {}
|
||||||
+23
-2
@@ -7,7 +7,11 @@ mod effect;
|
|||||||
#[cfg(feature = "zigbee")]
|
#[cfg(feature = "zigbee")]
|
||||||
mod effects_cluster;
|
mod effects_cluster;
|
||||||
mod encoder;
|
mod encoder;
|
||||||
|
mod flash;
|
||||||
mod light;
|
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))]
|
#[cfg_attr(not(feature = "zigbee"), allow(dead_code))]
|
||||||
mod scene;
|
mod scene;
|
||||||
mod status;
|
mod status;
|
||||||
@@ -48,6 +52,17 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
|
|||||||
|
|
||||||
esp_alloc::heap_allocator!(size: 32 * 1024);
|
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
|
// the adapter derives its pulse timings from this frequency, so the same
|
||||||
// rate has to be handed to both calls
|
// rate has to be handed to both calls
|
||||||
let rmt_freq = Rate::from_mhz(80);
|
let rmt_freq = Rate::from_mhz(80);
|
||||||
@@ -80,7 +95,6 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
|
|||||||
{
|
{
|
||||||
use embassy_embedded_hal::adapter::BlockingAsync;
|
use embassy_embedded_hal::adapter::BlockingAsync;
|
||||||
use esp_radio::ieee802154::Ieee802154;
|
use esp_radio::ieee802154::Ieee802154;
|
||||||
use esp_storage::FlashStorage;
|
|
||||||
use static_cell::StaticCell;
|
use static_cell::StaticCell;
|
||||||
use zigbee_mac::esp::EspMlme;
|
use zigbee_mac::esp::EspMlme;
|
||||||
|
|
||||||
@@ -90,7 +104,7 @@ async fn main(spawner: embassy_executor::Spawner) -> ! {
|
|||||||
|
|
||||||
// the stack owns persistence: the information bases are restored here
|
// the stack owns persistence: the information bases are restored here
|
||||||
// and written back whenever the stack changes them
|
// and written back whenever the stack changes them
|
||||||
let flash = BlockingAsync::new(FlashStorage::new(peripherals.FLASH));
|
let flash = BlockingAsync::new(flash::SharedFlash);
|
||||||
let storage = zigbee::storage::FlashStorage::new(flash, zigbee_stack::FLASH_RANGE).await;
|
let storage = zigbee::storage::FlashStorage::new(flash, zigbee_stack::FLASH_RANGE).await;
|
||||||
|
|
||||||
let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
|
let ieee802154 = Ieee802154::new(peripherals.IEEE802154);
|
||||||
@@ -107,6 +121,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 +140,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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+164
@@ -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()
|
||||||
|
}
|
||||||
+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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+62
-2
@@ -6,10 +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 esp_storage::FlashStorage;
|
use embassy_time::with_timeout;
|
||||||
use zigbee::aps::apsde::ApsdeSapConfirmStatus;
|
use zigbee::aps::apsde::ApsdeSapConfirmStatus;
|
||||||
use zigbee::CurrentPowerMode;
|
use zigbee::CurrentPowerMode;
|
||||||
use zigbee::CurrentPowerSourceLevel;
|
use zigbee::CurrentPowerSourceLevel;
|
||||||
@@ -56,7 +58,9 @@ use zigbee_types::ShortAddress;
|
|||||||
|
|
||||||
use crate::effects_cluster;
|
use crate::effects_cluster;
|
||||||
use crate::effects_cluster::EffectsServer;
|
use crate::effects_cluster::EffectsServer;
|
||||||
|
use crate::flash::SharedFlash;
|
||||||
use crate::light;
|
use crate::light;
|
||||||
|
use crate::status;
|
||||||
|
|
||||||
/// Flash region reserved for Zigbee persistence.
|
/// Flash region reserved for Zigbee persistence.
|
||||||
///
|
///
|
||||||
@@ -123,7 +127,7 @@ static COLOR_CONTROL: ColorControlServer<'static> =
|
|||||||
ColorControlServer::new(370).with_reporting(&REPORTING);
|
ColorControlServer::new(370).with_reporting(&REPORTING);
|
||||||
static EFFECTS: EffectsServer = EffectsServer;
|
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
|
/// Cluster servers in the order they are offered a request. The responder is
|
||||||
/// last so an unclaimed cluster draws UNSUPPORTED_CLUSTER rather than silence
|
/// last so an unclaimed cluster draws UNSUPPORTED_CLUSTER rather than silence
|
||||||
@@ -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