Skip to main content

zigbee_znp/
message.rs

1//! Typed requests the host sends and indications the NCP sends.
2//!
3//! Every type here encodes to a [`Frame`] and decodes from one, so the
4//! client, the simulator and the fuzz targets share one definition of each
5//! layout.
6
7use thiserror::Error;
8use zigbee_primitives::wire::{Reader, Truncated, Writer};
9use zigbee_primitives::{Ieee, Key, NodeId};
10
11use crate::frame::{Frame, Kind};
12use crate::ids::{af, app_cnf, subsystem as sub, sys, util, zdo};
13
14/// A frame did not decode.
15#[derive(Debug, Clone, PartialEq, Eq, Error)]
16pub enum DecodeError {
17    /// Too short.
18    #[error(transparent)]
19    Truncated(#[from] Truncated),
20    /// Not a frame this type knows.
21    #[error("unknown MT command {kind:?} {subsystem:#04x} {id:#04x}")]
22    Unknown {
23        /// Type.
24        kind: Kind,
25        /// Subsystem.
26        subsystem: u8,
27        /// Command.
28        id: u8,
29    },
30    /// A length field disagrees with the data.
31    #[error("length field {0} does not fit the frame")]
32    Length(usize),
33}
34
35/// A request from the host.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum Request {
38    /// `SYS_RESET_REQ` (asynchronous; the NCP answers with a reset
39    /// indication).
40    SysReset {
41        /// Soft (1) or hard (0) reset.
42        soft: bool,
43    },
44    /// `SYS_PING`.
45    SysPing,
46    /// `SYS_VERSION`.
47    SysVersion,
48    /// `SYS_OSAL_NV_ITEM_INIT`.
49    OsalNvItemInit {
50        /// Item.
51        id: u16,
52        /// Item length.
53        len: u16,
54        /// Initial value.
55        init: Vec<u8>,
56    },
57    /// `SYS_OSAL_NV_READ`.
58    OsalNvRead {
59        /// Item.
60        id: u16,
61        /// Offset.
62        offset: u8,
63    },
64    /// `SYS_OSAL_NV_WRITE`.
65    OsalNvWrite {
66        /// Item.
67        id: u16,
68        /// Offset.
69        offset: u8,
70        /// Value.
71        value: Vec<u8>,
72    },
73    /// `SYS_OSAL_NV_DELETE`.
74    OsalNvDelete {
75        /// Item.
76        id: u16,
77        /// Its length.
78        len: u16,
79    },
80    /// `SYS_OSAL_NV_LENGTH`.
81    OsalNvLength {
82        /// Item.
83        id: u16,
84    },
85    /// `SYS_SET_TX_POWER`.
86    SetTxPower {
87        /// dBm.
88        dbm: i8,
89    },
90    /// `SYS_NV_LENGTH` (extended NV).
91    NvLength {
92        /// System id.
93        sysid: u8,
94        /// Item.
95        item: u16,
96        /// Sub-item.
97        sub: u16,
98    },
99    /// `SYS_NV_READ` (extended NV).
100    NvRead {
101        /// System id.
102        sysid: u8,
103        /// Item.
104        item: u16,
105        /// Sub-item.
106        sub: u16,
107        /// Offset.
108        offset: u16,
109        /// Bytes to read.
110        len: u8,
111    },
112    /// `SYS_NV_WRITE` (extended NV).
113    NvWrite {
114        /// System id.
115        sysid: u8,
116        /// Item.
117        item: u16,
118        /// Sub-item.
119        sub: u16,
120        /// Offset.
121        offset: u16,
122        /// Value.
123        value: Vec<u8>,
124    },
125    /// `UTIL_GET_DEVICE_INFO`.
126    UtilGetDeviceInfo,
127    /// `ZDO_SET_LINK_KEY`.
128    ZdoSetLinkKey {
129        /// The device's network address.
130        nwk: NodeId,
131        /// Its IEEE address.
132        ieee: Ieee,
133        /// The key.
134        key: Key,
135    },
136    /// `ZDO_NWK_DISCOVERY_REQ`: an active scan.
137    ZdoNwkDiscovery {
138        /// Channels.
139        channel_mask: u32,
140        /// Scan duration exponent per channel.
141        scan_duration: u8,
142    },
143    /// `ZDO_SEND_DATA`: a raw ZDO frame with the host's sequence number.
144    ZdoSendData {
145        /// Destination.
146        destination: NodeId,
147        /// ZDO sequence number.
148        tsn: u8,
149        /// ZDO cluster.
150        cluster: u16,
151        /// The ZDO payload after the sequence number.
152        data: Vec<u8>,
153    },
154    /// `ZDO_MGMT_PERMIT_JOIN_REQ`.
155    ZdoMgmtPermitJoin {
156        /// Address mode ([`crate::ids::addr_mode`]).
157        addr_mode: u8,
158        /// Destination.
159        destination: NodeId,
160        /// Seconds; 0 closes.
161        duration: u8,
162        /// Trust center significance.
163        tc_significance: u8,
164    },
165    /// `ZDO_MGMT_NWK_UPDATE_REQ`.
166    ZdoMgmtNwkUpdate {
167        /// Destination.
168        destination: NodeId,
169        /// Address mode.
170        addr_mode: u8,
171        /// Channels.
172        channel_mask: u32,
173        /// Scan duration, or 0xFE to change channel.
174        scan_duration: u8,
175        /// Scans per channel.
176        scan_count: u8,
177        /// Network manager.
178        manager: NodeId,
179    },
180    /// `ZDO_MSG_CB_REGISTER`.
181    ZdoMsgCbRegister {
182        /// Cluster, or 0xFFFF for every ZDO cluster.
183        cluster: u16,
184    },
185    /// `ZDO_STARTUP_FROM_APP`.
186    ZdoStartupFromApp {
187        /// Delay, milliseconds.
188        delay: u16,
189    },
190    /// `ZDO_EXT_NWK_INFO`.
191    ZdoExtNwkInfo,
192    /// `AF_REGISTER`.
193    AfRegister {
194        /// Endpoint.
195        endpoint: u8,
196        /// Profile.
197        profile: u16,
198        /// Device id.
199        device_id: u16,
200        /// Device version.
201        version: u8,
202        /// Server clusters.
203        input_clusters: Vec<u16>,
204        /// Client clusters.
205        output_clusters: Vec<u16>,
206    },
207    /// `AF_DATA_REQUEST`.
208    AfDataRequest {
209        /// Destination.
210        destination: NodeId,
211        /// Destination endpoint.
212        destination_endpoint: u8,
213        /// Source endpoint.
214        source_endpoint: u8,
215        /// Cluster.
216        cluster: u16,
217        /// Transaction id, named again in the confirm.
218        trans_id: u8,
219        /// Options ([`crate::ids::af_option`]).
220        options: u8,
221        /// Radius.
222        radius: u8,
223        /// Payload.
224        data: Vec<u8>,
225    },
226    /// `AF_DATA_REQUEST_EXT`.
227    AfDataRequestExt {
228        /// Address mode.
229        addr_mode: u8,
230        /// Destination: a group, network or IEEE address.
231        destination: u64,
232        /// Destination endpoint.
233        destination_endpoint: u8,
234        /// Destination PAN (0 for this one).
235        destination_pan: u16,
236        /// Source endpoint.
237        source_endpoint: u8,
238        /// Cluster.
239        cluster: u16,
240        /// Transaction id.
241        trans_id: u8,
242        /// Options.
243        options: u8,
244        /// Radius.
245        radius: u8,
246        /// Payload.
247        data: Vec<u8>,
248    },
249    /// `APP_CNF_SET_ALLOWREJOIN_TC_POLICY`.
250    SetAllowRejoinTcPolicy {
251        /// Allow.
252        allow: bool,
253    },
254    /// `APP_CNF_BDB_ADD_INSTALLCODE`.
255    BdbAddInstallCode {
256        /// 1: install code with CRC; 2: derived key.
257        format: u8,
258        /// The device.
259        ieee: Ieee,
260        /// The code or key.
261        code: Vec<u8>,
262    },
263    /// `APP_CNF_BDB_SET_JOINUSESINSTALLCODEKEY`.
264    BdbSetJoinUsesInstallCodeKey {
265        /// Only devices with an install code may join.
266        required: bool,
267    },
268    /// `APP_CNF_BDB_START_COMMISSIONING`.
269    BdbStartCommissioning {
270        /// Mode ([`crate::ids::commissioning`]).
271        mode: u8,
272    },
273    /// `APP_CNF_BDB_SET_CHANNEL`.
274    BdbSetChannel {
275        /// The primary (or secondary) channel set.
276        primary: bool,
277        /// Channels.
278        channel_mask: u32,
279    },
280    /// `APP_CNF_BDB_SET_TC_REQUIRE_KEY_EXCHANGE`.
281    BdbSetTcRequireKeyExchange {
282        /// Required.
283        required: bool,
284    },
285}
286
287fn u8_list(r: &mut Reader<'_>) -> Result<Vec<u16>, DecodeError> {
288    let n = r.u8()?;
289    Ok(r.u16_list(usize::from(n))?)
290}
291
292fn put_u16_list(w: &mut Vec<u8>, list: &[u16]) {
293    let list = list.get(..list.len().min(255)).unwrap_or(list);
294    w.put_u8(list.len() as u8);
295    for c in list {
296        w.put_u16(*c);
297    }
298}
299
300impl Request {
301    /// The frame type: everything but a reset is synchronous.
302    pub fn kind(&self) -> Kind {
303        match self {
304            Request::SysReset { .. } => Kind::Areq,
305            _ => Kind::Sreq,
306        }
307    }
308
309    /// Subsystem and command id.
310    pub fn command(&self) -> (u8, u8) {
311        use Request::*;
312        match self {
313            SysReset { .. } => (sub::SYS, sys::RESET_REQ),
314            SysPing => (sub::SYS, sys::PING),
315            SysVersion => (sub::SYS, sys::VERSION),
316            OsalNvItemInit { .. } => (sub::SYS, sys::OSAL_NV_ITEM_INIT),
317            OsalNvRead { .. } => (sub::SYS, sys::OSAL_NV_READ),
318            OsalNvWrite { .. } => (sub::SYS, sys::OSAL_NV_WRITE),
319            OsalNvDelete { .. } => (sub::SYS, sys::OSAL_NV_DELETE),
320            OsalNvLength { .. } => (sub::SYS, sys::OSAL_NV_LENGTH),
321            SetTxPower { .. } => (sub::SYS, sys::SET_TX_POWER),
322            NvLength { .. } => (sub::SYS, sys::NV_LENGTH),
323            NvRead { .. } => (sub::SYS, sys::NV_READ),
324            NvWrite { .. } => (sub::SYS, sys::NV_WRITE),
325            UtilGetDeviceInfo => (sub::UTIL, util::GET_DEVICE_INFO),
326            ZdoSetLinkKey { .. } => (sub::ZDO, zdo::SET_LINK_KEY),
327            ZdoNwkDiscovery { .. } => (sub::ZDO, zdo::NWK_DISCOVERY_REQ),
328            ZdoSendData { .. } => (sub::ZDO, zdo::SEND_DATA),
329            ZdoMgmtPermitJoin { .. } => (sub::ZDO, zdo::MGMT_PERMIT_JOIN_REQ),
330            ZdoMgmtNwkUpdate { .. } => (sub::ZDO, zdo::MGMT_NWK_UPDATE_REQ),
331            ZdoMsgCbRegister { .. } => (sub::ZDO, zdo::MSG_CB_REGISTER),
332            ZdoStartupFromApp { .. } => (sub::ZDO, zdo::STARTUP_FROM_APP),
333            ZdoExtNwkInfo => (sub::ZDO, zdo::EXT_NWK_INFO),
334            AfRegister { .. } => (sub::AF, af::REGISTER),
335            AfDataRequest { .. } => (sub::AF, af::DATA_REQUEST),
336            AfDataRequestExt { .. } => (sub::AF, af::DATA_REQUEST_EXT),
337            SetAllowRejoinTcPolicy { .. } => (sub::APP_CNF, app_cnf::SET_ALLOWREJOIN_TC_POLICY),
338            BdbAddInstallCode { .. } => (sub::APP_CNF, app_cnf::BDB_ADD_INSTALLCODE),
339            BdbSetJoinUsesInstallCodeKey { .. } => {
340                (sub::APP_CNF, app_cnf::BDB_SET_JOINUSESINSTALLCODEKEY)
341            }
342            BdbStartCommissioning { .. } => (sub::APP_CNF, app_cnf::BDB_START_COMMISSIONING),
343            BdbSetChannel { .. } => (sub::APP_CNF, app_cnf::BDB_SET_CHANNEL),
344            BdbSetTcRequireKeyExchange { .. } => {
345                (sub::APP_CNF, app_cnf::BDB_SET_TC_REQUIRE_KEY_EXCHANGE)
346            }
347        }
348    }
349
350    /// The frame; [`Frame::encode`] refuses one over 250 bytes.
351    pub fn encode(&self) -> Frame {
352        use Request::*;
353        let mut w = Vec::new();
354        match self {
355            SysReset { soft } => w.put_u8(u8::from(*soft)),
356            SysPing | SysVersion | UtilGetDeviceInfo | ZdoExtNwkInfo => {}
357            OsalNvItemInit { id, len, init } => {
358                w.put_u16(*id);
359                w.put_u16(*len);
360                w.put_u8_prefixed(init);
361            }
362            OsalNvRead { id, offset } => {
363                w.put_u16(*id);
364                w.put_u8(*offset);
365            }
366            OsalNvWrite { id, offset, value } => {
367                w.put_u16(*id);
368                w.put_u8(*offset);
369                w.put_u8_prefixed(value);
370            }
371            OsalNvDelete { id, len } => {
372                w.put_u16(*id);
373                w.put_u16(*len);
374            }
375            OsalNvLength { id } => w.put_u16(*id),
376            SetTxPower { dbm } => w.put_u8(*dbm as u8),
377            NvLength { sysid, item, sub } => {
378                w.put_u8(*sysid);
379                w.put_u16(*item);
380                w.put_u16(*sub);
381            }
382            NvRead {
383                sysid,
384                item,
385                sub,
386                offset,
387                len,
388            } => {
389                w.put_u8(*sysid);
390                w.put_u16(*item);
391                w.put_u16(*sub);
392                w.put_u16(*offset);
393                w.put_u8(*len);
394            }
395            NvWrite {
396                sysid,
397                item,
398                sub,
399                offset,
400                value,
401            } => {
402                w.put_u8(*sysid);
403                w.put_u16(*item);
404                w.put_u16(*sub);
405                w.put_u16(*offset);
406                w.put_u8_prefixed(value);
407            }
408            ZdoSetLinkKey { nwk, ieee, key } => {
409                w.put_u16(*nwk);
410                w.put_ieee(*ieee);
411                w.put_key(key);
412            }
413            ZdoNwkDiscovery {
414                channel_mask,
415                scan_duration,
416            } => {
417                w.put_u32(*channel_mask);
418                w.put_u8(*scan_duration);
419            }
420            ZdoSendData {
421                destination,
422                tsn,
423                cluster,
424                data,
425            } => {
426                w.put_u16(*destination);
427                w.put_u8(*tsn);
428                w.put_u16(*cluster);
429                w.put_u8_prefixed(data);
430            }
431            ZdoMgmtPermitJoin {
432                addr_mode,
433                destination,
434                duration,
435                tc_significance,
436            } => {
437                w.put_u8(*addr_mode);
438                w.put_u16(*destination);
439                w.put_u8(*duration);
440                w.put_u8(*tc_significance);
441            }
442            ZdoMgmtNwkUpdate {
443                destination,
444                addr_mode,
445                channel_mask,
446                scan_duration,
447                scan_count,
448                manager,
449            } => {
450                w.put_u16(*destination);
451                w.put_u8(*addr_mode);
452                w.put_u32(*channel_mask);
453                w.put_u8(*scan_duration);
454                w.put_u8(*scan_count);
455                w.put_u16(*manager);
456            }
457            ZdoMsgCbRegister { cluster } => w.put_u16(*cluster),
458            ZdoStartupFromApp { delay } => w.put_u16(*delay),
459            AfRegister {
460                endpoint,
461                profile,
462                device_id,
463                version,
464                input_clusters,
465                output_clusters,
466            } => {
467                w.put_u8(*endpoint);
468                w.put_u16(*profile);
469                w.put_u16(*device_id);
470                w.put_u8(*version);
471                w.put_u8(0); // latency: none
472                put_u16_list(&mut w, input_clusters);
473                put_u16_list(&mut w, output_clusters);
474            }
475            AfDataRequest {
476                destination,
477                destination_endpoint,
478                source_endpoint,
479                cluster,
480                trans_id,
481                options,
482                radius,
483                data,
484            } => {
485                w.put_u16(*destination);
486                w.put_u8(*destination_endpoint);
487                w.put_u8(*source_endpoint);
488                w.put_u16(*cluster);
489                w.put_u8(*trans_id);
490                w.put_u8(*options);
491                w.put_u8(*radius);
492                w.put_u8_prefixed(data);
493            }
494            AfDataRequestExt {
495                addr_mode,
496                destination,
497                destination_endpoint,
498                destination_pan,
499                source_endpoint,
500                cluster,
501                trans_id,
502                options,
503                radius,
504                data,
505            } => {
506                w.put_u8(*addr_mode);
507                w.put_u64(*destination);
508                w.put_u8(*destination_endpoint);
509                w.put_u16(*destination_pan);
510                w.put_u8(*source_endpoint);
511                w.put_u16(*cluster);
512                w.put_u8(*trans_id);
513                w.put_u8(*options);
514                w.put_u8(*radius);
515                w.put_u16(data.len() as u16);
516                w.put_bytes(data);
517            }
518            SetAllowRejoinTcPolicy { allow } => w.put_u8(u8::from(*allow)),
519            BdbAddInstallCode { format, ieee, code } => {
520                w.put_u8(*format);
521                w.put_ieee(*ieee);
522                w.put_bytes(code);
523            }
524            BdbStartCommissioning { mode } => w.put_u8(*mode),
525            BdbSetChannel {
526                primary,
527                channel_mask,
528            } => {
529                w.put_u8(u8::from(*primary));
530                w.put_u32(*channel_mask);
531            }
532            BdbSetTcRequireKeyExchange { required } | BdbSetJoinUsesInstallCodeKey { required } => {
533                w.put_u8(u8::from(*required))
534            }
535        }
536        let (subsystem, id) = self.command();
537        Frame::new(self.kind(), subsystem, id, w)
538    }
539
540    /// Decode a request (the simulator's side).
541    pub fn decode(frame: &Frame) -> Result<Request, DecodeError> {
542        use Request::*;
543        let mut r = Reader::new(&frame.data);
544        let unknown = || DecodeError::Unknown {
545            kind: frame.kind,
546            subsystem: frame.subsystem,
547            id: frame.id,
548        };
549        let request = match (frame.kind, frame.subsystem, frame.id) {
550            (Kind::Areq, sub::SYS, sys::RESET_REQ) => SysReset { soft: r.u8()? != 0 },
551            (Kind::Sreq, sub::SYS, sys::PING) => SysPing,
552            (Kind::Sreq, sub::SYS, sys::VERSION) => SysVersion,
553            (Kind::Sreq, sub::SYS, sys::OSAL_NV_ITEM_INIT) => OsalNvItemInit {
554                id: r.u16()?,
555                len: r.u16()?,
556                init: r.u8_prefixed()?.to_vec(),
557            },
558            (Kind::Sreq, sub::SYS, sys::OSAL_NV_READ) => OsalNvRead {
559                id: r.u16()?,
560                offset: r.u8()?,
561            },
562            (Kind::Sreq, sub::SYS, sys::OSAL_NV_WRITE) => OsalNvWrite {
563                id: r.u16()?,
564                offset: r.u8()?,
565                value: r.u8_prefixed()?.to_vec(),
566            },
567            (Kind::Sreq, sub::SYS, sys::OSAL_NV_DELETE) => OsalNvDelete {
568                id: r.u16()?,
569                len: r.u16()?,
570            },
571            (Kind::Sreq, sub::SYS, sys::OSAL_NV_LENGTH) => OsalNvLength { id: r.u16()? },
572            (Kind::Sreq, sub::SYS, sys::SET_TX_POWER) => SetTxPower { dbm: r.i8()? },
573            (Kind::Sreq, sub::SYS, sys::NV_LENGTH) => NvLength {
574                sysid: r.u8()?,
575                item: r.u16()?,
576                sub: r.u16()?,
577            },
578            (Kind::Sreq, sub::SYS, sys::NV_READ) => NvRead {
579                sysid: r.u8()?,
580                item: r.u16()?,
581                sub: r.u16()?,
582                offset: r.u16()?,
583                len: r.u8()?,
584            },
585            (Kind::Sreq, sub::SYS, sys::NV_WRITE) => NvWrite {
586                sysid: r.u8()?,
587                item: r.u16()?,
588                sub: r.u16()?,
589                offset: r.u16()?,
590                value: r.u8_prefixed()?.to_vec(),
591            },
592            (Kind::Sreq, sub::UTIL, util::GET_DEVICE_INFO) => UtilGetDeviceInfo,
593            (Kind::Sreq, sub::ZDO, zdo::SET_LINK_KEY) => ZdoSetLinkKey {
594                nwk: r.u16()?,
595                ieee: r.ieee()?,
596                key: r.key()?,
597            },
598            (Kind::Sreq, sub::ZDO, zdo::NWK_DISCOVERY_REQ) => ZdoNwkDiscovery {
599                channel_mask: r.u32()?,
600                scan_duration: r.u8()?,
601            },
602            (Kind::Sreq, sub::ZDO, zdo::SEND_DATA) => ZdoSendData {
603                destination: r.u16()?,
604                tsn: r.u8()?,
605                cluster: r.u16()?,
606                data: r.u8_prefixed()?.to_vec(),
607            },
608            (Kind::Sreq, sub::ZDO, zdo::MGMT_PERMIT_JOIN_REQ) => ZdoMgmtPermitJoin {
609                addr_mode: r.u8()?,
610                destination: r.u16()?,
611                duration: r.u8()?,
612                tc_significance: r.u8()?,
613            },
614            (Kind::Sreq, sub::ZDO, zdo::MGMT_NWK_UPDATE_REQ) => ZdoMgmtNwkUpdate {
615                destination: r.u16()?,
616                addr_mode: r.u8()?,
617                channel_mask: r.u32()?,
618                scan_duration: r.u8()?,
619                scan_count: r.u8()?,
620                manager: r.u16()?,
621            },
622            (Kind::Sreq, sub::ZDO, zdo::MSG_CB_REGISTER) => ZdoMsgCbRegister { cluster: r.u16()? },
623            (Kind::Sreq, sub::ZDO, zdo::STARTUP_FROM_APP) => ZdoStartupFromApp { delay: r.u16()? },
624            (Kind::Sreq, sub::ZDO, zdo::EXT_NWK_INFO) => ZdoExtNwkInfo,
625            (Kind::Sreq, sub::AF, af::REGISTER) => {
626                let endpoint = r.u8()?;
627                let profile = r.u16()?;
628                let device_id = r.u16()?;
629                let version = r.u8()?;
630                let _latency = r.u8()?;
631                AfRegister {
632                    endpoint,
633                    profile,
634                    device_id,
635                    version,
636                    input_clusters: u8_list(&mut r)?,
637                    output_clusters: u8_list(&mut r)?,
638                }
639            }
640            (Kind::Sreq, sub::AF, af::DATA_REQUEST) => AfDataRequest {
641                destination: r.u16()?,
642                destination_endpoint: r.u8()?,
643                source_endpoint: r.u8()?,
644                cluster: r.u16()?,
645                trans_id: r.u8()?,
646                options: r.u8()?,
647                radius: r.u8()?,
648                data: r.u8_prefixed()?.to_vec(),
649            },
650            (Kind::Sreq, sub::AF, af::DATA_REQUEST_EXT) => AfDataRequestExt {
651                addr_mode: r.u8()?,
652                destination: r.u64()?,
653                destination_endpoint: r.u8()?,
654                destination_pan: r.u16()?,
655                source_endpoint: r.u8()?,
656                cluster: r.u16()?,
657                trans_id: r.u8()?,
658                options: r.u8()?,
659                radius: r.u8()?,
660                data: {
661                    let n = usize::from(r.u16()?);
662                    r.bytes(n)?.to_vec()
663                },
664            },
665            (Kind::Sreq, sub::APP_CNF, app_cnf::SET_ALLOWREJOIN_TC_POLICY) => {
666                SetAllowRejoinTcPolicy {
667                    allow: r.u8()? != 0,
668                }
669            }
670            (Kind::Sreq, sub::APP_CNF, app_cnf::BDB_ADD_INSTALLCODE) => BdbAddInstallCode {
671                format: r.u8()?,
672                ieee: r.ieee()?,
673                code: r.rest().to_vec(),
674            },
675            (Kind::Sreq, sub::APP_CNF, app_cnf::BDB_SET_JOINUSESINSTALLCODEKEY) => {
676                BdbSetJoinUsesInstallCodeKey {
677                    required: r.u8()? != 0,
678                }
679            }
680            (Kind::Sreq, sub::APP_CNF, app_cnf::BDB_START_COMMISSIONING) => {
681                BdbStartCommissioning { mode: r.u8()? }
682            }
683            (Kind::Sreq, sub::APP_CNF, app_cnf::BDB_SET_CHANNEL) => BdbSetChannel {
684                primary: r.u8()? != 0,
685                channel_mask: r.u32()?,
686            },
687            (Kind::Sreq, sub::APP_CNF, app_cnf::BDB_SET_TC_REQUIRE_KEY_EXCHANGE) => {
688                BdbSetTcRequireKeyExchange {
689                    required: r.u8()? != 0,
690                }
691            }
692            _ => return Err(unknown()),
693        };
694        Ok(request)
695    }
696}
697
698/// An `AF_INCOMING_MSG` or `AF_INCOMING_MSG_EXT`.
699#[derive(Debug, Clone, PartialEq, Eq)]
700pub struct IncomingMsg {
701    /// The group, 0 for none.
702    pub group: u16,
703    /// Cluster.
704    pub cluster: u16,
705    /// The sender's network address (the short form's only address).
706    pub source: NodeId,
707    /// The sender's IEEE address, when the extended form carried one.
708    pub source_ieee: Option<Ieee>,
709    /// Source endpoint.
710    pub source_endpoint: u8,
711    /// Destination endpoint.
712    pub destination_endpoint: u8,
713    /// Sent as a broadcast.
714    pub broadcast: bool,
715    /// Link quality.
716    pub lqi: u8,
717    /// Was APS-secured.
718    pub secured: bool,
719    /// The NCP's timestamp.
720    pub timestamp: u32,
721    /// APS counter.
722    pub tsn: u8,
723    /// Payload.
724    pub data: Vec<u8>,
725    /// The last hop's network address, when the firmware reports it.
726    pub last_hop: Option<NodeId>,
727    /// The extended form (long payloads, IEEE source).
728    pub extended: bool,
729}
730
731/// A beacon from `ZDO_BEACON_NOTIFY_IND`.
732#[derive(Debug, Clone, PartialEq, Eq)]
733pub struct Beacon {
734    /// The sender.
735    pub source: NodeId,
736    /// PAN id.
737    pub pan_id: u16,
738    /// Channel.
739    pub channel: u8,
740    /// Accepting joins.
741    pub permit_joining: bool,
742    /// Router capacity left.
743    pub router_capacity: bool,
744    /// End device capacity left.
745    pub device_capacity: bool,
746    /// Protocol version.
747    pub protocol_version: u8,
748    /// Stack profile.
749    pub stack_profile: u8,
750    /// Link quality.
751    pub lqi: u8,
752    /// Depth.
753    pub depth: u8,
754    /// Network update id.
755    pub update_id: u8,
756    /// Extended PAN id.
757    pub extended_pan_id: zigbee_primitives::ExtPanId,
758}
759
760/// An asynchronous frame from the NCP.
761#[derive(Debug, Clone, PartialEq, Eq)]
762pub enum Indication {
763    /// `SYS_RESET_IND`.
764    Reset {
765        /// Why: 0 power-up, 1 external, 2 watchdog.
766        reason: u8,
767        /// Transport revision.
768        transport: u8,
769        /// Product ([`crate::ids::product`]).
770        product: u8,
771        /// Major release.
772        major: u8,
773        /// Minor release.
774        minor: u8,
775        /// Hardware revision.
776        hw: u8,
777    },
778    /// `AF_DATA_CONFIRM`.
779    DataConfirm {
780        /// Status.
781        status: u8,
782        /// Endpoint.
783        endpoint: u8,
784        /// The request's transaction id.
785        trans_id: u8,
786    },
787    /// `AF_INCOMING_MSG` or `AF_INCOMING_MSG_EXT`.
788    Incoming(Box<IncomingMsg>),
789    /// `ZDO_STATE_CHANGE_IND`.
790    StateChange {
791        /// The new state ([`crate::ids::state`]).
792        state: u8,
793    },
794    /// `ZDO_END_DEVICE_ANNCE_IND`.
795    DeviceAnnounce {
796        /// Sender.
797        source: NodeId,
798        /// The device's network address.
799        nwk: NodeId,
800        /// Its IEEE address.
801        ieee: Ieee,
802        /// Capabilities.
803        capabilities: u8,
804    },
805    /// `ZDO_SRC_RTG_IND`.
806    SourceRoute {
807        /// The originator.
808        source: NodeId,
809        /// Relays.
810        relays: Vec<NodeId>,
811    },
812    /// `ZDO_BEACON_NOTIFY_IND`.
813    Beacons(Vec<Beacon>),
814    /// `ZDO_NWK_DISCOVERY_CNF`.
815    DiscoveryDone {
816        /// Status.
817        status: u8,
818    },
819    /// `ZDO_LEAVE_IND`.
820    Leave {
821        /// Network address.
822        nwk: NodeId,
823        /// IEEE address.
824        ieee: Ieee,
825        /// A leave request rather than an indication.
826        request: bool,
827        /// Children leave too.
828        remove_children: bool,
829        /// The device will rejoin.
830        rejoin: bool,
831    },
832    /// `ZDO_TC_DEV_IND`.
833    TcDevice {
834        /// Network address.
835        nwk: NodeId,
836        /// IEEE address.
837        ieee: Ieee,
838        /// Parent.
839        parent: NodeId,
840    },
841    /// `ZDO_PERMIT_JOIN_IND`.
842    PermitJoin {
843        /// Seconds.
844        duration: u8,
845    },
846    /// `ZDO_MSG_CB_INCOMING`: a raw ZDO frame.
847    ZdoMessage {
848        /// Sender.
849        source: NodeId,
850        /// Sent as a broadcast.
851        broadcast: bool,
852        /// Cluster.
853        cluster: u16,
854        /// APS-secured.
855        secured: bool,
856        /// ZDO sequence number.
857        tsn: u8,
858        /// MAC destination.
859        mac_destination: NodeId,
860        /// The payload after the sequence number.
861        data: Vec<u8>,
862    },
863    /// `APP_CNF_BDB_COMMISSIONING_NOTIFICATION`.
864    Commissioning {
865        /// Status: 0 success, 1 in progress, others failures.
866        status: u8,
867        /// The mode that reported.
868        mode: u8,
869        /// Modes still to run.
870        remaining: u8,
871    },
872}
873
874impl Indication {
875    /// Decode an asynchronous frame.
876    pub fn decode(frame: &Frame) -> Result<Indication, DecodeError> {
877        use Indication::*;
878        let mut r = Reader::new(&frame.data);
879        if frame.kind != Kind::Areq {
880            return Err(DecodeError::Unknown {
881                kind: frame.kind,
882                subsystem: frame.subsystem,
883                id: frame.id,
884            });
885        }
886        let ind = match (frame.subsystem, frame.id) {
887            (sub::SYS, sys::RESET_IND) => Reset {
888                reason: r.u8()?,
889                transport: r.u8()?,
890                product: r.u8()?,
891                major: r.u8()?,
892                minor: r.u8()?,
893                hw: r.u8()?,
894            },
895            (sub::AF, af::DATA_CONFIRM) => DataConfirm {
896                status: r.u8()?,
897                endpoint: r.u8()?,
898                trans_id: r.u8()?,
899            },
900            (sub::AF, af::INCOMING_MSG) => {
901                let group = r.u16()?;
902                let cluster = r.u16()?;
903                let source = r.u16()?;
904                let source_endpoint = r.u8()?;
905                let destination_endpoint = r.u8()?;
906                let broadcast = r.u8()? != 0;
907                let lqi = r.u8()?;
908                let secured = r.u8()? != 0;
909                let timestamp = r.u32()?;
910                let tsn = r.u8()?;
911                let data = r.u8_prefixed()?.to_vec();
912                let last_hop = if r.remaining() >= 2 {
913                    Some(r.u16()?)
914                } else {
915                    None
916                };
917                Incoming(Box::new(IncomingMsg {
918                    group,
919                    cluster,
920                    source,
921                    source_ieee: None,
922                    source_endpoint,
923                    destination_endpoint,
924                    broadcast,
925                    lqi,
926                    secured,
927                    timestamp,
928                    tsn,
929                    data,
930                    last_hop,
931                    extended: false,
932                }))
933            }
934            (sub::AF, af::INCOMING_MSG_EXT) => {
935                let group = r.u16()?;
936                let cluster = r.u16()?;
937                let mode = r.u8()?;
938                let address = r.u64()?;
939                let (source, source_ieee) = if mode == crate::ids::addr_mode::IEEE {
940                    (0xFFFE, Some(Ieee(address)))
941                } else {
942                    (address as u16, None)
943                };
944                let source_endpoint = r.u8()?;
945                let _source_pan = r.u16()?;
946                let destination_endpoint = r.u8()?;
947                let broadcast = r.u8()? != 0;
948                let lqi = r.u8()?;
949                let secured = r.u8()? != 0;
950                let timestamp = r.u32()?;
951                let tsn = r.u8()?;
952                let n = usize::from(r.u16()?);
953                let data = r.bytes(n)?.to_vec();
954                Incoming(Box::new(IncomingMsg {
955                    group,
956                    cluster,
957                    source,
958                    source_ieee,
959                    source_endpoint,
960                    destination_endpoint,
961                    broadcast,
962                    lqi,
963                    secured,
964                    timestamp,
965                    tsn,
966                    data,
967                    last_hop: None,
968                    extended: true,
969                }))
970            }
971            (sub::ZDO, zdo::STATE_CHANGE_IND) => StateChange { state: r.u8()? },
972            (sub::ZDO, zdo::END_DEVICE_ANNCE_IND) => DeviceAnnounce {
973                source: r.u16()?,
974                nwk: r.u16()?,
975                ieee: r.ieee()?,
976                capabilities: r.u8()?,
977            },
978            (sub::ZDO, zdo::SRC_RTG_IND) => {
979                let source = r.u16()?;
980                let n = r.u8()?;
981                SourceRoute {
982                    source,
983                    relays: r.u16_list(usize::from(n))?,
984                }
985            }
986            (sub::ZDO, zdo::BEACON_NOTIFY_IND) => {
987                let n = usize::from(r.u8()?);
988                let mut beacons = Vec::with_capacity(n.min(r.remaining() / 21 + 1));
989                for _ in 0..n {
990                    beacons.push(Beacon {
991                        source: r.u16()?,
992                        pan_id: r.u16()?,
993                        channel: r.u8()?,
994                        permit_joining: r.u8()? != 0,
995                        router_capacity: r.u8()? != 0,
996                        device_capacity: r.u8()? != 0,
997                        protocol_version: r.u8()?,
998                        stack_profile: r.u8()?,
999                        lqi: r.u8()?,
1000                        depth: r.u8()?,
1001                        update_id: r.u8()?,
1002                        extended_pan_id: r.ext_pan_id()?,
1003                    });
1004                }
1005                Beacons(beacons)
1006            }
1007            (sub::ZDO, zdo::NWK_DISCOVERY_CNF) => DiscoveryDone { status: r.u8()? },
1008            (sub::ZDO, zdo::LEAVE_IND) => Leave {
1009                nwk: r.u16()?,
1010                ieee: r.ieee()?,
1011                request: r.u8()? != 0,
1012                remove_children: r.u8()? != 0,
1013                rejoin: r.u8()? != 0,
1014            },
1015            (sub::ZDO, zdo::TC_DEV_IND) => TcDevice {
1016                nwk: r.u16()?,
1017                ieee: r.ieee()?,
1018                parent: r.u16()?,
1019            },
1020            (sub::ZDO, zdo::PERMIT_JOIN_IND) => PermitJoin { duration: r.u8()? },
1021            (sub::ZDO, zdo::MSG_CB_INCOMING) => ZdoMessage {
1022                source: r.u16()?,
1023                broadcast: r.u8()? != 0,
1024                cluster: r.u16()?,
1025                secured: r.u8()? != 0,
1026                tsn: r.u8()?,
1027                mac_destination: r.u16()?,
1028                data: r.rest().to_vec(),
1029            },
1030            (sub::APP_CNF, app_cnf::BDB_COMMISSIONING_NOTIFICATION) => Commissioning {
1031                status: r.u8()?,
1032                mode: r.u8()?,
1033                remaining: r.u8()?,
1034            },
1035            _ => {
1036                return Err(DecodeError::Unknown {
1037                    kind: frame.kind,
1038                    subsystem: frame.subsystem,
1039                    id: frame.id,
1040                })
1041            }
1042        };
1043        Ok(ind)
1044    }
1045
1046    /// Encode (the simulator's side).
1047    pub fn encode(&self) -> Frame {
1048        use Indication::*;
1049        let mut w = Vec::new();
1050        let (subsystem, id) = match self {
1051            Reset {
1052                reason,
1053                transport,
1054                product,
1055                major,
1056                minor,
1057                hw,
1058            } => {
1059                w.put_bytes(&[*reason, *transport, *product, *major, *minor, *hw]);
1060                (sub::SYS, sys::RESET_IND)
1061            }
1062            DataConfirm {
1063                status,
1064                endpoint,
1065                trans_id,
1066            } => {
1067                w.put_bytes(&[*status, *endpoint, *trans_id]);
1068                (sub::AF, af::DATA_CONFIRM)
1069            }
1070            Incoming(m) if m.extended => {
1071                w.put_u16(m.group);
1072                w.put_u16(m.cluster);
1073                match m.source_ieee {
1074                    Some(ieee) => {
1075                        w.put_u8(crate::ids::addr_mode::IEEE);
1076                        w.put_ieee(ieee);
1077                    }
1078                    None => {
1079                        w.put_u8(crate::ids::addr_mode::SHORT);
1080                        w.put_u64(u64::from(m.source));
1081                    }
1082                }
1083                w.put_u8(m.source_endpoint);
1084                w.put_u16(0);
1085                w.put_u8(m.destination_endpoint);
1086                w.put_u8(u8::from(m.broadcast));
1087                w.put_u8(m.lqi);
1088                w.put_u8(u8::from(m.secured));
1089                w.put_u32(m.timestamp);
1090                w.put_u8(m.tsn);
1091                w.put_u16(m.data.len() as u16);
1092                w.put_bytes(&m.data);
1093                (sub::AF, af::INCOMING_MSG_EXT)
1094            }
1095            Incoming(m) => {
1096                w.put_u16(m.group);
1097                w.put_u16(m.cluster);
1098                w.put_u16(m.source);
1099                w.put_u8(m.source_endpoint);
1100                w.put_u8(m.destination_endpoint);
1101                w.put_u8(u8::from(m.broadcast));
1102                w.put_u8(m.lqi);
1103                w.put_u8(u8::from(m.secured));
1104                w.put_u32(m.timestamp);
1105                w.put_u8(m.tsn);
1106                w.put_u8_prefixed(&m.data);
1107                if let Some(hop) = m.last_hop {
1108                    w.put_u16(hop);
1109                    w.put_u8(0); // radius
1110                }
1111                (sub::AF, af::INCOMING_MSG)
1112            }
1113            StateChange { state } => {
1114                w.put_u8(*state);
1115                (sub::ZDO, zdo::STATE_CHANGE_IND)
1116            }
1117            DeviceAnnounce {
1118                source,
1119                nwk,
1120                ieee,
1121                capabilities,
1122            } => {
1123                w.put_u16(*source);
1124                w.put_u16(*nwk);
1125                w.put_ieee(*ieee);
1126                w.put_u8(*capabilities);
1127                (sub::ZDO, zdo::END_DEVICE_ANNCE_IND)
1128            }
1129            SourceRoute { source, relays } => {
1130                w.put_u16(*source);
1131                put_u16_list(&mut w, relays);
1132                (sub::ZDO, zdo::SRC_RTG_IND)
1133            }
1134            Beacons(beacons) => {
1135                w.put_u8(beacons.len().min(255) as u8);
1136                for b in beacons.iter().take(255) {
1137                    w.put_u16(b.source);
1138                    w.put_u16(b.pan_id);
1139                    w.put_u8(b.channel);
1140                    w.put_u8(u8::from(b.permit_joining));
1141                    w.put_u8(u8::from(b.router_capacity));
1142                    w.put_u8(u8::from(b.device_capacity));
1143                    w.put_u8(b.protocol_version);
1144                    w.put_u8(b.stack_profile);
1145                    w.put_u8(b.lqi);
1146                    w.put_u8(b.depth);
1147                    w.put_u8(b.update_id);
1148                    w.put_ext_pan_id(b.extended_pan_id);
1149                }
1150                (sub::ZDO, zdo::BEACON_NOTIFY_IND)
1151            }
1152            DiscoveryDone { status } => {
1153                w.put_u8(*status);
1154                (sub::ZDO, zdo::NWK_DISCOVERY_CNF)
1155            }
1156            Leave {
1157                nwk,
1158                ieee,
1159                request,
1160                remove_children,
1161                rejoin,
1162            } => {
1163                w.put_u16(*nwk);
1164                w.put_ieee(*ieee);
1165                w.put_u8(u8::from(*request));
1166                w.put_u8(u8::from(*remove_children));
1167                w.put_u8(u8::from(*rejoin));
1168                (sub::ZDO, zdo::LEAVE_IND)
1169            }
1170            TcDevice { nwk, ieee, parent } => {
1171                w.put_u16(*nwk);
1172                w.put_ieee(*ieee);
1173                w.put_u16(*parent);
1174                (sub::ZDO, zdo::TC_DEV_IND)
1175            }
1176            PermitJoin { duration } => {
1177                w.put_u8(*duration);
1178                (sub::ZDO, zdo::PERMIT_JOIN_IND)
1179            }
1180            ZdoMessage {
1181                source,
1182                broadcast,
1183                cluster,
1184                secured,
1185                tsn,
1186                mac_destination,
1187                data,
1188            } => {
1189                w.put_u16(*source);
1190                w.put_u8(u8::from(*broadcast));
1191                w.put_u16(*cluster);
1192                w.put_u8(u8::from(*secured));
1193                w.put_u8(*tsn);
1194                w.put_u16(*mac_destination);
1195                w.put_bytes(data);
1196                (sub::ZDO, zdo::MSG_CB_INCOMING)
1197            }
1198            Commissioning {
1199                status,
1200                mode,
1201                remaining,
1202            } => {
1203                w.put_bytes(&[*status, *mode, *remaining]);
1204                (sub::APP_CNF, app_cnf::BDB_COMMISSIONING_NOTIFICATION)
1205            }
1206        };
1207        Frame::new(Kind::Areq, subsystem, id, w)
1208    }
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213    use super::*;
1214
1215    #[test]
1216    fn requests_round_trip() {
1217        let requests = [
1218            Request::SysReset { soft: true },
1219            Request::OsalNvWrite {
1220                id: 0x0062,
1221                offset: 0,
1222                value: vec![1; 16],
1223            },
1224            Request::NvRead {
1225                sysid: 1,
1226                item: 7,
1227                sub: 0,
1228                offset: 0,
1229                len: 12,
1230            },
1231            Request::ZdoSendData {
1232                destination: 0x1234,
1233                tsn: 9,
1234                cluster: 0x0005,
1235                data: vec![0x34, 0x12],
1236            },
1237            Request::AfRegister {
1238                endpoint: 1,
1239                profile: 0x0104,
1240                device_id: 5,
1241                version: 0,
1242                input_clusters: vec![0, 6],
1243                output_clusters: vec![0x0019],
1244            },
1245            Request::AfDataRequestExt {
1246                addr_mode: 1,
1247                destination: 0x0010,
1248                destination_endpoint: 0xFF,
1249                destination_pan: 0,
1250                source_endpoint: 1,
1251                cluster: 6,
1252                trans_id: 3,
1253                options: 0,
1254                radius: 30,
1255                data: vec![1, 2, 3],
1256            },
1257            Request::BdbAddInstallCode {
1258                format: 2,
1259                ieee: Ieee(1),
1260                code: vec![7; 16],
1261            },
1262        ];
1263        for r in requests {
1264            let f = r.encode();
1265            assert_eq!(Request::decode(&f), Ok(r));
1266            assert!(f.encode().is_ok());
1267        }
1268    }
1269
1270    #[test]
1271    fn indications_round_trip() {
1272        let incoming = IncomingMsg {
1273            group: 0,
1274            cluster: 0x0402,
1275            source: 0x1234,
1276            source_ieee: None,
1277            source_endpoint: 1,
1278            destination_endpoint: 1,
1279            broadcast: false,
1280            lqi: 200,
1281            secured: false,
1282            timestamp: 5,
1283            tsn: 1,
1284            data: vec![0x18, 1, 0x0A],
1285            last_hop: Some(0x1234),
1286            extended: false,
1287        };
1288        let inds = [
1289            Indication::Incoming(Box::new(incoming.clone())),
1290            Indication::Incoming(Box::new(IncomingMsg {
1291                extended: true,
1292                last_hop: None,
1293                source_ieee: Some(Ieee(9)),
1294                source: 0xFFFE,
1295                ..incoming
1296            })),
1297            Indication::SourceRoute {
1298                source: 1,
1299                relays: vec![2, 3],
1300            },
1301            Indication::ZdoMessage {
1302                source: 1,
1303                broadcast: false,
1304                cluster: 0x8005,
1305                secured: false,
1306                tsn: 4,
1307                mac_destination: 0,
1308                data: vec![0, 1, 0, 1, 1],
1309            },
1310        ];
1311        for i in inds {
1312            assert_eq!(Indication::decode(&i.encode()), Ok(i));
1313        }
1314    }
1315}