Skip to main content

zigbee_ezsp/
types.rs

1//! EZSP structures and the status type, with their wire encodings.
2
3use std::fmt;
4
5use zigbee_primitives::wire::{Reader, Truncated, Writer};
6use zigbee_primitives::{ExtPanId, Ieee, Key, NodeId, PanId};
7
8/// The oldest EZSP protocol version this crate speaks (EmberZNet 6.7 to
9/// 6.10, the last firmware for the EM35x). Versions 9 to 12 (EmberZNet 7.0
10/// to 7.3) are refused: [`ProtocolVersion::is_supported`].
11pub const MIN_PROTOCOL_VERSION: u8 = 8;
12/// The oldest version with the security manager key commands (EmberZNet
13/// 7.4); older versions use `getKey` and the key table commands.
14pub const SEC_MAN_PROTOCOL_VERSION: u8 = 13;
15/// The newest EZSP protocol version this crate speaks (EmberZNet 8.x).
16pub const MAX_PROTOCOL_VERSION: u8 = 19;
17
18/// A negotiated EZSP protocol version.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct ProtocolVersion(pub u8);
21
22impl ProtocolVersion {
23    /// The newest version this crate speaks, which the host asks for first.
24    pub const LATEST: ProtocolVersion = ProtocolVersion(MAX_PROTOCOL_VERSION);
25
26    /// From version 14 (EmberZNet 8.0) statuses are 32-bit `sl_status_t`
27    /// and several frames changed layout; version 13 uses 8-bit
28    /// `EmberStatus`.
29    pub fn sl_status(self) -> bool {
30        self.0 >= 14
31    }
32
33    /// From version 13 (EmberZNet 7.4) keys go through the security
34    /// manager (`exportKey`, `importLinkKey`, `importTransientKey`); before
35    /// it through `getKey`, `getKeyTableEntry`, `setKeyTableEntry` and
36    /// `addTransientLinkKey`.
37    pub fn sec_man(self) -> bool {
38        self.0 >= SEC_MAN_PROTOCOL_VERSION
39    }
40
41    /// True when this crate can speak the version: 8, and 13 to 19.
42    pub fn is_supported(self) -> bool {
43        self.0 == MIN_PROTOCOL_VERSION
44            || (SEC_MAN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION).contains(&self.0)
45    }
46}
47
48/// A status code from the NCP.
49///
50/// Version 13 sends 8-bit `EmberStatus` codes, version 14 and later 32-bit
51/// `sl_status_t`; `legacy` says which space `raw` is in. Use the predicates
52/// rather than comparing `raw`.
53#[derive(Clone, Copy, PartialEq, Eq, Hash)]
54pub struct Status {
55    /// The code as sent.
56    pub raw: u32,
57    /// True for an 8-bit `EmberStatus` (or `EzspStatus`) code.
58    pub legacy: bool,
59}
60
61macro_rules! statuses {
62    ($($name:ident, $pred:ident, $sl:expr, $ember:expr;)*) => {
63        impl Status {
64            $(
65                #[doc = concat!("`", stringify!($name), "` in the given version's code space.")]
66                pub fn $name(v: ProtocolVersion) -> Status {
67                    if v.sl_status() { Status { raw: $sl, legacy: false } } else { Status { raw: $ember, legacy: true } }
68                }
69                #[doc = concat!("True for `", stringify!($name), "`.")]
70                pub fn $pred(&self) -> bool {
71                    if self.legacy { self.raw == $ember } else { self.raw == $sl }
72                }
73            )*
74
75            fn name(&self) -> Option<&'static str> {
76                $( if self.$pred() { return Some(stringify!($name)); } )*
77                None
78            }
79        }
80    };
81}
82
83statuses! {
84    ok, is_ok, 0x0000, 0x00;
85    fail, is_fail, 0x0001, 0x01;
86    invalid_parameter, is_invalid_parameter, 0x0021, 0x02;
87    not_found_sl, is_not_found, 0x002D, 0x002D;
88    not_joined, is_not_joined, 0x0017, 0x93;
89    network_up, is_network_up, 0x0015, 0x90;
90    network_down, is_network_down, 0x0016, 0x91;
91    network_opened, is_network_opened, 0x0C18, 0x9C;
92    network_closed, is_network_closed, 0x0C19, 0x9D;
93    delivery_failed, is_delivery_failed, 0x0C02, 0x66;
94    invalid_call, is_invalid_call, 0x0002, 0x70;
95}
96
97impl Status {
98    /// Read a status in the version's width.
99    pub fn read(r: &mut Reader<'_>, v: ProtocolVersion) -> Result<Status, Truncated> {
100        if v.sl_status() {
101            Ok(Status {
102                raw: r.u32()?,
103                legacy: false,
104            })
105        } else {
106            Ok(Status {
107                raw: u32::from(r.u8()?),
108                legacy: true,
109            })
110        }
111    }
112
113    /// Read a status that is 32 bits in every version (the security
114    /// manager commands).
115    pub fn read_sl(r: &mut Reader<'_>) -> Result<Status, Truncated> {
116        Ok(Status {
117            raw: r.u32()?,
118            legacy: false,
119        })
120    }
121
122    /// Write in the status's own width.
123    pub fn write(&self, w: &mut Vec<u8>) {
124        if self.legacy {
125            w.put_u8(self.raw as u8);
126        } else {
127            w.put_u32(self.raw);
128        }
129    }
130
131    /// `ok` as a 32-bit status, for commands that always use `sl_status_t`.
132    pub const SL_OK: Status = Status {
133        raw: 0,
134        legacy: false,
135    };
136    /// `not_found` as a 32-bit status.
137    pub const SL_NOT_FOUND: Status = Status {
138        raw: 0x002D,
139        legacy: false,
140    };
141}
142
143impl fmt::Debug for Status {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        fmt::Display::fmt(self, f)
146    }
147}
148
149impl fmt::Display for Status {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        match (self.name(), self.legacy) {
152            (Some(name), true) => write!(f, "{name} (ember {:#04x})", self.raw),
153            (Some(name), false) => write!(f, "{name} ({:#06x})", self.raw),
154            (None, true) => write!(f, "ember status {:#04x}", self.raw),
155            (None, false) => write!(f, "sl status {:#06x}", self.raw),
156        }
157    }
158}
159
160/// `EmberApsFrame`.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
162pub struct ApsFrame {
163    /// Application profile (0x0000 ZDO, 0x0104 Home Automation).
164    pub profile_id: u16,
165    /// Cluster id.
166    pub cluster_id: u16,
167    /// Source endpoint.
168    pub source_endpoint: u8,
169    /// Destination endpoint.
170    pub destination_endpoint: u8,
171    /// [`crate::ids::aps_option`] bits.
172    pub options: u16,
173    /// Group id, for multicast.
174    pub group_id: u16,
175    /// APS counter.
176    pub sequence: u8,
177}
178
179impl ApsFrame {
180    /// Decode.
181    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
182        Ok(ApsFrame {
183            profile_id: r.u16()?,
184            cluster_id: r.u16()?,
185            source_endpoint: r.u8()?,
186            destination_endpoint: r.u8()?,
187            options: r.u16()?,
188            group_id: r.u16()?,
189            sequence: r.u8()?,
190        })
191    }
192
193    /// Encode.
194    pub fn write(&self, w: &mut Vec<u8>) {
195        w.put_u16(self.profile_id);
196        w.put_u16(self.cluster_id);
197        w.put_u8(self.source_endpoint);
198        w.put_u8(self.destination_endpoint);
199        w.put_u16(self.options);
200        w.put_u16(self.group_id);
201        w.put_u8(self.sequence);
202    }
203}
204
205/// How a message arrived: the sender and the last hop's link quality.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub struct RxPacketInfo {
208    /// The sender's network address.
209    pub sender: NodeId,
210    /// The sender's IEEE address, when the frame carried it (version 14+).
211    pub sender_ieee: Option<Ieee>,
212    /// Binding table index, 0xFF for none.
213    pub binding_index: u8,
214    /// Address table index, 0xFF for none.
215    pub address_index: u8,
216    /// Link quality of the last hop.
217    pub last_hop_lqi: u8,
218    /// Received signal strength of the last hop, dBm.
219    pub last_hop_rssi: i8,
220    /// Receive time of the last hop (version 14+).
221    pub last_hop_timestamp: u32,
222}
223
224impl RxPacketInfo {
225    /// Decode the version 14+ `EmberRxPacketInfo`.
226    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
227        let sender = r.u16()?;
228        let ieee = r.ieee()?;
229        Ok(RxPacketInfo {
230            sender,
231            sender_ieee: (ieee != Ieee::ZERO && ieee != Ieee::UNSET).then_some(ieee),
232            binding_index: r.u8()?,
233            address_index: r.u8()?,
234            last_hop_lqi: r.u8()?,
235            last_hop_rssi: r.i8()?,
236            last_hop_timestamp: r.u32()?,
237        })
238    }
239
240    /// Encode the version 14+ `EmberRxPacketInfo`.
241    pub fn write(&self, w: &mut Vec<u8>) {
242        w.put_u16(self.sender);
243        w.put_ieee(self.sender_ieee.unwrap_or(Ieee::ZERO));
244        w.put_u8(self.binding_index);
245        w.put_u8(self.address_index);
246        w.put_u8(self.last_hop_lqi);
247        w.put_u8(self.last_hop_rssi as u8);
248        w.put_u32(self.last_hop_timestamp);
249    }
250}
251
252/// `EmberNetworkParameters`.
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
254pub struct NetworkParameters {
255    /// Extended PAN id.
256    pub extended_pan_id: ExtPanId,
257    /// PAN id.
258    pub pan_id: PanId,
259    /// Transmit power, dBm.
260    pub radio_tx_power: i8,
261    /// Channel, 11 to 26.
262    pub radio_channel: u8,
263    /// `EmberJoinMethod`; 0 (MAC association) when forming.
264    pub join_method: u8,
265    /// Network manager's address.
266    pub nwk_manager_id: NodeId,
267    /// Network update id.
268    pub nwk_update_id: u8,
269    /// Channel mask.
270    pub channels: u32,
271}
272
273impl NetworkParameters {
274    /// Decode.
275    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
276        Ok(NetworkParameters {
277            extended_pan_id: r.ext_pan_id()?,
278            pan_id: r.u16()?,
279            radio_tx_power: r.i8()?,
280            radio_channel: r.u8()?,
281            join_method: r.u8()?,
282            nwk_manager_id: r.u16()?,
283            nwk_update_id: r.u8()?,
284            channels: r.u32()?,
285        })
286    }
287
288    /// Encode.
289    pub fn write(&self, w: &mut Vec<u8>) {
290        w.put_ext_pan_id(self.extended_pan_id);
291        w.put_u16(self.pan_id);
292        w.put_u8(self.radio_tx_power as u8);
293        w.put_u8(self.radio_channel);
294        w.put_u8(self.join_method);
295        w.put_u16(self.nwk_manager_id);
296        w.put_u8(self.nwk_update_id);
297        w.put_u32(self.channels);
298    }
299}
300
301/// `EmberInitialSecurityState`.
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
303pub struct InitialSecurityState {
304    /// [`crate::ids::security`] bits.
305    pub bitmask: u16,
306    /// Trust center link key (with hashed link keys, the root key).
307    pub preconfigured_key: Key,
308    /// Network key.
309    pub network_key: Key,
310    /// Network key sequence number.
311    pub network_key_sequence: u8,
312    /// Trust center IEEE address, or zero.
313    pub preconfigured_trust_center: Ieee,
314}
315
316impl InitialSecurityState {
317    /// Decode.
318    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
319        Ok(InitialSecurityState {
320            bitmask: r.u16()?,
321            preconfigured_key: r.key()?,
322            network_key: r.key()?,
323            network_key_sequence: r.u8()?,
324            preconfigured_trust_center: r.ieee()?,
325        })
326    }
327
328    /// Encode.
329    pub fn write(&self, w: &mut Vec<u8>) {
330        w.put_u16(self.bitmask);
331        w.put_key(&self.preconfigured_key);
332        w.put_key(&self.network_key);
333        w.put_u8(self.network_key_sequence);
334        w.put_ieee(self.preconfigured_trust_center);
335    }
336}
337
338/// `sl_zb_sec_man_context_t`: which key a security manager call means.
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
340pub struct SecManContext {
341    /// [`crate::ids::key_type`].
342    pub core_key_type: u8,
343    /// Key table index.
344    pub key_index: u8,
345    /// Derived key type, 0 for none.
346    pub derived_type: u16,
347    /// The partner's IEEE address, for link keys.
348    pub ieee: Ieee,
349    /// Network index.
350    pub multi_network_index: u8,
351    /// Flags.
352    pub flags: u8,
353    /// PSA key algorithm permission.
354    pub psa_key_alg_permission: u32,
355}
356
357impl SecManContext {
358    /// A context for a key type, everything else zero.
359    pub fn for_key(core_key_type: u8) -> Self {
360        SecManContext {
361            core_key_type,
362            ..Default::default()
363        }
364    }
365
366    /// Decode.
367    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
368        Ok(SecManContext {
369            core_key_type: r.u8()?,
370            key_index: r.u8()?,
371            derived_type: r.u16()?,
372            ieee: r.ieee()?,
373            multi_network_index: r.u8()?,
374            flags: r.u8()?,
375            psa_key_alg_permission: r.u32()?,
376        })
377    }
378
379    /// Encode.
380    pub fn write(&self, w: &mut Vec<u8>) {
381        w.put_u8(self.core_key_type);
382        w.put_u8(self.key_index);
383        w.put_u16(self.derived_type);
384        w.put_ieee(self.ieee);
385        w.put_u8(self.multi_network_index);
386        w.put_u8(self.flags);
387        w.put_u32(self.psa_key_alg_permission);
388    }
389}
390
391/// `sl_zb_sec_man_aps_key_metadata_t`.
392#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
393pub struct ApsKeyMetadata {
394    /// Key properties.
395    pub bitmask: u16,
396    /// Outgoing APS frame counter.
397    pub outgoing_frame_counter: u32,
398    /// Incoming APS frame counter.
399    pub incoming_frame_counter: u32,
400    /// Seconds left for a transient key.
401    pub ttl_seconds: u16,
402}
403
404impl ApsKeyMetadata {
405    /// Decode.
406    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
407        Ok(ApsKeyMetadata {
408            bitmask: r.u16()?,
409            outgoing_frame_counter: r.u32()?,
410            incoming_frame_counter: r.u32()?,
411            ttl_seconds: r.u16()?,
412        })
413    }
414
415    /// Encode.
416    pub fn write(&self, w: &mut Vec<u8>) {
417        w.put_u16(self.bitmask);
418        w.put_u32(self.outgoing_frame_counter);
419        w.put_u32(self.incoming_frame_counter);
420        w.put_u16(self.ttl_seconds);
421    }
422}
423
424/// `sl_zb_sec_man_network_key_info_t`.
425#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
426pub struct NetworkKeyInfo {
427    /// A network key is set.
428    pub network_key_set: bool,
429    /// An alternate network key is set.
430    pub alternate_network_key_set: bool,
431    /// Network key sequence number.
432    pub network_key_sequence: u8,
433    /// Alternate key sequence number.
434    pub alternate_network_key_sequence: u8,
435    /// Outgoing network frame counter.
436    pub network_key_frame_counter: u32,
437}
438
439impl NetworkKeyInfo {
440    /// Decode.
441    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
442        Ok(NetworkKeyInfo {
443            network_key_set: r.bool()?,
444            alternate_network_key_set: r.bool()?,
445            network_key_sequence: r.u8()?,
446            alternate_network_key_sequence: r.u8()?,
447            network_key_frame_counter: r.u32()?,
448        })
449    }
450
451    /// Encode.
452    pub fn write(&self, w: &mut Vec<u8>) {
453        w.put_u8(u8::from(self.network_key_set));
454        w.put_u8(u8::from(self.alternate_network_key_set));
455        w.put_u8(self.network_key_sequence);
456        w.put_u8(self.alternate_network_key_sequence);
457        w.put_u32(self.network_key_frame_counter);
458    }
459}
460
461/// `EmberKeyStruct`: a key and its counters, from `getKey` and
462/// `getKeyTableEntry` (protocol versions before 13).
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
464pub struct KeyStruct {
465    /// [`crate::ids::key_struct`] bits: which fields are valid.
466    pub bitmask: u16,
467    /// [`crate::ids::ember_key_type`].
468    pub key_type: u8,
469    /// The key.
470    pub key: Key,
471    /// Outgoing frame counter.
472    pub outgoing_frame_counter: u32,
473    /// Incoming frame counter.
474    pub incoming_frame_counter: u32,
475    /// Key sequence number (network keys).
476    pub sequence_number: u8,
477    /// The partner's IEEE address (link keys).
478    pub partner: Ieee,
479}
480
481impl KeyStruct {
482    /// Decode.
483    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
484        Ok(KeyStruct {
485            bitmask: r.u16()?,
486            key_type: r.u8()?,
487            key: r.key()?,
488            outgoing_frame_counter: r.u32()?,
489            incoming_frame_counter: r.u32()?,
490            sequence_number: r.u8()?,
491            partner: r.ieee()?,
492        })
493    }
494
495    /// Encode.
496    pub fn write(&self, w: &mut Vec<u8>) {
497        w.put_u16(self.bitmask);
498        w.put_u8(self.key_type);
499        w.put_key(&self.key);
500        w.put_u32(self.outgoing_frame_counter);
501        w.put_u32(self.incoming_frame_counter);
502        w.put_u8(self.sequence_number);
503        w.put_ieee(self.partner);
504    }
505}
506
507/// `EmberVersion`, from the `VERSION_INFO` value: the EmberZNet release.
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
509pub struct StackVersion {
510    /// Build number.
511    pub build: u16,
512    /// Major version.
513    pub major: u8,
514    /// Minor version.
515    pub minor: u8,
516    /// Patch version.
517    pub patch: u8,
518    /// Special version.
519    pub special: u8,
520    /// Release type: 0x00 pre-release, 0x33 alpha, 0x66 beta, 0xAA GA.
521    pub kind: u8,
522}
523
524impl StackVersion {
525    /// Decode the 7-byte `VERSION_INFO` value.
526    pub fn read(r: &mut Reader<'_>) -> Result<Self, Truncated> {
527        Ok(StackVersion {
528            build: r.u16()?,
529            major: r.u8()?,
530            minor: r.u8()?,
531            patch: r.u8()?,
532            special: r.u8()?,
533            kind: r.u8()?,
534        })
535    }
536
537    /// Encode as the 7-byte `VERSION_INFO` value.
538    pub fn to_bytes(&self) -> Vec<u8> {
539        let mut w = Vec::with_capacity(7);
540        w.put_u16(self.build);
541        w.put_u8(self.major);
542        w.put_u8(self.minor);
543        w.put_u8(self.patch);
544        w.put_u8(self.special);
545        w.put_u8(self.kind);
546        w
547    }
548}
549
550impl fmt::Display for StackVersion {
551    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552        write!(
553            f,
554            "{}.{}.{}.{} build {}",
555            self.major, self.minor, self.patch, self.special, self.build
556        )?;
557        match self.kind {
558            0xAA => Ok(()),
559            0x00 => f.write_str(" pre-release"),
560            0x33 => f.write_str(" alpha"),
561            0x66 => f.write_str(" beta"),
562            other => write!(f, " (type {other:#04x})"),
563        }
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    #[test]
572    fn status_spaces() {
573        let v13 = ProtocolVersion(13);
574        let v16 = ProtocolVersion(16);
575        assert!(Status::network_up(v13).is_network_up());
576        assert_eq!(Status::network_up(v13).raw, 0x90);
577        assert_eq!(Status::network_up(v16).raw, 0x15);
578        assert!(!Status {
579            raw: 0x90,
580            legacy: false
581        }
582        .is_network_up());
583        assert_eq!(Status::ok(v16).to_string(), "ok (0x0000)");
584        assert_eq!(
585            Status {
586                raw: 0x42,
587                legacy: true
588            }
589            .to_string(),
590            "ember status 0x42"
591        );
592    }
593
594    #[test]
595    fn structures_round_trip() {
596        let p = NetworkParameters {
597            extended_pan_id: ExtPanId(0xDDDDDDDDDDDDDDDD),
598            pan_id: 0x1A62,
599            radio_tx_power: -3,
600            radio_channel: 15,
601            join_method: 0,
602            nwk_manager_id: 0,
603            nwk_update_id: 2,
604            channels: 0x07FF_F800,
605        };
606        let mut w = Vec::new();
607        p.write(&mut w);
608        assert_eq!(w.len(), 20);
609        assert_eq!(NetworkParameters::read(&mut Reader::new(&w)).unwrap(), p);
610        let v = StackVersion {
611            build: 380,
612            major: 7,
613            minor: 4,
614            patch: 4,
615            special: 0,
616            kind: 0xAA,
617        };
618        assert_eq!(
619            StackVersion::read(&mut Reader::new(&v.to_bytes())).unwrap(),
620            v
621        );
622        assert_eq!(v.to_string(), "7.4.4.0 build 380");
623        let k = KeyStruct {
624            bitmask: 0x0B,
625            key_type: crate::ids::ember_key_type::APPLICATION_LINK,
626            key: Key([9; 16]),
627            outgoing_frame_counter: 7,
628            incoming_frame_counter: 8,
629            sequence_number: 0,
630            partner: Ieee(0x00124B0000000001),
631        };
632        let mut w = Vec::new();
633        k.write(&mut w);
634        assert_eq!(w.len(), 36);
635        assert_eq!(KeyStruct::read(&mut Reader::new(&w)).unwrap(), k);
636    }
637
638    #[test]
639    fn supported_versions() {
640        let supported: Vec<u8> = (0..=25)
641            .filter(|v| ProtocolVersion(*v).is_supported())
642            .collect();
643        assert_eq!(supported, [8, 13, 14, 15, 16, 17, 18, 19]);
644        assert!(!ProtocolVersion(8).sec_man());
645        assert!(!ProtocolVersion(8).sl_status());
646        assert!(ProtocolVersion(13).sec_man());
647    }
648}