//! Zigbee end device: commissioning, the stack task, and the clusters served. //! //! 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 embassy_time::with_timeout; use esp_storage::FlashStorage; use zigbee::aps::apsde::ApsdeSapConfirmStatus; use zigbee::CurrentPowerMode; use zigbee::CurrentPowerSourceLevel; use zigbee::DeviceConfig; use zigbee::LogicalType; use zigbee::NetworkConfig; use zigbee::PowerSource; use zigbee::TimingConfig; use zigbee::config::StackConfig; use zigbee::nwk::nib::CapabilityInformation; use zigbee::zdo::config::DiscoveryType; use zigbee::zdo::descriptor::DeviceDescriptorConfig; use zigbee::zdo::descriptor::EndpointDescriptor; use zigbee::zdo::descriptor::NodeDescriptorConfig; 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::light; use crate::status; /// Flash region reserved for Zigbee persistence. /// /// 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 = 0x3e_0000..0x3e_4000; /// 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 = 25; /// Scan duration exponent (beacon order). 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), 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; 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 0x010d: Extended Color Light. device_id: 0x010d, device_version: 1, input_clusters: &INPUT_CLUSTERS, output_clusters: &OUTPUT_CLUSTERS, }]; static BASIC: BasicServer = BasicServer { zcl_version: 8, application_version: 1, stack_version: 0, hw_version: 1, manufacturer_name: "smart-light", model_identifier: "smart-light.ws2812", // 0x01: mains (single phase) power_source: 0x01, }; pub static IDENTIFY: IdentifyServer = IdentifyServer::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>>; /// 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>, ( &'static LevelControlServer<'static>, ( &'static ColorControlServer<'static>, (&'static EffectsServer, UnsupportedClusterResponder<'static>), ), ), ), ), ); pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>; pub fn handler() -> Handler { ( BASIC, ( &IDENTIFY, ( &ON_OFF, ( &LEVEL_CONTROL, ( &COLOR_CONTROL, ( &EFFECTS, UnsupportedClusterResponder::new(&INPUT_CLUSTERS), ), ), ), ), ), ) } pub fn config() -> StackConfig<'static> { StackConfig::new( NetworkConfig { extended_pan_id: IeeeAddress(EXTENDED_PAN_ID), channels: CHANNEL..CHANNEL + 1, scan_duration: SCAN_DURATION, }, DeviceConfig { logical_type: LogicalType::EndDevice, capability_information: CapabilityInformation(CAPABILITY), discovery_type: DiscoveryType::default(), tc_link_key_exchange: true, }, TimingConfig::default(), DeviceDescriptorConfig { node: NodeDescriptorConfig { // bit 3: 2400 MHz band frequency_band: 0x08, manufacturer_code: effects_cluster::MANUFACTURER_CODE, maximum_buffer_size: 80, maximum_incoming_transfer_size: 128, server_mask: 0, maximum_outgoing_transfer_size: 128, descriptor_capability_field: 0, ..NodeDescriptorConfig::default() }, power: PowerDescriptorConfig { current_power_mode: CurrentPowerMode::Synchronized, available_power_sources: &[PowerSource::ConstantMainPower], current_power_source: PowerSource::ConstantMainPower, current_power_source_level: CurrentPowerSourceLevel::Full, }, endpoints: &ENDPOINTS, }, ) } /// Drives the stack: commissioning, discovery, cluster reads and writes, the /// parent link, and persistence. #[embassy_executor::task] pub async fn stack_task(stack: &'static Stack) { 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; } } async fn report_attribute( stack: &'static Stack, attribute: &Attribute, 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 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; 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(), } } 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; } } } } /// Counts the Identify state down once a second (ZCL 3.5.2.2.1). #[embassy_executor::task] pub async fn identify_task() { loop { Timer::after(Duration::from_secs(1)).await; if IDENTIFY.is_identifying() { let remaining = IDENTIFY.tick(1); log::info!("identifying ({remaining}s remaining)"); } } } 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; } }