1use zigbee_primitives::wire::{Reader, Truncated, Writer};
8use zigbee_primitives::{Ieee, Key, NodeId};
9
10use crate::ids::frame as id;
11use crate::types::{
12 ApsFrame, ApsKeyMetadata, InitialSecurityState, NetworkKeyInfo, NetworkParameters,
13 ProtocolVersion, SecManContext, Status,
14};
15
16#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
18pub enum DecodeError {
19 #[error(transparent)]
21 Truncated(#[from] Truncated),
22 #[error("{0} trailing bytes")]
24 Trailing(usize),
25 #[error("unknown frame id {0:#06x}")]
27 UnknownFrame(u16),
28}
29
30fn done(r: &Reader<'_>) -> Result<(), DecodeError> {
31 match r.remaining() {
32 0 => Ok(()),
33 n => Err(DecodeError::Trailing(n)),
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39#[allow(missing_docs)]
40pub enum Command {
41 Version {
43 desired: u8,
44 },
45 GetConfigurationValue {
46 config_id: u8,
47 },
48 SetConfigurationValue {
49 config_id: u8,
50 value: u16,
51 },
52 AddEndpoint {
53 endpoint: u8,
54 profile_id: u16,
55 device_id: u16,
56 device_version: u8,
57 input_clusters: Vec<u16>,
58 output_clusters: Vec<u16>,
59 },
60 SetPolicy {
61 policy_id: u8,
62 decision: u8,
63 },
64 GetValue {
65 value_id: u8,
66 },
67 SetValue {
68 value_id: u8,
69 value: Vec<u8>,
70 },
71 SetManufacturerCode {
72 code: u16,
73 },
74 NetworkInit {
75 bitmask: u16,
76 },
77 NetworkState,
78 FormNetwork {
79 parameters: NetworkParameters,
80 },
81 LeaveNetwork {
82 options: u8,
83 },
84 PermitJoining {
85 duration: u8,
86 },
87 GetNetworkParameters,
88 GetEui64,
89 GetNodeId,
90 SetInitialSecurityState {
91 state: InitialSecurityState,
92 },
93 ExportKey {
94 context: SecManContext,
95 },
96 GetNetworkKeyInfo,
97 ExportLinkKeyByIndex {
98 index: u8,
99 },
100 ImportLinkKey {
101 index: u8,
102 ieee: Ieee,
103 key: Key,
104 },
105 EraseKeyTableEntry {
106 index: u8,
107 },
108 ImportTransientKey {
109 ieee: Ieee,
110 key: Key,
111 },
112 ClearTransientLinkKeys,
113 ClearKeyTable,
114 SendUnicast {
115 kind: u8,
116 destination: NodeId,
117 aps: ApsFrame,
118 tag: u16,
119 payload: Vec<u8>,
120 },
121 SendBroadcast {
122 alias: NodeId,
123 destination: NodeId,
124 nwk_sequence: u8,
125 aps: ApsFrame,
126 radius: u8,
127 tag: u16,
128 payload: Vec<u8>,
129 },
130 SetConcentrator {
131 on: bool,
132 kind: u16,
133 min_time: u16,
134 max_time: u16,
135 route_error_threshold: u8,
136 delivery_failure_threshold: u8,
137 max_hops: u8,
138 },
139 SetSourceRouteDiscoveryMode {
140 mode: u8,
141 },
142 GetMfgToken {
143 token_id: u8,
144 },
145 SetMfgToken {
146 token_id: u8,
147 data: Vec<u8>,
148 },
149 StartScan {
150 scan_type: u8,
151 channel_mask: u32,
152 duration: u8,
153 },
154 LookupEui64ByNodeId {
155 node_id: NodeId,
156 },
157 SetRadioPower {
158 power: i8,
159 },
160 Echo {
161 data: Vec<u8>,
162 },
163 Nop,
164}
165
166impl Command {
167 pub fn frame_id(&self) -> u16 {
169 match self {
170 Command::Version { .. } => id::VERSION,
171 Command::GetConfigurationValue { .. } => id::GET_CONFIGURATION_VALUE,
172 Command::SetConfigurationValue { .. } => id::SET_CONFIGURATION_VALUE,
173 Command::AddEndpoint { .. } => id::ADD_ENDPOINT,
174 Command::SetPolicy { .. } => id::SET_POLICY,
175 Command::GetValue { .. } => id::GET_VALUE,
176 Command::SetValue { .. } => id::SET_VALUE,
177 Command::SetManufacturerCode { .. } => id::SET_MANUFACTURER_CODE,
178 Command::NetworkInit { .. } => id::NETWORK_INIT,
179 Command::NetworkState => id::NETWORK_STATE,
180 Command::FormNetwork { .. } => id::FORM_NETWORK,
181 Command::LeaveNetwork { .. } => id::LEAVE_NETWORK,
182 Command::PermitJoining { .. } => id::PERMIT_JOINING,
183 Command::GetNetworkParameters => id::GET_NETWORK_PARAMETERS,
184 Command::GetEui64 => id::GET_EUI64,
185 Command::GetNodeId => id::GET_NODE_ID,
186 Command::SetInitialSecurityState { .. } => id::SET_INITIAL_SECURITY_STATE,
187 Command::ExportKey { .. } => id::EXPORT_KEY,
188 Command::GetNetworkKeyInfo => id::GET_NETWORK_KEY_INFO,
189 Command::ExportLinkKeyByIndex { .. } => id::EXPORT_LINK_KEY_BY_INDEX,
190 Command::ImportLinkKey { .. } => id::IMPORT_LINK_KEY,
191 Command::EraseKeyTableEntry { .. } => id::ERASE_KEY_TABLE_ENTRY,
192 Command::ImportTransientKey { .. } => id::IMPORT_TRANSIENT_KEY,
193 Command::ClearTransientLinkKeys => id::CLEAR_TRANSIENT_LINK_KEYS,
194 Command::ClearKeyTable => id::CLEAR_KEY_TABLE,
195 Command::SendUnicast { .. } => id::SEND_UNICAST,
196 Command::SendBroadcast { .. } => id::SEND_BROADCAST,
197 Command::SetConcentrator { .. } => id::SET_CONCENTRATOR,
198 Command::SetSourceRouteDiscoveryMode { .. } => id::SET_SOURCE_ROUTE_DISCOVERY_MODE,
199 Command::GetMfgToken { .. } => id::GET_MFG_TOKEN,
200 Command::SetMfgToken { .. } => id::SET_MFG_TOKEN,
201 Command::StartScan { .. } => id::START_SCAN,
202 Command::LookupEui64ByNodeId { .. } => id::LOOKUP_EUI64_BY_NODE_ID,
203 Command::SetRadioPower { .. } => id::SET_RADIO_POWER,
204 Command::Echo { .. } => id::ECHO,
205 Command::Nop => id::NOP,
206 }
207 }
208
209 pub fn encode(&self, v: ProtocolVersion) -> Vec<u8> {
211 let mut w = Vec::with_capacity(32);
212 match self {
213 Command::Version { desired } => w.put_u8(*desired),
214 Command::GetConfigurationValue { config_id } => w.put_u8(*config_id),
215 Command::SetConfigurationValue { config_id, value } => {
216 w.put_u8(*config_id);
217 w.put_u16(*value);
218 }
219 Command::AddEndpoint {
220 endpoint,
221 profile_id,
222 device_id,
223 device_version,
224 input_clusters,
225 output_clusters,
226 } => {
227 w.put_u8(*endpoint);
228 w.put_u16(*profile_id);
229 w.put_u16(*device_id);
230 w.put_u8(*device_version);
231 w.put_u8(input_clusters.len() as u8);
232 w.put_u8(output_clusters.len() as u8);
233 input_clusters.iter().for_each(|c| w.put_u16(*c));
234 output_clusters.iter().for_each(|c| w.put_u16(*c));
235 }
236 Command::SetPolicy {
237 policy_id,
238 decision,
239 } => {
240 w.put_u8(*policy_id);
241 w.put_u8(*decision);
242 }
243 Command::GetValue { value_id } => w.put_u8(*value_id),
244 Command::SetValue { value_id, value } => {
245 w.put_u8(*value_id);
246 w.put_u8_prefixed(value);
247 }
248 Command::SetManufacturerCode { code } => w.put_u16(*code),
249 Command::NetworkInit { bitmask } => w.put_u16(*bitmask),
250 Command::FormNetwork { parameters } => parameters.write(&mut w),
251 Command::LeaveNetwork { options } => {
252 if v.sl_status() {
253 w.put_u8(*options);
254 }
255 }
256 Command::PermitJoining { duration } => w.put_u8(*duration),
257 Command::SetInitialSecurityState { state } => state.write(&mut w),
258 Command::ExportKey { context } => context.write(&mut w),
259 Command::ExportLinkKeyByIndex { index } | Command::EraseKeyTableEntry { index } => {
260 w.put_u8(*index)
261 }
262 Command::ImportLinkKey { index, ieee, key } => {
263 w.put_u8(*index);
264 w.put_ieee(*ieee);
265 w.put_key(key);
266 }
267 Command::ImportTransientKey { ieee, key } => {
268 w.put_ieee(*ieee);
269 w.put_key(key);
270 if !v.sl_status() {
271 w.put_u8(0); }
273 }
274 Command::SendUnicast {
275 kind,
276 destination,
277 aps,
278 tag,
279 payload,
280 } => {
281 w.put_u8(*kind);
282 w.put_u16(*destination);
283 aps.write(&mut w);
284 put_tag(&mut w, v, *tag);
285 w.put_u8_prefixed(payload);
286 }
287 Command::SendBroadcast {
288 alias,
289 destination,
290 nwk_sequence,
291 aps,
292 radius,
293 tag,
294 payload,
295 } => {
296 if v.sl_status() {
297 w.put_u16(*alias);
298 w.put_u16(*destination);
299 w.put_u8(*nwk_sequence);
300 } else {
301 w.put_u16(*destination);
302 }
303 aps.write(&mut w);
304 w.put_u8(*radius);
305 put_tag(&mut w, v, *tag);
306 w.put_u8_prefixed(payload);
307 }
308 Command::SetConcentrator {
309 on,
310 kind,
311 min_time,
312 max_time,
313 route_error_threshold,
314 delivery_failure_threshold,
315 max_hops,
316 } => {
317 w.put_u8(u8::from(*on));
318 w.put_u16(*kind);
319 w.put_u16(*min_time);
320 w.put_u16(*max_time);
321 w.put_u8(*route_error_threshold);
322 w.put_u8(*delivery_failure_threshold);
323 w.put_u8(*max_hops);
324 }
325 Command::SetSourceRouteDiscoveryMode { mode } => w.put_u8(*mode),
326 Command::GetMfgToken { token_id } => w.put_u8(*token_id),
327 Command::SetMfgToken { token_id, data } => {
328 w.put_u8(*token_id);
329 w.put_u8_prefixed(data);
330 }
331 Command::StartScan {
332 scan_type,
333 channel_mask,
334 duration,
335 } => {
336 w.put_u8(*scan_type);
337 w.put_u32(*channel_mask);
338 w.put_u8(*duration);
339 }
340 Command::LookupEui64ByNodeId { node_id } => w.put_u16(*node_id),
341 Command::SetRadioPower { power } => w.put_u8(*power as u8),
342 Command::Echo { data } => w.put_u8_prefixed(data),
343 Command::NetworkState
344 | Command::GetNetworkParameters
345 | Command::GetEui64
346 | Command::GetNodeId
347 | Command::GetNetworkKeyInfo
348 | Command::ClearTransientLinkKeys
349 | Command::ClearKeyTable
350 | Command::Nop => {}
351 }
352 w
353 }
354
355 pub fn decode(
357 v: ProtocolVersion,
358 frame_id: u16,
359 params: &[u8],
360 ) -> Result<Command, DecodeError> {
361 let mut r = Reader::new(params);
362 let c = match frame_id {
363 id::VERSION => Command::Version { desired: r.u8()? },
364 id::GET_CONFIGURATION_VALUE => Command::GetConfigurationValue { config_id: r.u8()? },
365 id::SET_CONFIGURATION_VALUE => Command::SetConfigurationValue {
366 config_id: r.u8()?,
367 value: r.u16()?,
368 },
369 id::ADD_ENDPOINT => {
370 let endpoint = r.u8()?;
371 let profile_id = r.u16()?;
372 let device_id = r.u16()?;
373 let device_version = r.u8()?;
374 let inputs = usize::from(r.u8()?);
375 let outputs = usize::from(r.u8()?);
376 Command::AddEndpoint {
377 endpoint,
378 profile_id,
379 device_id,
380 device_version,
381 input_clusters: r.u16_list(inputs)?,
382 output_clusters: r.u16_list(outputs)?,
383 }
384 }
385 id::SET_POLICY => Command::SetPolicy {
386 policy_id: r.u8()?,
387 decision: r.u8()?,
388 },
389 id::GET_VALUE => Command::GetValue { value_id: r.u8()? },
390 id::SET_VALUE => Command::SetValue {
391 value_id: r.u8()?,
392 value: r.u8_prefixed()?.to_vec(),
393 },
394 id::SET_MANUFACTURER_CODE => Command::SetManufacturerCode { code: r.u16()? },
395 id::NETWORK_INIT => Command::NetworkInit { bitmask: r.u16()? },
396 id::NETWORK_STATE => Command::NetworkState,
397 id::FORM_NETWORK => Command::FormNetwork {
398 parameters: NetworkParameters::read(&mut r)?,
399 },
400 id::LEAVE_NETWORK => Command::LeaveNetwork {
401 options: if v.sl_status() { r.u8()? } else { 0 },
402 },
403 id::PERMIT_JOINING => Command::PermitJoining { duration: r.u8()? },
404 id::GET_NETWORK_PARAMETERS => Command::GetNetworkParameters,
405 id::GET_EUI64 => Command::GetEui64,
406 id::GET_NODE_ID => Command::GetNodeId,
407 id::SET_INITIAL_SECURITY_STATE => Command::SetInitialSecurityState {
408 state: InitialSecurityState::read(&mut r)?,
409 },
410 id::EXPORT_KEY => Command::ExportKey {
411 context: SecManContext::read(&mut r)?,
412 },
413 id::GET_NETWORK_KEY_INFO => Command::GetNetworkKeyInfo,
414 id::EXPORT_LINK_KEY_BY_INDEX => Command::ExportLinkKeyByIndex { index: r.u8()? },
415 id::IMPORT_LINK_KEY => Command::ImportLinkKey {
416 index: r.u8()?,
417 ieee: r.ieee()?,
418 key: r.key()?,
419 },
420 id::ERASE_KEY_TABLE_ENTRY => Command::EraseKeyTableEntry { index: r.u8()? },
421 id::IMPORT_TRANSIENT_KEY => {
422 let c = Command::ImportTransientKey {
423 ieee: r.ieee()?,
424 key: r.key()?,
425 };
426 if !v.sl_status() {
427 r.u8()?;
428 }
429 c
430 }
431 id::CLEAR_TRANSIENT_LINK_KEYS => Command::ClearTransientLinkKeys,
432 id::CLEAR_KEY_TABLE => Command::ClearKeyTable,
433 id::SEND_UNICAST => Command::SendUnicast {
434 kind: r.u8()?,
435 destination: r.u16()?,
436 aps: ApsFrame::read(&mut r)?,
437 tag: read_tag(&mut r, v)?,
438 payload: r.u8_prefixed()?.to_vec(),
439 },
440 id::SEND_BROADCAST => {
441 let (alias, destination, nwk_sequence) = if v.sl_status() {
442 (r.u16()?, r.u16()?, r.u8()?)
443 } else {
444 (0, r.u16()?, 0)
445 };
446 Command::SendBroadcast {
447 alias,
448 destination,
449 nwk_sequence,
450 aps: ApsFrame::read(&mut r)?,
451 radius: r.u8()?,
452 tag: read_tag(&mut r, v)?,
453 payload: r.u8_prefixed()?.to_vec(),
454 }
455 }
456 id::SET_CONCENTRATOR => Command::SetConcentrator {
457 on: r.bool()?,
458 kind: r.u16()?,
459 min_time: r.u16()?,
460 max_time: r.u16()?,
461 route_error_threshold: r.u8()?,
462 delivery_failure_threshold: r.u8()?,
463 max_hops: r.u8()?,
464 },
465 id::SET_SOURCE_ROUTE_DISCOVERY_MODE => {
466 Command::SetSourceRouteDiscoveryMode { mode: r.u8()? }
467 }
468 id::GET_MFG_TOKEN => Command::GetMfgToken { token_id: r.u8()? },
469 id::SET_MFG_TOKEN => Command::SetMfgToken {
470 token_id: r.u8()?,
471 data: r.u8_prefixed()?.to_vec(),
472 },
473 id::START_SCAN => Command::StartScan {
474 scan_type: r.u8()?,
475 channel_mask: r.u32()?,
476 duration: r.u8()?,
477 },
478 id::LOOKUP_EUI64_BY_NODE_ID => Command::LookupEui64ByNodeId { node_id: r.u16()? },
479 id::SET_RADIO_POWER => Command::SetRadioPower { power: r.i8()? },
480 id::ECHO => Command::Echo {
481 data: r.u8_prefixed()?.to_vec(),
482 },
483 id::NOP => Command::Nop,
484 other => return Err(DecodeError::UnknownFrame(other)),
485 };
486 done(&r)?;
487 Ok(c)
488 }
489}
490
491fn put_tag(w: &mut Vec<u8>, v: ProtocolVersion, tag: u16) {
492 if v.sl_status() {
493 w.put_u16(tag);
494 } else {
495 w.put_u8(tag as u8);
496 }
497}
498
499fn read_tag(r: &mut Reader<'_>, v: ProtocolVersion) -> Result<u16, Truncated> {
500 if v.sl_status() {
501 r.u16()
502 } else {
503 r.u8().map(u16::from)
504 }
505}
506
507#[derive(Debug, Clone, PartialEq, Eq)]
510#[allow(missing_docs)]
511pub enum Response {
512 Version {
513 protocol_version: u8,
514 stack_type: u8,
515 stack_version: u16,
516 },
517 GetConfigurationValue {
518 status: Status,
519 value: u16,
520 },
521 Status {
523 frame_id: u16,
524 status: Status,
525 },
526 GetValue {
527 status: Status,
528 value: Vec<u8>,
529 },
530 NetworkState {
531 state: u8,
532 },
533 GetNetworkParameters {
534 status: Status,
535 node_type: u8,
536 parameters: NetworkParameters,
537 },
538 GetEui64 {
539 ieee: Ieee,
540 },
541 GetNodeId {
542 node_id: NodeId,
543 },
544 ExportKey {
545 status: Status,
546 key: Key,
547 context: SecManContext,
548 },
549 GetNetworkKeyInfo {
550 status: Status,
551 info: NetworkKeyInfo,
552 },
553 ExportLinkKeyByIndex {
554 status: Status,
555 context: SecManContext,
556 key: Key,
557 metadata: ApsKeyMetadata,
558 },
559 Sent {
561 frame_id: u16,
562 status: Status,
563 aps_sequence: u8,
564 },
565 SetSourceRouteDiscoveryMode {
566 remaining_ms: u32,
567 },
568 GetMfgToken {
569 data: Vec<u8>,
570 },
571 LookupEui64ByNodeId {
572 status: Status,
573 ieee: Ieee,
574 },
575 Echo {
576 data: Vec<u8>,
577 },
578 Empty {
580 frame_id: u16,
581 },
582 InvalidCommand {
584 reason: u8,
585 },
586}
587
588enum Shape {
590 Status,
592 EzspStatus,
594 SlStatus,
596 Empty,
597 Special,
598}
599
600fn shape(frame_id: u16) -> Option<Shape> {
601 Some(match frame_id {
602 id::SET_CONFIGURATION_VALUE | id::ADD_ENDPOINT | id::SET_POLICY | id::SET_VALUE => {
603 Shape::EzspStatus
604 }
605 id::NETWORK_INIT
606 | id::FORM_NETWORK
607 | id::LEAVE_NETWORK
608 | id::PERMIT_JOINING
609 | id::SET_INITIAL_SECURITY_STATE
610 | id::ERASE_KEY_TABLE_ENTRY
611 | id::CLEAR_KEY_TABLE
612 | id::SET_CONCENTRATOR
613 | id::SET_MFG_TOKEN
614 | id::SET_RADIO_POWER => Shape::Status,
615 id::IMPORT_LINK_KEY | id::IMPORT_TRANSIENT_KEY | id::START_SCAN => Shape::SlStatus,
616 id::SET_MANUFACTURER_CODE | id::CLEAR_TRANSIENT_LINK_KEYS | id::NOP => Shape::Empty,
617 id::VERSION
618 | id::GET_CONFIGURATION_VALUE
619 | id::GET_VALUE
620 | id::NETWORK_STATE
621 | id::GET_NETWORK_PARAMETERS
622 | id::GET_EUI64
623 | id::GET_NODE_ID
624 | id::EXPORT_KEY
625 | id::GET_NETWORK_KEY_INFO
626 | id::EXPORT_LINK_KEY_BY_INDEX
627 | id::SEND_UNICAST
628 | id::SEND_BROADCAST
629 | id::SET_SOURCE_ROUTE_DISCOVERY_MODE
630 | id::GET_MFG_TOKEN
631 | id::LOOKUP_EUI64_BY_NODE_ID
632 | id::ECHO
633 | id::INVALID_COMMAND => Shape::Special,
634 _ => return None,
635 })
636}
637
638fn read_ezsp_status(r: &mut Reader<'_>, v: ProtocolVersion) -> Result<Status, Truncated> {
639 Status::read(r, v)
640}
641
642impl Response {
643 pub fn frame_id(&self) -> u16 {
645 match self {
646 Response::Version { .. } => id::VERSION,
647 Response::GetConfigurationValue { .. } => id::GET_CONFIGURATION_VALUE,
648 Response::Status { frame_id, .. }
649 | Response::Sent { frame_id, .. }
650 | Response::Empty { frame_id } => *frame_id,
651 Response::GetValue { .. } => id::GET_VALUE,
652 Response::NetworkState { .. } => id::NETWORK_STATE,
653 Response::GetNetworkParameters { .. } => id::GET_NETWORK_PARAMETERS,
654 Response::GetEui64 { .. } => id::GET_EUI64,
655 Response::GetNodeId { .. } => id::GET_NODE_ID,
656 Response::ExportKey { .. } => id::EXPORT_KEY,
657 Response::GetNetworkKeyInfo { .. } => id::GET_NETWORK_KEY_INFO,
658 Response::ExportLinkKeyByIndex { .. } => id::EXPORT_LINK_KEY_BY_INDEX,
659 Response::SetSourceRouteDiscoveryMode { .. } => id::SET_SOURCE_ROUTE_DISCOVERY_MODE,
660 Response::GetMfgToken { .. } => id::GET_MFG_TOKEN,
661 Response::LookupEui64ByNodeId { .. } => id::LOOKUP_EUI64_BY_NODE_ID,
662 Response::Echo { .. } => id::ECHO,
663 Response::InvalidCommand { .. } => id::INVALID_COMMAND,
664 }
665 }
666
667 pub fn status(&self) -> Option<Status> {
669 match self {
670 Response::GetConfigurationValue { status, .. }
671 | Response::Status { status, .. }
672 | Response::GetValue { status, .. }
673 | Response::GetNetworkParameters { status, .. }
674 | Response::ExportKey { status, .. }
675 | Response::GetNetworkKeyInfo { status, .. }
676 | Response::ExportLinkKeyByIndex { status, .. }
677 | Response::Sent { status, .. }
678 | Response::LookupEui64ByNodeId { status, .. } => Some(*status),
679 _ => None,
680 }
681 }
682
683 pub fn decode(
685 v: ProtocolVersion,
686 frame_id: u16,
687 params: &[u8],
688 ) -> Result<Response, DecodeError> {
689 let mut r = Reader::new(params);
690 let shape = shape(frame_id).ok_or(DecodeError::UnknownFrame(frame_id))?;
691 let response = match shape {
692 Shape::Status => Response::Status {
693 frame_id,
694 status: Status::read(&mut r, v)?,
695 },
696 Shape::EzspStatus => Response::Status {
697 frame_id,
698 status: read_ezsp_status(&mut r, v)?,
699 },
700 Shape::SlStatus => Response::Status {
701 frame_id,
702 status: Status::read_sl(&mut r)?,
703 },
704 Shape::Empty => Response::Empty { frame_id },
705 Shape::Special => match frame_id {
706 id::VERSION => Response::Version {
707 protocol_version: r.u8()?,
708 stack_type: r.u8()?,
709 stack_version: r.u16()?,
710 },
711 id::GET_CONFIGURATION_VALUE => Response::GetConfigurationValue {
712 status: read_ezsp_status(&mut r, v)?,
713 value: r.u16()?,
714 },
715 id::GET_VALUE => Response::GetValue {
716 status: read_ezsp_status(&mut r, v)?,
717 value: r.u8_prefixed()?.to_vec(),
718 },
719 id::NETWORK_STATE => Response::NetworkState { state: r.u8()? },
720 id::GET_NETWORK_PARAMETERS => Response::GetNetworkParameters {
721 status: Status::read(&mut r, v)?,
722 node_type: r.u8()?,
723 parameters: NetworkParameters::read(&mut r)?,
724 },
725 id::GET_EUI64 => Response::GetEui64 { ieee: r.ieee()? },
726 id::GET_NODE_ID => Response::GetNodeId { node_id: r.u16()? },
727 id::EXPORT_KEY => {
728 if v.sl_status() {
729 let status = Status::read_sl(&mut r)?;
730 let key = r.key()?;
731 Response::ExportKey {
732 status,
733 key,
734 context: SecManContext::read(&mut r)?,
735 }
736 } else {
737 let key = r.key()?;
738 Response::ExportKey {
739 status: Status::read_sl(&mut r)?,
740 key,
741 context: SecManContext::default(),
742 }
743 }
744 }
745 id::GET_NETWORK_KEY_INFO => Response::GetNetworkKeyInfo {
746 status: Status::read_sl(&mut r)?,
747 info: NetworkKeyInfo::read(&mut r)?,
748 },
749 id::EXPORT_LINK_KEY_BY_INDEX => {
750 if v.sl_status() {
751 let status = Status::read_sl(&mut r)?;
752 let context = SecManContext::read(&mut r)?;
753 let key = r.key()?;
754 Response::ExportLinkKeyByIndex {
755 status,
756 context,
757 key,
758 metadata: ApsKeyMetadata::read(&mut r)?,
759 }
760 } else {
761 let ieee = r.ieee()?;
762 let key = r.key()?;
763 let metadata = ApsKeyMetadata::read(&mut r)?;
764 let status = Status::read_sl(&mut r)?;
765 let context = SecManContext {
766 core_key_type: crate::ids::key_type::APP_LINK,
767 ieee,
768 ..Default::default()
769 };
770 Response::ExportLinkKeyByIndex {
771 status,
772 context,
773 key,
774 metadata,
775 }
776 }
777 }
778 id::SEND_UNICAST | id::SEND_BROADCAST => Response::Sent {
779 frame_id,
780 status: Status::read(&mut r, v)?,
781 aps_sequence: r.u8()?,
782 },
783 id::SET_SOURCE_ROUTE_DISCOVERY_MODE => Response::SetSourceRouteDiscoveryMode {
784 remaining_ms: r.u32()?,
785 },
786 id::GET_MFG_TOKEN => Response::GetMfgToken {
787 data: r.u8_prefixed()?.to_vec(),
788 },
789 id::LOOKUP_EUI64_BY_NODE_ID => Response::LookupEui64ByNodeId {
790 status: Status::read(&mut r, v)?,
791 ieee: r.ieee()?,
792 },
793 id::ECHO => Response::Echo {
794 data: r.u8_prefixed()?.to_vec(),
795 },
796 id::INVALID_COMMAND => Response::InvalidCommand { reason: r.u8()? },
797 other => return Err(DecodeError::UnknownFrame(other)),
798 },
799 };
800 Ok(response)
803 }
804
805 pub fn encode(&self, v: ProtocolVersion) -> Vec<u8> {
808 let mut w = Vec::with_capacity(32);
809 match self {
810 Response::Version {
811 protocol_version,
812 stack_type,
813 stack_version,
814 } => {
815 w.put_u8(*protocol_version);
816 w.put_u8(*stack_type);
817 w.put_u16(*stack_version);
818 }
819 Response::GetConfigurationValue { status, value } => {
820 status.write(&mut w);
821 w.put_u16(*value);
822 }
823 Response::Status { status, .. } => status.write(&mut w),
824 Response::GetValue { status, value } => {
825 status.write(&mut w);
826 w.put_u8_prefixed(value);
827 }
828 Response::NetworkState { state } => w.put_u8(*state),
829 Response::GetNetworkParameters {
830 status,
831 node_type,
832 parameters,
833 } => {
834 status.write(&mut w);
835 w.put_u8(*node_type);
836 parameters.write(&mut w);
837 }
838 Response::GetEui64 { ieee } => w.put_ieee(*ieee),
839 Response::GetNodeId { node_id } => w.put_u16(*node_id),
840 Response::ExportKey {
841 status,
842 key,
843 context,
844 } => {
845 if v.sl_status() {
846 status.write(&mut w);
847 w.put_key(key);
848 context.write(&mut w);
849 } else {
850 w.put_key(key);
851 status.write(&mut w);
852 }
853 }
854 Response::GetNetworkKeyInfo { status, info } => {
855 status.write(&mut w);
856 info.write(&mut w);
857 }
858 Response::ExportLinkKeyByIndex {
859 status,
860 context,
861 key,
862 metadata,
863 } => {
864 if v.sl_status() {
865 status.write(&mut w);
866 context.write(&mut w);
867 w.put_key(key);
868 metadata.write(&mut w);
869 } else {
870 w.put_ieee(context.ieee);
871 w.put_key(key);
872 metadata.write(&mut w);
873 status.write(&mut w);
874 }
875 }
876 Response::Sent {
877 status,
878 aps_sequence,
879 ..
880 } => {
881 status.write(&mut w);
882 w.put_u8(*aps_sequence);
883 }
884 Response::SetSourceRouteDiscoveryMode { remaining_ms } => w.put_u32(*remaining_ms),
885 Response::GetMfgToken { data } | Response::Echo { data } => w.put_u8_prefixed(data),
886 Response::LookupEui64ByNodeId { status, ieee } => {
887 status.write(&mut w);
888 w.put_ieee(*ieee);
889 }
890 Response::Empty { .. } => {}
891 Response::InvalidCommand { reason } => w.put_u8(*reason),
892 }
893 w
894 }
895}
896
897#[cfg(test)]
898mod tests {
899 use super::*;
900
901 fn every_command() -> Vec<Command> {
902 let aps = ApsFrame {
903 profile_id: 0x0104,
904 cluster_id: 6,
905 source_endpoint: 1,
906 destination_endpoint: 1,
907 options: 0x140,
908 group_id: 0,
909 sequence: 9,
910 };
911 vec![
912 Command::Version { desired: 13 },
913 Command::GetConfigurationValue { config_id: 0x1E },
914 Command::SetConfigurationValue {
915 config_id: 0x11,
916 value: 32,
917 },
918 Command::AddEndpoint {
919 endpoint: 1,
920 profile_id: 0x0104,
921 device_id: 5,
922 device_version: 0,
923 input_clusters: vec![0, 3],
924 output_clusters: vec![6],
925 },
926 Command::SetPolicy {
927 policy_id: 5,
928 decision: 0x51,
929 },
930 Command::GetValue { value_id: 0x11 },
931 Command::SetValue {
932 value_id: 0x23,
933 value: vec![1, 2, 3, 4],
934 },
935 Command::SetManufacturerCode { code: 0x1049 },
936 Command::NetworkInit { bitmask: 3 },
937 Command::NetworkState,
938 Command::FormNetwork {
939 parameters: NetworkParameters {
940 radio_channel: 15,
941 ..Default::default()
942 },
943 },
944 Command::PermitJoining { duration: 254 },
945 Command::GetNetworkParameters,
946 Command::GetEui64,
947 Command::GetNodeId,
948 Command::SetInitialSecurityState {
949 state: InitialSecurityState {
950 bitmask: 0x0B84,
951 ..Default::default()
952 },
953 },
954 Command::ExportKey {
955 context: SecManContext::for_key(1),
956 },
957 Command::GetNetworkKeyInfo,
958 Command::ExportLinkKeyByIndex { index: 3 },
959 Command::ImportLinkKey {
960 index: 1,
961 ieee: Ieee(42),
962 key: Key([7; 16]),
963 },
964 Command::EraseKeyTableEntry { index: 2 },
965 Command::ImportTransientKey {
966 ieee: Ieee(9),
967 key: Key::ZIGBEE_ALLIANCE_09,
968 },
969 Command::ClearTransientLinkKeys,
970 Command::ClearKeyTable,
971 Command::SendUnicast {
972 kind: 0,
973 destination: 0x1234,
974 aps,
975 tag: 7,
976 payload: vec![0x10, 1, 0, 0, 0],
977 },
978 Command::SetConcentrator {
979 on: true,
980 kind: 0xFFF9,
981 min_time: 5,
982 max_time: 60,
983 route_error_threshold: 3,
984 delivery_failure_threshold: 1,
985 max_hops: 0,
986 },
987 Command::SetSourceRouteDiscoveryMode { mode: 2 },
988 Command::GetMfgToken { token_id: 0x0C },
989 Command::SetMfgToken {
990 token_id: 0x0C,
991 data: vec![1; 8],
992 },
993 Command::StartScan {
994 scan_type: 0,
995 channel_mask: 0x07FF_F800,
996 duration: 3,
997 },
998 Command::LookupEui64ByNodeId { node_id: 0x1234 },
999 Command::SetRadioPower { power: -4 },
1000 Command::Echo {
1001 data: vec![1, 2, 3],
1002 },
1003 Command::Nop,
1004 ]
1005 }
1006
1007 #[test]
1008 fn commands_round_trip_in_both_layouts() {
1009 for v in [ProtocolVersion(13), ProtocolVersion(16)] {
1010 for c in every_command() {
1011 let bytes = c.encode(v);
1012 assert_eq!(
1013 Command::decode(v, c.frame_id(), &bytes),
1014 Ok(c.clone()),
1015 "{c:?} v{}",
1016 v.0
1017 );
1018 }
1019 let b = Command::SendBroadcast {
1020 alias: if v.sl_status() { 1 } else { 0 },
1021 destination: 0xFFFC,
1022 nwk_sequence: 0,
1023 aps: ApsFrame::default(),
1024 radius: 30,
1025 tag: 1,
1026 payload: vec![0, 1, 2],
1027 };
1028 assert_eq!(Command::decode(v, b.frame_id(), &b.encode(v)), Ok(b));
1029 }
1030 }
1031
1032 #[test]
1033 fn unicast_layout_differs_by_version() {
1034 let c = Command::SendUnicast {
1035 kind: 0,
1036 destination: 1,
1037 aps: ApsFrame::default(),
1038 tag: 0x0102,
1039 payload: vec![],
1040 };
1041 assert_eq!(
1042 c.encode(ProtocolVersion(13)).len() + 1,
1043 c.encode(ProtocolVersion(14)).len()
1044 );
1045 }
1046
1047 #[test]
1048 fn responses_round_trip() {
1049 for v in [ProtocolVersion(13), ProtocolVersion(18)] {
1050 let responses = vec![
1051 Response::Version {
1052 protocol_version: 13,
1053 stack_type: 2,
1054 stack_version: 0x7440,
1055 },
1056 Response::GetConfigurationValue {
1057 status: Status::ok(v),
1058 value: 12,
1059 },
1060 Response::Status {
1061 frame_id: id::FORM_NETWORK,
1062 status: Status::ok(v),
1063 },
1064 Response::Status {
1065 frame_id: id::IMPORT_TRANSIENT_KEY,
1066 status: Status::SL_OK,
1067 },
1068 Response::GetValue {
1069 status: Status::ok(v),
1070 value: vec![1, 2, 3, 4, 5, 6, 7],
1071 },
1072 Response::NetworkState { state: 2 },
1073 Response::GetEui64 { ieee: Ieee(0x1122) },
1074 Response::GetNodeId { node_id: 0 },
1075 Response::GetNetworkKeyInfo {
1076 status: Status::SL_OK,
1077 info: NetworkKeyInfo {
1078 network_key_set: true,
1079 network_key_frame_counter: 99,
1080 ..Default::default()
1081 },
1082 },
1083 Response::Sent {
1084 frame_id: id::SEND_UNICAST,
1085 status: Status::ok(v),
1086 aps_sequence: 3,
1087 },
1088 Response::Empty { frame_id: id::NOP },
1089 Response::InvalidCommand { reason: 0x58 },
1090 ];
1091 for resp in responses {
1092 assert_eq!(
1093 Response::decode(v, resp.frame_id(), &resp.encode(v)),
1094 Ok(resp.clone()),
1095 "{resp:?}"
1096 );
1097 }
1098 let export = Response::ExportLinkKeyByIndex {
1099 status: Status::SL_OK,
1100 context: SecManContext {
1101 core_key_type: crate::ids::key_type::APP_LINK,
1102 ieee: Ieee(77),
1103 ..Default::default()
1104 },
1105 key: Key([3; 16]),
1106 metadata: ApsKeyMetadata {
1107 outgoing_frame_counter: 5,
1108 ..Default::default()
1109 },
1110 };
1111 assert_eq!(
1112 Response::decode(v, export.frame_id(), &export.encode(v)),
1113 Ok(export)
1114 );
1115 }
1116 }
1117}