1use std::fmt;
4
5use zigbee_primitives::wire::{Reader, Truncated, Writer};
6use zigbee_primitives::{ExtPanId, Ieee, Key, NodeId, PanId};
7
8pub const MIN_PROTOCOL_VERSION: u8 = 8;
12pub const SEC_MAN_PROTOCOL_VERSION: u8 = 13;
15pub const MAX_PROTOCOL_VERSION: u8 = 19;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct ProtocolVersion(pub u8);
21
22impl ProtocolVersion {
23 pub const LATEST: ProtocolVersion = ProtocolVersion(MAX_PROTOCOL_VERSION);
25
26 pub fn sl_status(self) -> bool {
30 self.0 >= 14
31 }
32
33 pub fn sec_man(self) -> bool {
38 self.0 >= SEC_MAN_PROTOCOL_VERSION
39 }
40
41 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#[derive(Clone, Copy, PartialEq, Eq, Hash)]
54pub struct Status {
55 pub raw: u32,
57 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 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 pub fn read_sl(r: &mut Reader<'_>) -> Result<Status, Truncated> {
116 Ok(Status {
117 raw: r.u32()?,
118 legacy: false,
119 })
120 }
121
122 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 pub const SL_OK: Status = Status {
133 raw: 0,
134 legacy: false,
135 };
136 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
162pub struct ApsFrame {
163 pub profile_id: u16,
165 pub cluster_id: u16,
167 pub source_endpoint: u8,
169 pub destination_endpoint: u8,
171 pub options: u16,
173 pub group_id: u16,
175 pub sequence: u8,
177}
178
179impl ApsFrame {
180 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub struct RxPacketInfo {
208 pub sender: NodeId,
210 pub sender_ieee: Option<Ieee>,
212 pub binding_index: u8,
214 pub address_index: u8,
216 pub last_hop_lqi: u8,
218 pub last_hop_rssi: i8,
220 pub last_hop_timestamp: u32,
222}
223
224impl RxPacketInfo {
225 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
254pub struct NetworkParameters {
255 pub extended_pan_id: ExtPanId,
257 pub pan_id: PanId,
259 pub radio_tx_power: i8,
261 pub radio_channel: u8,
263 pub join_method: u8,
265 pub nwk_manager_id: NodeId,
267 pub nwk_update_id: u8,
269 pub channels: u32,
271}
272
273impl NetworkParameters {
274 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
303pub struct InitialSecurityState {
304 pub bitmask: u16,
306 pub preconfigured_key: Key,
308 pub network_key: Key,
310 pub network_key_sequence: u8,
312 pub preconfigured_trust_center: Ieee,
314}
315
316impl InitialSecurityState {
317 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
340pub struct SecManContext {
341 pub core_key_type: u8,
343 pub key_index: u8,
345 pub derived_type: u16,
347 pub ieee: Ieee,
349 pub multi_network_index: u8,
351 pub flags: u8,
353 pub psa_key_alg_permission: u32,
355}
356
357impl SecManContext {
358 pub fn for_key(core_key_type: u8) -> Self {
360 SecManContext {
361 core_key_type,
362 ..Default::default()
363 }
364 }
365
366 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
393pub struct ApsKeyMetadata {
394 pub bitmask: u16,
396 pub outgoing_frame_counter: u32,
398 pub incoming_frame_counter: u32,
400 pub ttl_seconds: u16,
402}
403
404impl ApsKeyMetadata {
405 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
426pub struct NetworkKeyInfo {
427 pub network_key_set: bool,
429 pub alternate_network_key_set: bool,
431 pub network_key_sequence: u8,
433 pub alternate_network_key_sequence: u8,
435 pub network_key_frame_counter: u32,
437}
438
439impl NetworkKeyInfo {
440 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
464pub struct KeyStruct {
465 pub bitmask: u16,
467 pub key_type: u8,
469 pub key: Key,
471 pub outgoing_frame_counter: u32,
473 pub incoming_frame_counter: u32,
475 pub sequence_number: u8,
477 pub partner: Ieee,
479}
480
481impl KeyStruct {
482 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
509pub struct StackVersion {
510 pub build: u16,
512 pub major: u8,
514 pub minor: u8,
516 pub patch: u8,
518 pub special: u8,
520 pub kind: u8,
522}
523
524impl StackVersion {
525 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 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}