Skip to main content

zigbee_ezsp/
callback.rs

1//! Typed EZSP callbacks (NCP to host, unsolicited).
2
3use zigbee_primitives::wire::{Reader, Writer};
4use zigbee_primitives::{ExtPanId, Ieee, NodeId};
5
6use crate::command::DecodeError;
7use crate::ids::frame as id;
8use crate::types::{ApsFrame, ProtocolVersion, RxPacketInfo, Status};
9
10/// A callback from the NCP.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Callback {
13    /// The network came up, went down, opened or closed for joining.
14    StackStatus {
15        /// The new state.
16        status: Status,
17    },
18    /// The outcome of a `sendUnicast` or `sendBroadcast`.
19    MessageSent {
20        /// Delivery status.
21        status: Status,
22        /// [`crate::ids::outgoing`] type.
23        kind: u8,
24        /// Destination address or table index.
25        destination: NodeId,
26        /// The APS frame sent.
27        aps: ApsFrame,
28        /// The tag given when sending.
29        tag: u16,
30    },
31    /// A message for the host.
32    IncomingMessage {
33        /// [`crate::ids::incoming`] type.
34        kind: u8,
35        /// The APS frame.
36        aps: ApsFrame,
37        /// Sender and link quality.
38        info: RxPacketInfo,
39        /// The APS payload (ZDO or ZCL frame).
40        payload: Vec<u8>,
41    },
42    /// A device joined, rejoined or left (trust center view).
43    TrustCenterJoin {
44        /// Its network address.
45        node_id: NodeId,
46        /// Its IEEE address.
47        ieee: Ieee,
48        /// [`crate::ids::device_update`].
49        status: u8,
50        /// [`crate::ids::join_decision`] the trust center took.
51        decision: u8,
52        /// Its parent's network address.
53        parent: NodeId,
54    },
55    /// A child of the coordinator joined or left.
56    ChildJoin {
57        /// Child table index.
58        index: u8,
59        /// Joined (true) or left.
60        joining: bool,
61        /// Its network address.
62        node_id: NodeId,
63        /// Its IEEE address.
64        ieee: Ieee,
65        /// [`crate::ids::node_type`].
66        node_type: u8,
67    },
68    /// A route record: the path a device's message took to the coordinator.
69    IncomingRouteRecord {
70        /// The originator.
71        source: NodeId,
72        /// The originator's IEEE address.
73        ieee: Ieee,
74        /// Link quality of the last hop.
75        last_hop_lqi: u8,
76        /// Signal strength of the last hop, dBm.
77        last_hop_rssi: i8,
78        /// Relays, from the one nearest the source to the one nearest the
79        /// coordinator.
80        relays: Vec<NodeId>,
81    },
82    /// Key establishment with a partner progressed or failed.
83    ZigbeeKeyEstablishment {
84        /// The partner.
85        partner: Ieee,
86        /// [`crate::ids::key_status`].
87        status: u8,
88    },
89    /// One channel's result of an energy scan.
90    EnergyScanResult {
91        /// Channel.
92        channel: u8,
93        /// Strongest signal heard, dBm.
94        max_rssi: i8,
95    },
96    /// An active scan heard a network's beacon.
97    NetworkFound {
98        /// Channel.
99        channel: u8,
100        /// PAN id.
101        pan_id: u16,
102        /// Extended PAN id.
103        extended_pan_id: ExtPanId,
104        /// Its routers accept joins.
105        allowing_join: bool,
106        /// Stack profile (2: Zigbee PRO).
107        stack_profile: u8,
108        /// Network update id.
109        nwk_update_id: u8,
110        /// Link quality of the beacon.
111        lqi: u8,
112        /// Signal strength of the beacon, dBm.
113        rssi: i8,
114    },
115    /// A scan finished (or failed on `channel`).
116    ScanComplete {
117        /// Channel that failed, or the last channel.
118        channel: u8,
119        /// Outcome.
120        status: Status,
121    },
122    /// Two devices share a network address.
123    IdConflict {
124        /// The address.
125        node_id: NodeId,
126    },
127    /// A route error arrived.
128    IncomingRouteError {
129        /// The error.
130        status: Status,
131        /// The unreachable target.
132        target: NodeId,
133    },
134    /// A network status command arrived.
135    IncomingNetworkStatus {
136        /// The network status code.
137        code: u8,
138        /// Its target.
139        target: NodeId,
140    },
141    /// A concentrator's many-to-one route request was heard.
142    IncomingManyToOneRouteRequest {
143        /// The concentrator.
144        source: NodeId,
145        /// Its IEEE address.
146        ieee: Ieee,
147        /// Path cost.
148        cost: u8,
149    },
150    /// A stack token changed.
151    StackTokenChanged {
152        /// The token's address.
153        token: u16,
154    },
155    /// The NCP had no callbacks waiting.
156    NoCallbacks,
157    /// A callback this crate does not decode, passed through.
158    Other {
159        /// Frame id.
160        frame_id: u16,
161        /// Raw parameters.
162        params: Vec<u8>,
163    },
164}
165
166impl Callback {
167    /// The frame id.
168    pub fn frame_id(&self) -> u16 {
169        match self {
170            Callback::StackStatus { .. } => id::STACK_STATUS_HANDLER,
171            Callback::MessageSent { .. } => id::MESSAGE_SENT_HANDLER,
172            Callback::IncomingMessage { .. } => id::INCOMING_MESSAGE_HANDLER,
173            Callback::TrustCenterJoin { .. } => id::TRUST_CENTER_JOIN_HANDLER,
174            Callback::ChildJoin { .. } => id::CHILD_JOIN_HANDLER,
175            Callback::IncomingRouteRecord { .. } => id::INCOMING_ROUTE_RECORD_HANDLER,
176            Callback::ZigbeeKeyEstablishment { .. } => id::ZIGBEE_KEY_ESTABLISHMENT_HANDLER,
177            Callback::EnergyScanResult { .. } => id::ENERGY_SCAN_RESULT_HANDLER,
178            Callback::NetworkFound { .. } => id::NETWORK_FOUND_HANDLER,
179            Callback::ScanComplete { .. } => id::SCAN_COMPLETE_HANDLER,
180            Callback::IdConflict { .. } => id::ID_CONFLICT_HANDLER,
181            Callback::IncomingRouteError { .. } => id::INCOMING_ROUTE_ERROR_HANDLER,
182            Callback::IncomingNetworkStatus { .. } => id::INCOMING_NETWORK_STATUS_HANDLER,
183            Callback::IncomingManyToOneRouteRequest { .. } => {
184                id::INCOMING_MANY_TO_ONE_ROUTE_REQUEST_HANDLER
185            }
186            Callback::StackTokenChanged { .. } => id::STACK_TOKEN_CHANGED_HANDLER,
187            Callback::NoCallbacks => id::NO_CALLBACKS,
188            Callback::Other { frame_id, .. } => *frame_id,
189        }
190    }
191
192    /// Decode a callback. Unknown frame ids become [`Callback::Other`];
193    /// malformed known ones are errors.
194    pub fn decode(
195        v: ProtocolVersion,
196        frame_id: u16,
197        params: &[u8],
198    ) -> Result<Callback, DecodeError> {
199        let mut r = Reader::new(params);
200        Ok(match frame_id {
201            id::STACK_STATUS_HANDLER => Callback::StackStatus {
202                status: Status::read(&mut r, v)?,
203            },
204            id::MESSAGE_SENT_HANDLER => {
205                if v.sl_status() {
206                    let status = Status::read_sl(&mut r)?;
207                    Callback::MessageSent {
208                        status,
209                        kind: r.u8()?,
210                        destination: r.u16()?,
211                        aps: ApsFrame::read(&mut r)?,
212                        tag: r.u16()?,
213                    }
214                } else {
215                    let kind = r.u8()?;
216                    let destination = r.u16()?;
217                    let aps = ApsFrame::read(&mut r)?;
218                    let tag = u16::from(r.u8()?);
219                    Callback::MessageSent {
220                        status: Status::read(&mut r, v)?,
221                        kind,
222                        destination,
223                        aps,
224                        tag,
225                    }
226                }
227            }
228            id::INCOMING_MESSAGE_HANDLER => {
229                let kind = r.u8()?;
230                let aps = ApsFrame::read(&mut r)?;
231                let info = if v.sl_status() {
232                    RxPacketInfo::read(&mut r)?
233                } else {
234                    let last_hop_lqi = r.u8()?;
235                    let last_hop_rssi = r.i8()?;
236                    let sender = r.u16()?;
237                    let binding_index = r.u8()?;
238                    let address_index = r.u8()?;
239                    RxPacketInfo {
240                        sender,
241                        sender_ieee: None,
242                        binding_index,
243                        address_index,
244                        last_hop_lqi,
245                        last_hop_rssi,
246                        last_hop_timestamp: 0,
247                    }
248                };
249                Callback::IncomingMessage {
250                    kind,
251                    aps,
252                    info,
253                    payload: r.u8_prefixed()?.to_vec(),
254                }
255            }
256            id::TRUST_CENTER_JOIN_HANDLER => Callback::TrustCenterJoin {
257                node_id: r.u16()?,
258                ieee: r.ieee()?,
259                status: r.u8()?,
260                decision: r.u8()?,
261                parent: r.u16()?,
262            },
263            id::CHILD_JOIN_HANDLER => Callback::ChildJoin {
264                index: r.u8()?,
265                joining: r.bool()?,
266                node_id: r.u16()?,
267                ieee: r.ieee()?,
268                node_type: r.u8()?,
269            },
270            id::INCOMING_ROUTE_RECORD_HANDLER => {
271                let source = r.u16()?;
272                let ieee = r.ieee()?;
273                let last_hop_lqi = r.u8()?;
274                let last_hop_rssi = r.i8()?;
275                let count = usize::from(r.u8()?);
276                Callback::IncomingRouteRecord {
277                    source,
278                    ieee,
279                    last_hop_lqi,
280                    last_hop_rssi,
281                    relays: r.u16_list(count)?,
282                }
283            }
284            id::ZIGBEE_KEY_ESTABLISHMENT_HANDLER => Callback::ZigbeeKeyEstablishment {
285                partner: r.ieee()?,
286                status: r.u8()?,
287            },
288            id::ENERGY_SCAN_RESULT_HANDLER => Callback::EnergyScanResult {
289                channel: r.u8()?,
290                max_rssi: r.i8()?,
291            },
292            id::NETWORK_FOUND_HANDLER => Callback::NetworkFound {
293                channel: r.u8()?,
294                pan_id: r.u16()?,
295                extended_pan_id: r.ext_pan_id()?,
296                allowing_join: r.u8()? != 0,
297                stack_profile: r.u8()?,
298                nwk_update_id: r.u8()?,
299                lqi: r.u8()?,
300                rssi: r.i8()?,
301            },
302            id::SCAN_COMPLETE_HANDLER => Callback::ScanComplete {
303                channel: r.u8()?,
304                status: Status::read(&mut r, v)?,
305            },
306            id::ID_CONFLICT_HANDLER => Callback::IdConflict { node_id: r.u16()? },
307            id::INCOMING_ROUTE_ERROR_HANDLER => Callback::IncomingRouteError {
308                status: Status::read(&mut r, v)?,
309                target: r.u16()?,
310            },
311            id::INCOMING_NETWORK_STATUS_HANDLER => Callback::IncomingNetworkStatus {
312                code: r.u8()?,
313                target: r.u16()?,
314            },
315            id::INCOMING_MANY_TO_ONE_ROUTE_REQUEST_HANDLER => {
316                Callback::IncomingManyToOneRouteRequest {
317                    source: r.u16()?,
318                    ieee: r.ieee()?,
319                    cost: r.u8()?,
320                }
321            }
322            id::STACK_TOKEN_CHANGED_HANDLER => Callback::StackTokenChanged { token: r.u16()? },
323            id::NO_CALLBACKS => Callback::NoCallbacks,
324            other => Callback::Other {
325                frame_id: other,
326                params: params.to_vec(),
327            },
328        })
329    }
330
331    /// Encode the parameters (the NCP side).
332    pub fn encode(&self, v: ProtocolVersion) -> Vec<u8> {
333        let mut w = Vec::with_capacity(48);
334        match self {
335            Callback::StackStatus { status } => status.write(&mut w),
336            Callback::MessageSent {
337                status,
338                kind,
339                destination,
340                aps,
341                tag,
342            } => {
343                if v.sl_status() {
344                    status.write(&mut w);
345                    w.put_u8(*kind);
346                    w.put_u16(*destination);
347                    aps.write(&mut w);
348                    w.put_u16(*tag);
349                } else {
350                    w.put_u8(*kind);
351                    w.put_u16(*destination);
352                    aps.write(&mut w);
353                    w.put_u8(*tag as u8);
354                    status.write(&mut w);
355                }
356                w.put_u8(0); // message contents: tag only (MESSAGE_TAG_ONLY_IN_CALLBACK)
357            }
358            Callback::IncomingMessage {
359                kind,
360                aps,
361                info,
362                payload,
363            } => {
364                w.put_u8(*kind);
365                aps.write(&mut w);
366                if v.sl_status() {
367                    info.write(&mut w);
368                } else {
369                    w.put_u8(info.last_hop_lqi);
370                    w.put_u8(info.last_hop_rssi as u8);
371                    w.put_u16(info.sender);
372                    w.put_u8(info.binding_index);
373                    w.put_u8(info.address_index);
374                }
375                w.put_u8_prefixed(payload);
376            }
377            Callback::TrustCenterJoin {
378                node_id,
379                ieee,
380                status,
381                decision,
382                parent,
383            } => {
384                w.put_u16(*node_id);
385                w.put_ieee(*ieee);
386                w.put_u8(*status);
387                w.put_u8(*decision);
388                w.put_u16(*parent);
389            }
390            Callback::ChildJoin {
391                index,
392                joining,
393                node_id,
394                ieee,
395                node_type,
396            } => {
397                w.put_u8(*index);
398                w.put_u8(u8::from(*joining));
399                w.put_u16(*node_id);
400                w.put_ieee(*ieee);
401                w.put_u8(*node_type);
402            }
403            Callback::IncomingRouteRecord {
404                source,
405                ieee,
406                last_hop_lqi,
407                last_hop_rssi,
408                relays,
409            } => {
410                w.put_u16(*source);
411                w.put_ieee(*ieee);
412                w.put_u8(*last_hop_lqi);
413                w.put_u8(*last_hop_rssi as u8);
414                w.put_u8(relays.len() as u8);
415                relays.iter().for_each(|r| w.put_u16(*r));
416            }
417            Callback::ZigbeeKeyEstablishment { partner, status } => {
418                w.put_ieee(*partner);
419                w.put_u8(*status);
420            }
421            Callback::EnergyScanResult { channel, max_rssi } => {
422                w.put_u8(*channel);
423                w.put_u8(*max_rssi as u8);
424            }
425            Callback::NetworkFound {
426                channel,
427                pan_id,
428                extended_pan_id,
429                allowing_join,
430                stack_profile,
431                nwk_update_id,
432                lqi,
433                rssi,
434            } => {
435                w.put_u8(*channel);
436                w.put_u16(*pan_id);
437                w.put_ext_pan_id(*extended_pan_id);
438                w.put_u8(u8::from(*allowing_join));
439                w.put_u8(*stack_profile);
440                w.put_u8(*nwk_update_id);
441                w.put_u8(*lqi);
442                w.put_u8(*rssi as u8);
443            }
444            Callback::ScanComplete { channel, status } => {
445                w.put_u8(*channel);
446                status.write(&mut w);
447            }
448            Callback::IdConflict { node_id } => w.put_u16(*node_id),
449            Callback::IncomingRouteError { status, target } => {
450                status.write(&mut w);
451                w.put_u16(*target);
452            }
453            Callback::IncomingNetworkStatus { code, target } => {
454                w.put_u8(*code);
455                w.put_u16(*target);
456            }
457            Callback::IncomingManyToOneRouteRequest { source, ieee, cost } => {
458                w.put_u16(*source);
459                w.put_ieee(*ieee);
460                w.put_u8(*cost);
461            }
462            Callback::StackTokenChanged { token } => w.put_u16(*token),
463            Callback::NoCallbacks => {}
464            Callback::Other { params, .. } => w.put_bytes(params),
465        }
466        w
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    #[test]
475    fn callbacks_round_trip_in_both_layouts() {
476        for v in [ProtocolVersion(13), ProtocolVersion(17)] {
477            let aps = ApsFrame {
478                profile_id: 0x0104,
479                cluster_id: 0x0402,
480                source_endpoint: 1,
481                destination_endpoint: 1,
482                options: 0,
483                group_id: 0,
484                sequence: 4,
485            };
486            let info = RxPacketInfo {
487                sender: 0x4A2B,
488                sender_ieee: v.sl_status().then_some(Ieee(0x00124B0000000001)),
489                binding_index: 0xFF,
490                address_index: 0xFF,
491                last_hop_lqi: 200,
492                last_hop_rssi: -50,
493                last_hop_timestamp: if v.sl_status() { 1234 } else { 0 },
494            };
495            let callbacks = vec![
496                Callback::NetworkFound {
497                    channel: 20,
498                    pan_id: 0x1A62,
499                    extended_pan_id: ExtPanId(0xDDDD_DDDD_DDDD_DDDD),
500                    allowing_join: true,
501                    stack_profile: 2,
502                    nwk_update_id: 3,
503                    lqi: 180,
504                    rssi: -61,
505                },
506                Callback::StackStatus {
507                    status: Status::network_up(v),
508                },
509                Callback::MessageSent {
510                    status: Status::ok(v),
511                    kind: 0,
512                    destination: 0x4A2B,
513                    aps,
514                    tag: 9,
515                },
516                Callback::IncomingMessage {
517                    kind: 0,
518                    aps,
519                    info,
520                    payload: vec![0x18, 1, 0x0A, 0, 0, 0x29, 0x66, 0x08],
521                },
522                Callback::TrustCenterJoin {
523                    node_id: 0x4A2B,
524                    ieee: Ieee(1),
525                    status: 1,
526                    decision: 0,
527                    parent: 0,
528                },
529                Callback::ChildJoin {
530                    index: 0,
531                    joining: true,
532                    node_id: 0x4A2B,
533                    ieee: Ieee(1),
534                    node_type: 4,
535                },
536                Callback::IncomingRouteRecord {
537                    source: 0x4A2B,
538                    ieee: Ieee(1),
539                    last_hop_lqi: 99,
540                    last_hop_rssi: -70,
541                    relays: vec![0x1111, 0x2222],
542                },
543                Callback::ZigbeeKeyEstablishment {
544                    partner: Ieee(1),
545                    status: 0x06,
546                },
547                Callback::EnergyScanResult {
548                    channel: 15,
549                    max_rssi: -90,
550                },
551                Callback::ScanComplete {
552                    channel: 26,
553                    status: Status::ok(v),
554                },
555                Callback::IdConflict { node_id: 7 },
556                Callback::IncomingRouteError {
557                    status: Status::fail(v),
558                    target: 7,
559                },
560                Callback::IncomingNetworkStatus {
561                    code: 0x10,
562                    target: 7,
563                },
564                Callback::IncomingManyToOneRouteRequest {
565                    source: 7,
566                    ieee: Ieee(2),
567                    cost: 3,
568                },
569                Callback::StackTokenChanged { token: 0x0100 },
570                Callback::NoCallbacks,
571                Callback::Other {
572                    frame_id: 0x0147,
573                    params: vec![1, 2],
574                },
575            ];
576            for c in callbacks {
577                assert_eq!(
578                    Callback::decode(v, c.frame_id(), &c.encode(v)),
579                    Ok(c.clone()),
580                    "{c:?}"
581                );
582            }
583        }
584    }
585}