Skip to main content

zigbee_ezsp/
command.rs

1//! Typed EZSP commands (host to NCP) and their responses (NCP to host).
2//!
3//! Both directions encode and decode, so the host and the repository's NCP
4//! simulator share one definition of every frame. Layouts that changed
5//! between protocol version 13 and 14 take the version.
6
7use 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, KeyStruct, NetworkKeyInfo, NetworkParameters,
13    ProtocolVersion, SecManContext, Status,
14};
15
16/// A frame's parameters did not decode.
17#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
18pub enum DecodeError {
19    /// Too short.
20    #[error(transparent)]
21    Truncated(#[from] Truncated),
22    /// Bytes were left over.
23    #[error("{0} trailing bytes")]
24    Trailing(usize),
25    /// The frame id is not one this crate knows in this direction.
26    #[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/// A command from the host.
38#[derive(Debug, Clone, PartialEq, Eq)]
39#[allow(missing_docs)]
40pub enum Command {
41    /// Negotiate the protocol version.
42    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    /// Before protocol 13: read a key by [`crate::ids::ember_key_type`].
115    GetKey {
116        key_type: u8,
117    },
118    /// Before protocol 13: read a key table entry.
119    GetKeyTableEntry {
120        index: u8,
121    },
122    /// Before protocol 13: write a key table entry.
123    SetKeyTableEntry {
124        index: u8,
125        ieee: Ieee,
126        link_key: bool,
127        key: Key,
128    },
129    /// Before protocol 13: a temporary key for one joining device.
130    AddTransientLinkKey {
131        ieee: Ieee,
132        key: Key,
133    },
134    SendUnicast {
135        kind: u8,
136        destination: NodeId,
137        aps: ApsFrame,
138        tag: u16,
139        payload: Vec<u8>,
140    },
141    SendBroadcast {
142        alias: NodeId,
143        destination: NodeId,
144        nwk_sequence: u8,
145        aps: ApsFrame,
146        radius: u8,
147        tag: u16,
148        payload: Vec<u8>,
149    },
150    SetConcentrator {
151        on: bool,
152        kind: u16,
153        min_time: u16,
154        max_time: u16,
155        route_error_threshold: u8,
156        delivery_failure_threshold: u8,
157        max_hops: u8,
158    },
159    SetSourceRouteDiscoveryMode {
160        mode: u8,
161    },
162    GetMfgToken {
163        token_id: u8,
164    },
165    SetMfgToken {
166        token_id: u8,
167        data: Vec<u8>,
168    },
169    StartScan {
170        scan_type: u8,
171        channel_mask: u32,
172        duration: u8,
173    },
174    LookupEui64ByNodeId {
175        node_id: NodeId,
176    },
177    SetRadioPower {
178        power: i8,
179    },
180    Echo {
181        data: Vec<u8>,
182    },
183    Nop,
184}
185
186impl Command {
187    /// The frame id.
188    pub fn frame_id(&self) -> u16 {
189        match self {
190            Command::Version { .. } => id::VERSION,
191            Command::GetConfigurationValue { .. } => id::GET_CONFIGURATION_VALUE,
192            Command::SetConfigurationValue { .. } => id::SET_CONFIGURATION_VALUE,
193            Command::AddEndpoint { .. } => id::ADD_ENDPOINT,
194            Command::SetPolicy { .. } => id::SET_POLICY,
195            Command::GetValue { .. } => id::GET_VALUE,
196            Command::SetValue { .. } => id::SET_VALUE,
197            Command::SetManufacturerCode { .. } => id::SET_MANUFACTURER_CODE,
198            Command::NetworkInit { .. } => id::NETWORK_INIT,
199            Command::NetworkState => id::NETWORK_STATE,
200            Command::FormNetwork { .. } => id::FORM_NETWORK,
201            Command::LeaveNetwork { .. } => id::LEAVE_NETWORK,
202            Command::PermitJoining { .. } => id::PERMIT_JOINING,
203            Command::GetNetworkParameters => id::GET_NETWORK_PARAMETERS,
204            Command::GetEui64 => id::GET_EUI64,
205            Command::GetNodeId => id::GET_NODE_ID,
206            Command::SetInitialSecurityState { .. } => id::SET_INITIAL_SECURITY_STATE,
207            Command::ExportKey { .. } => id::EXPORT_KEY,
208            Command::GetNetworkKeyInfo => id::GET_NETWORK_KEY_INFO,
209            Command::ExportLinkKeyByIndex { .. } => id::EXPORT_LINK_KEY_BY_INDEX,
210            Command::ImportLinkKey { .. } => id::IMPORT_LINK_KEY,
211            Command::EraseKeyTableEntry { .. } => id::ERASE_KEY_TABLE_ENTRY,
212            Command::ImportTransientKey { .. } => id::IMPORT_TRANSIENT_KEY,
213            Command::ClearTransientLinkKeys => id::CLEAR_TRANSIENT_LINK_KEYS,
214            Command::ClearKeyTable => id::CLEAR_KEY_TABLE,
215            Command::GetKey { .. } => id::GET_KEY,
216            Command::GetKeyTableEntry { .. } => id::GET_KEY_TABLE_ENTRY,
217            Command::SetKeyTableEntry { .. } => id::SET_KEY_TABLE_ENTRY,
218            Command::AddTransientLinkKey { .. } => id::ADD_TRANSIENT_LINK_KEY,
219            Command::SendUnicast { .. } => id::SEND_UNICAST,
220            Command::SendBroadcast { .. } => id::SEND_BROADCAST,
221            Command::SetConcentrator { .. } => id::SET_CONCENTRATOR,
222            Command::SetSourceRouteDiscoveryMode { .. } => id::SET_SOURCE_ROUTE_DISCOVERY_MODE,
223            Command::GetMfgToken { .. } => id::GET_MFG_TOKEN,
224            Command::SetMfgToken { .. } => id::SET_MFG_TOKEN,
225            Command::StartScan { .. } => id::START_SCAN,
226            Command::LookupEui64ByNodeId { .. } => id::LOOKUP_EUI64_BY_NODE_ID,
227            Command::SetRadioPower { .. } => id::SET_RADIO_POWER,
228            Command::Echo { .. } => id::ECHO,
229            Command::Nop => id::NOP,
230        }
231    }
232
233    /// Encode the parameters.
234    pub fn encode(&self, v: ProtocolVersion) -> Vec<u8> {
235        let mut w = Vec::with_capacity(32);
236        match self {
237            Command::Version { desired } => w.put_u8(*desired),
238            Command::GetConfigurationValue { config_id } => w.put_u8(*config_id),
239            Command::SetConfigurationValue { config_id, value } => {
240                w.put_u8(*config_id);
241                w.put_u16(*value);
242            }
243            Command::AddEndpoint {
244                endpoint,
245                profile_id,
246                device_id,
247                device_version,
248                input_clusters,
249                output_clusters,
250            } => {
251                w.put_u8(*endpoint);
252                w.put_u16(*profile_id);
253                w.put_u16(*device_id);
254                w.put_u8(*device_version);
255                w.put_u8(input_clusters.len() as u8);
256                w.put_u8(output_clusters.len() as u8);
257                input_clusters.iter().for_each(|c| w.put_u16(*c));
258                output_clusters.iter().for_each(|c| w.put_u16(*c));
259            }
260            Command::SetPolicy {
261                policy_id,
262                decision,
263            } => {
264                w.put_u8(*policy_id);
265                w.put_u8(*decision);
266            }
267            Command::GetValue { value_id } => w.put_u8(*value_id),
268            Command::SetValue { value_id, value } => {
269                w.put_u8(*value_id);
270                w.put_u8_prefixed(value);
271            }
272            Command::SetManufacturerCode { code } => w.put_u16(*code),
273            Command::NetworkInit { bitmask } => w.put_u16(*bitmask),
274            Command::FormNetwork { parameters } => parameters.write(&mut w),
275            Command::LeaveNetwork { options } => {
276                if v.sl_status() {
277                    w.put_u8(*options);
278                }
279            }
280            Command::PermitJoining { duration } => w.put_u8(*duration),
281            Command::SetInitialSecurityState { state } => state.write(&mut w),
282            Command::ExportKey { context } => context.write(&mut w),
283            Command::ExportLinkKeyByIndex { index }
284            | Command::EraseKeyTableEntry { index }
285            | Command::GetKeyTableEntry { index } => w.put_u8(*index),
286            Command::GetKey { key_type } => w.put_u8(*key_type),
287            Command::SetKeyTableEntry {
288                index,
289                ieee,
290                link_key,
291                key,
292            } => {
293                w.put_u8(*index);
294                w.put_ieee(*ieee);
295                w.put_u8(u8::from(*link_key));
296                w.put_key(key);
297            }
298            Command::AddTransientLinkKey { ieee, key } => {
299                w.put_ieee(*ieee);
300                w.put_key(key);
301            }
302            Command::ImportLinkKey { index, ieee, key } => {
303                w.put_u8(*index);
304                w.put_ieee(*ieee);
305                w.put_key(key);
306            }
307            Command::ImportTransientKey { ieee, key } => {
308                w.put_ieee(*ieee);
309                w.put_key(key);
310                if !v.sl_status() {
311                    w.put_u8(0); // sl_zb_sec_man_flags_t: none
312                }
313            }
314            Command::SendUnicast {
315                kind,
316                destination,
317                aps,
318                tag,
319                payload,
320            } => {
321                w.put_u8(*kind);
322                w.put_u16(*destination);
323                aps.write(&mut w);
324                put_tag(&mut w, v, *tag);
325                w.put_u8_prefixed(payload);
326            }
327            Command::SendBroadcast {
328                alias,
329                destination,
330                nwk_sequence,
331                aps,
332                radius,
333                tag,
334                payload,
335            } => {
336                if v.sl_status() {
337                    w.put_u16(*alias);
338                    w.put_u16(*destination);
339                    w.put_u8(*nwk_sequence);
340                } else {
341                    w.put_u16(*destination);
342                }
343                aps.write(&mut w);
344                w.put_u8(*radius);
345                put_tag(&mut w, v, *tag);
346                w.put_u8_prefixed(payload);
347            }
348            Command::SetConcentrator {
349                on,
350                kind,
351                min_time,
352                max_time,
353                route_error_threshold,
354                delivery_failure_threshold,
355                max_hops,
356            } => {
357                w.put_u8(u8::from(*on));
358                w.put_u16(*kind);
359                w.put_u16(*min_time);
360                w.put_u16(*max_time);
361                w.put_u8(*route_error_threshold);
362                w.put_u8(*delivery_failure_threshold);
363                w.put_u8(*max_hops);
364            }
365            Command::SetSourceRouteDiscoveryMode { mode } => w.put_u8(*mode),
366            Command::GetMfgToken { token_id } => w.put_u8(*token_id),
367            Command::SetMfgToken { token_id, data } => {
368                w.put_u8(*token_id);
369                w.put_u8_prefixed(data);
370            }
371            Command::StartScan {
372                scan_type,
373                channel_mask,
374                duration,
375            } => {
376                w.put_u8(*scan_type);
377                w.put_u32(*channel_mask);
378                w.put_u8(*duration);
379            }
380            Command::LookupEui64ByNodeId { node_id } => w.put_u16(*node_id),
381            Command::SetRadioPower { power } => w.put_u8(*power as u8),
382            Command::Echo { data } => w.put_u8_prefixed(data),
383            Command::NetworkState
384            | Command::GetNetworkParameters
385            | Command::GetEui64
386            | Command::GetNodeId
387            | Command::GetNetworkKeyInfo
388            | Command::ClearTransientLinkKeys
389            | Command::ClearKeyTable
390            | Command::Nop => {}
391        }
392        w
393    }
394
395    /// Decode a command (the NCP side).
396    pub fn decode(
397        v: ProtocolVersion,
398        frame_id: u16,
399        params: &[u8],
400    ) -> Result<Command, DecodeError> {
401        let mut r = Reader::new(params);
402        let c = match frame_id {
403            id::VERSION => Command::Version { desired: r.u8()? },
404            id::GET_CONFIGURATION_VALUE => Command::GetConfigurationValue { config_id: r.u8()? },
405            id::SET_CONFIGURATION_VALUE => Command::SetConfigurationValue {
406                config_id: r.u8()?,
407                value: r.u16()?,
408            },
409            id::ADD_ENDPOINT => {
410                let endpoint = r.u8()?;
411                let profile_id = r.u16()?;
412                let device_id = r.u16()?;
413                let device_version = r.u8()?;
414                let inputs = usize::from(r.u8()?);
415                let outputs = usize::from(r.u8()?);
416                Command::AddEndpoint {
417                    endpoint,
418                    profile_id,
419                    device_id,
420                    device_version,
421                    input_clusters: r.u16_list(inputs)?,
422                    output_clusters: r.u16_list(outputs)?,
423                }
424            }
425            id::SET_POLICY => Command::SetPolicy {
426                policy_id: r.u8()?,
427                decision: r.u8()?,
428            },
429            id::GET_VALUE => Command::GetValue { value_id: r.u8()? },
430            id::SET_VALUE => Command::SetValue {
431                value_id: r.u8()?,
432                value: r.u8_prefixed()?.to_vec(),
433            },
434            id::SET_MANUFACTURER_CODE => Command::SetManufacturerCode { code: r.u16()? },
435            id::NETWORK_INIT => Command::NetworkInit { bitmask: r.u16()? },
436            id::NETWORK_STATE => Command::NetworkState,
437            id::FORM_NETWORK => Command::FormNetwork {
438                parameters: NetworkParameters::read(&mut r)?,
439            },
440            id::LEAVE_NETWORK => Command::LeaveNetwork {
441                options: if v.sl_status() { r.u8()? } else { 0 },
442            },
443            id::PERMIT_JOINING => Command::PermitJoining { duration: r.u8()? },
444            id::GET_NETWORK_PARAMETERS => Command::GetNetworkParameters,
445            id::GET_EUI64 => Command::GetEui64,
446            id::GET_NODE_ID => Command::GetNodeId,
447            id::SET_INITIAL_SECURITY_STATE => Command::SetInitialSecurityState {
448                state: InitialSecurityState::read(&mut r)?,
449            },
450            id::EXPORT_KEY => Command::ExportKey {
451                context: SecManContext::read(&mut r)?,
452            },
453            id::GET_NETWORK_KEY_INFO => Command::GetNetworkKeyInfo,
454            id::EXPORT_LINK_KEY_BY_INDEX => Command::ExportLinkKeyByIndex { index: r.u8()? },
455            id::IMPORT_LINK_KEY => Command::ImportLinkKey {
456                index: r.u8()?,
457                ieee: r.ieee()?,
458                key: r.key()?,
459            },
460            id::ERASE_KEY_TABLE_ENTRY => Command::EraseKeyTableEntry { index: r.u8()? },
461            id::IMPORT_TRANSIENT_KEY => {
462                let c = Command::ImportTransientKey {
463                    ieee: r.ieee()?,
464                    key: r.key()?,
465                };
466                if !v.sl_status() {
467                    r.u8()?;
468                }
469                c
470            }
471            id::CLEAR_TRANSIENT_LINK_KEYS => Command::ClearTransientLinkKeys,
472            id::CLEAR_KEY_TABLE => Command::ClearKeyTable,
473            id::GET_KEY => Command::GetKey { key_type: r.u8()? },
474            id::GET_KEY_TABLE_ENTRY => Command::GetKeyTableEntry { index: r.u8()? },
475            id::SET_KEY_TABLE_ENTRY => Command::SetKeyTableEntry {
476                index: r.u8()?,
477                ieee: r.ieee()?,
478                link_key: r.bool()?,
479                key: r.key()?,
480            },
481            id::ADD_TRANSIENT_LINK_KEY => Command::AddTransientLinkKey {
482                ieee: r.ieee()?,
483                key: r.key()?,
484            },
485            id::SEND_UNICAST => Command::SendUnicast {
486                kind: r.u8()?,
487                destination: r.u16()?,
488                aps: ApsFrame::read(&mut r)?,
489                tag: read_tag(&mut r, v)?,
490                payload: r.u8_prefixed()?.to_vec(),
491            },
492            id::SEND_BROADCAST => {
493                let (alias, destination, nwk_sequence) = if v.sl_status() {
494                    (r.u16()?, r.u16()?, r.u8()?)
495                } else {
496                    (0, r.u16()?, 0)
497                };
498                Command::SendBroadcast {
499                    alias,
500                    destination,
501                    nwk_sequence,
502                    aps: ApsFrame::read(&mut r)?,
503                    radius: r.u8()?,
504                    tag: read_tag(&mut r, v)?,
505                    payload: r.u8_prefixed()?.to_vec(),
506                }
507            }
508            id::SET_CONCENTRATOR => Command::SetConcentrator {
509                on: r.bool()?,
510                kind: r.u16()?,
511                min_time: r.u16()?,
512                max_time: r.u16()?,
513                route_error_threshold: r.u8()?,
514                delivery_failure_threshold: r.u8()?,
515                max_hops: r.u8()?,
516            },
517            id::SET_SOURCE_ROUTE_DISCOVERY_MODE => {
518                Command::SetSourceRouteDiscoveryMode { mode: r.u8()? }
519            }
520            id::GET_MFG_TOKEN => Command::GetMfgToken { token_id: r.u8()? },
521            id::SET_MFG_TOKEN => Command::SetMfgToken {
522                token_id: r.u8()?,
523                data: r.u8_prefixed()?.to_vec(),
524            },
525            id::START_SCAN => Command::StartScan {
526                scan_type: r.u8()?,
527                channel_mask: r.u32()?,
528                duration: r.u8()?,
529            },
530            id::LOOKUP_EUI64_BY_NODE_ID => Command::LookupEui64ByNodeId { node_id: r.u16()? },
531            id::SET_RADIO_POWER => Command::SetRadioPower { power: r.i8()? },
532            id::ECHO => Command::Echo {
533                data: r.u8_prefixed()?.to_vec(),
534            },
535            id::NOP => Command::Nop,
536            other => return Err(DecodeError::UnknownFrame(other)),
537        };
538        done(&r)?;
539        Ok(c)
540    }
541}
542
543fn put_tag(w: &mut Vec<u8>, v: ProtocolVersion, tag: u16) {
544    if v.sl_status() {
545        w.put_u16(tag);
546    } else {
547        w.put_u8(tag as u8);
548    }
549}
550
551fn read_tag(r: &mut Reader<'_>, v: ProtocolVersion) -> Result<u16, Truncated> {
552    if v.sl_status() {
553        r.u16()
554    } else {
555        r.u8().map(u16::from)
556    }
557}
558
559/// A response from the NCP. Each variant is the response to the
560/// [`Command`] of the same frame id.
561#[derive(Debug, Clone, PartialEq, Eq)]
562#[allow(missing_docs)]
563pub enum Response {
564    Version {
565        protocol_version: u8,
566        stack_type: u8,
567        stack_version: u16,
568    },
569    GetConfigurationValue {
570        status: Status,
571        value: u16,
572    },
573    /// Every command whose only result is a status.
574    Status {
575        frame_id: u16,
576        status: Status,
577    },
578    GetValue {
579        status: Status,
580        value: Vec<u8>,
581    },
582    NetworkState {
583        state: u8,
584    },
585    GetNetworkParameters {
586        status: Status,
587        node_type: u8,
588        parameters: NetworkParameters,
589    },
590    GetEui64 {
591        ieee: Ieee,
592    },
593    GetNodeId {
594        node_id: NodeId,
595    },
596    ExportKey {
597        status: Status,
598        key: Key,
599        context: SecManContext,
600    },
601    GetNetworkKeyInfo {
602        status: Status,
603        info: NetworkKeyInfo,
604    },
605    ExportLinkKeyByIndex {
606        status: Status,
607        context: SecManContext,
608        key: Key,
609        metadata: ApsKeyMetadata,
610    },
611    /// `getKey` (before protocol 13).
612    GetKey {
613        status: Status,
614        key: KeyStruct,
615    },
616    /// `getKeyTableEntry` (before protocol 13).
617    GetKeyTableEntry {
618        status: Status,
619        key: KeyStruct,
620    },
621    /// `sendUnicast` and `sendBroadcast`.
622    Sent {
623        frame_id: u16,
624        status: Status,
625        aps_sequence: u8,
626    },
627    SetSourceRouteDiscoveryMode {
628        remaining_ms: u32,
629    },
630    GetMfgToken {
631        data: Vec<u8>,
632    },
633    LookupEui64ByNodeId {
634        status: Status,
635        ieee: Ieee,
636    },
637    Echo {
638        data: Vec<u8>,
639    },
640    /// Commands with no return values.
641    Empty {
642        frame_id: u16,
643    },
644    /// The NCP did not understand the command (`invalidCommand`).
645    InvalidCommand {
646        reason: u8,
647    },
648}
649
650/// How each command's response is laid out.
651enum Shape {
652    /// Status in the version's width (`EmberStatus` before 14).
653    Status,
654    /// `EzspStatus`: one byte before 14, `sl_status_t` after.
655    EzspStatus,
656    /// `sl_status_t` in every version.
657    SlStatus,
658    Empty,
659    Special,
660}
661
662fn shape(frame_id: u16, v: ProtocolVersion) -> Option<Shape> {
663    Some(match frame_id {
664        // `startScan` returned an `EmberStatus` until protocol 13.
665        id::START_SCAN if !v.sec_man() => Shape::Status,
666        id::SET_CONFIGURATION_VALUE | id::ADD_ENDPOINT | id::SET_POLICY | id::SET_VALUE => {
667            Shape::EzspStatus
668        }
669        id::NETWORK_INIT
670        | id::FORM_NETWORK
671        | id::LEAVE_NETWORK
672        | id::PERMIT_JOINING
673        | id::SET_INITIAL_SECURITY_STATE
674        | id::ERASE_KEY_TABLE_ENTRY
675        | id::CLEAR_KEY_TABLE
676        | id::SET_CONCENTRATOR
677        | id::SET_MFG_TOKEN
678        | id::SET_RADIO_POWER
679        | id::SET_KEY_TABLE_ENTRY
680        | id::ADD_TRANSIENT_LINK_KEY => Shape::Status,
681        id::IMPORT_LINK_KEY | id::IMPORT_TRANSIENT_KEY | id::START_SCAN => Shape::SlStatus,
682        id::SET_MANUFACTURER_CODE | id::CLEAR_TRANSIENT_LINK_KEYS | id::NOP => Shape::Empty,
683        id::VERSION
684        | id::GET_CONFIGURATION_VALUE
685        | id::GET_VALUE
686        | id::NETWORK_STATE
687        | id::GET_NETWORK_PARAMETERS
688        | id::GET_EUI64
689        | id::GET_NODE_ID
690        | id::EXPORT_KEY
691        | id::GET_NETWORK_KEY_INFO
692        | id::EXPORT_LINK_KEY_BY_INDEX
693        | id::GET_KEY
694        | id::GET_KEY_TABLE_ENTRY
695        | id::SEND_UNICAST
696        | id::SEND_BROADCAST
697        | id::SET_SOURCE_ROUTE_DISCOVERY_MODE
698        | id::GET_MFG_TOKEN
699        | id::LOOKUP_EUI64_BY_NODE_ID
700        | id::ECHO
701        | id::INVALID_COMMAND => Shape::Special,
702        _ => return None,
703    })
704}
705
706fn read_ezsp_status(r: &mut Reader<'_>, v: ProtocolVersion) -> Result<Status, Truncated> {
707    Status::read(r, v)
708}
709
710impl Response {
711    /// The frame id this response answers.
712    pub fn frame_id(&self) -> u16 {
713        match self {
714            Response::Version { .. } => id::VERSION,
715            Response::GetConfigurationValue { .. } => id::GET_CONFIGURATION_VALUE,
716            Response::Status { frame_id, .. }
717            | Response::Sent { frame_id, .. }
718            | Response::Empty { frame_id } => *frame_id,
719            Response::GetValue { .. } => id::GET_VALUE,
720            Response::NetworkState { .. } => id::NETWORK_STATE,
721            Response::GetNetworkParameters { .. } => id::GET_NETWORK_PARAMETERS,
722            Response::GetEui64 { .. } => id::GET_EUI64,
723            Response::GetNodeId { .. } => id::GET_NODE_ID,
724            Response::ExportKey { .. } => id::EXPORT_KEY,
725            Response::GetNetworkKeyInfo { .. } => id::GET_NETWORK_KEY_INFO,
726            Response::ExportLinkKeyByIndex { .. } => id::EXPORT_LINK_KEY_BY_INDEX,
727            Response::GetKey { .. } => id::GET_KEY,
728            Response::GetKeyTableEntry { .. } => id::GET_KEY_TABLE_ENTRY,
729            Response::SetSourceRouteDiscoveryMode { .. } => id::SET_SOURCE_ROUTE_DISCOVERY_MODE,
730            Response::GetMfgToken { .. } => id::GET_MFG_TOKEN,
731            Response::LookupEui64ByNodeId { .. } => id::LOOKUP_EUI64_BY_NODE_ID,
732            Response::Echo { .. } => id::ECHO,
733            Response::InvalidCommand { .. } => id::INVALID_COMMAND,
734        }
735    }
736
737    /// The status, for responses that carry one.
738    pub fn status(&self) -> Option<Status> {
739        match self {
740            Response::GetConfigurationValue { status, .. }
741            | Response::Status { status, .. }
742            | Response::GetValue { status, .. }
743            | Response::GetNetworkParameters { status, .. }
744            | Response::ExportKey { status, .. }
745            | Response::GetNetworkKeyInfo { status, .. }
746            | Response::ExportLinkKeyByIndex { status, .. }
747            | Response::GetKey { status, .. }
748            | Response::GetKeyTableEntry { status, .. }
749            | Response::Sent { status, .. }
750            | Response::LookupEui64ByNodeId { status, .. } => Some(*status),
751            _ => None,
752        }
753    }
754
755    /// Decode a response (the host side).
756    pub fn decode(
757        v: ProtocolVersion,
758        frame_id: u16,
759        params: &[u8],
760    ) -> Result<Response, DecodeError> {
761        let mut r = Reader::new(params);
762        let shape = shape(frame_id, v).ok_or(DecodeError::UnknownFrame(frame_id))?;
763        let response = match shape {
764            Shape::Status => Response::Status {
765                frame_id,
766                status: Status::read(&mut r, v)?,
767            },
768            Shape::EzspStatus => Response::Status {
769                frame_id,
770                status: read_ezsp_status(&mut r, v)?,
771            },
772            Shape::SlStatus => Response::Status {
773                frame_id,
774                status: Status::read_sl(&mut r)?,
775            },
776            Shape::Empty => Response::Empty { frame_id },
777            Shape::Special => match frame_id {
778                id::VERSION => Response::Version {
779                    protocol_version: r.u8()?,
780                    stack_type: r.u8()?,
781                    stack_version: r.u16()?,
782                },
783                id::GET_CONFIGURATION_VALUE => Response::GetConfigurationValue {
784                    status: read_ezsp_status(&mut r, v)?,
785                    value: r.u16()?,
786                },
787                id::GET_VALUE => Response::GetValue {
788                    status: read_ezsp_status(&mut r, v)?,
789                    value: r.u8_prefixed()?.to_vec(),
790                },
791                id::NETWORK_STATE => Response::NetworkState { state: r.u8()? },
792                id::GET_NETWORK_PARAMETERS => Response::GetNetworkParameters {
793                    status: Status::read(&mut r, v)?,
794                    node_type: r.u8()?,
795                    parameters: NetworkParameters::read(&mut r)?,
796                },
797                id::GET_EUI64 => Response::GetEui64 { ieee: r.ieee()? },
798                id::GET_NODE_ID => Response::GetNodeId { node_id: r.u16()? },
799                id::EXPORT_KEY => {
800                    if v.sl_status() {
801                        let status = Status::read_sl(&mut r)?;
802                        let key = r.key()?;
803                        Response::ExportKey {
804                            status,
805                            key,
806                            context: SecManContext::read(&mut r)?,
807                        }
808                    } else {
809                        let key = r.key()?;
810                        Response::ExportKey {
811                            status: Status::read_sl(&mut r)?,
812                            key,
813                            context: SecManContext::default(),
814                        }
815                    }
816                }
817                id::GET_NETWORK_KEY_INFO => Response::GetNetworkKeyInfo {
818                    status: Status::read_sl(&mut r)?,
819                    info: NetworkKeyInfo::read(&mut r)?,
820                },
821                id::EXPORT_LINK_KEY_BY_INDEX => {
822                    if v.sl_status() {
823                        let status = Status::read_sl(&mut r)?;
824                        let context = SecManContext::read(&mut r)?;
825                        let key = r.key()?;
826                        Response::ExportLinkKeyByIndex {
827                            status,
828                            context,
829                            key,
830                            metadata: ApsKeyMetadata::read(&mut r)?,
831                        }
832                    } else {
833                        let ieee = r.ieee()?;
834                        let key = r.key()?;
835                        let metadata = ApsKeyMetadata::read(&mut r)?;
836                        let status = Status::read_sl(&mut r)?;
837                        let context = SecManContext {
838                            core_key_type: crate::ids::key_type::APP_LINK,
839                            ieee,
840                            ..Default::default()
841                        };
842                        Response::ExportLinkKeyByIndex {
843                            status,
844                            context,
845                            key,
846                            metadata,
847                        }
848                    }
849                }
850                id::GET_KEY => Response::GetKey {
851                    status: Status::read(&mut r, v)?,
852                    key: KeyStruct::read(&mut r)?,
853                },
854                id::GET_KEY_TABLE_ENTRY => Response::GetKeyTableEntry {
855                    status: Status::read(&mut r, v)?,
856                    key: KeyStruct::read(&mut r)?,
857                },
858                id::SEND_UNICAST | id::SEND_BROADCAST => Response::Sent {
859                    frame_id,
860                    status: Status::read(&mut r, v)?,
861                    aps_sequence: r.u8()?,
862                },
863                id::SET_SOURCE_ROUTE_DISCOVERY_MODE => Response::SetSourceRouteDiscoveryMode {
864                    remaining_ms: r.u32()?,
865                },
866                id::GET_MFG_TOKEN => Response::GetMfgToken {
867                    data: r.u8_prefixed()?.to_vec(),
868                },
869                id::LOOKUP_EUI64_BY_NODE_ID => Response::LookupEui64ByNodeId {
870                    status: Status::read(&mut r, v)?,
871                    ieee: r.ieee()?,
872                },
873                id::ECHO => Response::Echo {
874                    data: r.u8_prefixed()?.to_vec(),
875                },
876                id::INVALID_COMMAND => Response::InvalidCommand { reason: r.u8()? },
877                other => return Err(DecodeError::UnknownFrame(other)),
878            },
879        };
880        // The NCP may append fields this version of the crate does not
881        // know; trailing bytes are tolerated in responses.
882        Ok(response)
883    }
884
885    /// Encode the parameters (the NCP side). Statuses are written in their
886    /// own width, so build them for the negotiated version.
887    pub fn encode(&self, v: ProtocolVersion) -> Vec<u8> {
888        let mut w = Vec::with_capacity(32);
889        match self {
890            Response::Version {
891                protocol_version,
892                stack_type,
893                stack_version,
894            } => {
895                w.put_u8(*protocol_version);
896                w.put_u8(*stack_type);
897                w.put_u16(*stack_version);
898            }
899            Response::GetConfigurationValue { status, value } => {
900                status.write(&mut w);
901                w.put_u16(*value);
902            }
903            Response::Status { status, .. } => status.write(&mut w),
904            Response::GetValue { status, value } => {
905                status.write(&mut w);
906                w.put_u8_prefixed(value);
907            }
908            Response::NetworkState { state } => w.put_u8(*state),
909            Response::GetNetworkParameters {
910                status,
911                node_type,
912                parameters,
913            } => {
914                status.write(&mut w);
915                w.put_u8(*node_type);
916                parameters.write(&mut w);
917            }
918            Response::GetEui64 { ieee } => w.put_ieee(*ieee),
919            Response::GetNodeId { node_id } => w.put_u16(*node_id),
920            Response::ExportKey {
921                status,
922                key,
923                context,
924            } => {
925                if v.sl_status() {
926                    status.write(&mut w);
927                    w.put_key(key);
928                    context.write(&mut w);
929                } else {
930                    w.put_key(key);
931                    status.write(&mut w);
932                }
933            }
934            Response::GetNetworkKeyInfo { status, info } => {
935                status.write(&mut w);
936                info.write(&mut w);
937            }
938            Response::ExportLinkKeyByIndex {
939                status,
940                context,
941                key,
942                metadata,
943            } => {
944                if v.sl_status() {
945                    status.write(&mut w);
946                    context.write(&mut w);
947                    w.put_key(key);
948                    metadata.write(&mut w);
949                } else {
950                    w.put_ieee(context.ieee);
951                    w.put_key(key);
952                    metadata.write(&mut w);
953                    status.write(&mut w);
954                }
955            }
956            Response::GetKey { status, key } | Response::GetKeyTableEntry { status, key } => {
957                status.write(&mut w);
958                key.write(&mut w);
959            }
960            Response::Sent {
961                status,
962                aps_sequence,
963                ..
964            } => {
965                status.write(&mut w);
966                w.put_u8(*aps_sequence);
967            }
968            Response::SetSourceRouteDiscoveryMode { remaining_ms } => w.put_u32(*remaining_ms),
969            Response::GetMfgToken { data } | Response::Echo { data } => w.put_u8_prefixed(data),
970            Response::LookupEui64ByNodeId { status, ieee } => {
971                status.write(&mut w);
972                w.put_ieee(*ieee);
973            }
974            Response::Empty { .. } => {}
975            Response::InvalidCommand { reason } => w.put_u8(*reason),
976        }
977        w
978    }
979}
980
981#[cfg(test)]
982mod tests {
983    use super::*;
984
985    fn every_command() -> Vec<Command> {
986        let aps = ApsFrame {
987            profile_id: 0x0104,
988            cluster_id: 6,
989            source_endpoint: 1,
990            destination_endpoint: 1,
991            options: 0x140,
992            group_id: 0,
993            sequence: 9,
994        };
995        vec![
996            Command::Version { desired: 13 },
997            Command::GetConfigurationValue { config_id: 0x1E },
998            Command::SetConfigurationValue {
999                config_id: 0x11,
1000                value: 32,
1001            },
1002            Command::AddEndpoint {
1003                endpoint: 1,
1004                profile_id: 0x0104,
1005                device_id: 5,
1006                device_version: 0,
1007                input_clusters: vec![0, 3],
1008                output_clusters: vec![6],
1009            },
1010            Command::SetPolicy {
1011                policy_id: 5,
1012                decision: 0x51,
1013            },
1014            Command::GetValue { value_id: 0x11 },
1015            Command::SetValue {
1016                value_id: 0x23,
1017                value: vec![1, 2, 3, 4],
1018            },
1019            Command::SetManufacturerCode { code: 0x1049 },
1020            Command::NetworkInit { bitmask: 3 },
1021            Command::NetworkState,
1022            Command::FormNetwork {
1023                parameters: NetworkParameters {
1024                    radio_channel: 15,
1025                    ..Default::default()
1026                },
1027            },
1028            Command::PermitJoining { duration: 254 },
1029            Command::GetNetworkParameters,
1030            Command::GetEui64,
1031            Command::GetNodeId,
1032            Command::SetInitialSecurityState {
1033                state: InitialSecurityState {
1034                    bitmask: 0x0B84,
1035                    ..Default::default()
1036                },
1037            },
1038            Command::ExportKey {
1039                context: SecManContext::for_key(1),
1040            },
1041            Command::GetNetworkKeyInfo,
1042            Command::ExportLinkKeyByIndex { index: 3 },
1043            Command::ImportLinkKey {
1044                index: 1,
1045                ieee: Ieee(42),
1046                key: Key([7; 16]),
1047            },
1048            Command::EraseKeyTableEntry { index: 2 },
1049            Command::ImportTransientKey {
1050                ieee: Ieee(9),
1051                key: Key::ZIGBEE_ALLIANCE_09,
1052            },
1053            Command::ClearTransientLinkKeys,
1054            Command::ClearKeyTable,
1055            Command::GetKey { key_type: 3 },
1056            Command::GetKeyTableEntry { index: 4 },
1057            Command::SetKeyTableEntry {
1058                index: 4,
1059                ieee: Ieee(42),
1060                link_key: true,
1061                key: Key([5; 16]),
1062            },
1063            Command::AddTransientLinkKey {
1064                ieee: Ieee::UNSET,
1065                key: Key::ZIGBEE_ALLIANCE_09,
1066            },
1067            Command::SendUnicast {
1068                kind: 0,
1069                destination: 0x1234,
1070                aps,
1071                tag: 7,
1072                payload: vec![0x10, 1, 0, 0, 0],
1073            },
1074            Command::SetConcentrator {
1075                on: true,
1076                kind: 0xFFF9,
1077                min_time: 5,
1078                max_time: 60,
1079                route_error_threshold: 3,
1080                delivery_failure_threshold: 1,
1081                max_hops: 0,
1082            },
1083            Command::SetSourceRouteDiscoveryMode { mode: 2 },
1084            Command::GetMfgToken { token_id: 0x0C },
1085            Command::SetMfgToken {
1086                token_id: 0x0C,
1087                data: vec![1; 8],
1088            },
1089            Command::StartScan {
1090                scan_type: 0,
1091                channel_mask: 0x07FF_F800,
1092                duration: 3,
1093            },
1094            Command::LookupEui64ByNodeId { node_id: 0x1234 },
1095            Command::SetRadioPower { power: -4 },
1096            Command::Echo {
1097                data: vec![1, 2, 3],
1098            },
1099            Command::Nop,
1100        ]
1101    }
1102
1103    #[test]
1104    fn commands_round_trip_in_both_layouts() {
1105        for v in [ProtocolVersion(8), ProtocolVersion(13), ProtocolVersion(16)] {
1106            for c in every_command() {
1107                let bytes = c.encode(v);
1108                assert_eq!(
1109                    Command::decode(v, c.frame_id(), &bytes),
1110                    Ok(c.clone()),
1111                    "{c:?} v{}",
1112                    v.0
1113                );
1114            }
1115            let b = Command::SendBroadcast {
1116                alias: if v.sl_status() { 1 } else { 0 },
1117                destination: 0xFFFC,
1118                nwk_sequence: 0,
1119                aps: ApsFrame::default(),
1120                radius: 30,
1121                tag: 1,
1122                payload: vec![0, 1, 2],
1123            };
1124            assert_eq!(Command::decode(v, b.frame_id(), &b.encode(v)), Ok(b));
1125        }
1126    }
1127
1128    #[test]
1129    fn unicast_layout_differs_by_version() {
1130        let c = Command::SendUnicast {
1131            kind: 0,
1132            destination: 1,
1133            aps: ApsFrame::default(),
1134            tag: 0x0102,
1135            payload: vec![],
1136        };
1137        assert_eq!(
1138            c.encode(ProtocolVersion(13)).len() + 1,
1139            c.encode(ProtocolVersion(14)).len()
1140        );
1141    }
1142
1143    #[test]
1144    fn responses_round_trip() {
1145        for v in [ProtocolVersion(8), ProtocolVersion(13), ProtocolVersion(18)] {
1146            let responses = vec![
1147                Response::Version {
1148                    protocol_version: 13,
1149                    stack_type: 2,
1150                    stack_version: 0x7440,
1151                },
1152                Response::GetConfigurationValue {
1153                    status: Status::ok(v),
1154                    value: 12,
1155                },
1156                Response::Status {
1157                    frame_id: id::FORM_NETWORK,
1158                    status: Status::ok(v),
1159                },
1160                Response::Status {
1161                    frame_id: id::IMPORT_TRANSIENT_KEY,
1162                    status: Status::SL_OK,
1163                },
1164                Response::GetValue {
1165                    status: Status::ok(v),
1166                    value: vec![1, 2, 3, 4, 5, 6, 7],
1167                },
1168                Response::NetworkState { state: 2 },
1169                Response::GetEui64 { ieee: Ieee(0x1122) },
1170                Response::GetNodeId { node_id: 0 },
1171                Response::GetNetworkKeyInfo {
1172                    status: Status::SL_OK,
1173                    info: NetworkKeyInfo {
1174                        network_key_set: true,
1175                        network_key_frame_counter: 99,
1176                        ..Default::default()
1177                    },
1178                },
1179                Response::Sent {
1180                    frame_id: id::SEND_UNICAST,
1181                    status: Status::ok(v),
1182                    aps_sequence: 3,
1183                },
1184                Response::Empty { frame_id: id::NOP },
1185                Response::InvalidCommand { reason: 0x58 },
1186                Response::GetKey {
1187                    status: Status::ok(v),
1188                    key: KeyStruct {
1189                        bitmask: 0x03,
1190                        key_type: 3,
1191                        key: Key([1; 16]),
1192                        outgoing_frame_counter: 1000,
1193                        sequence_number: 2,
1194                        ..Default::default()
1195                    },
1196                },
1197                Response::GetKeyTableEntry {
1198                    status: Status::ok(v),
1199                    key: KeyStruct::default(),
1200                },
1201                Response::Status {
1202                    frame_id: id::ADD_TRANSIENT_LINK_KEY,
1203                    status: Status::ok(v),
1204                },
1205            ];
1206            for resp in responses {
1207                assert_eq!(
1208                    Response::decode(v, resp.frame_id(), &resp.encode(v)),
1209                    Ok(resp.clone()),
1210                    "{resp:?}"
1211                );
1212            }
1213            let export = Response::ExportLinkKeyByIndex {
1214                status: Status::SL_OK,
1215                context: SecManContext {
1216                    core_key_type: crate::ids::key_type::APP_LINK,
1217                    ieee: Ieee(77),
1218                    ..Default::default()
1219                },
1220                key: Key([3; 16]),
1221                metadata: ApsKeyMetadata {
1222                    outgoing_frame_counter: 5,
1223                    ..Default::default()
1224                },
1225            };
1226            assert_eq!(
1227                Response::decode(v, export.frame_id(), &export.encode(v)),
1228                Ok(export)
1229            );
1230        }
1231    }
1232}
1233
1234#[cfg(test)]
1235mod v8_tests {
1236    use super::*;
1237
1238    /// `startScan` answered with a one-byte `EmberStatus` before protocol 13.
1239    #[test]
1240    fn start_scan_status_width() {
1241        let ok8 = Response::decode(ProtocolVersion(8), id::START_SCAN, &[0x00]).unwrap();
1242        assert_eq!(ok8.status(), Some(Status::ok(ProtocolVersion(8))));
1243        let ok13 = Response::decode(ProtocolVersion(13), id::START_SCAN, &[0, 0, 0, 0]).unwrap();
1244        assert_eq!(ok13.status(), Some(Status::SL_OK));
1245    }
1246
1247    /// A `getKey(CURRENT_NETWORK)` response as an EmberZNet 6.7 NCP lays it out.
1248    #[test]
1249    fn get_key_wire_layout() {
1250        let mut bytes = vec![0x00, 0x03, 0x00, 0x03];
1251        bytes.extend([0xAB; 16]);
1252        bytes.extend(1234u32.to_le_bytes());
1253        bytes.extend(0u32.to_le_bytes());
1254        bytes.push(7);
1255        bytes.extend([0u8; 8]);
1256        match Response::decode(ProtocolVersion(8), id::GET_KEY, &bytes).unwrap() {
1257            Response::GetKey { status, key } => {
1258                assert!(status.is_ok());
1259                assert_eq!(key.key_type, crate::ids::ember_key_type::CURRENT_NETWORK);
1260                assert_eq!(key.key, Key([0xAB; 16]));
1261                assert_eq!(key.outgoing_frame_counter, 1234);
1262                assert_eq!(key.sequence_number, 7);
1263            }
1264            other => panic!("{other:?}"),
1265        }
1266    }
1267}