Skip to main content

zigbee_zdo/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(
3    not(test),
4    deny(
5        clippy::indexing_slicing,
6        clippy::unwrap_used,
7        clippy::expect_used,
8        clippy::panic
9    )
10)]
11
12use zigbee_primitives::wire::{Reader, Truncated, Writer};
13use zigbee_primitives::{ExtPanId, Ieee, NodeId};
14
15/// ZDO cluster ids. A response's id is its request's with bit 15 set.
16pub mod cluster {
17    #![allow(missing_docs)]
18    pub const NWK_ADDR_REQ: u16 = 0x0000;
19    pub const IEEE_ADDR_REQ: u16 = 0x0001;
20    pub const NODE_DESC_REQ: u16 = 0x0002;
21    pub const POWER_DESC_REQ: u16 = 0x0003;
22    pub const SIMPLE_DESC_REQ: u16 = 0x0004;
23    pub const ACTIVE_EP_REQ: u16 = 0x0005;
24    pub const MATCH_DESC_REQ: u16 = 0x0006;
25    pub const DEVICE_ANNCE: u16 = 0x0013;
26    pub const BIND_REQ: u16 = 0x0021;
27    pub const UNBIND_REQ: u16 = 0x0022;
28    pub const MGMT_LQI_REQ: u16 = 0x0031;
29    pub const MGMT_RTG_REQ: u16 = 0x0032;
30    pub const MGMT_BIND_REQ: u16 = 0x0033;
31    pub const MGMT_LEAVE_REQ: u16 = 0x0034;
32    pub const MGMT_PERMIT_JOINING_REQ: u16 = 0x0036;
33    pub const MGMT_NWK_UPDATE_REQ: u16 = 0x0038;
34    pub const NWK_ADDR_RSP: u16 = 0x8000;
35    pub const IEEE_ADDR_RSP: u16 = 0x8001;
36    pub const NODE_DESC_RSP: u16 = 0x8002;
37    pub const POWER_DESC_RSP: u16 = 0x8003;
38    pub const SIMPLE_DESC_RSP: u16 = 0x8004;
39    pub const ACTIVE_EP_RSP: u16 = 0x8005;
40    pub const MATCH_DESC_RSP: u16 = 0x8006;
41    pub const BIND_RSP: u16 = 0x8021;
42    pub const UNBIND_RSP: u16 = 0x8022;
43    pub const MGMT_LQI_RSP: u16 = 0x8031;
44    pub const MGMT_RTG_RSP: u16 = 0x8032;
45    pub const MGMT_BIND_RSP: u16 = 0x8033;
46    pub const MGMT_LEAVE_RSP: u16 = 0x8034;
47    pub const MGMT_PERMIT_JOINING_RSP: u16 = 0x8036;
48    pub const MGMT_NWK_UPDATE_NOTIFY: u16 = 0x8038;
49}
50
51/// ZDO status codes.
52pub mod status {
53    #![allow(missing_docs)]
54    pub const SUCCESS: u8 = 0x00;
55    pub const INV_REQUESTTYPE: u8 = 0x80;
56    pub const DEVICE_NOT_FOUND: u8 = 0x81;
57    pub const INVALID_EP: u8 = 0x82;
58    pub const NOT_ACTIVE: u8 = 0x83;
59    pub const NOT_SUPPORTED: u8 = 0x84;
60    pub const TIMEOUT: u8 = 0x85;
61    pub const NO_MATCH: u8 = 0x86;
62    pub const NO_ENTRY: u8 = 0x88;
63    pub const NO_DESCRIPTOR: u8 = 0x89;
64    pub const INSUFFICIENT_SPACE: u8 = 0x8A;
65    pub const NOT_PERMITTED: u8 = 0x8B;
66    pub const TABLE_FULL: u8 = 0x8C;
67    pub const NOT_AUTHORIZED: u8 = 0x8D;
68}
69
70/// The ZDO profile id.
71pub const PROFILE_ID: u16 = 0x0000;
72/// The ZDO endpoint.
73pub const ENDPOINT: u8 = 0x00;
74
75/// A ZDO frame did not decode.
76#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
77pub enum Error {
78    /// Too short.
79    #[error(transparent)]
80    Truncated(#[from] Truncated),
81    /// Bytes left over.
82    #[error("{0} trailing bytes")]
83    Trailing(usize),
84    /// A bind address mode other than group (1) or extended (3).
85    #[error("bind address mode {0} is not 1 or 3")]
86    AddressMode(u8),
87}
88
89/// The node descriptor (2.3.2.3).
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
91#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
92pub struct NodeDescriptor {
93    /// Logical type (bits 0-2), complex/user descriptor flags (bits 3-4).
94    pub byte0: u8,
95    /// APS flags (bits 0-2) and frequency band (bits 3-7).
96    pub byte1: u8,
97    /// MAC capability flags.
98    pub mac_capabilities: u8,
99    /// Manufacturer code.
100    pub manufacturer_code: u16,
101    /// Maximum NSDU size.
102    pub max_buffer_size: u8,
103    /// Maximum incoming transfer size.
104    pub max_incoming_transfer: u16,
105    /// Server mask (bits 9-15: stack compliance revision).
106    pub server_mask: u16,
107    /// Maximum outgoing transfer size.
108    pub max_outgoing_transfer: u16,
109    /// Descriptor capability field.
110    pub descriptor_capability: u8,
111}
112
113/// A device's logical type.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115#[cfg_attr(
116    feature = "serde",
117    derive(serde::Serialize, serde::Deserialize),
118    serde(rename_all = "snake_case")
119)]
120pub enum LogicalType {
121    /// The coordinator.
122    Coordinator,
123    /// A router.
124    Router,
125    /// An end device.
126    EndDevice,
127    /// A reserved value.
128    Reserved(u8),
129}
130
131impl NodeDescriptor {
132    /// The device's logical type.
133    pub fn logical_type(&self) -> LogicalType {
134        match self.byte0 & 0x07 {
135            0 => LogicalType::Coordinator,
136            1 => LogicalType::Router,
137            2 => LogicalType::EndDevice,
138            other => LogicalType::Reserved(other),
139        }
140    }
141
142    /// The receiver is on when idle (not a sleepy device).
143    pub fn rx_on_when_idle(&self) -> bool {
144        self.mac_capabilities & 0x08 != 0
145    }
146
147    /// Mains powered.
148    pub fn mains_powered(&self) -> bool {
149        self.mac_capabilities & 0x04 != 0
150    }
151
152    /// The stack compliance revision (21 and later for Zigbee 3.0
153    /// devices; 0 for pre-R21 devices).
154    pub fn stack_compliance_revision(&self) -> u8 {
155        (self.server_mask >> 9) as u8
156    }
157
158    fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
159        Ok(NodeDescriptor {
160            byte0: r.u8()?,
161            byte1: r.u8()?,
162            mac_capabilities: r.u8()?,
163            manufacturer_code: r.u16()?,
164            max_buffer_size: r.u8()?,
165            max_incoming_transfer: r.u16()?,
166            server_mask: r.u16()?,
167            max_outgoing_transfer: r.u16()?,
168            descriptor_capability: r.u8()?,
169        })
170    }
171
172    fn write(&self, w: &mut Vec<u8>) {
173        w.put_u8(self.byte0);
174        w.put_u8(self.byte1);
175        w.put_u8(self.mac_capabilities);
176        w.put_u16(self.manufacturer_code);
177        w.put_u8(self.max_buffer_size);
178        w.put_u16(self.max_incoming_transfer);
179        w.put_u16(self.server_mask);
180        w.put_u16(self.max_outgoing_transfer);
181        w.put_u8(self.descriptor_capability);
182    }
183}
184
185/// A simple descriptor: one endpoint and its clusters (2.3.2.5).
186#[derive(Debug, Clone, PartialEq, Eq, Default)]
187#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
188pub struct SimpleDescriptor {
189    /// Endpoint, 1 to 240.
190    pub endpoint: u8,
191    /// Application profile.
192    pub profile_id: u16,
193    /// Device id within the profile.
194    pub device_id: u16,
195    /// Device version (low 4 bits).
196    pub device_version: u8,
197    /// Server (input) clusters.
198    pub input_clusters: Vec<u16>,
199    /// Client (output) clusters.
200    pub output_clusters: Vec<u16>,
201}
202
203impl SimpleDescriptor {
204    fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
205        let endpoint = r.u8()?;
206        let profile_id = r.u16()?;
207        let device_id = r.u16()?;
208        let device_version = r.u8()?;
209        let inputs = usize::from(r.u8()?);
210        let input_clusters = r.u16_list(inputs)?;
211        let outputs = usize::from(r.u8()?);
212        let output_clusters = r.u16_list(outputs)?;
213        Ok(SimpleDescriptor {
214            endpoint,
215            profile_id,
216            device_id,
217            device_version,
218            input_clusters,
219            output_clusters,
220        })
221    }
222
223    fn write(&self, w: &mut Vec<u8>) {
224        w.put_u8(self.endpoint);
225        w.put_u16(self.profile_id);
226        w.put_u16(self.device_id);
227        w.put_u8(self.device_version);
228        w.put_u8(self.input_clusters.len().min(255) as u8);
229        self.input_clusters
230            .iter()
231            .take(255)
232            .for_each(|c| w.put_u16(*c));
233        w.put_u8(self.output_clusters.len().min(255) as u8);
234        self.output_clusters
235            .iter()
236            .take(255)
237            .for_each(|c| w.put_u16(*c));
238    }
239}
240
241/// A neighbor table entry, from `Mgmt_Lqi_rsp`.
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
244pub struct Neighbor {
245    /// The neighbor's extended PAN id.
246    pub extended_pan_id: ExtPanId,
247    /// Its IEEE address.
248    pub ieee: Ieee,
249    /// Its network address.
250    pub nwk: NodeId,
251    /// Device type (bits 0-1), rx on when idle (2-3), relationship (4-6).
252    pub flags: u8,
253    /// Permit joining (bits 0-1).
254    pub permit_joining: u8,
255    /// Tree depth.
256    pub depth: u8,
257    /// Link quality.
258    pub lqi: u8,
259}
260
261impl Neighbor {
262    /// 0 coordinator, 1 router, 2 end device, 3 unknown.
263    pub fn device_type(&self) -> u8 {
264        self.flags & 0x03
265    }
266
267    /// 0 parent, 1 child, 2 sibling, 3 none, 4 previous child.
268    pub fn relationship(&self) -> u8 {
269        (self.flags >> 4) & 0x07
270    }
271}
272
273/// A routing table entry, from `Mgmt_Rtg_rsp`.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
276pub struct Route {
277    /// Destination.
278    pub destination: NodeId,
279    /// Status (bits 0-2) and flags.
280    pub flags: u8,
281    /// Next hop.
282    pub next_hop: NodeId,
283}
284
285/// Where a binding points.
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287#[cfg_attr(
288    feature = "serde",
289    derive(serde::Serialize, serde::Deserialize),
290    serde(rename_all = "snake_case")
291)]
292pub enum BindTarget {
293    /// A group.
294    Group(u16),
295    /// A device's endpoint.
296    Endpoint {
297        /// The device.
298        ieee: Ieee,
299        /// Its endpoint.
300        endpoint: u8,
301    },
302}
303
304impl BindTarget {
305    fn read(r: &mut Reader<'_>) -> Result<Self, Error> {
306        match r.u8()? {
307            0x01 => Ok(BindTarget::Group(r.u16()?)),
308            0x03 => Ok(BindTarget::Endpoint {
309                ieee: r.ieee()?,
310                endpoint: r.u8()?,
311            }),
312            other => Err(Error::AddressMode(other)),
313        }
314    }
315
316    fn write(&self, w: &mut Vec<u8>) {
317        match self {
318            BindTarget::Group(g) => {
319                w.put_u8(0x01);
320                w.put_u16(*g);
321            }
322            BindTarget::Endpoint { ieee, endpoint } => {
323                w.put_u8(0x03);
324                w.put_ieee(*ieee);
325                w.put_u8(*endpoint);
326            }
327        }
328    }
329}
330
331/// A binding table entry.
332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
333#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
334pub struct Binding {
335    /// Source device.
336    pub source: Ieee,
337    /// Source endpoint.
338    pub source_endpoint: u8,
339    /// Cluster.
340    pub cluster: u16,
341    /// Destination.
342    pub target: BindTarget,
343}
344
345/// Address list in `NWK_addr_rsp` / `IEEE_addr_rsp` (extended requests).
346#[derive(Debug, Clone, PartialEq, Eq)]
347pub struct AssociatedDevices {
348    /// Index of the first address.
349    pub start_index: u8,
350    /// Network addresses of associated devices.
351    pub addresses: Vec<NodeId>,
352}
353
354/// A ZDO frame body.
355#[derive(Debug, Clone, PartialEq, Eq)]
356#[allow(missing_docs)]
357pub enum Body {
358    NwkAddrReq {
359        ieee: Ieee,
360        request_type: u8,
361        start_index: u8,
362    },
363    IeeeAddrReq {
364        nwk: NodeId,
365        request_type: u8,
366        start_index: u8,
367    },
368    NodeDescReq {
369        nwk: NodeId,
370    },
371    PowerDescReq {
372        nwk: NodeId,
373    },
374    SimpleDescReq {
375        nwk: NodeId,
376        endpoint: u8,
377    },
378    ActiveEpReq {
379        nwk: NodeId,
380    },
381    MatchDescReq {
382        nwk: NodeId,
383        profile_id: u16,
384        input_clusters: Vec<u16>,
385        output_clusters: Vec<u16>,
386    },
387    DeviceAnnce {
388        nwk: NodeId,
389        ieee: Ieee,
390        capability: u8,
391    },
392    BindReq(Binding),
393    UnbindReq(Binding),
394    MgmtLqiReq {
395        start_index: u8,
396    },
397    MgmtRtgReq {
398        start_index: u8,
399    },
400    MgmtBindReq {
401        start_index: u8,
402    },
403    MgmtLeaveReq {
404        ieee: Ieee,
405        flags: u8,
406    },
407    MgmtPermitJoiningReq {
408        duration: u8,
409        tc_significance: u8,
410    },
411    MgmtNwkUpdateReq {
412        channel_mask: u32,
413        scan_duration: u8,
414        scan_count: Option<u8>,
415        nwk_update_id: Option<u8>,
416        manager: Option<NodeId>,
417    },
418    NwkAddrRsp {
419        status: u8,
420        ieee: Ieee,
421        nwk: NodeId,
422        associated: Option<AssociatedDevices>,
423    },
424    IeeeAddrRsp {
425        status: u8,
426        ieee: Ieee,
427        nwk: NodeId,
428        associated: Option<AssociatedDevices>,
429    },
430    NodeDescRsp {
431        status: u8,
432        nwk: NodeId,
433        descriptor: Option<NodeDescriptor>,
434    },
435    PowerDescRsp {
436        status: u8,
437        nwk: NodeId,
438        descriptor: Option<u16>,
439    },
440    SimpleDescRsp {
441        status: u8,
442        nwk: NodeId,
443        descriptor: Option<SimpleDescriptor>,
444    },
445    ActiveEpRsp {
446        status: u8,
447        nwk: NodeId,
448        endpoints: Vec<u8>,
449    },
450    MatchDescRsp {
451        status: u8,
452        nwk: NodeId,
453        endpoints: Vec<u8>,
454    },
455    BindRsp {
456        status: u8,
457    },
458    UnbindRsp {
459        status: u8,
460    },
461    MgmtLqiRsp {
462        status: u8,
463        total: u8,
464        start_index: u8,
465        neighbors: Vec<Neighbor>,
466    },
467    MgmtRtgRsp {
468        status: u8,
469        total: u8,
470        start_index: u8,
471        routes: Vec<Route>,
472    },
473    MgmtBindRsp {
474        status: u8,
475        total: u8,
476        start_index: u8,
477        bindings: Vec<Binding>,
478    },
479    MgmtLeaveRsp {
480        status: u8,
481    },
482    MgmtPermitJoiningRsp {
483        status: u8,
484    },
485    MgmtNwkUpdateNotify {
486        status: u8,
487        scanned_channels: u32,
488        total_transmissions: u16,
489        transmission_failures: u16,
490        energy: Vec<u8>,
491    },
492    /// A cluster this crate does not decode.
493    Other {
494        cluster: u16,
495        payload: Vec<u8>,
496    },
497}
498
499/// A ZDO frame.
500#[derive(Debug, Clone, PartialEq, Eq)]
501pub struct Message {
502    /// Transaction sequence number, echoed in the response.
503    pub tsn: u8,
504    /// The body.
505    pub body: Body,
506}
507
508fn read_binding(r: &mut Reader<'_>) -> Result<Binding, Error> {
509    Ok(Binding {
510        source: r.ieee()?,
511        source_endpoint: r.u8()?,
512        cluster: r.u16()?,
513        target: BindTarget::read(r)?,
514    })
515}
516
517fn write_binding(b: &Binding, w: &mut Vec<u8>) {
518    w.put_ieee(b.source);
519    w.put_u8(b.source_endpoint);
520    w.put_u16(b.cluster);
521    b.target.write(w);
522}
523
524fn read_list8(r: &mut Reader<'_>) -> Result<Vec<u8>, Truncated> {
525    let n = usize::from(r.u8()?);
526    Ok(r.bytes(n)?.to_vec())
527}
528
529fn read_associated(r: &mut Reader<'_>) -> Result<Option<AssociatedDevices>, Truncated> {
530    if r.is_empty() {
531        return Ok(None);
532    }
533    let count = usize::from(r.u8()?);
534    let start_index = r.u8()?;
535    Ok(Some(AssociatedDevices {
536        start_index,
537        addresses: r.u16_list(count)?,
538    }))
539}
540
541fn write_associated(a: &Option<AssociatedDevices>, w: &mut Vec<u8>) {
542    if let Some(a) = a {
543        w.put_u8(a.addresses.len().min(255) as u8);
544        w.put_u8(a.start_index);
545        a.addresses.iter().take(255).for_each(|n| w.put_u16(*n));
546    }
547}
548
549/// Read a table header and `count` entries, bounding the allocation by
550/// the input.
551fn read_table<T>(
552    r: &mut Reader<'_>,
553    entry_size: usize,
554    mut read: impl FnMut(&mut Reader<'_>) -> Result<T, Error>,
555) -> Result<(u8, u8, u8, Vec<T>), Error> {
556    let status = r.u8()?;
557    if r.is_empty() {
558        return Ok((status, 0, 0, Vec::new()));
559    }
560    let total = r.u8()?;
561    let start = r.u8()?;
562    let count = usize::from(r.u8()?);
563    let mut entries = Vec::with_capacity(count.min(r.remaining() / entry_size.max(1)));
564    for _ in 0..count {
565        entries.push(read(r)?);
566    }
567    Ok((status, total, start, entries))
568}
569
570impl Message {
571    /// The cluster id for this body.
572    pub fn cluster(&self) -> u16 {
573        use crate::cluster as c;
574        match &self.body {
575            Body::NwkAddrReq { .. } => c::NWK_ADDR_REQ,
576            Body::IeeeAddrReq { .. } => c::IEEE_ADDR_REQ,
577            Body::NodeDescReq { .. } => c::NODE_DESC_REQ,
578            Body::PowerDescReq { .. } => c::POWER_DESC_REQ,
579            Body::SimpleDescReq { .. } => c::SIMPLE_DESC_REQ,
580            Body::ActiveEpReq { .. } => c::ACTIVE_EP_REQ,
581            Body::MatchDescReq { .. } => c::MATCH_DESC_REQ,
582            Body::DeviceAnnce { .. } => c::DEVICE_ANNCE,
583            Body::BindReq(_) => c::BIND_REQ,
584            Body::UnbindReq(_) => c::UNBIND_REQ,
585            Body::MgmtLqiReq { .. } => c::MGMT_LQI_REQ,
586            Body::MgmtRtgReq { .. } => c::MGMT_RTG_REQ,
587            Body::MgmtBindReq { .. } => c::MGMT_BIND_REQ,
588            Body::MgmtLeaveReq { .. } => c::MGMT_LEAVE_REQ,
589            Body::MgmtPermitJoiningReq { .. } => c::MGMT_PERMIT_JOINING_REQ,
590            Body::MgmtNwkUpdateReq { .. } => c::MGMT_NWK_UPDATE_REQ,
591            Body::NwkAddrRsp { .. } => c::NWK_ADDR_RSP,
592            Body::IeeeAddrRsp { .. } => c::IEEE_ADDR_RSP,
593            Body::NodeDescRsp { .. } => c::NODE_DESC_RSP,
594            Body::PowerDescRsp { .. } => c::POWER_DESC_RSP,
595            Body::SimpleDescRsp { .. } => c::SIMPLE_DESC_RSP,
596            Body::ActiveEpRsp { .. } => c::ACTIVE_EP_RSP,
597            Body::MatchDescRsp { .. } => c::MATCH_DESC_RSP,
598            Body::BindRsp { .. } => c::BIND_RSP,
599            Body::UnbindRsp { .. } => c::UNBIND_RSP,
600            Body::MgmtLqiRsp { .. } => c::MGMT_LQI_RSP,
601            Body::MgmtRtgRsp { .. } => c::MGMT_RTG_RSP,
602            Body::MgmtBindRsp { .. } => c::MGMT_BIND_RSP,
603            Body::MgmtLeaveRsp { .. } => c::MGMT_LEAVE_RSP,
604            Body::MgmtPermitJoiningRsp { .. } => c::MGMT_PERMIT_JOINING_RSP,
605            Body::MgmtNwkUpdateNotify { .. } => c::MGMT_NWK_UPDATE_NOTIFY,
606            Body::Other { cluster, .. } => *cluster,
607        }
608    }
609
610    /// The status of a response body.
611    pub fn status(&self) -> Option<u8> {
612        match &self.body {
613            Body::NwkAddrRsp { status, .. }
614            | Body::IeeeAddrRsp { status, .. }
615            | Body::NodeDescRsp { status, .. }
616            | Body::PowerDescRsp { status, .. }
617            | Body::SimpleDescRsp { status, .. }
618            | Body::ActiveEpRsp { status, .. }
619            | Body::MatchDescRsp { status, .. }
620            | Body::BindRsp { status }
621            | Body::UnbindRsp { status }
622            | Body::MgmtLqiRsp { status, .. }
623            | Body::MgmtRtgRsp { status, .. }
624            | Body::MgmtBindRsp { status, .. }
625            | Body::MgmtLeaveRsp { status }
626            | Body::MgmtPermitJoiningRsp { status }
627            | Body::MgmtNwkUpdateNotify { status, .. } => Some(*status),
628            _ => None,
629        }
630    }
631
632    /// Parse a ZDO frame of `cluster` (tsn first).
633    pub fn parse(cluster: u16, data: &[u8]) -> Result<Message, Error> {
634        use crate::cluster as c;
635        let mut r = Reader::new(data);
636        let tsn = r.u8()?;
637        let body = match cluster {
638            c::NWK_ADDR_REQ => Body::NwkAddrReq {
639                ieee: r.ieee()?,
640                request_type: r.u8()?,
641                start_index: r.u8()?,
642            },
643            c::IEEE_ADDR_REQ => Body::IeeeAddrReq {
644                nwk: r.u16()?,
645                request_type: r.u8()?,
646                start_index: r.u8()?,
647            },
648            c::NODE_DESC_REQ => Body::NodeDescReq { nwk: r.u16()? },
649            c::POWER_DESC_REQ => Body::PowerDescReq { nwk: r.u16()? },
650            c::SIMPLE_DESC_REQ => Body::SimpleDescReq {
651                nwk: r.u16()?,
652                endpoint: r.u8()?,
653            },
654            c::ACTIVE_EP_REQ => Body::ActiveEpReq { nwk: r.u16()? },
655            c::MATCH_DESC_REQ => {
656                let nwk = r.u16()?;
657                let profile_id = r.u16()?;
658                let n = usize::from(r.u8()?);
659                let input_clusters = r.u16_list(n)?;
660                let n = usize::from(r.u8()?);
661                Body::MatchDescReq {
662                    nwk,
663                    profile_id,
664                    input_clusters,
665                    output_clusters: r.u16_list(n)?,
666                }
667            }
668            c::DEVICE_ANNCE => Body::DeviceAnnce {
669                nwk: r.u16()?,
670                ieee: r.ieee()?,
671                capability: r.u8()?,
672            },
673            c::BIND_REQ => Body::BindReq(read_binding(&mut r)?),
674            c::UNBIND_REQ => Body::UnbindReq(read_binding(&mut r)?),
675            c::MGMT_LQI_REQ => Body::MgmtLqiReq {
676                start_index: r.u8()?,
677            },
678            c::MGMT_RTG_REQ => Body::MgmtRtgReq {
679                start_index: r.u8()?,
680            },
681            c::MGMT_BIND_REQ => Body::MgmtBindReq {
682                start_index: r.u8()?,
683            },
684            c::MGMT_LEAVE_REQ => Body::MgmtLeaveReq {
685                ieee: r.ieee()?,
686                flags: r.u8()?,
687            },
688            c::MGMT_PERMIT_JOINING_REQ => Body::MgmtPermitJoiningReq {
689                duration: r.u8()?,
690                tc_significance: r.u8()?,
691            },
692            c::MGMT_NWK_UPDATE_REQ => {
693                let channel_mask = r.u32()?;
694                let scan_duration = r.u8()?;
695                let scan_count = if scan_duration <= 5 {
696                    Some(r.u8()?)
697                } else {
698                    None
699                };
700                let nwk_update_id = if scan_duration >= 0xFE {
701                    Some(r.u8()?)
702                } else {
703                    None
704                };
705                let manager = if scan_duration == 0xFF {
706                    Some(r.u16()?)
707                } else {
708                    None
709                };
710                Body::MgmtNwkUpdateReq {
711                    channel_mask,
712                    scan_duration,
713                    scan_count,
714                    nwk_update_id,
715                    manager,
716                }
717            }
718            c::NWK_ADDR_RSP | c::IEEE_ADDR_RSP => {
719                let status = r.u8()?;
720                let ieee = r.ieee()?;
721                let nwk = r.u16()?;
722                let associated = read_associated(&mut r)?;
723                if cluster == c::NWK_ADDR_RSP {
724                    Body::NwkAddrRsp {
725                        status,
726                        ieee,
727                        nwk,
728                        associated,
729                    }
730                } else {
731                    Body::IeeeAddrRsp {
732                        status,
733                        ieee,
734                        nwk,
735                        associated,
736                    }
737                }
738            }
739            c::NODE_DESC_RSP => {
740                let status = r.u8()?;
741                let nwk = r.u16()?;
742                let descriptor = if r.is_empty() {
743                    None
744                } else {
745                    Some(NodeDescriptor::read(&mut r)?)
746                };
747                Body::NodeDescRsp {
748                    status,
749                    nwk,
750                    descriptor,
751                }
752            }
753            c::POWER_DESC_RSP => {
754                let status = r.u8()?;
755                let nwk = r.u16()?;
756                let descriptor = if r.is_empty() { None } else { Some(r.u16()?) };
757                Body::PowerDescRsp {
758                    status,
759                    nwk,
760                    descriptor,
761                }
762            }
763            c::SIMPLE_DESC_RSP => {
764                let status = r.u8()?;
765                let nwk = r.u16()?;
766                let len = if r.is_empty() {
767                    0
768                } else {
769                    usize::from(r.u8()?)
770                };
771                let descriptor = if len == 0 {
772                    None
773                } else {
774                    let mut inner = Reader::new(r.bytes(len)?);
775                    let d = SimpleDescriptor::read(&mut inner)?;
776                    if !inner.is_empty() {
777                        return Err(Error::Trailing(inner.remaining()));
778                    }
779                    Some(d)
780                };
781                Body::SimpleDescRsp {
782                    status,
783                    nwk,
784                    descriptor,
785                }
786            }
787            c::ACTIVE_EP_RSP | c::MATCH_DESC_RSP => {
788                let status = r.u8()?;
789                let nwk = r.u16()?;
790                let endpoints = if r.is_empty() {
791                    Vec::new()
792                } else {
793                    read_list8(&mut r)?
794                };
795                if cluster == c::ACTIVE_EP_RSP {
796                    Body::ActiveEpRsp {
797                        status,
798                        nwk,
799                        endpoints,
800                    }
801                } else {
802                    Body::MatchDescRsp {
803                        status,
804                        nwk,
805                        endpoints,
806                    }
807                }
808            }
809            c::BIND_RSP => Body::BindRsp { status: r.u8()? },
810            c::UNBIND_RSP => Body::UnbindRsp { status: r.u8()? },
811            c::MGMT_LEAVE_RSP => Body::MgmtLeaveRsp { status: r.u8()? },
812            c::MGMT_PERMIT_JOINING_RSP => Body::MgmtPermitJoiningRsp { status: r.u8()? },
813            c::MGMT_LQI_RSP => {
814                let (status, total, start_index, neighbors) = read_table(&mut r, 22, |r| {
815                    Ok(Neighbor {
816                        extended_pan_id: r.ext_pan_id()?,
817                        ieee: r.ieee()?,
818                        nwk: r.u16()?,
819                        flags: r.u8()?,
820                        permit_joining: r.u8()?,
821                        depth: r.u8()?,
822                        lqi: r.u8()?,
823                    })
824                })?;
825                Body::MgmtLqiRsp {
826                    status,
827                    total,
828                    start_index,
829                    neighbors,
830                }
831            }
832            c::MGMT_RTG_RSP => {
833                let (status, total, start_index, routes) = read_table(&mut r, 5, |r| {
834                    Ok(Route {
835                        destination: r.u16()?,
836                        flags: r.u8()?,
837                        next_hop: r.u16()?,
838                    })
839                })?;
840                Body::MgmtRtgRsp {
841                    status,
842                    total,
843                    start_index,
844                    routes,
845                }
846            }
847            c::MGMT_BIND_RSP => {
848                let (status, total, start_index, bindings) = read_table(&mut r, 14, read_binding)?;
849                Body::MgmtBindRsp {
850                    status,
851                    total,
852                    start_index,
853                    bindings,
854                }
855            }
856            c::MGMT_NWK_UPDATE_NOTIFY => Body::MgmtNwkUpdateNotify {
857                status: r.u8()?,
858                scanned_channels: r.u32()?,
859                total_transmissions: r.u16()?,
860                transmission_failures: r.u16()?,
861                energy: read_list8(&mut r)?,
862            },
863            other => Body::Other {
864                cluster: other,
865                payload: r.rest().to_vec(),
866            },
867        };
868        match r.remaining() {
869            0 => Ok(Message { tsn, body }),
870            n => Err(Error::Trailing(n)),
871        }
872    }
873
874    /// Encode: the cluster id and the frame (tsn first).
875    pub fn encode(&self) -> (u16, Vec<u8>) {
876        let mut w = Vec::with_capacity(16);
877        w.put_u8(self.tsn);
878        match &self.body {
879            Body::NwkAddrReq {
880                ieee,
881                request_type,
882                start_index,
883            } => {
884                w.put_ieee(*ieee);
885                w.put_u8(*request_type);
886                w.put_u8(*start_index);
887            }
888            Body::IeeeAddrReq {
889                nwk,
890                request_type,
891                start_index,
892            } => {
893                w.put_u16(*nwk);
894                w.put_u8(*request_type);
895                w.put_u8(*start_index);
896            }
897            Body::NodeDescReq { nwk } | Body::PowerDescReq { nwk } | Body::ActiveEpReq { nwk } => {
898                w.put_u16(*nwk)
899            }
900            Body::SimpleDescReq { nwk, endpoint } => {
901                w.put_u16(*nwk);
902                w.put_u8(*endpoint);
903            }
904            Body::MatchDescReq {
905                nwk,
906                profile_id,
907                input_clusters,
908                output_clusters,
909            } => {
910                w.put_u16(*nwk);
911                w.put_u16(*profile_id);
912                for list in [input_clusters, output_clusters] {
913                    w.put_u8(list.len().min(255) as u8);
914                    list.iter().take(255).for_each(|c| w.put_u16(*c));
915                }
916            }
917            Body::DeviceAnnce {
918                nwk,
919                ieee,
920                capability,
921            } => {
922                w.put_u16(*nwk);
923                w.put_ieee(*ieee);
924                w.put_u8(*capability);
925            }
926            Body::BindReq(b) | Body::UnbindReq(b) => write_binding(b, &mut w),
927            Body::MgmtLqiReq { start_index }
928            | Body::MgmtRtgReq { start_index }
929            | Body::MgmtBindReq { start_index } => w.put_u8(*start_index),
930            Body::MgmtLeaveReq { ieee, flags } => {
931                w.put_ieee(*ieee);
932                w.put_u8(*flags);
933            }
934            Body::MgmtPermitJoiningReq {
935                duration,
936                tc_significance,
937            } => {
938                w.put_u8(*duration);
939                w.put_u8(*tc_significance);
940            }
941            Body::MgmtNwkUpdateReq {
942                channel_mask,
943                scan_duration,
944                scan_count,
945                nwk_update_id,
946                manager,
947            } => {
948                w.put_u32(*channel_mask);
949                w.put_u8(*scan_duration);
950                if *scan_duration <= 5 {
951                    w.put_u8(scan_count.unwrap_or(1));
952                }
953                if *scan_duration >= 0xFE {
954                    w.put_u8(nwk_update_id.unwrap_or(0));
955                }
956                if *scan_duration == 0xFF {
957                    w.put_u16(manager.unwrap_or(0));
958                }
959            }
960            Body::NwkAddrRsp {
961                status,
962                ieee,
963                nwk,
964                associated,
965            }
966            | Body::IeeeAddrRsp {
967                status,
968                ieee,
969                nwk,
970                associated,
971            } => {
972                w.put_u8(*status);
973                w.put_ieee(*ieee);
974                w.put_u16(*nwk);
975                write_associated(associated, &mut w);
976            }
977            Body::NodeDescRsp {
978                status,
979                nwk,
980                descriptor,
981            } => {
982                w.put_u8(*status);
983                w.put_u16(*nwk);
984                if let Some(d) = descriptor {
985                    d.write(&mut w);
986                }
987            }
988            Body::PowerDescRsp {
989                status,
990                nwk,
991                descriptor,
992            } => {
993                w.put_u8(*status);
994                w.put_u16(*nwk);
995                if let Some(d) = descriptor {
996                    w.put_u16(*d);
997                }
998            }
999            Body::SimpleDescRsp {
1000                status,
1001                nwk,
1002                descriptor,
1003            } => {
1004                w.put_u8(*status);
1005                w.put_u16(*nwk);
1006                match descriptor {
1007                    Some(d) => {
1008                        let mut inner = Vec::new();
1009                        d.write(&mut inner);
1010                        w.put_u8_prefixed(&inner);
1011                    }
1012                    None => w.put_u8(0),
1013                }
1014            }
1015            Body::ActiveEpRsp {
1016                status,
1017                nwk,
1018                endpoints,
1019            }
1020            | Body::MatchDescRsp {
1021                status,
1022                nwk,
1023                endpoints,
1024            } => {
1025                w.put_u8(*status);
1026                w.put_u16(*nwk);
1027                w.put_u8_prefixed(endpoints);
1028            }
1029            Body::BindRsp { status }
1030            | Body::UnbindRsp { status }
1031            | Body::MgmtLeaveRsp { status }
1032            | Body::MgmtPermitJoiningRsp { status } => w.put_u8(*status),
1033            Body::MgmtLqiRsp {
1034                status,
1035                total,
1036                start_index,
1037                neighbors,
1038            } => {
1039                w.put_u8(*status);
1040                w.put_u8(*total);
1041                w.put_u8(*start_index);
1042                w.put_u8(neighbors.len().min(255) as u8);
1043                for n in neighbors.iter().take(255) {
1044                    w.put_ext_pan_id(n.extended_pan_id);
1045                    w.put_ieee(n.ieee);
1046                    w.put_u16(n.nwk);
1047                    w.put_u8(n.flags);
1048                    w.put_u8(n.permit_joining);
1049                    w.put_u8(n.depth);
1050                    w.put_u8(n.lqi);
1051                }
1052            }
1053            Body::MgmtRtgRsp {
1054                status,
1055                total,
1056                start_index,
1057                routes,
1058            } => {
1059                w.put_u8(*status);
1060                w.put_u8(*total);
1061                w.put_u8(*start_index);
1062                w.put_u8(routes.len().min(255) as u8);
1063                for route in routes.iter().take(255) {
1064                    w.put_u16(route.destination);
1065                    w.put_u8(route.flags);
1066                    w.put_u16(route.next_hop);
1067                }
1068            }
1069            Body::MgmtBindRsp {
1070                status,
1071                total,
1072                start_index,
1073                bindings,
1074            } => {
1075                w.put_u8(*status);
1076                w.put_u8(*total);
1077                w.put_u8(*start_index);
1078                w.put_u8(bindings.len().min(255) as u8);
1079                bindings
1080                    .iter()
1081                    .take(255)
1082                    .for_each(|b| write_binding(b, &mut w));
1083            }
1084            Body::MgmtNwkUpdateNotify {
1085                status,
1086                scanned_channels,
1087                total_transmissions,
1088                transmission_failures,
1089                energy,
1090            } => {
1091                w.put_u8(*status);
1092                w.put_u32(*scanned_channels);
1093                w.put_u16(*total_transmissions);
1094                w.put_u16(*transmission_failures);
1095                w.put_u8_prefixed(energy);
1096            }
1097            Body::Other { payload, .. } => w.put_bytes(payload),
1098        }
1099        (self.cluster(), w)
1100    }
1101}
1102
1103#[cfg(test)]
1104mod tests {
1105    use super::*;
1106
1107    fn round_trip(body: Body) {
1108        let m = Message { tsn: 42, body };
1109        let (cluster, bytes) = m.encode();
1110        assert_eq!(Message::parse(cluster, &bytes), Ok(m));
1111    }
1112
1113    #[test]
1114    fn every_body_round_trips() {
1115        let ieee = Ieee(0x00124B0001020304);
1116        let nd = NodeDescriptor {
1117            byte0: 0x02,
1118            byte1: 0x40,
1119            mac_capabilities: 0x80,
1120            manufacturer_code: 0x115F,
1121            max_buffer_size: 127,
1122            max_incoming_transfer: 100,
1123            server_mask: 0x2C00,
1124            max_outgoing_transfer: 100,
1125            descriptor_capability: 0,
1126        };
1127        let sd = SimpleDescriptor {
1128            endpoint: 1,
1129            profile_id: 0x0104,
1130            device_id: 0x0302,
1131            device_version: 1,
1132            input_clusters: vec![0, 1, 0x0402],
1133            output_clusters: vec![0x0019],
1134        };
1135        let binding = Binding {
1136            source: ieee,
1137            source_endpoint: 1,
1138            cluster: 0x0402,
1139            target: BindTarget::Endpoint {
1140                ieee: Ieee(1),
1141                endpoint: 1,
1142            },
1143        };
1144        for body in [
1145            Body::NwkAddrReq {
1146                ieee,
1147                request_type: 0,
1148                start_index: 0,
1149            },
1150            Body::IeeeAddrReq {
1151                nwk: 0x1234,
1152                request_type: 1,
1153                start_index: 0,
1154            },
1155            Body::NodeDescReq { nwk: 0x1234 },
1156            Body::SimpleDescReq {
1157                nwk: 0x1234,
1158                endpoint: 1,
1159            },
1160            Body::ActiveEpReq { nwk: 0x1234 },
1161            Body::MatchDescReq {
1162                nwk: 0xFFFD,
1163                profile_id: 0x0104,
1164                input_clusters: vec![0x0019],
1165                output_clusters: vec![],
1166            },
1167            Body::DeviceAnnce {
1168                nwk: 0x1234,
1169                ieee,
1170                capability: 0x80,
1171            },
1172            Body::BindReq(binding),
1173            Body::UnbindReq(Binding {
1174                target: BindTarget::Group(5),
1175                ..binding
1176            }),
1177            Body::MgmtLqiReq { start_index: 3 },
1178            Body::MgmtLeaveReq { ieee, flags: 0x40 },
1179            Body::MgmtPermitJoiningReq {
1180                duration: 180,
1181                tc_significance: 1,
1182            },
1183            Body::MgmtNwkUpdateReq {
1184                channel_mask: 1 << 15,
1185                scan_duration: 0xFE,
1186                scan_count: None,
1187                nwk_update_id: Some(3),
1188                manager: None,
1189            },
1190            Body::MgmtNwkUpdateReq {
1191                channel_mask: 0x07FFF800,
1192                scan_duration: 3,
1193                scan_count: Some(1),
1194                nwk_update_id: None,
1195                manager: None,
1196            },
1197            Body::NwkAddrRsp {
1198                status: 0,
1199                ieee,
1200                nwk: 0x1234,
1201                associated: None,
1202            },
1203            Body::IeeeAddrRsp {
1204                status: 0,
1205                ieee,
1206                nwk: 0x1234,
1207                associated: Some(AssociatedDevices {
1208                    start_index: 0,
1209                    addresses: vec![1, 2],
1210                }),
1211            },
1212            Body::NodeDescRsp {
1213                status: 0,
1214                nwk: 0x1234,
1215                descriptor: Some(nd),
1216            },
1217            Body::NodeDescRsp {
1218                status: status::DEVICE_NOT_FOUND,
1219                nwk: 0x1234,
1220                descriptor: None,
1221            },
1222            Body::SimpleDescRsp {
1223                status: 0,
1224                nwk: 0x1234,
1225                descriptor: Some(sd),
1226            },
1227            Body::SimpleDescRsp {
1228                status: status::INVALID_EP,
1229                nwk: 0x1234,
1230                descriptor: None,
1231            },
1232            Body::ActiveEpRsp {
1233                status: 0,
1234                nwk: 0x1234,
1235                endpoints: vec![1, 2],
1236            },
1237            Body::BindRsp { status: 0 },
1238            Body::MgmtLqiRsp {
1239                status: 0,
1240                total: 1,
1241                start_index: 0,
1242                neighbors: vec![Neighbor {
1243                    extended_pan_id: ExtPanId(7),
1244                    ieee,
1245                    nwk: 0x1234,
1246                    flags: 0x25,
1247                    permit_joining: 2,
1248                    depth: 1,
1249                    lqi: 180,
1250                }],
1251            },
1252            Body::MgmtRtgRsp {
1253                status: 0,
1254                total: 1,
1255                start_index: 0,
1256                routes: vec![Route {
1257                    destination: 0x1234,
1258                    flags: 0,
1259                    next_hop: 0x5678,
1260                }],
1261            },
1262            Body::MgmtBindRsp {
1263                status: 0,
1264                total: 1,
1265                start_index: 0,
1266                bindings: vec![binding],
1267            },
1268            Body::MgmtLeaveRsp { status: 0 },
1269            Body::MgmtPermitJoiningRsp { status: 0 },
1270            Body::MgmtNwkUpdateNotify {
1271                status: 0,
1272                scanned_channels: 0x07FFF800,
1273                total_transmissions: 10,
1274                transmission_failures: 1,
1275                energy: vec![10, 20],
1276            },
1277            Body::Other {
1278                cluster: 0x0040,
1279                payload: vec![1, 2],
1280            },
1281        ] {
1282            round_trip(body);
1283        }
1284        assert_eq!(nd.logical_type(), LogicalType::EndDevice);
1285        assert_eq!(nd.stack_compliance_revision(), 22);
1286        assert!(!nd.rx_on_when_idle());
1287    }
1288
1289    #[test]
1290    fn rejects_truncated_and_hostile_tables() {
1291        assert!(Message::parse(cluster::NODE_DESC_REQ, &[1]).is_err());
1292        // Claims 255 neighbors with no bytes for them.
1293        assert!(Message::parse(cluster::MGMT_LQI_RSP, &[1, 0, 255, 0, 255]).is_err());
1294        assert!(Message::parse(
1295            cluster::BIND_REQ,
1296            &[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0x02]
1297        )
1298        .is_err());
1299    }
1300}