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