diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 6bc88e19..2f68e061 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -10,6 +10,8 @@ use ziggurat_phy::{ use ziggurat_zigbee::Instant as CoreInstant; use ziggurat_zigbee::aps::frame::{ApsFrame, parse_aps_frame}; use ziggurat_zigbee::beacon::ZigbeeBeacon; +use ziggurat_zigbee::zcl::endpoints::Endpoints; +use ziggurat_zigbee::zdp::descriptors::Descriptors; use thiserror::Error; @@ -37,6 +39,7 @@ mod route; mod send_handle; mod sends; mod tasklets; +mod zcl; mod zdp; use send_handle::SendWatches; @@ -81,6 +84,9 @@ const FRAME_COUNTER_NOTIFY_INTERVAL: u32 = 100; /// that wasn't reading has already missed it and re-syncs on reconnect. const NOTIFICATION_QUEUE_CAP: usize = 64; +/// Channels 11 to 26 of channel page 0, the default `apsChannelMaskList`. +const ALL_2400_MHZ_CHANNELS: u32 = 0x07FF_F800; + /// A synchronous admission failure, returned by the `send_*` entry points. /// /// An `Err` means nothing was enqueued and no later confirmation follows; `retry_in` @@ -368,6 +374,8 @@ pub struct Nib { pub nwk_security: NwkSecurity, /// The EUI64-to-network-address map, one owner per network address pub address_map: AddressMap, + /// `nwkManagerAddr`: the device that manages the network's channel + pub manager_address: Nwk, /// `nwkIsConcentrator`: we advertise many-to-one routes to ourselves and /// source-route through the route records they bring back. Whoever controls the /// node decides, at any time. @@ -394,6 +402,9 @@ pub struct Aib { /// derivation, command encryption). Holds the non-spec TCLK seed used to derive /// keys when the network was taken over from a microcontroller stack. pub aps_security: ApsSecurity, + /// `apsChannelMaskList`: the channels the network may use, for a router that has + /// to find it again after missing a channel change + pub channel_mask: u32, } /// Host-side mirror of the MAC PIB attributes we drive on the RCP. The MAC sub-layer @@ -422,6 +433,12 @@ pub struct ZigbeeCore { /// lock because resolving one reads the address map and the routing table. pub address_conflicts: AddressConflicts, + /// The local endpoints and manufacturer codes, read by ZDP discovery requests. + pub descriptors: Descriptors, + + /// The application endpoints the stack serves itself, rather than the client. + pub endpoints: Endpoints, + /// Deadline until which the coordinator advertises `association_permit` in its /// beacon and accepts direct MAC associations. A deadline rather than a flag lets /// renewals extend the window. `None` or past means direct joins are denied. @@ -484,7 +501,6 @@ pub struct State { pub role: NwkDeviceType, pub capability_information: NwkCapabilityInformation, - pub nwk_manager_addr: Nwk, /// Our tree depth, advertised in beacons. The coordinator is the root, at 0. pub depth: u8, @@ -540,6 +556,7 @@ impl State { FRAME_COUNTER_NOTIFY_INTERVAL, ), address_map: AddressMap::new(config.network_address, config.ieee_address), + manager_address: Nwk(0x0000), is_concentrator: config.concentrator, }, aib: Aib { @@ -550,6 +567,7 @@ impl State { config.tclk_seed.clone(), FRAME_COUNTER_NOTIFY_INTERVAL, ), + channel_mask: ALL_2400_MHZ_CHANNELS, }, mac: MacState { channel: config.channel, @@ -558,6 +576,12 @@ impl State { }, sends: SendTable::default(), address_conflicts: AddressConflicts::default(), + descriptors: Descriptors::new( + config.network_address, + config.ieee_address, + config.role, + ), + endpoints: Endpoints::default(), permitting_joins_until: None, trust_center_joins_until: None, beacon_spam_until: None, @@ -588,7 +612,6 @@ impl State { security_capability: NwkSecurityCapability::Capable, allocate_address: true, }, - nwk_manager_addr: Nwk(0x0000), network_address: config.network_address, extended_pan_id: config.extended_pan_id, security_level: 5, @@ -1076,10 +1099,11 @@ impl ZigbeeStack { continue; } - // The ZDP commands that maintain stack state (the neighbor and - // address tables live here, not in the client) are consumed by - // the stack; the client still observes the frames - self.handle_zdp_frame(&nwk_frame, &aps_frame); + // The stack consumes the ZDP commands that read or change its own + // state: the neighbor and address tables, and the descriptors. + // The client still observes the frames + self.handle_zdp_frame(&nwk_frame, &aps_frame, aps_source_eui64); + self.handle_zcl_frame(&nwk_frame, &aps_frame, aps_source_eui64); let notification = ZigbeeNotification::ReceivedApsCommand { source: nwk_frame.nwk_header.source, diff --git a/crates/ziggurat-driver/src/zigbee_stack/zcl.rs b/crates/ziggurat-driver/src/zigbee_stack/zcl.rs new file mode 100644 index 00000000..8d0de158 --- /dev/null +++ b/crates/ziggurat-driver/src/zigbee_stack/zcl.rs @@ -0,0 +1,80 @@ +use crate::runtime::Runtime; +use ziggurat_ieee_802154::types::Eui64; +use ziggurat_phy::RadioPhy; +use ziggurat_zigbee::aps::frame::{ApsDataFrame, ApsDeliveryMode}; +use ziggurat_zigbee::nwk::frame::{NwkFrame, is_broadcast}; +use ziggurat_zigbee::zcl::endpoints::{BROADCAST_ENDPOINT, Endpoint, Indication}; + +use super::{ApsAck, RouteDirective, TxPriority, ZigbeeStack}; + +impl ZigbeeStack { + /// Serve an application endpoint from the stack, rather than the client. Its + /// simple descriptor joins the ones ZDP requests read. + pub fn add_application_endpoint(&self, endpoint: Endpoint) { + let mut core = self.core(); + core.descriptors.add_endpoint(endpoint.simple_descriptor()); + core.endpoints.add(endpoint); + } + + /// Carry out a ZCL frame for the endpoints the stack serves. Replies mirror the + /// APS security of the frame; `aps_security` is the sender's EUI64 if it was + /// APS-secured. The client still observes the frame. + pub(super) fn handle_zcl_frame( + &self, + nwk_frame: &NwkFrame, + aps_frame: &ApsDataFrame, + aps_security: Option, + ) { + // Group frames carry no endpoint, and we serve no groups + let Some(destination_endpoint) = aps_frame.destination_endpoint else { + return; + }; + + let replies = { + let mut core = self.core(); + + if destination_endpoint != BROADCAST_ENDPOINT + && !core.endpoints.contains(destination_endpoint) + { + return; + } + + let indication = Indication { + source: nwk_frame.nwk_header.source, + source_endpoint: aps_frame.source_endpoint, + destination_endpoint, + profile_id: aps_frame.profile_id, + cluster_id: aps_frame.cluster_id, + unicast: aps_frame.frame_control.delivery_mode == ApsDeliveryMode::Unicast + && !is_broadcast(nwk_frame.nwk_header.destination), + aps_secured: aps_security.is_some(), + asdu: &aps_frame.asdu, + }; + + core.endpoints.receive(&indication, self.core_now()) + }; + + for reply in replies { + if let Err(err) = self.send_aps_unicast( + reply.destination, + reply.profile_id, + reply.cluster_id, + reply.source_endpoint, + reply.destination_endpoint, + ApsAck::None, + None, + 0, + reply.asdu.to_vec(), + aps_security, + false, + TxPriority::UserNormal, + RouteDirective::StackDecides, + ) { + tracing::warn!( + "Failed to send a ZCL reply to {:?}: {err}", + reply.destination + ); + } + } + } +} diff --git a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs index 68fafc2d..dd82caf7 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/zdp.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/zdp.rs @@ -1,26 +1,29 @@ use crate::runtime::Runtime; +use alloc::vec; use alloc::vec::Vec; use core::time::Duration; use ziggurat_ieee_802154::types::{Eui64, Nwk}; -use ziggurat_ieee_802154::{TooLong, write_frame}; +use ziggurat_ieee_802154::{TooLong, energy_detect_value, write_frame}; use ziggurat_phy::RadioPhy; -use ziggurat_zigbee::aps::frame::{ApsDataFrame, ApsDeliveryMode, ApsFrameControl, ApsFrameType}; -use ziggurat_zigbee::nwk::frame::{ - BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame, NwkRouteDiscovery, -}; +use ziggurat_zigbee::aps::frame::{ApsDataFrame, ApsDeliveryMode, Asdu}; +use ziggurat_zigbee::nwk::frame::{BROADCAST_ALL_ROUTERS_AND_COORDINATOR, NwkFrame, is_broadcast}; +use ziggurat_zigbee::zdp::nwk_update::{self, NwkUpdate}; use ziggurat_zigbee::zdp::{ - DeviceAnnce, MgmtLqiReq, MgmtLqiRsp, MgmtRtgReq, MgmtRtgRsp, NeighborDescriptor, ParentAnnce, - ParentAnnceRsp, RoutingDescriptor, ZDP_PROFILE_ID, ZdpAffinity, ZdpClusterId, ZdpCommand, - ZdpDeviceType, ZdpPermitJoining, ZdpRouteStatus, ZdpRxOnWhenIdle, ZdpStatus, mgmt_table_page, + DeviceAnnce, MgmtBindReq, MgmtBindRsp, MgmtLqiReq, MgmtLqiRsp, MgmtNwkUpdateReq, MgmtRtgReq, + MgmtRtgRsp, NeighborDescriptor, ParentAnnce, ParentAnnceRsp, RoutingDescriptor, ZDP_PROFILE_ID, + ZdpAffinity, ZdpClusterId, ZdpCommand, ZdpDeviceType, ZdpPermitJoining, ZdpRouteStatus, + ZdpRxOnWhenIdle, ZdpStatus, mgmt_table_page, }; -use super::TrafficClass; use super::{ - Broadcast, Confirm, EnqueueError, MAX_DEPTH, NwkDeviceType, NwkSecurityMode, RouteDirective, - SendHandle, SendMode, TxPolicy, TxPriority, Unicast, ZigbeeStack, neighbors, routing, + ApsAck, EnqueueError, MAX_DEPTH, NwkDeviceType, RouteDirective, SendHandle, TxPriority, + ZigbeeCore, ZigbeeStack, neighbors, routing, }; +/// A ZDP response's cluster is its request's with the high bit set (spec 2.4.4.1). +const ZDP_RESPONSE_BIT: u16 = 0x8000; + /// EUI64s per Parent_annce frame, keeping the ASDU within the NWK payload budget. const PARENT_ANNCE_CHILDREN_PER_FRAME: usize = 8; @@ -33,20 +36,269 @@ const MGMT_RTG_DESCRIPTORS_PER_FRAME: usize = 10; impl ZigbeeStack { /// Dispatch the ZDP commands the stack itself consumes: the neighbor table they - /// maintain lives here. The client still observes the frames. - pub(super) fn handle_zdp_frame(&self, nwk_frame: &NwkFrame, aps_frame: &ApsDataFrame) { + /// maintain and the descriptors they read live here. The client still observes the + /// frames. `aps_security` is the requester's EUI64 if the request was APS-secured. + pub(super) fn handle_zdp_frame( + &self, + nwk_frame: &NwkFrame, + aps_frame: &ApsDataFrame, + aps_security: Option, + ) { if aps_frame.profile_id != ZDP_PROFILE_ID || aps_frame.destination_endpoint != Some(0) { return; } + let source = nwk_frame.nwk_header.source; + let broadcast = is_broadcast(nwk_frame.nwk_header.destination); + match ZdpClusterId::try_from(aps_frame.cluster_id) { Ok(ZdpClusterId::DeviceAnnce) => self.handle_device_annce(nwk_frame, aps_frame), Ok(ZdpClusterId::ParentAnnce) => self.handle_parent_annce(nwk_frame, aps_frame), Ok(ZdpClusterId::ParentAnnceRsp) => self.handle_parent_annce_rsp(nwk_frame, aps_frame), Ok(ZdpClusterId::MgmtLqiReq) => self.handle_mgmt_lqi_req(nwk_frame, aps_frame), Ok(ZdpClusterId::MgmtRtgReq) => self.handle_mgmt_rtg_req(nwk_frame, aps_frame), - // Management responses from other devices are the client's business - Ok(ZdpClusterId::MgmtLqiRsp | ZdpClusterId::MgmtRtgRsp) | Err(_) => {} + Ok(ZdpClusterId::NwkAddrReq) => { + self.answer_zdp_request(aps_frame, source, aps_security, |core, request| { + core.descriptors + .nwk_addr_rsp(request, &core.nib.neighbors, broadcast) + }); + } + Ok(ZdpClusterId::IeeeAddrReq) => { + self.answer_zdp_request(aps_frame, source, aps_security, |core, request| { + core.descriptors + .ieee_addr_rsp(request, &core.nib.neighbors, broadcast) + }); + } + Ok(ZdpClusterId::NodeDescReq) => { + self.answer_zdp_request(aps_frame, source, aps_security, |core, request| { + let requester = aps_security + .or(nwk_frame.nwk_header.source_ieee) + .or_else(|| core.nib.address_map.eui64_for(source)); + core.descriptors.node_desc_rsp( + request, + &core.nib.neighbors, + broadcast, + requester, + ) + }); + } + Ok(ZdpClusterId::PowerDescReq) => { + self.answer_zdp_request(aps_frame, source, aps_security, |core, request| { + core.descriptors + .power_desc_rsp(request, &core.nib.neighbors, broadcast) + }); + } + Ok(ZdpClusterId::SimpleDescReq) => { + self.answer_zdp_request(aps_frame, source, aps_security, |core, request| { + core.descriptors + .simple_desc_rsp(request, &core.nib.neighbors, broadcast) + }); + } + Ok(ZdpClusterId::ActiveEpReq) => { + self.answer_zdp_request(aps_frame, source, aps_security, |core, request| { + core.descriptors.active_ep_rsp(request, broadcast) + }); + } + Ok(ZdpClusterId::MatchDescReq) => { + self.answer_zdp_request(aps_frame, source, aps_security, |core, request| { + core.descriptors + .match_desc_rsp(request, &core.nib.neighbors, broadcast) + }); + } + // Spec 2.4.4.3.4: a router keeps no binding table, and reports it empty. + // The coordinator's bindings are the client's business + Ok(ZdpClusterId::MgmtBindReq) if self.state.role == NwkDeviceType::Router => { + self.answer_zdp_request(aps_frame, source, aps_security, |_, _: &MgmtBindReq| { + (!broadcast).then_some(MgmtBindRsp { + status: ZdpStatus::Success, + binding_table_entries: 0, + start_index: 0, + binding_table_list_count: 0, + }) + }); + } + Ok(ZdpClusterId::MgmtBindReq) => {} + Ok(ZdpClusterId::MgmtNwkUpdateReq) if self.state.role == NwkDeviceType::Router => { + self.handle_mgmt_nwk_update_req(nwk_frame, aps_frame, aps_security); + } + // The coordinator's channel is the client's to manage + Ok(ZdpClusterId::MgmtNwkUpdateReq) => {} + // Responses from other devices are the client's business + Ok( + ZdpClusterId::NwkAddrRsp + | ZdpClusterId::IeeeAddrRsp + | ZdpClusterId::NodeDescRsp + | ZdpClusterId::PowerDescRsp + | ZdpClusterId::SimpleDescRsp + | ZdpClusterId::ActiveEpRsp + | ZdpClusterId::MatchDescRsp + | ZdpClusterId::MgmtLqiRsp + | ZdpClusterId::MgmtRtgRsp + | ZdpClusterId::MgmtBindRsp + | ZdpClusterId::MgmtNwkUpdateNotify, + ) => {} + Err(_) if aps_frame.cluster_id & ZDP_RESPONSE_BIT == 0 => { + self.reject_unsupported_zdp_request(nwk_frame, aps_frame, aps_security); + } + Err(_) => {} + } + } + + /// Spec 2.4.3.3.9.2: change channel, store a new manager, or scan for energy, as + /// the network manager asks. + fn handle_mgmt_nwk_update_req( + &self, + nwk_frame: &NwkFrame, + aps_frame: &ApsDataFrame, + aps_security: Option, + ) { + let source = nwk_frame.nwk_header.source; + + let (tsn, request) = match MgmtNwkUpdateReq::deserialize(&aps_frame.asdu) { + Ok(parsed) => parsed, + Err(err) => { + tracing::warn!("Malformed network update request from {source:?}: {err}"); + return; + } + }; + + let unicast = !is_broadcast(nwk_frame.nwk_header.destination) + && aps_frame.frame_control.delivery_mode == ApsDeliveryMode::Unicast; + + let Some(update) = NwkUpdate::from_request(&request, unicast) else { + return; + }; + + let arc_self = self + .self_weak + .upgrade() + .expect("Unable to upgrade self reference"); + + match update { + NwkUpdate::ChangeChannel { channel, update_id } => { + self.tasklets.push(async move { + arc_self.change_channel_on_request(channel, update_id).await; + }); + } + NwkUpdate::UpdateManager { + channel_mask, + manager, + } => { + let mut core = self.core(); + core.aib.channel_mask = channel_mask; + core.nib.manager_address = manager; + } + NwkUpdate::EnergyScan { + channels, + duration, + count, + } => { + self.tasklets.push(async move { + arc_self + .report_energy_scans(source, tsn, channels, duration, count, aps_security) + .await; + }); + } + NwkUpdate::Reject(status) => { + if let Err(err) = + self.send_zdp_unicast(source, tsn, &nwk_update::rejection(status), aps_security) + { + tracing::warn!("Failed to refuse a network update from {source:?}: {err}"); + } + } + } + } + + /// Frequency agility annex: switch channel once the request had time to reach + /// every router, adopt its update id, and restart the transmission counts. The + /// update id goes first so no beacon on the new channel advertises the old one. + async fn change_channel_on_request(&self, channel: u8, update_id: u8) { + R::sleep(self.tunables.broadcast_delivery_time()).await; + + tracing::info!("Changing to channel {channel} as the network manager asked"); + self.set_nwk_update_id(update_id); + + if let Err(err) = self.set_channel(channel).await { + tracing::warn!("Failed to change to channel {channel}: {err}"); + return; + } + + let mut core = self.core(); + core.nib.tx_total = 0; + core.nib.neighbors.reset_transmit_failures(); + } + + /// Spec 2.4.3.3.9.2 step 5: scan the channels `count` times, reporting each pass + /// to the requester. + async fn report_energy_scans( + &self, + requester: Nwk, + tsn: u8, + channels: Vec, + duration: Duration, + count: u8, + aps_security: Option, + ) { + for _ in 0..count { + let mut energy_values = Vec::with_capacity(channels.len()); + + for &channel in &channels { + match self.energy_detect(channel, duration).await { + Ok(rssi) => energy_values.push(energy_detect_value(rssi)), + Err(err) => { + tracing::warn!("Energy scan of channel {channel} failed: {err}"); + return; + } + } + } + + let total_transmissions = self.core().nib.tx_total; + let report = nwk_update::scan_report(&channels, energy_values, total_transmissions); + + if let Err(err) = self.send_zdp_unicast(requester, tsn, &report, aps_security) { + tracing::warn!("Failed to report an energy scan to {requester:?}: {err}"); + } + } + } + + /// Spec 2.4.4.1: a router answers a unicast request it does not support with only + /// the response cluster and NOT_SUPPORTED, and drops a broadcast one. On the + /// coordinator the client may support the request. + fn reject_unsupported_zdp_request( + &self, + nwk_frame: &NwkFrame, + aps_frame: &ApsDataFrame, + aps_security: Option, + ) { + if self.state.role != NwkDeviceType::Router + || is_broadcast(nwk_frame.nwk_header.destination) + || aps_frame.frame_control.delivery_mode != ApsDeliveryMode::Unicast + { + return; + } + + let Some(&tsn) = aps_frame.asdu.first() else { + return; + }; + + let source = nwk_frame.nwk_header.source; + + if let Err(err) = self.send_aps_unicast( + source, + ZDP_PROFILE_ID, + aps_frame.cluster_id | ZDP_RESPONSE_BIT, + 0, + 0, + ApsAck::None, + None, + 0, + vec![tsn, ZdpStatus::NotSupported as u8], + aps_security, + false, + TxPriority::UserNormal, + RouteDirective::StackDecides, + ) { + tracing::warn!("Failed to reject a ZDP request from {source:?}: {err}"); } } @@ -128,7 +380,7 @@ impl ZigbeeStack { neighbor_table_list: descriptors, }; - if let Err(err) = self.send_zdp_command(source, ApsDeliveryMode::Unicast, tsn, &response) { + if let Err(err) = self.send_zdp_unicast(source, tsn, &response, None) { tracing::warn!("Failed to send a neighbor table response to {source:?}: {err}"); } } @@ -189,7 +441,7 @@ impl ZigbeeStack { routing_table_list: descriptors, }; - if let Err(err) = self.send_zdp_command(source, ApsDeliveryMode::Unicast, tsn, &response) { + if let Err(err) = self.send_zdp_unicast(source, tsn, &response, None) { tracing::warn!("Failed to send a routing table response to {source:?}: {err}"); } } @@ -273,70 +525,88 @@ impl ZigbeeStack { children: claimed, }; - if let Err(err) = self.send_zdp_command(source, ApsDeliveryMode::Unicast, tsn, &response) { + if let Err(err) = self.send_zdp_unicast(source, tsn, &response, None) { tracing::warn!("Failed to send a parent announcement response to {source:?}: {err}"); } } - /// Build and enqueue a ZDP command. - fn send_zdp_command( + /// Answer a device and service discovery request. The answer is unicast to the + /// requester, with the APS security the request arrived with. + fn answer_zdp_request( + &self, + aps_frame: &ApsDataFrame, + source: Nwk, + aps_security: Option, + answer: impl FnOnce(&ZigbeeCore, &Req) -> Option, + ) { + let (tsn, request) = match Req::deserialize(&aps_frame.asdu) { + Ok(parsed) => parsed, + Err(err) => { + tracing::warn!("Malformed {:?} from {source:?}: {err}", Req::CLUSTER_ID); + return; + } + }; + + let Some(response) = answer(&self.core(), &request) else { + return; + }; + + if let Err(err) = self.send_zdp_unicast(source, tsn, &response, aps_security) { + tracing::warn!("Failed to send {:?} to {source:?}: {err}", Rsp::CLUSTER_ID); + } + } + + /// Unicast a ZDP command between endpoints 0. `aps_security` secures it with the + /// link key shared with that device. Unacknowledged: a lost response is covered by + /// the requester's own retries. + fn send_zdp_unicast( &self, destination: Nwk, - delivery_mode: ApsDeliveryMode, tsn: u8, command: &T, + aps_security: Option, ) -> Result { - let asdu = write_frame(|writer| command.serialize(tsn, writer)) + let asdu: Asdu = write_frame(|writer| command.serialize(tsn, writer)) .map_err(|TooLong| EnqueueError::PayloadTooLong)?; - let aps_frame = ApsDataFrame { - frame_control: ApsFrameControl { - frame_type: ApsFrameType::Data, - delivery_mode, - reserved1: 0b0, - security: false, - ack_request: false, - extended_header: false, - }, - group_id: None, - destination_endpoint: Some(0), - cluster_id: T::CLUSTER_ID as u16, - profile_id: ZDP_PROFILE_ID, - source_endpoint: 0, - counter: self.next_aps_counter(), - asdu, - }; + self.send_aps_unicast( + destination, + ZDP_PROFILE_ID, + T::CLUSTER_ID as u16, + 0, + 0, + ApsAck::None, + None, + 0, + asdu.to_vec(), + aps_security, + false, + TxPriority::UserNormal, + RouteDirective::StackDecides, + ) + .map(|(handle, _)| handle) + } - tracing::trace!("Prepared unicast ZDP APS frame: {aps_frame:?}"); - let nwk_frame = self - .nwk_data_frame( - destination, - write_frame(|writer| aps_frame.serialize(writer)) - .map_err(|TooLong| EnqueueError::PayloadTooLong)?, - ) - .with_discover_route(NwkRouteDiscovery::Enable) - .with_radius(2 * MAX_DEPTH); - - // ZDP responses are answerable to the remote requester's retries: best-effort - let policy = TxPolicy { - priority: TxPriority::UserNormal, - class: TrafficClass::Host, - }; + /// Broadcast a ZDP command between endpoints 0. + fn send_zdp_broadcast( + &self, + destination: Nwk, + tsn: u8, + command: &T, + ) -> Result { + let asdu: Asdu = write_frame(|writer| command.serialize(tsn, writer)) + .map_err(|TooLong| EnqueueError::PayloadTooLong)?; - match delivery_mode { - ApsDeliveryMode::Broadcast => self.send_broadcast(Broadcast { - frame: nwk_frame, - security: NwkSecurityMode::NetworkKey, - policy, - }), - ApsDeliveryMode::Unicast | ApsDeliveryMode::Multicast => self.send_unicast(Unicast { - frame: nwk_frame, - security: NwkSecurityMode::NetworkKey, - mode: SendMode::Route(RouteDirective::StackDecides), - policy, - confirm: Confirm::OnHandoff, - }), - } + self.send_aps_broadcast( + destination, + ZDP_PROFILE_ID, + T::CLUSTER_ID as u16, + 0, + 0, + 0, + asdu.to_vec(), + TxPriority::UserNormal, + ) } /// Spec 2.4.4.2.22.2: a router answered our parent announcement, claiming @@ -423,12 +693,8 @@ impl ZigbeeStack { let tsn = self.next_aps_counter(); let started = self.core_now(); - match self.send_zdp_command( - BROADCAST_ALL_ROUTERS_AND_COORDINATOR, - ApsDeliveryMode::Broadcast, - tsn, - &announcement, - ) { + match self.send_zdp_broadcast(BROADCAST_ALL_ROUTERS_AND_COORDINATOR, tsn, &announcement) + { Ok(send) => { let _ = send.handed_off().await; } diff --git a/crates/ziggurat-ieee-802154/src/lib.rs b/crates/ziggurat-ieee-802154/src/lib.rs index 21714002..996fd7df 100644 --- a/crates/ziggurat-ieee-802154/src/lib.rs +++ b/crates/ziggurat-ieee-802154/src/lib.rs @@ -19,6 +19,18 @@ pub const MAX_MAC_PAYLOAD_SIZE: usize = 118; /// A whole 802.15.4 frame. Frames are built in one of these and handed to the radio. pub type Psdu = heapless::Vec; +/// 12.3.4: the receiver sensitivity the O-QPSK PHY must reach. +const O_QPSK_RECEIVER_SENSITIVITY_DBM: i16 = -85; + +/// 10.2.6: the energy detection value of a received power. Zero is less than 10 dB +/// above the PHY's specified receiver sensitivity, and the values rise linearly over +/// the 40 dB above that. +pub fn energy_detect_value(rssi_dbm: i8) -> u8 { + let floor = O_QPSK_RECEIVER_SENSITIVITY_DBM + 10; + let scaled = (i16::from(rssi_dbm) - floor) * 255 / 40; + scaled.clamp(0, 255) as u8 +} + /// The payload of one 802.15.4 frame. pub type Msdu = heapless::Vec; @@ -73,6 +85,11 @@ impl<'a> FrameWriter<'a> { self.len() == 0 } + /// How many more bytes this writer accepts. + pub fn remaining(&self) -> usize { + self.end - self.buffer.len() + } + pub fn extend(&mut self, bytes: &[u8]) -> Result<(), TooLong> { if self.buffer.len() + bytes.len() > self.end { return Err(TooLong); diff --git a/crates/ziggurat-ncp-api/src/protocol.rs b/crates/ziggurat-ncp-api/src/protocol.rs index 2f09fbb8..06095af4 100644 --- a/crates/ziggurat-ncp-api/src/protocol.rs +++ b/crates/ziggurat-ncp-api/src/protocol.rs @@ -171,6 +171,18 @@ async fn dispatch( proto::set_tunable(&**configured(app)?, &payload)?; Ok(Response::Empty) } + Request::AddEndpoint(payload) => { + proto::add_endpoint(&**configured(app)?, payload)?; + Ok(Response::Empty) + } + Request::SetManufacturerCodes(payload) => { + proto::set_manufacturer_codes(&**configured(app)?, payload)?; + Ok(Response::Empty) + } + Request::SetConcentrator(payload) => { + configured(app)?.set_concentrator(payload.enabled); + Ok(Response::Empty) + } Request::CancelRequest(payload) => { let stack = running(app)?.clone(); let result = crate::with_send_tracker(&app.sends, |tracker| { diff --git a/crates/ziggurat-protocol/src/bridge.rs b/crates/ziggurat-protocol/src/bridge.rs index 5777a1b3..329a6ae2 100644 --- a/crates/ziggurat-protocol/src/bridge.rs +++ b/crates/ziggurat-protocol/src/bridge.rs @@ -19,6 +19,8 @@ use ziggurat_phy::RadioPhy; use ziggurat_zigbee::nwk::frame::NwkSecurityHeaderKeyId; use ziggurat_zigbee::nwk::neighbors::{ChildDescriptor, Relationship}; use ziggurat_zigbee::nwk::routing; +use ziggurat_zigbee::zdp::descriptors::ManufacturerCode; +use ziggurat_zigbee::zdp::SimpleDescriptor; use crate::send_tracker::{ConfirmKind, SendTracker}; @@ -247,6 +249,65 @@ pub fn apply_source_routes( } } +#[allow(clippy::significant_drop_tightening)] +pub fn add_endpoint( + stack: &ZigbeeStack, + payload: AddEndpointPayload, +) -> Result<(), Error> { + if !(1..=254).contains(&payload.endpoint) { + tracing::warn!("Rejecting endpoint {}", payload.endpoint); + return Err(Status::InvalidRequest.into()); + } + + let mut core = stack.state.core.lock(); + + // The stack serves this endpoint itself, and describes it from what it serves + if core.endpoints.contains(payload.endpoint) { + tracing::warn!( + "Rejecting endpoint {}: the stack serves it", + payload.endpoint + ); + return Err(Status::InvalidRequest.into()); + } + + core.descriptors.add_endpoint(SimpleDescriptor { + endpoint: payload.endpoint, + profile_id: payload.profile_id, + device_id: payload.device_id, + device_version: payload.device_version, + input_clusters: payload.input_clusters, + output_clusters: payload.output_clusters, + }); + Ok(()) +} + +pub fn set_manufacturer_codes( + stack: &ZigbeeStack, + payload: SetManufacturerCodesPayload, +) -> Result<(), Error> { + if payload.entries.iter().any(|entry| entry.prefix.len() > 8) { + tracing::warn!("Rejecting a manufacturer code prefix longer than an EUI64"); + return Err(Status::InvalidRequest.into()); + } + + let codes = payload + .entries + .into_iter() + .map(|entry| ManufacturerCode { + prefix: entry.prefix, + code: entry.code, + }) + .collect(); + + stack + .state + .core + .lock() + .descriptors + .set_manufacturer_codes(codes); + Ok(()) +} + impl From<&NetworkBeacon> for BeaconPayload { fn from(beacon: &NetworkBeacon) -> Self { Self { diff --git a/crates/ziggurat-protocol/src/wire.rs b/crates/ziggurat-protocol/src/wire.rs index f79c2ebf..6a8e230e 100644 --- a/crates/ziggurat-protocol/src/wire.rs +++ b/crates/ziggurat-protocol/src/wire.rs @@ -80,6 +80,9 @@ pub enum RequestCommand { SetProvisionalKey = 0x37, SetTunable = 0x38, SendGpdf = 0x39, + AddEndpoint = 0x3A, + SetManufacturerCodes = 0x3B, + SetConcentrator = 0x3C, // Radio scans and packet capture. EnergyScan = 0x40, NetworkScan = 0x41, @@ -297,6 +300,8 @@ pub struct NetworkState { #[derive(Debug, Clone)] pub struct ConfigurePayload { pub role: NodeRole, + /// Deprecated: use `SetConcentrator`. Still honored as the starting concentrator + /// state, for clients that predate the command. pub source_routing: bool, /// A router's tree depth; the coordinator's is always 0. Older clients leave these /// bits reserved, as 0. @@ -634,6 +639,57 @@ pub struct SetTunablePayload { pub value: u64, } +/// Registers a local endpoint, which the stack describes in its answers to ZDP +/// discovery requests. It replaces an earlier registration of the same endpoint. Valid +/// endpoints are 1 to 254. +#[abstract_bits] +#[derive(Debug, Clone)] +pub struct AddEndpointPayload { + pub endpoint: u8, + pub profile_id: u16, + pub device_id: u16, + pub device_version: u4, + pub reserved: u4, + pub input_count: u8, + #[abstract_bits(length_from = input_count)] + pub input_clusters: Vec, + pub output_count: u8, + #[abstract_bits(length_from = output_count)] + pub output_clusters: Vec, +} + +/// The manufacturer code reported in our node descriptor to devices whose EUI64 starts +/// with `prefix` (most significant byte first, at most 8 bytes). An empty prefix +/// matches every device. +#[abstract_bits] +#[derive(Debug, Clone)] +pub struct ManufacturerCodeEntry { + pub prefix_len: u8, + #[abstract_bits(length_from = prefix_len)] + pub prefix: Vec, + pub code: u16, +} + +/// Replaces the whole manufacturer code table. For each device, the entry with the +/// longest matching prefix wins. +#[abstract_bits] +#[derive(Debug, Clone)] +pub struct SetManufacturerCodesPayload { + pub count: u8, + #[abstract_bits(length_from = count)] + pub entries: Vec, +} + +/// Become a concentrator, advertising many-to-one routes to the node and +/// source-routing through the route records they bring back, or stop being one. It +/// takes effect at once. +#[abstract_bits] +#[derive(Debug, Clone)] +pub struct ConcentratorPayload { + pub enabled: bool, + pub reserved: u7, +} + #[abstract_bits] #[derive(Debug, Clone)] pub struct ScanRequestPayload { @@ -886,6 +942,9 @@ pub enum Request { SetTunable(SetTunablePayload), CancelRequest(CancelRequestPayload), SendGpdf(SendGpdfPayload), + AddEndpoint(AddEndpointPayload), + SetManufacturerCodes(SetManufacturerCodesPayload), + SetConcentrator(ConcentratorPayload), } impl Request { @@ -921,6 +980,9 @@ impl Request { RequestCommand::SetTunable => Self::SetTunable(require(payload)?), RequestCommand::CancelRequest => Self::CancelRequest(require(payload)?), RequestCommand::SendGpdf => Self::SendGpdf(require(payload)?), + RequestCommand::AddEndpoint => Self::AddEndpoint(require(payload)?), + RequestCommand::SetManufacturerCodes => Self::SetManufacturerCodes(require(payload)?), + RequestCommand::SetConcentrator => Self::SetConcentrator(require(payload)?), }) } } diff --git a/crates/ziggurat-server/src/main.rs b/crates/ziggurat-server/src/main.rs index 6a578e7e..031f7542 100644 --- a/crates/ziggurat-server/src/main.rs +++ b/crates/ziggurat-server/src/main.rs @@ -641,6 +641,18 @@ impl ZigguratServer { proto::set_tunable(&*self.configured()?, &payload)?; Ok(proto::Response::Empty) } + R::AddEndpoint(payload) => { + proto::add_endpoint(&*self.configured()?, payload)?; + Ok(proto::Response::Empty) + } + R::SetManufacturerCodes(payload) => { + proto::set_manufacturer_codes(&*self.configured()?, payload)?; + Ok(proto::Response::Empty) + } + R::SetConcentrator(payload) => { + self.configured()?.set_concentrator(payload.enabled); + Ok(proto::Response::Empty) + } R::CancelRequest(payload) => { let stack = self.running()?; let mut tracker = sends.tracker.lock().unwrap(); diff --git a/crates/ziggurat-zigbee/src/lib.rs b/crates/ziggurat-zigbee/src/lib.rs index 8444f3aa..6a47b526 100644 --- a/crates/ziggurat-zigbee/src/lib.rs +++ b/crates/ziggurat-zigbee/src/lib.rs @@ -13,6 +13,7 @@ pub mod nwk; pub mod ring_buffer; pub mod sends; pub mod time; +pub mod zcl; pub mod zdp; pub use time::Instant; diff --git a/crates/ziggurat-zigbee/src/nwk/commands.rs b/crates/ziggurat-zigbee/src/nwk/commands.rs index 85848225..862d0c52 100644 --- a/crates/ziggurat-zigbee/src/nwk/commands.rs +++ b/crates/ziggurat-zigbee/src/nwk/commands.rs @@ -192,10 +192,10 @@ pub struct NwkRejoinCapabilityInformation { pub receiver_on_when_idle: bool, /// This field will always have a value of 0 in implementations of this /// specification. - reserved1: u1, + pub reserved1: u1, /// This field will always have a value of 0 in implementations of this /// specification. - reserved2: u1, + pub reserved2: u1, /// This field SHALL have a value of 0. Note that this overrides the default meaning /// specified in \[B1\] (802.15.4-2020, IEEE Standard for Local and metropolitan area /// networks--Part 15.4: Low-Rate Wireless Personal Area Networks (LR-WPANs)) diff --git a/crates/ziggurat-zigbee/src/nwk/frame.rs b/crates/ziggurat-zigbee/src/nwk/frame.rs index 268b5179..5e9f9f23 100644 --- a/crates/ziggurat-zigbee/src/nwk/frame.rs +++ b/crates/ziggurat-zigbee/src/nwk/frame.rs @@ -38,6 +38,11 @@ pub const BROADCAST_RX_ON_WHEN_IDLE: Nwk = Nwk(0xFFFD); pub const BROADCAST_ALL_ROUTERS_AND_COORDINATOR: Nwk = Nwk(0xFFFC); pub const BROADCAST_LOW_POWER_ROUTERS: Nwk = Nwk(0xFFFB); +/// Spec Table 3-80: addresses 0xFFF8 to 0xFFFF are broadcast addresses. +pub const fn is_broadcast(address: Nwk) -> bool { + address.as_u16() >= 0xFFF8 +} + #[abstract_bits(bits = 2)] #[derive(Debug, Eq, PartialEq, TryFromPrimitive, Clone, Copy)] #[repr(u8)] diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index 2a5670a3..eaa8530e 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -313,6 +313,26 @@ impl Neighbors { }) } + /// The network address of the end device child with the given EUI64, if one exists. + pub fn end_device_child_nwk(&self, eui64: Eui64) -> Option { + self.table + .get(&eui64) + .filter(|entry| entry.is_child() && entry.device_type == NwkDeviceType::EndDevice) + .map(|entry| entry.network_address) + } + + /// The network addresses of every end device child, in ascending order. + pub fn end_device_child_addresses(&self) -> Vec { + let mut addresses: Vec = self + .table + .values() + .filter(|entry| entry.is_child() && entry.device_type == NwkDeviceType::EndDevice) + .map(|entry| entry.network_address) + .collect(); + addresses.sort_by_key(Nwk::as_u16); + addresses + } + /// Spec 3.3.1.1.8: after validating the source (3.6.2.2), a router parent SHALL /// clear the End Device Initiator bit when relaying a frame sent by one of its end /// device children. Otherwise the next router searches its own neighbor table for diff --git a/crates/ziggurat-zigbee/src/zcl.rs b/crates/ziggurat-zigbee/src/zcl.rs new file mode 100644 index 00000000..d086902e --- /dev/null +++ b/crates/ziggurat-zigbee/src/zcl.rs @@ -0,0 +1,6 @@ +pub mod cluster; +pub mod clusters; +pub mod endpoints; +pub mod foundation; +pub mod frame; +pub mod types; diff --git a/crates/ziggurat-zigbee/src/zcl/cluster.rs b/crates/ziggurat-zigbee/src/zcl/cluster.rs new file mode 100644 index 00000000..0c3992b2 --- /dev/null +++ b/crates/ziggurat-zigbee/src/zcl/cluster.rs @@ -0,0 +1,410 @@ +//! The server side of a cluster: its attributes and commands. +//! +//! A cluster supplies only its own attributes and commands through [`ClusterServer`]. +//! The behavior the global commands share across clusters lives here: the +//! ClusterRevision attribute, the access and data type checks, the order of the write +//! checks, and fitting records into the response frame. + +use alloc::vec::Vec; +use core::fmt::Debug; +use ziggurat_ieee_802154::{FrameWriter, write_frame}; + +use super::foundation::{ + AttributeInformation, DiscoverAttributes, DiscoverAttributesResponse, + ReadAttributeStatusRecord, ReadAttributes, Status, WriteAttributeRecord, + WriteAttributeStatusRecord, WriteAttributes, WriteAttributesResponse, +}; +use super::types::{AttributeValue, DataType}; +use crate::Instant; +use crate::aps::frame::MAX_ASDU_SIZE; + +/// ZCL 2.3.4.5.1: the global attribute every cluster has. +pub const CLUSTER_REVISION_ATTRIBUTE_ID: u16 = 0xFFFD; + +/// ZCL 2.3.4.4: whether an attribute can be written. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Access { + Read, + ReadWrite, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AttributeSpec { + pub id: u16, + pub data_type: DataType, + pub access: Access, +} + +/// What a cluster-specific command did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CommandOutcome { + /// Carried out with no response of its own: a Default Response reports SUCCESS if + /// the sender asked for one. + Done, + /// Carried out, answered with a cluster-specific response command. + Respond { command_id: u8, payload: Vec }, + /// Not carried out: a Default Response reports the status. + Failed(Status), +} + +/// A cluster's server side. Methods take the current time, for clusters whose state +/// changes over time; a cluster never reads a clock. +pub trait ClusterServer: Debug + Send { + fn cluster_id(&self) -> u16; + + /// The value of the ClusterRevision attribute. + fn revision(&self) -> u16; + + /// The cluster's own attributes. ClusterRevision is added for every cluster. + fn attributes(&self) -> &[AttributeSpec]; + + /// The current value of one of [`Self::attributes`], of its declared type. + fn read(&self, attribute_id: u16, now: Instant) -> AttributeValue; + + /// Check a write to a writable attribute, of its declared type, before any write + /// happens: INVALID_VALUE for a value out of range, NOT_AUTHORIZED when writes are + /// not accepted now. + fn validate(&self, _attribute_id: u16, _value: &AttributeValue) -> Result<(), Status> { + Ok(()) + } + + /// Write a value that passed [`Self::validate`]. + fn write(&mut self, attribute_id: u16, _value: AttributeValue, _now: Instant) { + unreachable!( + "cluster {:#06x} declares attribute {attribute_id:#06x} writable but cannot write it", + self.cluster_id() + ) + } + + /// Carry out a cluster-specific command sent to the server. + fn command(&mut self, _command_id: u8, _payload: &[u8], _now: Instant) -> CommandOutcome { + CommandOutcome::Failed(Status::UnsupCommand) + } +} + +fn attribute_spec(cluster: &dyn ClusterServer, attribute_id: u16) -> Option { + if attribute_id == CLUSTER_REVISION_ATTRIBUTE_ID { + return Some(AttributeSpec { + id: CLUSTER_REVISION_ATTRIBUTE_ID, + data_type: DataType::Uint16, + access: Access::Read, + }); + } + + cluster + .attributes() + .iter() + .find(|spec| spec.id == attribute_id) + .copied() +} + +fn read_attribute( + cluster: &dyn ClusterServer, + attribute_id: u16, + now: Instant, +) -> Result { + if attribute_id == CLUSTER_REVISION_ATTRIBUTE_ID { + return Ok(AttributeValue::Uint16(cluster.revision())); + } + + attribute_spec(cluster, attribute_id) + .map(|spec| cluster.read(spec.id, now)) + .ok_or(Status::UnsupportedAttribute) +} + +/// ZCL 2.5.1.3: write a status record for each requested attribute. A record that +/// does not fit is replaced by an INSUFFICIENT_SPACE record; when that does not fit +/// either, the response ends there. +pub fn read_attributes( + cluster: &dyn ClusterServer, + request: &ReadAttributes, + now: Instant, + writer: &mut FrameWriter, +) { + for &attribute_id in &request.attribute_ids { + let record = ReadAttributeStatusRecord { + attribute_id, + result: read_attribute(cluster, attribute_id, now), + }; + + if append_record(writer, &record) { + continue; + } + + let record = ReadAttributeStatusRecord { + attribute_id, + result: Err(Status::InsufficientSpace), + }; + + if !append_record(writer, &record) { + return; + } + } +} + +/// Append a whole record or nothing: a record that does not fit leaves no partial +/// bytes behind. +fn append_record(writer: &mut FrameWriter, record: &ReadAttributeStatusRecord) -> bool { + write_frame::(|record_writer| record.serialize(record_writer)) + .is_ok_and(|bytes| writer.extend(&bytes).is_ok()) +} + +/// ZCL 2.5.3.3: the checks of one write record, in the order the spec lists them. +fn check_write(cluster: &dyn ClusterServer, record: &WriteAttributeRecord) -> Result<(), Status> { + let spec = attribute_spec(cluster, record.attribute_id).ok_or(Status::UnsupportedAttribute)?; + + if record.value.data_type() != spec.data_type { + return Err(Status::InvalidDataType); + } + + if spec.access == Access::Read { + return Err(Status::ReadOnly); + } + + cluster.validate(record.attribute_id, &record.value) +} + +/// ZCL 2.5.3.3: write every record that passes its checks. +pub fn write_attributes( + cluster: &mut dyn ClusterServer, + request: WriteAttributes, + now: Instant, +) -> WriteAttributesResponse { + let mut failures = Vec::new(); + + for record in request.records { + match check_write(cluster, &record) { + Ok(()) => cluster.write(record.attribute_id, record.value, now), + Err(status) => failures.push(WriteAttributeStatusRecord { + status, + attribute_id: record.attribute_id, + }), + } + } + + WriteAttributesResponse { failures } +} + +/// ZCL 2.5.4: write every record only if all of them pass their checks. +pub fn write_attributes_undivided( + cluster: &mut dyn ClusterServer, + request: WriteAttributes, + now: Instant, +) -> WriteAttributesResponse { + let failures: Vec = request + .records + .iter() + .filter_map(|record| { + check_write(cluster, record) + .err() + .map(|status| WriteAttributeStatusRecord { + status, + attribute_id: record.attribute_id, + }) + }) + .collect(); + + if failures.is_empty() { + for record in request.records { + cluster.write(record.attribute_id, record.value, now); + } + } + + WriteAttributesResponse { failures } +} + +/// ZCL 2.5.6.3: write every record that passes its checks, and skip the others. +pub fn write_attributes_no_response( + cluster: &mut dyn ClusterServer, + request: WriteAttributes, + now: Instant, +) { + for record in request.records { + if check_write(cluster, &record).is_ok() { + cluster.write(record.attribute_id, record.value, now); + } + } +} + +/// ZCL 2.5.13.3: the attributes from the start identifier on, in ascending order, +/// as many as the request and the frame allow. +pub fn discover_attributes( + cluster: &dyn ClusterServer, + request: &DiscoverAttributes, + writer: &FrameWriter, +) -> DiscoverAttributesResponse { + // The discovery complete flag takes one byte, each record three + let room = writer.remaining().saturating_sub(1) / 3; + let limit = room.min(usize::from(request.maximum_attribute_ids)); + + let mut ids: Vec = cluster + .attributes() + .iter() + .map(|spec| spec.id) + .chain([CLUSTER_REVISION_ATTRIBUTE_ID]) + .filter(|&id| id >= request.start_attribute_id) + .collect(); + ids.sort_unstable(); + + let attributes = ids + .iter() + .take(limit) + .map(|&id| AttributeInformation { + attribute_id: id, + data_type: attribute_spec(cluster, id) + .expect("the identifier came from the cluster") + .data_type, + }) + .collect(); + + DiscoverAttributesResponse { + discovery_complete: ids.len() <= limit, + attributes, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + /// 0x0000 is a read-only uint8 of 7, 0x0001 a writable uint16 up to 100, 0x0002 a + /// read-only 20-byte string. + #[derive(Debug, Default)] + struct TestCluster { + writable: u16, + } + + const ATTRIBUTES: [AttributeSpec; 3] = [ + AttributeSpec { + id: 0x0000, + data_type: DataType::Uint8, + access: Access::Read, + }, + AttributeSpec { + id: 0x0001, + data_type: DataType::Uint16, + access: Access::ReadWrite, + }, + AttributeSpec { + id: 0x0002, + data_type: DataType::CharacterString, + access: Access::Read, + }, + ]; + + impl ClusterServer for TestCluster { + fn cluster_id(&self) -> u16 { + 0xFC00 + } + + fn revision(&self) -> u16 { + 1 + } + + fn attributes(&self) -> &[AttributeSpec] { + &ATTRIBUTES + } + + fn read(&self, attribute_id: u16, _now: Instant) -> AttributeValue { + match attribute_id { + 0x0000 => AttributeValue::Uint8(7), + 0x0001 => AttributeValue::Uint16(self.writable), + _ => AttributeValue::CharacterString(Some(vec![b'x'; 20])), + } + } + + fn validate(&self, _attribute_id: u16, value: &AttributeValue) -> Result<(), Status> { + match value { + AttributeValue::Uint16(value) if *value > 100 => Err(Status::InvalidValue), + _ => Ok(()), + } + } + + fn write(&mut self, _attribute_id: u16, value: AttributeValue, _now: Instant) { + let AttributeValue::Uint16(value) = value else { + unreachable!() + }; + self.writable = value; + } + } + + #[test] + fn read_attributes_falls_back_to_insufficient_space_then_stops() { + let mut buffer = heapless::Vec::::new(); + let mut writer = FrameWriter::new(&mut buffer, 10); + + let request = ReadAttributes { + attribute_ids: vec![0x0000, 0x0002, 0x0003], + }; + read_attributes( + &TestCluster::default(), + &request, + Instant::from_micros(0), + &mut writer, + ); + + assert_eq!( + writer.written(), + [ + // 0x0000: SUCCESS, uint8, 7 + 0x00, 0x00, 0x00, 0x20, 0x07, // 0x0002 does not fit: INSUFFICIENT_SPACE + 0x02, 0x00, + 0x89, + // 0x0003 does not fit even as a status record: the response ends + ] + ); + } + + #[test] + fn write_checks_run_in_spec_order_and_undivided_writes_all_or_nothing() { + let mut cluster = TestCluster::default(); + let record = |attribute_id, value| WriteAttributeRecord { + attribute_id, + value, + }; + let failure = |status, attribute_id| WriteAttributeStatusRecord { + status, + attribute_id, + }; + + let response = write_attributes( + &mut cluster, + WriteAttributes { + records: vec![ + record(0x0009, AttributeValue::Uint8(1)), + // A wrong data type is reported before read-only or range + record(0x0000, AttributeValue::Uint16(1)), + record(0x0000, AttributeValue::Uint8(1)), + record(0x0001, AttributeValue::Uint16(200)), + record(0x0001, AttributeValue::Uint16(50)), + ], + }, + Instant::from_micros(0), + ); + assert_eq!( + response.failures, + [ + failure(Status::UnsupportedAttribute, 0x0009), + failure(Status::InvalidDataType, 0x0000), + failure(Status::ReadOnly, 0x0000), + failure(Status::InvalidValue, 0x0001), + ] + ); + assert_eq!(cluster.writable, 50); + + // One failing record keeps the others from being written + let response = write_attributes_undivided( + &mut cluster, + WriteAttributes { + records: vec![ + record(0x0001, AttributeValue::Uint16(60)), + record(0x0000, AttributeValue::Uint8(1)), + ], + }, + Instant::from_micros(0), + ); + assert_eq!(response.failures, [failure(Status::ReadOnly, 0x0000)]); + assert_eq!(cluster.writable, 50); + } +} diff --git a/crates/ziggurat-zigbee/src/zcl/clusters.rs b/crates/ziggurat-zigbee/src/zcl/clusters.rs new file mode 100644 index 00000000..38883ee0 --- /dev/null +++ b/crates/ziggurat-zigbee/src/zcl/clusters.rs @@ -0,0 +1 @@ +pub mod basic; diff --git a/crates/ziggurat-zigbee/src/zcl/clusters/basic.rs b/crates/ziggurat-zigbee/src/zcl/clusters/basic.rs new file mode 100644 index 00000000..ce59330b --- /dev/null +++ b/crates/ziggurat-zigbee/src/zcl/clusters/basic.rs @@ -0,0 +1,135 @@ +//! The Basic cluster server (ZCL 3.2): what the device is and how it is powered. + +use alloc::vec::Vec; + +use crate::Instant; +use crate::zcl::cluster::{Access, AttributeSpec, ClusterServer}; +use crate::zcl::types::{AttributeValue, DataType}; + +pub const CLUSTER_ID: u16 = 0x0000; + +/// ZCL 3.2.1.1: the newest revision in the cluster's revision history. +const CLUSTER_REVISION: u16 = 3; + +/// The revision of the ZCL this implementation follows. +const ZCL_VERSION: u8 = 8; + +const ZCL_VERSION_ATTRIBUTE_ID: u16 = 0x0000; +const MANUFACTURER_NAME_ATTRIBUTE_ID: u16 = 0x0004; +const MODEL_IDENTIFIER_ATTRIBUTE_ID: u16 = 0x0005; +const DATE_CODE_ATTRIBUTE_ID: u16 = 0x0006; +const POWER_SOURCE_ATTRIBUTE_ID: u16 = 0x0007; +const SW_BUILD_ID_ATTRIBUTE_ID: u16 = 0x4000; + +/// ZCL Table 3-8: the primary power source. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum PowerSource { + Unknown = 0x00, + MainsSinglePhase = 0x01, + MainsThreePhase = 0x02, + Battery = 0x03, + DcSource = 0x04, + EmergencyMainsConstantlyPowered = 0x05, + EmergencyMainsAndTransferSwitch = 0x06, +} + +/// What a device reports about itself. The strings are optional attributes: one left +/// out is not supported, rather than reported empty. +#[derive(Debug, Clone)] +pub struct BasicInfo<'a> { + pub power_source: PowerSource, + /// ZCL 3.2.2.2.8: bit 7 of PowerSource, a battery backing the primary source. + pub battery_backup: bool, + /// At most 32 bytes. + pub manufacturer_name: Option<&'a str>, + /// At most 32 bytes. + pub model_identifier: Option<&'a str>, + /// At most 16 bytes. + pub date_code: Option<&'a str>, + /// At most 16 bytes. + pub sw_build_id: Option<&'a str>, +} + +#[derive(Debug)] +pub struct Basic { + power_source: u8, + /// The string attributes the device reports, by attribute identifier. + strings: Vec<(u16, Vec)>, + attributes: Vec, +} + +impl Basic { + pub fn new(info: &BasicInfo) -> Self { + let strings: Vec<(u16, Vec)> = [ + (MANUFACTURER_NAME_ATTRIBUTE_ID, info.manufacturer_name, 32), + (MODEL_IDENTIFIER_ATTRIBUTE_ID, info.model_identifier, 32), + (DATE_CODE_ATTRIBUTE_ID, info.date_code, 16), + (SW_BUILD_ID_ATTRIBUTE_ID, info.sw_build_id, 16), + ] + .into_iter() + .filter_map(|(id, value, max_length)| { + value.map(|value| { + assert!( + value.len() <= max_length, + "attribute {id:#06x} is longer than {max_length} bytes: {value:?}" + ); + (id, value.as_bytes().to_vec()) + }) + }) + .collect(); + + let mut attributes = Vec::from([ + AttributeSpec { + id: ZCL_VERSION_ATTRIBUTE_ID, + data_type: DataType::Uint8, + access: Access::Read, + }, + AttributeSpec { + id: POWER_SOURCE_ATTRIBUTE_ID, + data_type: DataType::Enum8, + access: Access::Read, + }, + ]); + attributes.extend(strings.iter().map(|&(id, _)| AttributeSpec { + id, + data_type: DataType::CharacterString, + access: Access::Read, + })); + + Self { + power_source: info.power_source as u8 | (u8::from(info.battery_backup) << 7), + strings, + attributes, + } + } +} + +impl ClusterServer for Basic { + fn cluster_id(&self) -> u16 { + CLUSTER_ID + } + + fn revision(&self) -> u16 { + CLUSTER_REVISION + } + + fn attributes(&self) -> &[AttributeSpec] { + &self.attributes + } + + fn read(&self, attribute_id: u16, _now: Instant) -> AttributeValue { + match attribute_id { + ZCL_VERSION_ATTRIBUTE_ID => AttributeValue::Uint8(ZCL_VERSION), + POWER_SOURCE_ATTRIBUTE_ID => AttributeValue::Enum8(self.power_source), + _ => { + let (_, value) = self + .strings + .iter() + .find(|(id, _)| *id == attribute_id) + .expect("only declared attributes are read"); + AttributeValue::CharacterString(Some(value.clone())) + } + } + } +} diff --git a/crates/ziggurat-zigbee/src/zcl/endpoints.rs b/crates/ziggurat-zigbee/src/zcl/endpoints.rs new file mode 100644 index 00000000..fecd12df --- /dev/null +++ b/crates/ziggurat-zigbee/src/zcl/endpoints.rs @@ -0,0 +1,500 @@ +//! The local application endpoints and the ZCL reception rules (ZCL 2.3.2): which +//! endpoints a frame reaches, which commands they carry out, and when a Default +//! Response goes back. + +use alloc::boxed::Box; +use alloc::vec::Vec; +use ziggurat_ieee_802154::types::Nwk; +use ziggurat_ieee_802154::{FrameWriter, write_frame}; + +use super::cluster::{self, ClusterServer, CommandOutcome}; +use super::foundation::{ + DefaultResponse, DiscoverAttributes, GlobalCommandId, ReadAttributes, Status, WriteAttributes, +}; +use super::frame::{Direction, FrameType, ZclHeader}; +use crate::Instant; +use crate::aps::frame::{Asdu, MAX_ASDU_SIZE}; +use crate::crypto::MIC_LENGTH; +use crate::zdp::SimpleDescriptor; + +/// ZCL 2.3.2.1: a frame to this endpoint reaches every endpoint with the cluster. +pub const BROADCAST_ENDPOINT: u8 = 0xFF; + +/// The ASDU room every frame loses to NWK security: the auxiliary header (frame +/// control, frame counter, source address, key sequence number) and the MIC. +const NWK_SECURITY_OVERHEAD: usize = 14 + MIC_LENGTH; + +/// The ASDU room a response mirroring APS security also loses: the auxiliary header +/// with an extended nonce, and the MIC. +const APS_SECURITY_OVERHEAD: usize = 13 + MIC_LENGTH; + +/// One application endpoint the stack serves, with the server side of its clusters. +/// Its client clusters only appear in its simple descriptor. +#[derive(Debug)] +pub struct Endpoint { + pub endpoint: u8, + pub profile_id: u16, + pub device_id: u16, + pub device_version: u8, + pub servers: Vec>, + pub client_clusters: Vec, +} + +impl Endpoint { + /// The descriptor ZDP requests read, derived from the clusters actually served. + pub fn simple_descriptor(&self) -> SimpleDescriptor { + SimpleDescriptor { + endpoint: self.endpoint, + profile_id: self.profile_id, + device_id: self.device_id, + device_version: self.device_version, + input_clusters: self + .servers + .iter() + .map(|server| server.cluster_id()) + .collect(), + output_clusters: self.client_clusters.clone(), + } + } + + fn server(&mut self, cluster_id: u16) -> Option<&mut Box> { + self.servers + .iter_mut() + .find(|server| server.cluster_id() == cluster_id) + } + + fn has_cluster(&self, cluster_id: u16) -> bool { + self.servers + .iter() + .any(|server| server.cluster_id() == cluster_id) + || self.client_clusters.contains(&cluster_id) + } +} + +/// A ZCL frame the APS layer delivered to an endpoint (not a group). +#[derive(Debug, Clone)] +pub struct Indication<'a> { + pub source: Nwk, + pub source_endpoint: u8, + pub destination_endpoint: u8, + pub profile_id: u16, + pub cluster_id: u16, + /// Sent to one device as an APS unicast, rather than broadcast. + pub unicast: bool, + /// Secured with an APS link key, which the response mirrors. + pub aps_secured: bool, + pub asdu: &'a [u8], +} + +/// A ZCL frame to send back to the originator of an indication. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Reply { + pub destination: Nwk, + pub source_endpoint: u8, + pub destination_endpoint: u8, + pub profile_id: u16, + pub cluster_id: u16, + pub asdu: Asdu, +} + +/// What a received command led to, before the Default Response rules apply. +enum Outcome { + /// A response command of its own. + Respond { + frame_type: FrameType, + command_id: u8, + payload: Asdu, + }, + /// No response command: a Default Response may report the status. + Status(Status), + /// Nothing goes back, not even a Default Response. + Silent, +} + +/// The stack's application endpoints. +#[derive(Debug, Default)] +pub struct Endpoints { + /// Sorted by endpoint. + endpoints: Vec, +} + +impl Endpoints { + /// Add an endpoint. Endpoints are set up once, so adding one twice is a bug. + pub fn add(&mut self, endpoint: Endpoint) { + assert!( + (1..=240).contains(&endpoint.endpoint), + "endpoint {} is not an application endpoint", + endpoint.endpoint + ); + + match self + .endpoints + .binary_search_by_key(&endpoint.endpoint, |existing| existing.endpoint) + { + Ok(_) => panic!("endpoint {} is already served", endpoint.endpoint), + Err(index) => self.endpoints.insert(index, endpoint), + } + } + + pub fn contains(&self, endpoint: u8) -> bool { + self.endpoints + .iter() + .any(|existing| existing.endpoint == endpoint) + } + + /// ZCL 2.3.2: carry out a received frame on the endpoints it reaches and return + /// what goes back. A frame for an endpoint we do not serve is not ours. + pub fn receive(&mut self, indication: &Indication, now: Instant) -> Vec { + // A header we cannot parse has no transaction to answer + let Ok((header, payload)) = ZclHeader::parse(indication.asdu) else { + return Vec::new(); + }; + + // ZCL 2.3.2.1: the broadcast endpoint reaches only the endpoints with the + // cluster, and never draws error responses + let broadcast_endpoint = indication.destination_endpoint == BROADCAST_ENDPOINT; + let unicast = indication.unicast && !broadcast_endpoint; + + let room = MAX_ASDU_SIZE + - NWK_SECURITY_OVERHEAD + - if indication.aps_secured { + APS_SECURITY_OVERHEAD + } else { + 0 + }; + + self.endpoints + .iter_mut() + .filter(|endpoint| { + if broadcast_endpoint { + endpoint.has_cluster(indication.cluster_id) + } else { + endpoint.endpoint == indication.destination_endpoint + } + }) + .filter_map(|endpoint| { + let outcome = carry_out(endpoint, indication, &header, payload, room, now); + let (frame_type, command_id, payload) = reply_command(outcome, &header, unicast)?; + + let response = header.response(frame_type, command_id); + let asdu = write_frame::(|writer| { + response.serialize(writer)?; + writer.extend(&payload) + }) + .expect("the response was built to fit"); + + Some(Reply { + destination: indication.source, + source_endpoint: endpoint.endpoint, + destination_endpoint: indication.source_endpoint, + profile_id: indication.profile_id, + cluster_id: indication.cluster_id, + asdu, + }) + }) + .collect() + } +} + +/// ZCL 2.5.12.2: the response command to send, if any. A command's own response goes +/// back however it arrived. A Default Response goes back only for a unicast command, +/// when no other response does, and only when the sender asked for one or the command +/// failed. +fn reply_command( + outcome: Outcome, + header: &ZclHeader, + unicast: bool, +) -> Option<(FrameType, u8, Asdu)> { + match outcome { + Outcome::Silent => None, + // A command sent to many devices draws no Default Response, even in error + Outcome::Status(_) if !unicast => None, + Outcome::Respond { + frame_type, + command_id, + payload, + } => Some((frame_type, command_id, payload)), + Outcome::Status(Status::Success) if header.disable_default_response => None, + Outcome::Status(status) => { + let payload = write_frame(|writer| { + writer.bits(&DefaultResponse { + command_id: header.command_id, + status, + }) + }) + .expect("a Default Response fits"); + Some(( + FrameType::Global, + GlobalCommandId::DefaultResponse as u8, + payload, + )) + } + } +} + +/// Carry out one command on one endpoint. +fn carry_out( + endpoint: &mut Endpoint, + indication: &Indication, + header: &ZclHeader, + payload: &[u8], + room: usize, + now: Instant, +) -> Outcome { + // A Default Response is never answered, whatever it carries (ZCL 2.5.12.2) + if header.frame_type == FrameType::Global + && header.command_id == GlobalCommandId::DefaultResponse as u8 + { + return Outcome::Silent; + } + + // ZCL 2.5.12.2: a cluster the endpoint lacks + if !endpoint.has_cluster(indication.cluster_id) { + return Outcome::Status(Status::UnsupportedCluster); + } + + // We implement no manufacturer specific commands, and serve no client side + if header.manufacturer_code.is_some() || header.direction == Direction::ServerToClient { + return Outcome::Status(Status::UnsupCommand); + } + + let Some(server) = endpoint.server(indication.cluster_id) else { + return Outcome::Status(Status::UnsupCommand); + }; + + // The room left for the payload once the response header is in + let room = room + - if header.manufacturer_code.is_some() { + 5 + } else { + 3 + }; + + match header.frame_type { + FrameType::Global => carry_out_global(&mut **server, header.command_id, payload, room, now), + FrameType::ClusterSpecific => match server.command(header.command_id, payload, now) { + CommandOutcome::Done => Outcome::Status(Status::Success), + CommandOutcome::Failed(status) => Outcome::Status(status), + CommandOutcome::Respond { + command_id, + payload, + } => match Asdu::from_slice(&payload) { + Ok(payload) if payload.len() <= room => Outcome::Respond { + frame_type: FrameType::ClusterSpecific, + command_id, + payload, + }, + _ => Outcome::Status(Status::InsufficientSpace), + }, + }, + } +} + +fn carry_out_global( + server: &mut dyn ClusterServer, + command_id: u8, + payload: &[u8], + room: usize, + now: Instant, +) -> Outcome { + let mut buffer = Asdu::new(); + let mut writer = FrameWriter::new(&mut buffer, room); + + let response = match GlobalCommandId::try_from(command_id) { + Ok(GlobalCommandId::ReadAttributes) => { + let request = ReadAttributes::parse(payload); + cluster::read_attributes(server, &request, now, &mut writer); + GlobalCommandId::ReadAttributesResponse + } + Ok(GlobalCommandId::WriteAttributes) => { + let Ok(request) = WriteAttributes::parse(payload) else { + return Outcome::Status(Status::MalformedCommand); + }; + cluster::write_attributes(server, request, now) + .serialize(&mut writer) + .expect("a write response fits"); + GlobalCommandId::WriteAttributesResponse + } + Ok(GlobalCommandId::WriteAttributesUndivided) => { + let Ok(request) = WriteAttributes::parse(payload) else { + return Outcome::Status(Status::MalformedCommand); + }; + cluster::write_attributes_undivided(server, request, now) + .serialize(&mut writer) + .expect("a write response fits"); + GlobalCommandId::WriteAttributesResponse + } + // ZCL 2.5.6.3: no response of any kind, even to a malformed command + Ok(GlobalCommandId::WriteAttributesNoResponse) => { + if let Ok(request) = WriteAttributes::parse(payload) { + cluster::write_attributes_no_response(server, request, now); + } + return Outcome::Silent; + } + Ok(GlobalCommandId::DiscoverAttributes) => { + let Ok(request) = DiscoverAttributes::parse(payload) else { + return Outcome::Status(Status::MalformedCommand); + }; + cluster::discover_attributes(server, &request, &writer) + .serialize(&mut writer) + .expect("the discovery was sized to fit"); + GlobalCommandId::DiscoverAttributesResponse + } + // Reporting, structured access, command discovery, and the responses to + // commands we never send + _ => return Outcome::Status(Status::UnsupCommand), + }; + + Outcome::Respond { + frame_type: FrameType::Global, + command_id: response as u8, + payload: buffer, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::zcl::clusters::basic::{self, Basic, BasicInfo, PowerSource}; + use alloc::vec; + + const ON_OFF_CLUSTER_ID: u16 = 0x0006; + + fn endpoint(endpoint: u8, client_clusters: Vec) -> Endpoint { + Endpoint { + endpoint, + profile_id: 0x0104, + device_id: 0x0008, + device_version: 0, + servers: vec![Box::new(Basic::new(&BasicInfo { + power_source: PowerSource::MainsSinglePhase, + battery_backup: false, + manufacturer_name: None, + model_identifier: None, + date_code: None, + sw_build_id: None, + }))], + client_clusters, + } + } + + fn receive( + endpoints: &mut Endpoints, + destination_endpoint: u8, + cluster_id: u16, + unicast: bool, + asdu: &[u8], + ) -> Vec<(u8, Vec)> { + let indication = Indication { + source: Nwk(0x0000), + source_endpoint: 1, + destination_endpoint, + profile_id: 0x0104, + cluster_id, + unicast, + aps_secured: false, + asdu, + }; + + endpoints + .receive(&indication, Instant::from_micros(0)) + .into_iter() + .map(|reply| (reply.source_endpoint, reply.asdu.to_vec())) + .collect() + } + + #[test] + fn default_response_only_for_unicast_and_never_beside_another_response() { + let mut endpoints = Endpoints::default(); + endpoints.add(endpoint(1, vec![])); + + // A cluster the endpoint lacks: UNSUPPORTED_CLUSTER, server to client, no + // Default Response asked for in return + let read_on_off = [0x00, 0x10, 0x00, 0x00, 0x00]; + assert_eq!( + receive(&mut endpoints, 1, ON_OFF_CLUSTER_ID, true, &read_on_off), + [(1, vec![0x18, 0x10, 0x0B, 0x00, 0xC3])] + ); + // The same, broadcast: discarded silently + assert_eq!( + receive(&mut endpoints, 1, ON_OFF_CLUSTER_ID, false, &read_on_off), + [] + ); + + // A cluster-specific command Basic does not implement fails even when no + // Default Response was asked for + assert_eq!( + receive( + &mut endpoints, + 1, + basic::CLUSTER_ID, + true, + &[0x11, 0x20, 0x00] + ), + [(1, vec![0x18, 0x20, 0x0B, 0x00, 0x81])] + ); + + // A Read Attributes Response is the only response, even with the Default + // Response asked for. ZCLVersion reads 8 + assert_eq!( + receive( + &mut endpoints, + 1, + basic::CLUSTER_ID, + true, + &[0x00, 0x30, 0x00, 0x00, 0x00] + ), + [(1, vec![0x18, 0x30, 0x01, 0x00, 0x00, 0x00, 0x20, 0x08])] + ); + + // A Default Response is never answered + assert_eq!( + receive( + &mut endpoints, + 1, + basic::CLUSTER_ID, + true, + &[0x00, 0x40, 0x0B, 0x00, 0x81] + ), + [] + ); + } + + #[test] + fn broadcast_endpoint_reaches_only_endpoints_with_the_cluster() { + let mut endpoints = Endpoints::default(); + endpoints.add(endpoint(1, vec![])); + endpoints.add(endpoint(2, vec![ON_OFF_CLUSTER_ID])); + + // Both serve Basic: both answer a read, though it is not unicast + let read_basic = [0x10, 0x50, 0x00, 0x00, 0x00]; + let replies = receive( + &mut endpoints, + BROADCAST_ENDPOINT, + basic::CLUSTER_ID, + true, + &read_basic, + ); + assert_eq!( + replies + .iter() + .map(|(endpoint, _)| *endpoint) + .collect::>(), + [1, 2] + ); + + // Only endpoint 2 has On/Off, as a client: the command is not for its client + // side, but through the broadcast endpoint the error goes unanswered + let read_on_off = [0x00, 0x60, 0x00, 0x00, 0x00]; + assert_eq!( + receive( + &mut endpoints, + BROADCAST_ENDPOINT, + ON_OFF_CLUSTER_ID, + true, + &read_on_off + ), + [] + ); + } +} diff --git a/crates/ziggurat-zigbee/src/zcl/foundation.rs b/crates/ziggurat-zigbee/src/zcl/foundation.rs new file mode 100644 index 00000000..0b5238b2 --- /dev/null +++ b/crates/ziggurat-zigbee/src/zcl/foundation.rs @@ -0,0 +1,228 @@ +//! The ZCL global commands (ZCL 2.5) that a cluster with attributes must support: +//! reading, writing and discovering attributes, and the Default Response. + +use abstract_bits::{AbstractBits, BitReader, abstract_bits}; +use alloc::vec::Vec; +use num_enum::TryFromPrimitive; +use ziggurat_ieee_802154::{FrameWriter, TooLong}; + +use super::types::{AttributeValue, DataType}; +use crate::ParseError; + +/// ZCL Table 2-3: global command identifiers. +#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive)] +#[repr(u8)] +pub enum GlobalCommandId { + ReadAttributes = 0x00, + ReadAttributesResponse = 0x01, + WriteAttributes = 0x02, + WriteAttributesUndivided = 0x03, + WriteAttributesResponse = 0x04, + WriteAttributesNoResponse = 0x05, + ConfigureReporting = 0x06, + ConfigureReportingResponse = 0x07, + ReadReportingConfiguration = 0x08, + ReadReportingConfigurationResponse = 0x09, + ReportAttributes = 0x0A, + DefaultResponse = 0x0B, + DiscoverAttributes = 0x0C, + DiscoverAttributesResponse = 0x0D, + ReadAttributesStructured = 0x0E, + WriteAttributesStructured = 0x0F, + WriteAttributesStructuredResponse = 0x10, + DiscoverCommandsReceived = 0x11, + DiscoverCommandsReceivedResponse = 0x12, + DiscoverCommandsGenerated = 0x13, + DiscoverCommandsGeneratedResponse = 0x14, + DiscoverAttributesExtended = 0x15, + DiscoverAttributesExtendedResponse = 0x16, +} + +/// ZCL Table 2-12 (partial): the status codes that are not deprecated. +#[abstract_bits(bits = 8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Status { + Success = 0x00, + Failure = 0x01, + NotAuthorized = 0x7E, + MalformedCommand = 0x80, + UnsupCommand = 0x81, + InvalidField = 0x85, + UnsupportedAttribute = 0x86, + InvalidValue = 0x87, + ReadOnly = 0x88, + InsufficientSpace = 0x89, + NotFound = 0x8B, + UnreportableAttribute = 0x8C, + InvalidDataType = 0x8D, + InvalidSelector = 0x8E, + Timeout = 0x94, + UnsupportedCluster = 0xC3, +} + +/// ZCL 2.5.1: the attribute identifiers to read. Each takes two bytes; a trailing +/// odd byte is ignored like any appended octets (ZCL 2.3.2). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReadAttributes { + pub attribute_ids: Vec, +} + +impl ReadAttributes { + pub fn parse(payload: &[u8]) -> Self { + Self { + attribute_ids: payload + .as_chunks::<2>() + .0 + .iter() + .map(|&id| u16::from_le_bytes(id)) + .collect(), + } + } +} + +/// ZCL 2.5.2.1: one read attribute status record. The data type and value follow +/// only on success. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReadAttributeStatusRecord { + pub attribute_id: u16, + pub result: Result, +} + +impl ReadAttributeStatusRecord { + pub fn serialize(&self, writer: &mut FrameWriter) -> Result<(), TooLong> { + writer.extend(&self.attribute_id.to_le_bytes())?; + + match &self.result { + Ok(value) => { + writer.bits(&Status::Success)?; + writer.bits(&value.data_type())?; + value.serialize(writer) + } + Err(status) => writer.bits(status), + } + } +} + +/// ZCL 2.5.3: one write attribute record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WriteAttributeRecord { + pub attribute_id: u16, + pub value: AttributeValue, +} + +/// ZCL 2.5.3, 2.5.4, 2.5.6: the records of a Write Attributes command, in any variant. +/// +/// A record of a data type we cannot parse makes the rest of the frame unreadable, so +/// the whole command fails to parse. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WriteAttributes { + pub records: Vec, +} + +impl WriteAttributes { + pub fn parse(mut payload: &[u8]) -> Result { + let mut records = Vec::new(); + + while let Some(([id_low, id_high, data_type], rest)) = payload.split_first_chunk::<3>() { + let data_type = + DataType::try_from(*data_type).map_err(|_| ParseError::InvalidDiscriminant { + ty: "DataType", + got: *data_type, + })?; + let (value, rest) = AttributeValue::parse(data_type, rest)?; + + records.push(WriteAttributeRecord { + attribute_id: u16::from_le_bytes([*id_low, *id_high]), + value, + }); + payload = rest; + } + + Ok(Self { records }) + } +} + +/// ZCL 2.5.5.1: one write attribute status record. +#[abstract_bits] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WriteAttributeStatusRecord { + pub status: Status, + pub attribute_id: u16, +} + +/// ZCL 2.5.5: the failed writes. When every write succeeded the response carries a +/// single SUCCESS status without an attribute identifier (ZCL 2.5.3.3). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WriteAttributesResponse { + pub failures: Vec, +} + +impl WriteAttributesResponse { + pub fn serialize(&self, writer: &mut FrameWriter) -> Result<(), TooLong> { + if self.failures.is_empty() { + return writer.bits(&Status::Success); + } + + for record in &self.failures { + writer.bits(record)?; + } + + Ok(()) + } +} + +/// ZCL 2.5.13. +#[abstract_bits] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DiscoverAttributes { + pub start_attribute_id: u16, + pub maximum_attribute_ids: u8, +} + +impl DiscoverAttributes { + pub fn parse(payload: &[u8]) -> Result { + Ok(Self::read_abstract_bits(&mut BitReader::from(payload))?) + } +} + +/// ZCL 2.5.14.1: one discovered attribute. +#[abstract_bits] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AttributeInformation { + pub attribute_id: u16, + pub data_type: DataType, +} + +/// ZCL 2.5.14. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DiscoverAttributesResponse { + pub discovery_complete: bool, + pub attributes: Vec, +} + +impl DiscoverAttributesResponse { + pub fn serialize(&self, writer: &mut FrameWriter) -> Result<(), TooLong> { + writer.push(u8::from(self.discovery_complete))?; + + for attribute in &self.attributes { + writer.bits(attribute)?; + } + + Ok(()) + } +} + +/// ZCL 2.5.12. +#[abstract_bits] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DefaultResponse { + pub command_id: u8, + pub status: Status, +} + +impl DefaultResponse { + pub fn parse(payload: &[u8]) -> Result { + Ok(Self::read_abstract_bits(&mut BitReader::from(payload))?) + } +} diff --git a/crates/ziggurat-zigbee/src/zcl/frame.rs b/crates/ziggurat-zigbee/src/zcl/frame.rs new file mode 100644 index 00000000..6af153f7 --- /dev/null +++ b/crates/ziggurat-zigbee/src/zcl/frame.rs @@ -0,0 +1,74 @@ +//! The ZCL general frame (ZCL 2.4): a header naming the command and how it was sent, +//! followed by the command's payload. + +use abstract_bits::{AbstractBits, BitReader, abstract_bits}; +use ziggurat_ieee_802154::{FrameWriter, TooLong}; + +use crate::ParseError; + +/// ZCL 2.4.1.1.1: whether the command is one of the global commands or one specific +/// to the cluster. +#[abstract_bits(bits = 2)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum FrameType { + Global = 0b00, + ClusterSpecific = 0b01, +} + +/// ZCL 2.4.1.1.3: which side of the cluster sent the command. +#[abstract_bits(bits = 1)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Direction { + ClientToServer = 0, + ServerToClient = 1, +} + +/// ZCL 2.4.1: the frame control field, the manufacturer code of a manufacturer +/// specific command, the transaction sequence number, and the command identifier. +/// Reserved frame control bits are ignored on receipt (ZCL 2.3.2). +#[abstract_bits] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZclHeader { + pub frame_type: FrameType, + manufacturer_specific: bool, + pub direction: Direction, + pub disable_default_response: bool, + reserved: u3, + #[abstract_bits(presence_from = manufacturer_specific)] + pub manufacturer_code: Option, + pub tsn: u8, + pub command_id: u8, +} + +impl ZclHeader { + /// Split a ZCL frame into its header and payload. Bytes past the payload a + /// command defines are left in the payload, for the command parser to ignore. + pub fn parse(bytes: &[u8]) -> Result<(Self, &[u8]), ParseError> { + let mut reader = BitReader::from(bytes); + let header = Self::read_abstract_bits(&mut reader)?; + Ok((header, &bytes[reader.bytes_read()..])) + } + + /// The header of a frame sent as the immediate effect of this one: the same + /// transaction and manufacturer, the opposite direction, and no Default Response + /// asked for (ZCL 2.4.1.1.4, 2.4.1.3). + pub const fn response(&self, frame_type: FrameType, command_id: u8) -> Self { + Self { + frame_type, + direction: match self.direction { + Direction::ClientToServer => Direction::ServerToClient, + Direction::ServerToClient => Direction::ClientToServer, + }, + disable_default_response: true, + manufacturer_code: self.manufacturer_code, + tsn: self.tsn, + command_id, + } + } + + pub fn serialize(&self, writer: &mut FrameWriter) -> Result<(), TooLong> { + writer.bits(self) + } +} diff --git a/crates/ziggurat-zigbee/src/zcl/types.rs b/crates/ziggurat-zigbee/src/zcl/types.rs new file mode 100644 index 00000000..463ca568 --- /dev/null +++ b/crates/ziggurat-zigbee/src/zcl/types.rs @@ -0,0 +1,173 @@ +//! ZCL data types (ZCL 2.6.2): the type identifiers carried next to attribute values, +//! and the values themselves. Only the types local attributes use are listed. + +use abstract_bits::abstract_bits; +use alloc::vec::Vec; +use num_enum::TryFromPrimitive; +use ziggurat_ieee_802154::{FrameWriter, TooLong}; + +use crate::ParseError; + +/// ZCL Table 2-11: data type identifiers. +#[abstract_bits(bits = 8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive)] +#[repr(u8)] +pub enum DataType { + Bool = 0x10, + Map8 = 0x18, + Map16 = 0x19, + Uint8 = 0x20, + Uint16 = 0x21, + Uint32 = 0x23, + Int8 = 0x28, + Int16 = 0x29, + Enum8 = 0x30, + Enum16 = 0x31, + OctetString = 0x41, + CharacterString = 0x42, +} + +/// An attribute value, tagged with its data type. Multi-byte values are little +/// endian; strings carry a one-byte length (ZCL 2.6.2). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AttributeValue { + Bool(bool), + Map8(u8), + Map16(u16), + Uint8(u8), + Uint16(u16), + Uint32(u32), + Int8(i8), + Int16(i16), + Enum8(u8), + Enum16(u16), + /// `None` is the non-value. + OctetString(Option>), + /// The encoded characters, UTF-8 unless stated otherwise. `None` is the non-value. + CharacterString(Option>), +} + +/// ZCL 2.6.2.13, 2.6.2.14: a string length of 0xFF is the non-value, with no data. +const NON_VALUE_LENGTH: u8 = 0xFF; + +impl AttributeValue { + pub const fn data_type(&self) -> DataType { + match self { + Self::Bool(_) => DataType::Bool, + Self::Map8(_) => DataType::Map8, + Self::Map16(_) => DataType::Map16, + Self::Uint8(_) => DataType::Uint8, + Self::Uint16(_) => DataType::Uint16, + Self::Uint32(_) => DataType::Uint32, + Self::Int8(_) => DataType::Int8, + Self::Int16(_) => DataType::Int16, + Self::Enum8(_) => DataType::Enum8, + Self::Enum16(_) => DataType::Enum16, + Self::OctetString(_) => DataType::OctetString, + Self::CharacterString(_) => DataType::CharacterString, + } + } + + /// Write the value alone, without its data type. + pub fn serialize(&self, writer: &mut FrameWriter) -> Result<(), TooLong> { + match self { + Self::Bool(value) => writer.push(u8::from(*value)), + Self::Map8(value) | Self::Uint8(value) | Self::Enum8(value) => writer.push(*value), + Self::Map16(value) | Self::Uint16(value) | Self::Enum16(value) => { + writer.extend(&value.to_le_bytes()) + } + Self::Uint32(value) => writer.extend(&value.to_le_bytes()), + Self::Int8(value) => writer.extend(&value.to_le_bytes()), + Self::Int16(value) => writer.extend(&value.to_le_bytes()), + Self::OctetString(None) | Self::CharacterString(None) => writer.push(NON_VALUE_LENGTH), + Self::OctetString(Some(bytes)) | Self::CharacterString(Some(bytes)) => { + let length = u8::try_from(bytes.len()) + .ok() + .filter(|&length| length != NON_VALUE_LENGTH) + .ok_or(TooLong)?; + writer.push(length)?; + writer.extend(bytes) + } + } + } + + /// Read a value of the given type off the front of `bytes`, returning it and the + /// bytes after it. + pub fn parse(data_type: DataType, bytes: &[u8]) -> Result<(Self, &[u8]), ParseError> { + Ok(match data_type { + DataType::Bool => { + let ([value], rest) = take(bytes)?; + (Self::Bool(value != 0), rest) + } + DataType::Map8 => { + let ([value], rest) = take(bytes)?; + (Self::Map8(value), rest) + } + DataType::Uint8 => { + let ([value], rest) = take(bytes)?; + (Self::Uint8(value), rest) + } + DataType::Enum8 => { + let ([value], rest) = take(bytes)?; + (Self::Enum8(value), rest) + } + DataType::Int8 => { + let (value, rest) = take(bytes)?; + (Self::Int8(i8::from_le_bytes(value)), rest) + } + DataType::Map16 => { + let (value, rest) = take(bytes)?; + (Self::Map16(u16::from_le_bytes(value)), rest) + } + DataType::Uint16 => { + let (value, rest) = take(bytes)?; + (Self::Uint16(u16::from_le_bytes(value)), rest) + } + DataType::Enum16 => { + let (value, rest) = take(bytes)?; + (Self::Enum16(u16::from_le_bytes(value)), rest) + } + DataType::Int16 => { + let (value, rest) = take(bytes)?; + (Self::Int16(i16::from_le_bytes(value)), rest) + } + DataType::Uint32 => { + let (value, rest) = take(bytes)?; + (Self::Uint32(u32::from_le_bytes(value)), rest) + } + DataType::OctetString => { + let (value, rest) = take_string(bytes)?; + (Self::OctetString(value), rest) + } + DataType::CharacterString => { + let (value, rest) = take_string(bytes)?; + (Self::CharacterString(value), rest) + } + }) + } +} + +fn take(bytes: &[u8]) -> Result<([u8; N], &[u8]), ParseError> { + let (value, rest) = bytes + .split_first_chunk::() + .ok_or(ParseError::UnexpectedEnd { + ty: "AttributeValue", + })?; + Ok((*value, rest)) +} + +/// A string with a one-byte length, or the non-value. +fn take_string(bytes: &[u8]) -> Result<(Option>, &[u8]), ParseError> { + let ([length], rest) = take(bytes)?; + + if length == NON_VALUE_LENGTH { + return Ok((None, rest)); + } + + let (value, rest) = + rest.split_at_checked(usize::from(length)) + .ok_or(ParseError::UnexpectedEnd { + ty: "AttributeValue", + })?; + Ok((Some(value.to_vec()), rest)) +} diff --git a/crates/ziggurat-zigbee/src/zdp.rs b/crates/ziggurat-zigbee/src/zdp.rs index 53f82cbb..86a6c926 100644 --- a/crates/ziggurat-zigbee/src/zdp.rs +++ b/crates/ziggurat-zigbee/src/zdp.rs @@ -2,11 +2,16 @@ use alloc::vec::Vec; use crate::nwk::commands::NwkRejoinCapabilityInformation; -use abstract_bits::{AbstractBits, BitReader, abstract_bits}; +use abstract_bits::{ + AbstractBits, BitReader, BitWriter, FromBytesError, ToBytesError, abstract_bits, +}; use num_enum::TryFromPrimitive; use ziggurat_ieee_802154::types::{Eui64, Nwk}; use ziggurat_ieee_802154::{FrameWriter, TooLong}; +pub mod descriptors; +pub mod nwk_update; + #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum DeserializeError { #[error("Could not deserialize payload to {ty}")] @@ -23,18 +28,35 @@ pub enum DeserializeError { /// endpoints 0 under this profile, with a transaction sequence number prefix. pub const ZDP_PROFILE_ID: u16 = 0x0000; -/// Zigbee spec 2.4.3/2.4.4: ZDP cluster identifiers. Only the clusters the stack -/// itself consumes are listed; everything else is the client's business. +/// Zigbee spec 2.4.3/2.4.4: ZDP cluster identifiers #[derive(Debug, Eq, PartialEq, TryFromPrimitive, Clone, Copy)] #[repr(u16)] pub enum ZdpClusterId { + NwkAddrReq = 0x0000, + IeeeAddrReq = 0x0001, + NodeDescReq = 0x0002, + PowerDescReq = 0x0003, + SimpleDescReq = 0x0004, + ActiveEpReq = 0x0005, + MatchDescReq = 0x0006, DeviceAnnce = 0x0013, ParentAnnce = 0x001F, MgmtLqiReq = 0x0031, MgmtRtgReq = 0x0032, + MgmtBindReq = 0x0033, + MgmtNwkUpdateReq = 0x0038, + NwkAddrRsp = 0x8000, + IeeeAddrRsp = 0x8001, + NodeDescRsp = 0x8002, + PowerDescRsp = 0x8003, + SimpleDescRsp = 0x8004, + ActiveEpRsp = 0x8005, + MatchDescRsp = 0x8006, ParentAnnceRsp = 0x801F, MgmtLqiRsp = 0x8031, MgmtRtgRsp = 0x8032, + MgmtBindRsp = 0x8033, + MgmtNwkUpdateNotify = 0x8038, } /// Zigbee spec Table 2-129 (partial): ZDP response status values. @@ -43,7 +65,335 @@ pub enum ZdpClusterId { #[repr(u8)] pub enum ZdpStatus { Success = 0x00, + InvRequestType = 0x80, + DeviceNotFound = 0x81, + InvalidEp = 0x82, + NotActive = 0x83, NotSupported = 0x84, + NoDescriptor = 0x89, +} + +/// The RequestType of a NWK_addr_req or IEEE_addr_req (spec Table 2-47). +pub const ADDR_REQUEST_SINGLE: u8 = 0x00; +pub const ADDR_REQUEST_EXTENDED: u8 = 0x01; + +/// Zigbee spec 2.4.3.1.1: find the network address of a device by its IEEE address. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct NwkAddrReq { + pub ieee_addr: Eui64, + pub request_type: u8, + pub start_index: u8, +} + +impl ZdpCommand for NwkAddrReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::NwkAddrReq; +} + +/// Zigbee spec 2.4.3.1.2: find the IEEE address of a device by its network address. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct IeeeAddrReq { + pub nwk_addr_of_interest: Nwk, + pub request_type: u8, + pub start_index: u8, +} + +impl ZdpCommand for IeeeAddrReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::IeeeAddrReq; +} + +/// The tail of an extended address response: a page of the network addresses of the +/// responder's end device children. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct AssociatedDevices { + num_assoc_dev: u8, + pub start_index: u8, + #[abstract_bits(length_from = num_assoc_dev)] + pub nwk_addr_assoc_dev_list: Vec, +} + +/// The two address responses share one layout. The associated devices are present +/// only in an extended response, and no field says so: they are present when bytes +/// remain after the addresses. `abstract_bits` cannot express that, so the +/// serialization is written by hand. +macro_rules! address_response { + ($(#[$doc:meta])* $name:ident, $cluster:expr) => { + $(#[$doc])* + #[derive(Debug, Clone, Eq, PartialEq)] + pub struct $name { + pub status: ZdpStatus, + pub ieee_addr_remote_dev: Eui64, + pub nwk_addr_remote_dev: Nwk, + pub associated_devices: Option, + } + + impl AbstractBits for $name { + const MIN_BITS: usize = ZdpStatus::MIN_BITS + Eui64::MIN_BITS + Nwk::MIN_BITS; + const MAX_BITS: usize = Self::MIN_BITS + AssociatedDevices::MAX_BITS; + + fn write_abstract_bits(&self, writer: &mut BitWriter) -> Result<(), ToBytesError> { + self.status.write_abstract_bits(writer)?; + self.ieee_addr_remote_dev.write_abstract_bits(writer)?; + self.nwk_addr_remote_dev.write_abstract_bits(writer)?; + if let Some(associated_devices) = &self.associated_devices { + associated_devices.write_abstract_bits(writer)?; + } + Ok(()) + } + + fn read_abstract_bits(reader: &mut BitReader) -> Result { + let status = ZdpStatus::read_abstract_bits(reader)?; + let ieee_addr_remote_dev = Eui64::read_abstract_bits(reader)?; + let nwk_addr_remote_dev = Nwk::read_abstract_bits(reader)?; + let associated_devices = if reader.remaining_bits() > 0 { + Some(AssociatedDevices::read_abstract_bits(reader)?) + } else { + None + }; + + Ok(Self { + status, + ieee_addr_remote_dev, + nwk_addr_remote_dev, + associated_devices, + }) + } + } + + impl ZdpCommand for $name { + const CLUSTER_ID: ZdpClusterId = $cluster; + } + }; +} + +address_response!( + /// Zigbee spec 2.4.4.2.1: the answer to a NWK_addr_req. + NwkAddrRsp, + ZdpClusterId::NwkAddrRsp +); + +address_response!( + /// Zigbee spec 2.4.4.2.2: the answer to an IEEE_addr_req. + IeeeAddrRsp, + ZdpClusterId::IeeeAddrRsp +); + +/// Zigbee spec 2.4.3.1.3. An R23 sender appends TLVs, which are ignored. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct NodeDescReq { + pub nwk_addr_of_interest: Nwk, +} + +impl ZdpCommand for NodeDescReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::NodeDescReq; +} + +/// Zigbee spec 2.4.3.1.4. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct PowerDescReq { + pub nwk_addr_of_interest: Nwk, +} + +impl ZdpCommand for PowerDescReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::PowerDescReq; +} + +/// Zigbee spec 2.4.3.1.5. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct SimpleDescReq { + pub nwk_addr_of_interest: Nwk, + pub endpoint: u8, +} + +impl ZdpCommand for SimpleDescReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::SimpleDescReq; +} + +/// Zigbee spec 2.4.3.1.6. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct ActiveEpReq { + pub nwk_addr_of_interest: Nwk, +} + +impl ZdpCommand for ActiveEpReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::ActiveEpReq; +} + +/// Zigbee spec 2.4.3.1.7: find the endpoints that serve or use any of the clusters. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct MatchDescReq { + pub nwk_addr_of_interest: Nwk, + pub profile_id: u16, + num_in_clusters: u8, + #[abstract_bits(length_from = num_in_clusters)] + pub in_cluster_list: Vec, + num_out_clusters: u8, + #[abstract_bits(length_from = num_out_clusters)] + pub out_cluster_list: Vec, +} + +impl ZdpCommand for MatchDescReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::MatchDescReq; +} + +/// Zigbee spec Table 2-34: the logical type field of the node descriptor. +#[abstract_bits(bits = 3)] +#[derive(Debug, Eq, PartialEq, Clone, Copy)] +#[repr(u8)] +pub enum LogicalType { + Coordinator = 0b000, + Router = 0b001, + EndDevice = 0b010, +} + +/// Zigbee spec Table 2-35: the frequency band field holds one bit per band. +pub const FREQUENCY_BAND_2400_MHZ: u8 = 0b01000; + +/// Zigbee spec 2.3.2.3.10: the server mask of the node descriptor. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct ServerMask { + pub primary_trust_center: bool, + pub backup_trust_center: bool, + reserved: u4, + pub network_manager: bool, + reserved: u2, + pub stack_compliance_revision: u7, +} + +/// Zigbee spec 2.3.2.3: the node descriptor. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct NodeDescriptor { + pub logical_type: LogicalType, + pub complex_descriptor_available: bool, + pub user_descriptor_available: bool, + reserved: u3, + pub aps_flags: u3, + pub frequency_band: u5, + pub mac_capability_flags: NwkRejoinCapabilityInformation, + pub manufacturer_code: u16, + pub maximum_buffer_size: u8, + pub maximum_incoming_transfer_size: u16, + pub server_mask: ServerMask, + pub maximum_outgoing_transfer_size: u16, + pub descriptor_capability_field: u8, +} + +/// Zigbee spec 2.4.4.2.3. The descriptor is present only on success. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct NodeDescRsp { + pub status: ZdpStatus, + pub nwk_addr_of_interest: Nwk, + #[abstract_bits(presence_from = matches!(status, ZdpStatus::Success))] + pub node_descriptor: Option, +} + +impl ZdpCommand for NodeDescRsp { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::NodeDescRsp; +} + +/// Zigbee spec 2.3.2.4: the power descriptor. Each field is a small enumeration or +/// bitmap; see Tables 2-36 to 2-39 for the values. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct PowerDescriptor { + pub current_power_mode: u4, + pub available_power_sources: u4, + pub current_power_source: u4, + pub current_power_source_level: u4, +} + +/// Zigbee spec 2.4.4.2.4. The descriptor is present only on success. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct PowerDescRsp { + pub status: ZdpStatus, + pub nwk_addr_of_interest: Nwk, + #[abstract_bits(presence_from = matches!(status, ZdpStatus::Success))] + pub power_descriptor: Option, +} + +impl ZdpCommand for PowerDescRsp { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::PowerDescRsp; +} + +/// Zigbee spec 2.3.2.5: the simple descriptor of one endpoint. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct SimpleDescriptor { + pub endpoint: u8, + pub profile_id: u16, + pub device_id: u16, + pub device_version: u4, + reserved: u4, + input_cluster_count: u8, + #[abstract_bits(length_from = input_cluster_count)] + pub input_clusters: Vec, + output_cluster_count: u8, + #[abstract_bits(length_from = output_cluster_count)] + pub output_clusters: Vec, +} + +impl SimpleDescriptor { + /// The serialized length in bytes: the fixed fields, two count bytes, and two + /// bytes per cluster. + pub const fn length(&self) -> u8 { + (8 + 2 * (self.input_clusters.len() + self.output_clusters.len())) as u8 + } +} + +/// Zigbee spec 2.4.4.2.5. `length` is the descriptor's byte length, 0 when absent. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct SimpleDescRsp { + pub status: ZdpStatus, + pub nwk_addr_of_interest: Nwk, + pub length: u8, + #[abstract_bits(presence_from = matches!(status, ZdpStatus::Success))] + pub simple_descriptor: Option, +} + +impl ZdpCommand for SimpleDescRsp { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::SimpleDescRsp; +} + +/// Zigbee spec 2.4.4.2.6. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct ActiveEpRsp { + pub status: ZdpStatus, + pub nwk_addr_of_interest: Nwk, + active_ep_count: u8, + #[abstract_bits(length_from = active_ep_count)] + pub active_ep_list: Vec, +} + +impl ZdpCommand for ActiveEpRsp { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::ActiveEpRsp; +} + +/// Zigbee spec 2.4.4.2.7. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct MatchDescRsp { + pub status: ZdpStatus, + pub nwk_addr_of_interest: Nwk, + match_length: u8, + #[abstract_bits(length_from = match_length)] + pub match_list: Vec, +} + +impl ZdpCommand for MatchDescRsp { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::MatchDescRsp; } pub trait ZdpCommand: AbstractBits + Sized { @@ -236,6 +586,70 @@ impl ZdpCommand for MgmtRtgRsp { const CLUSTER_ID: ZdpClusterId = ZdpClusterId::MgmtRtgRsp; } +/// Zigbee spec 2.4.3.3.4: request a slice of the remote device's binding table. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct MgmtBindReq { + pub start_index: u8, +} + +impl ZdpCommand for MgmtBindReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::MgmtBindReq; +} + +/// Zigbee spec 2.4.4.3.4: a slice of our binding table. We keep no binding table, so +/// the binding descriptor list is always empty and left out. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct MgmtBindRsp { + pub status: ZdpStatus, + pub binding_table_entries: u8, + pub start_index: u8, + pub binding_table_list_count: u8, +} + +impl ZdpCommand for MgmtBindRsp { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::MgmtBindRsp; +} + +/// Zigbee spec 2.4.3.3.9: ask for an energy scan, a channel change, or a new channel +/// mask and network manager, depending on the scan duration. The fields after it are +/// present only for the request they belong to. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct MgmtNwkUpdateReq { + pub scan_channels: u32, + pub scan_duration: u8, + #[abstract_bits(presence_from = matches!(scan_duration, 0x00..=0x05))] + pub scan_count: Option, + #[abstract_bits(presence_from = matches!(scan_duration, 0xFE | 0xFF))] + pub nwk_update_id: Option, + #[abstract_bits(presence_from = matches!(scan_duration, 0xFF))] + pub nwk_manager_addr: Option, +} + +impl ZdpCommand for MgmtNwkUpdateReq { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::MgmtNwkUpdateReq; +} + +/// Zigbee spec 2.4.4.3.9: the result of an energy scan, or the status of a failed +/// Mgmt_NWK_Update_req. +#[abstract_bits] +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct MgmtNwkUpdateNotify { + pub status: ZdpStatus, + pub scanned_channels: u32, + pub total_transmissions: u16, + pub transmission_failures: u16, + scanned_channels_list_count: u8, + #[abstract_bits(length_from = scanned_channels_list_count)] + pub energy_values: Vec, +} + +impl ZdpCommand for MgmtNwkUpdateNotify { + const CLUSTER_ID: ZdpClusterId = ZdpClusterId::MgmtNwkUpdateNotify; +} + /// Spec 2.4.4.3.2 / 2.4.4.3.3: one page of a Mgmt_Lqi_rsp or Mgmt_Rtg_rsp table. /// /// Returns the table size to report and at most `per_frame` records from diff --git a/crates/ziggurat-zigbee/src/zdp/descriptors.rs b/crates/ziggurat-zigbee/src/zdp/descriptors.rs new file mode 100644 index 00000000..827e30c1 --- /dev/null +++ b/crates/ziggurat-zigbee/src/zdp/descriptors.rs @@ -0,0 +1,471 @@ +//! The local node's descriptors (spec 2.3.2), read by ZDP requests from other devices, +//! and the answers to those requests. +//! +//! Each answer is `None` when the request gets no response. A request about a device +//! we know nothing of gets an error status only when it was unicast to us; answering +//! a broadcast with an error would have every router respond. + +use alloc::vec::Vec; + +use ziggurat_ieee_802154::types::{Eui64, Nwk}; + +use super::{ + ADDR_REQUEST_EXTENDED, ADDR_REQUEST_SINGLE, ActiveEpReq, ActiveEpRsp, AssociatedDevices, + FREQUENCY_BAND_2400_MHZ, IeeeAddrReq, IeeeAddrRsp, LogicalType, MatchDescReq, MatchDescRsp, + NodeDescReq, NodeDescRsp, NodeDescriptor, NwkAddrReq, NwkAddrRsp, PowerDescReq, PowerDescRsp, + PowerDescriptor, ServerMask, SimpleDescReq, SimpleDescRsp, SimpleDescriptor, ZdpStatus, +}; +use crate::nwk::NwkDeviceType; +use crate::nwk::commands::{ + NwkRejoinCapabilityInformation, NwkRejoinCapabilityInformationDeviceType, + NwkRejoinCapabilityInformationPowerSource, +}; +use crate::nwk::frame::is_broadcast; +use crate::nwk::neighbors::Neighbors; + +/// The manufacturer code reported when no table entry matches: the Open Home +/// Foundation's. +pub const DEFAULT_MANUFACTURER_CODE: u16 = 0x134B; + +/// The stack compliance revision in our server mask. Joiners read it to decide on the +/// trust center link key exchange (BDB 9.3). +const STACK_COMPLIANCE_REVISION: u8 = 22; + +/// End device child addresses per extended address response, keeping the ASDU within +/// the NWK payload budget. +const ASSOCIATED_DEVICES_PER_FRAME: usize = 30; + +/// Profile ID 0xFFFF in a Match_Desc_req matches every profile (spec 2.4.3.1.7.1). +const WILDCARD_PROFILE_ID: u16 = 0xFFFF; + +/// Spec 2.3.2.4: mains powered, receiver on as the node descriptor says. +const POWER_DESCRIPTOR: PowerDescriptor = PowerDescriptor { + current_power_mode: 0b0000, + available_power_sources: 0b0001, + current_power_source: 0b0001, + current_power_source_level: 0b1100, +}; + +/// A manufacturer code reported to the devices whose EUI64 starts with `prefix`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ManufacturerCode { + /// The leading EUI64 bytes, most significant first, as in `54:EF:44`. An empty + /// prefix matches every device. + pub prefix: Vec, + pub code: u16, +} + +/// The local node as ZDP describes it: its addresses and role, its endpoints, and the +/// manufacturer codes it reports. +#[derive(Debug)] +pub struct Descriptors { + nwk: Nwk, + ieee: Eui64, + role: NwkDeviceType, + /// Sorted by endpoint. + endpoints: Vec, + manufacturer_codes: Vec, +} + +impl Descriptors { + pub const fn new(nwk: Nwk, ieee: Eui64, role: NwkDeviceType) -> Self { + Self { + nwk, + ieee, + role, + endpoints: Vec::new(), + manufacturer_codes: Vec::new(), + } + } + + /// Register an endpoint, replacing an earlier descriptor for the same endpoint. + pub fn add_endpoint(&mut self, descriptor: SimpleDescriptor) { + match self + .endpoints + .binary_search_by_key(&descriptor.endpoint, |existing| existing.endpoint) + { + Ok(index) => self.endpoints[index] = descriptor, + Err(index) => self.endpoints.insert(index, descriptor), + } + } + + /// Replace the whole manufacturer code table. + pub fn set_manufacturer_codes(&mut self, codes: Vec) { + self.manufacturer_codes = codes; + } + + /// The manufacturer code to report to a device: the entry with the longest prefix + /// of its EUI64. A device whose EUI64 is unknown matches only an empty prefix. + #[allow(clippy::option_if_let_else)] + pub fn manufacturer_code(&self, requester: Option) -> u16 { + let requester = requester.map(|eui64| { + let mut bytes = eui64.0; + bytes.reverse(); + bytes + }); + + self.manufacturer_codes + .iter() + .filter(|entry| match requester { + Some(bytes) => bytes.starts_with(&entry.prefix), + None => entry.prefix.is_empty(), + }) + .max_by_key(|entry| entry.prefix.len()) + .map_or(DEFAULT_MANUFACTURER_CODE, |entry| entry.code) + } + + /// Spec 2.3.2.3: our node descriptor. The buffer sizes describe no APS + /// fragmentation. + pub fn node_descriptor(&self, manufacturer_code: u16) -> NodeDescriptor { + NodeDescriptor { + logical_type: match self.role { + NwkDeviceType::Coordinator => LogicalType::Coordinator, + NwkDeviceType::Router => LogicalType::Router, + NwkDeviceType::EndDevice => LogicalType::EndDevice, + }, + complex_descriptor_available: false, + user_descriptor_available: false, + aps_flags: 0, + frequency_band: FREQUENCY_BAND_2400_MHZ, + mac_capability_flags: NwkRejoinCapabilityInformation { + alternate_pan_coordinator: false, + device_type: match self.role { + NwkDeviceType::EndDevice => NwkRejoinCapabilityInformationDeviceType::EndDevice, + NwkDeviceType::Coordinator | NwkDeviceType::Router => { + NwkRejoinCapabilityInformationDeviceType::Router + } + }, + power_source: NwkRejoinCapabilityInformationPowerSource::MainsPowered, + receiver_on_when_idle: true, + reserved1: 0, + reserved2: 0, + security_capability: false, + allocate_address: true, + }, + manufacturer_code, + maximum_buffer_size: 82, + maximum_incoming_transfer_size: 128, + server_mask: ServerMask { + primary_trust_center: self.role == NwkDeviceType::Coordinator, + backup_trust_center: false, + network_manager: false, + stack_compliance_revision: STACK_COMPLIANCE_REVISION, + }, + maximum_outgoing_transfer_size: 128, + descriptor_capability_field: 0, + } + } + + /// Spec 2.4.3.1.1.2: answer for ourselves or for one of our end device children. + pub fn nwk_addr_rsp( + &self, + request: &NwkAddrReq, + neighbors: &Neighbors, + broadcast: bool, + ) -> Option { + let (nwk, is_local) = if request.ieee_addr == self.ieee { + (self.nwk, true) + } else if let Some(nwk) = neighbors.end_device_child_nwk(request.ieee_addr) { + (nwk, false) + } else if broadcast { + return None; + } else { + return Some(NwkAddrRsp { + status: ZdpStatus::DeviceNotFound, + ieee_addr_remote_dev: request.ieee_addr, + nwk_addr_remote_dev: Nwk(0xFFFF), + associated_devices: None, + }); + }; + + if !matches!( + request.request_type, + ADDR_REQUEST_SINGLE | ADDR_REQUEST_EXTENDED + ) { + if broadcast { + return None; + } + + return Some(NwkAddrRsp { + status: ZdpStatus::InvRequestType, + ieee_addr_remote_dev: request.ieee_addr, + nwk_addr_remote_dev: nwk, + associated_devices: None, + }); + } + + Some(NwkAddrRsp { + status: ZdpStatus::Success, + ieee_addr_remote_dev: request.ieee_addr, + nwk_addr_remote_dev: nwk, + associated_devices: address_tail( + neighbors, + request.request_type, + request.start_index, + is_local, + ), + }) + } + + /// Spec 2.4.3.1.2.2: answer for ourselves or for one of our end device children. + pub fn ieee_addr_rsp( + &self, + request: &IeeeAddrReq, + neighbors: &Neighbors, + broadcast: bool, + ) -> Option { + let nwk = request.nwk_addr_of_interest; + + let (ieee, is_local) = if nwk == self.nwk { + (self.ieee, true) + } else if let Some(ieee) = neighbors.end_device_child_eui64(nwk) { + (ieee, false) + } else if broadcast { + return None; + } else { + return Some(IeeeAddrRsp { + status: ZdpStatus::DeviceNotFound, + ieee_addr_remote_dev: Eui64([0xFF; 8]), + nwk_addr_remote_dev: nwk, + associated_devices: None, + }); + }; + + if !matches!( + request.request_type, + ADDR_REQUEST_SINGLE | ADDR_REQUEST_EXTENDED + ) { + if broadcast { + return None; + } + + return Some(IeeeAddrRsp { + status: ZdpStatus::InvRequestType, + ieee_addr_remote_dev: self.ieee, + nwk_addr_remote_dev: self.nwk, + associated_devices: None, + }); + } + + Some(IeeeAddrRsp { + status: ZdpStatus::Success, + ieee_addr_remote_dev: ieee, + nwk_addr_remote_dev: nwk, + associated_devices: address_tail( + neighbors, + request.request_type, + request.start_index, + is_local, + ), + }) + } + + /// Spec 2.4.4.2.3. The manufacturer code depends on the requester (`requester` is + /// its EUI64, if known): some devices finish joining only if they see their own + /// vendor's. + pub fn node_desc_rsp( + &self, + request: &NodeDescReq, + neighbors: &Neighbors, + broadcast: bool, + requester: Option, + ) -> Option { + let nwk = request.nwk_addr_of_interest; + + if nwk == self.nwk { + return Some(NodeDescRsp { + status: ZdpStatus::Success, + nwk_addr_of_interest: nwk, + node_descriptor: Some(self.node_descriptor(self.manufacturer_code(requester))), + }); + } + + (!broadcast).then(|| NodeDescRsp { + status: self.other_device_status(nwk, neighbors), + nwk_addr_of_interest: nwk, + node_descriptor: None, + }) + } + + /// Spec 2.4.4.2.4.1. + pub fn power_desc_rsp( + &self, + request: &PowerDescReq, + neighbors: &Neighbors, + broadcast: bool, + ) -> Option { + let nwk = request.nwk_addr_of_interest; + + if nwk == self.nwk { + return Some(PowerDescRsp { + status: ZdpStatus::Success, + nwk_addr_of_interest: nwk, + power_descriptor: Some(POWER_DESCRIPTOR), + }); + } + + (!broadcast).then(|| PowerDescRsp { + status: self.other_device_status(nwk, neighbors), + nwk_addr_of_interest: nwk, + power_descriptor: None, + }) + } + + /// Spec 2.4.4.2.6.1. We keep no discovery cache, so other devices are not found. + pub fn active_ep_rsp(&self, request: &ActiveEpReq, broadcast: bool) -> Option { + let nwk = request.nwk_addr_of_interest; + + if nwk == self.nwk { + return Some(ActiveEpRsp { + status: ZdpStatus::Success, + nwk_addr_of_interest: nwk, + active_ep_list: self + .endpoints + .iter() + .map(|descriptor| descriptor.endpoint) + .collect(), + }); + } + + (!broadcast).then(|| ActiveEpRsp { + status: if self.role == NwkDeviceType::EndDevice { + ZdpStatus::InvRequestType + } else { + ZdpStatus::DeviceNotFound + }, + nwk_addr_of_interest: nwk, + active_ep_list: Vec::new(), + }) + } + + /// Spec 2.4.4.2.5.1. + #[allow(clippy::option_if_let_else)] + pub fn simple_desc_rsp( + &self, + request: &SimpleDescReq, + neighbors: &Neighbors, + broadcast: bool, + ) -> Option { + let nwk = request.nwk_addr_of_interest; + let failure = |status| SimpleDescRsp { + status, + nwk_addr_of_interest: nwk, + length: 0, + simple_descriptor: None, + }; + + if nwk != self.nwk { + return (!broadcast).then(|| failure(self.other_device_status(nwk, neighbors))); + } + + if !(1..=254).contains(&request.endpoint) { + return Some(failure(ZdpStatus::InvalidEp)); + } + + let descriptor = self + .endpoints + .iter() + .find(|descriptor| descriptor.endpoint == request.endpoint); + + Some(match descriptor { + Some(descriptor) => SimpleDescRsp { + status: ZdpStatus::Success, + nwk_addr_of_interest: nwk, + length: descriptor.length(), + simple_descriptor: Some(descriptor.clone()), + }, + None => failure(ZdpStatus::NotActive), + }) + } + + /// Spec 2.4.4.2.7.1. + pub fn match_desc_rsp( + &self, + request: &MatchDescReq, + neighbors: &Neighbors, + broadcast: bool, + ) -> Option { + let nwk = request.nwk_addr_of_interest; + + if nwk != self.nwk && !is_broadcast(nwk) { + // We keep no descriptors of our children, so nothing of theirs can match + return (!broadcast).then(|| MatchDescRsp { + status: self.other_device_status(nwk, neighbors), + nwk_addr_of_interest: nwk, + match_list: Vec::new(), + }); + } + + let match_list: Vec = self + .endpoints + .iter() + .filter(|descriptor| descriptor_matches(descriptor, request)) + .map(|descriptor| descriptor.endpoint) + .collect(); + + if match_list.is_empty() && broadcast { + return None; + } + + Some(MatchDescRsp { + status: ZdpStatus::Success, + nwk_addr_of_interest: self.nwk, + match_list, + }) + } + + /// The status for a descriptor request about another device (spec 2.4.4.2.4.1). We + /// keep no descriptors of our children. + fn other_device_status(&self, nwk: Nwk, neighbors: &Neighbors) -> ZdpStatus { + if self.role == NwkDeviceType::EndDevice { + ZdpStatus::InvRequestType + } else if neighbors.end_device_child_eui64(nwk).is_some() { + ZdpStatus::NoDescriptor + } else { + ZdpStatus::DeviceNotFound + } + } +} + +/// The associated devices of an address response, if extended: a page of our end +/// device children's addresses. An end device child has none of its own. +fn address_tail( + neighbors: &Neighbors, + request_type: u8, + start_index: u8, + is_local: bool, +) -> Option { + if request_type != ADDR_REQUEST_EXTENDED { + return None; + } + + let page = if is_local { + neighbors + .end_device_child_addresses() + .into_iter() + .skip(usize::from(start_index)) + .take(ASSOCIATED_DEVICES_PER_FRAME) + .collect() + } else { + Vec::new() + }; + + Some(AssociatedDevices { + start_index, + nwk_addr_assoc_dev_list: page, + }) +} + +/// Spec 2.4.4.2.7.2: the profile matches, and any requested input or output cluster +/// is one the endpoint has on the same side. +fn descriptor_matches(descriptor: &SimpleDescriptor, request: &MatchDescReq) -> bool { + (request.profile_id == WILDCARD_PROFILE_ID || request.profile_id == descriptor.profile_id) + && (request + .in_cluster_list + .iter() + .any(|cluster| descriptor.input_clusters.contains(cluster)) + || request + .out_cluster_list + .iter() + .any(|cluster| descriptor.output_clusters.contains(cluster))) +} diff --git a/crates/ziggurat-zigbee/src/zdp/nwk_update.rs b/crates/ziggurat-zigbee/src/zdp/nwk_update.rs new file mode 100644 index 00000000..e59b5776 --- /dev/null +++ b/crates/ziggurat-zigbee/src/zdp/nwk_update.rs @@ -0,0 +1,125 @@ +//! Mgmt_NWK_Update_req on a router (spec 2.4.3.3.9.2): what the request asks for, or +//! why it is refused. + +use alloc::vec::Vec; +use core::ops::RangeInclusive; +use core::time::Duration; +use ziggurat_ieee_802154::types::Nwk; + +use super::{MgmtNwkUpdateNotify, MgmtNwkUpdateReq, ZdpStatus}; + +/// Channel page 0 holds the 2.4 GHz channels 11 to 26, one mask bit each (spec Table +/// 3-7). The five high bits of a mask hold the channel page. +const PAGE_0_CHANNELS: RangeInclusive = 11..=26; +const CHANNEL_PAGE_BITS: u32 = 0xF800_0000; +const CHANNEL_BITS: u32 = !CHANNEL_PAGE_BITS; + +/// 802.15.4 `aBaseSuperframeDuration`, and the 2.4 GHz symbol period. +const BASE_SUPERFRAME_DURATION_SYMBOLS: u64 = 960; +const SYMBOL_PERIOD_MICROS: u64 = 16; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NwkUpdate { + /// Switch to the channel once the request had time to reach the whole network. + ChangeChannel { channel: u8, update_id: u8 }, + /// Store a new channel mask and network manager. + UpdateManager { channel_mask: u32, manager: Nwk }, + /// Measure the energy on each channel, `count` times, reporting each pass. + EnergyScan { + channels: Vec, + duration: Duration, + count: u8, + }, + /// Refuse the request, reporting the status in a Mgmt_NWK_Update_notify. + Reject(ZdpStatus), +} + +impl NwkUpdate { + /// What the request asks for. Scans and refusals are only for a request unicast to + /// us: a broadcast one is dropped instead (spec 2.4.3.3.9.3). + pub fn from_request(request: &MgmtNwkUpdateReq, unicast: bool) -> Option { + let reject = || unicast.then_some(Self::Reject(ZdpStatus::InvRequestType)); + + let channels: Vec = if request.scan_channels & CHANNEL_PAGE_BITS == 0 { + PAGE_0_CHANNELS + .filter(|channel| request.scan_channels & (1 << channel) != 0) + .collect() + } else { + Vec::new() + }; + + match request.scan_duration { + 0xFE => { + let requested = (request.scan_channels & CHANNEL_BITS).count_ones(); + + // Exactly one channel, and one we support + match channels[..] { + [channel] if requested == 1 => Some(Self::ChangeChannel { + channel, + update_id: request + .nwk_update_id + .expect("a channel change carries an update id"), + }), + _ => reject(), + } + } + 0xFF => Some(Self::UpdateManager { + channel_mask: request.scan_channels, + manager: request + .nwk_manager_addr + .expect("a manager update carries the manager"), + }), + exponent @ 0x00..=0x05 => { + if !unicast { + return None; + } + + if channels.is_empty() { + return reject(); + } + + let symbols = BASE_SUPERFRAME_DURATION_SYMBOLS * ((1 << exponent) + 1); + Some(Self::EnergyScan { + channels, + duration: Duration::from_micros(symbols * SYMBOL_PERIOD_MICROS), + count: request + .scan_count + .expect("a scan request carries a scan count"), + }) + } + _ => reject(), + } + } +} + +/// The notify refusing a request. +pub const fn rejection(status: ZdpStatus) -> MgmtNwkUpdateNotify { + MgmtNwkUpdateNotify { + status, + scanned_channels: 0, + total_transmissions: 0, + transmission_failures: 0, + energy_values: Vec::new(), + } +} + +/// The notify reporting one energy scan pass: one energy value per scanned channel, +/// in ascending channel order. +pub fn scan_report( + channels: &[u8], + energy_values: Vec, + total_transmissions: u16, +) -> MgmtNwkUpdateNotify { + MgmtNwkUpdateNotify { + status: ZdpStatus::Success, + scanned_channels: channels + .iter() + .fold(0, |mask, channel| mask | (1 << channel)), + total_transmissions, + // TODO: the spec sums the neighbor table's TransmitFailure counters here + // (frequency agility annex). Ours are kept but never read, and zigpy ignores + // this field: sum them, or drop the dead counters + transmission_failures: 0, + energy_values, + } +}