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 = 13;
10pub const MAX_PROTOCOL_VERSION: u8 = 19;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct ProtocolVersion(pub u8);
16
17impl ProtocolVersion {
18 pub const LATEST: ProtocolVersion = ProtocolVersion(MAX_PROTOCOL_VERSION);
20
21 pub fn sl_status(self) -> bool {
25 self.0 >= 14
26 }
27
28 pub fn is_supported(self) -> bool {
30 (MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION).contains(&self.0)
31 }
32}
33
34#[derive(Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Status {
41 pub raw: u32,
43 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 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 pub fn read_sl(r: &mut Reader<'_>) -> Result<Status, Truncated> {
102 Ok(Status {
103 raw: r.u32()?,
104 legacy: false,
105 })
106 }
107
108 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 pub const SL_OK: Status = Status {
119 raw: 0,
120 legacy: false,
121 };
122 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
148pub struct ApsFrame {
149 pub profile_id: u16,
151 pub cluster_id: u16,
153 pub source_endpoint: u8,
155 pub destination_endpoint: u8,
157 pub options: u16,
159 pub group_id: u16,
161 pub sequence: u8,
163}
164
165impl ApsFrame {
166 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
193pub struct RxPacketInfo {
194 pub sender: NodeId,
196 pub sender_ieee: Option<Ieee>,
198 pub binding_index: u8,
200 pub address_index: u8,
202 pub last_hop_lqi: u8,
204 pub last_hop_rssi: i8,
206 pub last_hop_timestamp: u32,
208}
209
210impl RxPacketInfo {
211 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
240pub struct NetworkParameters {
241 pub extended_pan_id: ExtPanId,
243 pub pan_id: PanId,
245 pub radio_tx_power: i8,
247 pub radio_channel: u8,
249 pub join_method: u8,
251 pub nwk_manager_id: NodeId,
253 pub nwk_update_id: u8,
255 pub channels: u32,
257}
258
259impl NetworkParameters {
260 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
289pub struct InitialSecurityState {
290 pub bitmask: u16,
292 pub preconfigured_key: Key,
294 pub network_key: Key,
296 pub network_key_sequence: u8,
298 pub preconfigured_trust_center: Ieee,
300}
301
302impl InitialSecurityState {
303 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
326pub struct SecManContext {
327 pub core_key_type: u8,
329 pub key_index: u8,
331 pub derived_type: u16,
333 pub ieee: Ieee,
335 pub multi_network_index: u8,
337 pub flags: u8,
339 pub psa_key_alg_permission: u32,
341}
342
343impl SecManContext {
344 pub fn for_key(core_key_type: u8) -> Self {
346 SecManContext {
347 core_key_type,
348 ..Default::default()
349 }
350 }
351
352 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
379pub struct ApsKeyMetadata {
380 pub bitmask: u16,
382 pub outgoing_frame_counter: u32,
384 pub incoming_frame_counter: u32,
386 pub ttl_seconds: u16,
388}
389
390impl ApsKeyMetadata {
391 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
412pub struct NetworkKeyInfo {
413 pub network_key_set: bool,
415 pub alternate_network_key_set: bool,
417 pub network_key_sequence: u8,
419 pub alternate_network_key_sequence: u8,
421 pub network_key_frame_counter: u32,
423}
424
425impl NetworkKeyInfo {
426 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
449pub struct StackVersion {
450 pub build: u16,
452 pub major: u8,
454 pub minor: u8,
456 pub patch: u8,
458 pub special: u8,
460 pub kind: u8,
462}
463
464impl StackVersion {
465 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 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}