diff --git a/README.md b/README.md index 5aaa7e2..0448d66 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ The on-board user LED (GPIO15) blinks as a heartbeat. | 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 @@ -83,11 +84,23 @@ hardware checks, run with `cargo run --release --bin led_diag`. ## Joining the network -Put your coordinator into pairing mode (in ZHA, **Add device**). The light scans -every few seconds and joins when it finds the network permitting joins. After -that it rejoins by itself when it restarts. If it has lost its network keys, for -example after a long coordinator outage, put the coordinator back into pairing -mode and it will join again. +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 diff --git a/src/config.rs b/src/config.rs index 351bea4..b240bac 100644 --- a/src/config.rs +++ b/src/config.rs @@ -18,9 +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; diff --git a/src/encoder.rs b/src/encoder.rs index 47a44c2..490d6ce 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -15,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 { @@ -22,6 +23,8 @@ 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 @@ -63,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); } diff --git a/src/main.rs b/src/main.rs index 92db673..287d90d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -107,6 +107,8 @@ async fn main(spawner: embassy_executor::Spawner) -> ! { spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task")); spawner.spawn(zigbee_stack::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 { @@ -124,6 +126,11 @@ async fn main(spawner: embassy_executor::Spawner) -> ! { let on = light::toggle(); 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(); + } } } } diff --git a/src/status.rs b/src/status.rs index fd760c0..916ed0d 100644 --- a/src/status.rs +++ b/src/status.rs @@ -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 -//! task has panicked, which is otherwise invisible without a serial console. +//! 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; @@ -9,14 +14,30 @@ 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(HEARTBEAT_ON_MS)).await; + Timer::after(Duration::from_millis(on_ms)).await; 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; } } diff --git a/src/zigbee_stack.rs b/src/zigbee_stack.rs index 0d14643..6f4f733 100644 --- a/src/zigbee_stack.rs +++ b/src/zigbee_stack.rs @@ -6,9 +6,12 @@ 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 embassy_time::with_timeout; use esp_storage::FlashStorage; use zigbee::aps::apsde::ApsdeSapConfirmStatus; use zigbee::CurrentPowerMode; @@ -57,6 +60,7 @@ use zigbee_types::ShortAddress; use crate::effects_cluster; use crate::effects_cluster::EffectsServer; use crate::light; +use crate::status; /// Flash region reserved for Zigbee persistence. /// @@ -565,3 +569,59 @@ pub async fn identify_task() { } } } + +static NETWORK_RESET: Signal = 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; + } +}