feat: bootstrap esp32-c6 embassy lighting controller

This commit is contained in:
Matt Spencer committed 2026-10-17 15:21:58 +01:00
commit bb81182daa
13 files changed
+2926

No files matched your search

+211
View File
@@ -0,0 +1,211 @@
//! Zigbee end device: commissioning, the stack task, and the clusters served.
//!
//! The device is announced as an On/Off Light. Level Control and Color Control
//! (ZCL chapter 5) are deliberately absent: the vendored upstream does not
//! implement the lighting clusters yet, so for now brightness and hue are
//! local-only and the network sees on/off.
use core::ops::Range;
use embassy_embedded_hal::adapter::BlockingAsync;
use embassy_time::Duration;
use embassy_time::Timer;
use esp_storage::FlashStorage;
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::IdentifyServer;
use zigbee_cluster_library::clusters::general::on_off;
use zigbee_cluster_library::clusters::general::on_off::OnOffServer;
use zigbee_cluster_library::profile;
use zigbee_cluster_library::reporting::ReportingTable;
use zigbee_cluster_library::server::UnsupportedClusterResponder;
use zigbee_mac::esp::EspMlme;
use zigbee_types::IeeeAddress;
use crate::light;
/// Flash region reserved for Zigbee persistence.
///
/// MUST match the partition table: erase-sector aligned (4 KiB) and at least
/// two sectors so sequential-storage has a spare for garbage collection. The
/// address assumes the 4 MiB flash of the ESP32-C6-DevKitC-1.
pub const FLASH_RANGE: Range<u32> = 0x3f_0000..0x3f_4000;
/// Extended PAN ID of the network to join.
///
/// Placeholder: replace with the Extended PAN ID of your own coordinator.
const EXTENDED_PAN_ID: u64 = 0xabcd_ef01_2345_6789;
/// Channel to scan on; must match the coordinator.
const CHANNEL: u8 = 11;
/// 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) and
/// rx-on-when-idle (bit 3), so the coordinator can push commands at any time
/// rather than waiting for a poll.
const CAPABILITY: u8 = 0x8e;
static INPUT_CLUSTERS: [u16; 3] = [
basic::CLUSTER_ID,
identify::CLUSTER_ID,
on_off::CLUSTER_ID,
];
static OUTPUT_CLUSTERS: [u16; 0] = [];
static ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor {
endpoint: LIGHT_ENDPOINT,
profile_id: profile::HOME_AUTOMATION,
// HA device id 0x0100: On/Off Light. Becomes 0x0101 (Dimmable Light) once
// Level Control is implemented.
device_id: 0x0100,
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<4> = ReportingTable::new();
static ON_OFF: OnOffServer = OnOffServer::new().with_reporting(&REPORTING);
type ZigbeeFlash = zigbee::storage::FlashStorage<BlockingAsync<FlashStorage<'static>>>;
/// Cluster servers in the order they are offered a request. The responder is
/// last so an unclaimed cluster draws UNSUPPORTED_CLUSTER rather than silence
/// (ZCL 2.5.12.2).
type Handler = (
BasicServer<'static>,
&'static IdentifyServer,
&'static OnOffServer<'static>,
UnsupportedClusterResponder<'static>,
);
pub type Stack = zigbee::Stack<'static, EspMlme<'static>, Handler, ZigbeeFlash>;
pub fn handler() -> Handler {
(
BASIC,
&IDENTIFY,
&ON_OFF,
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: 0x1037,
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) {
// returns only once no rejoin can get us back: the network is gone or our
// keys are stale, so drop it and re-commission from scratch
let outcome = stack.run(embassy_time::Delay).await;
log::warn!("off the network ({outcome:?}), forgetting it and rebooting");
stack.forget_network().await;
esp_hal::system::software_reset();
}
/// Mirrors the On/Off attribute onto the strip, both ways.
///
/// The cluster server writes its attribute from the APS receive path without
/// any notification hook, so this samples it. The reverse direction keeps the
/// attribute truthful after a local button press.
#[embassy_executor::task]
pub async fn on_off_task() {
let mut last = ON_OFF.on_off();
loop {
Timer::after(Duration::from_millis(50)).await;
let remote = ON_OFF.on_off();
if remote != last {
last = remote;
light::set_on(remote);
continue;
}
let local = light::is_on();
if local != last {
last = local;
ON_OFF.set_on_off(local);
}
}
}
/// 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)");
}
}
}