Skip to main content

zigbee_sim/
mesh.rs

1//! The simulated network every NCP front-end shares: the stored network,
2//! devices, joins, leaves and frame delivery. A front-end (EZSP, ZNP,
3//! deCONZ) turns host commands into calls here and [`MeshEvent`]s into its
4//! own protocol's frames.
5
6use std::collections::{BTreeMap, HashMap};
7use std::time::{Duration, Instant};
8
9use tokio::sync::mpsc;
10use zigbee_primitives::{ExtPanId, Ieee, Key, NodeId, PanId};
11
12use crate::device::{DeviceState, Outgoing, SimDevice};
13
14/// The network the NCP has stored.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct SimNetwork {
17    /// Channel.
18    pub channel: u8,
19    /// PAN id.
20    pub pan_id: PanId,
21    /// Extended PAN id.
22    pub extended_pan_id: ExtPanId,
23    /// Network update id.
24    pub nwk_update_id: u8,
25    /// Channels the network may use.
26    pub channel_mask: u32,
27    /// Network key.
28    pub network_key: Key,
29    /// Key sequence number.
30    pub key_sequence: u8,
31    /// The trust center's key material: EmberZNet's hashed link key root,
32    /// Z-Stack's link key seed, or zero.
33    pub tc_root: Key,
34    /// Outgoing network frame counter.
35    pub frame_counter: u32,
36}
37
38/// Something that happened on the simulated network.
39#[derive(Debug, Clone)]
40pub(crate) enum MeshEvent {
41    /// A device joined.
42    Joined {
43        nwk: NodeId,
44        ieee: Ieee,
45        /// An end device (sleepy or not) rather than a router.
46        end_device: Option<bool>,
47        /// It asks for a unique link key (not a legacy device).
48        key_exchange: bool,
49    },
50    /// A device left.
51    Left { nwk: NodeId, ieee: Ieee },
52    /// A device sent the coordinator a frame.
53    Incoming {
54        nwk: NodeId,
55        ieee: Ieee,
56        lqi: u8,
57        rssi: i8,
58        aps_seq: u8,
59        out: Outgoing,
60    },
61}
62
63/// Work for later, run by the serving loop.
64#[derive(Debug)]
65pub(crate) enum Scheduled {
66    Join(Ieee),
67    /// The trust center removes a device.
68    Remove(Ieee),
69    Mesh(MeshEvent),
70    Ezsp(zigbee_ezsp::Callback),
71    Znp(zigbee_znp::Indication),
72    Deconz(crate::deconz::Pending),
73}
74
75pub(crate) struct Joined {
76    pub nwk: NodeId,
77    pub state: DeviceState,
78}
79
80pub(crate) struct Mesh {
81    pub join_delay: Duration,
82    pub reply_delay: Duration,
83    pub factory_ieee: Ieee,
84    pub ieee_override: Option<Ieee>,
85    pub devices: BTreeMap<Ieee, SimDevice>,
86    pub joined: BTreeMap<Ieee, Joined>,
87    pub network: Option<SimNetwork>,
88    pub up: bool,
89    pub permit_until: Option<Instant>,
90    /// The trust center admits joins.
91    pub allow_joins: bool,
92    /// Only devices with an install code key may join.
93    pub install_code_only: bool,
94    /// The well-known key is accepted for joins.
95    pub well_known_ok: bool,
96    /// Install code keys by device.
97    pub join_keys: HashMap<Ieee, Key>,
98    next_nwk: NodeId,
99    aps_seq: u8,
100    /// Other networks in range.
101    pub neighbors: Vec<crate::ncp::SimNeighbor>,
102    pub sink: Option<mpsc::UnboundedSender<(Duration, Scheduled)>>,
103}
104
105impl Mesh {
106    pub fn new(
107        factory_ieee: Ieee,
108        devices: &[SimDevice],
109        join_delay: Duration,
110        reply_delay: Duration,
111    ) -> Mesh {
112        Mesh {
113            join_delay,
114            reply_delay,
115            factory_ieee,
116            ieee_override: None,
117            devices: devices.iter().map(|d| (d.ieee, d.clone())).collect(),
118            joined: BTreeMap::new(),
119            network: None,
120            up: false,
121            permit_until: None,
122            allow_joins: false,
123            install_code_only: false,
124            well_known_ok: false,
125            join_keys: HashMap::new(),
126            next_nwk: 0x1A2B,
127            aps_seq: 0,
128            neighbors: Vec::new(),
129            sink: None,
130        }
131    }
132
133    pub fn ieee(&self) -> Ieee {
134        self.ieee_override.unwrap_or(self.factory_ieee)
135    }
136
137    pub fn schedule(&self, delay: Duration, what: Scheduled) {
138        if let Some(tx) = &self.sink {
139            let _ = tx.send((delay, what));
140        }
141    }
142
143    pub fn next_aps_seq(&mut self) -> u8 {
144        self.aps_seq = self.aps_seq.wrapping_add(1);
145        self.aps_seq
146    }
147
148    /// The stack restarted: the stored network stays, the rest is gone.
149    pub fn reset(&mut self) {
150        self.up = false;
151        self.permit_until = None;
152        self.allow_joins = false;
153        self.install_code_only = false;
154        self.well_known_ok = false;
155        self.join_keys.clear();
156    }
157
158    pub fn nwk_of(&self, ieee: Ieee) -> Option<NodeId> {
159        self.joined.get(&ieee).map(|j| j.nwk)
160    }
161
162    pub fn ieee_of(&self, nwk: NodeId) -> Option<Ieee> {
163        self.joined
164            .iter()
165            .find(|(_, j)| j.nwk == nwk)
166            .map(|(i, _)| *i)
167    }
168
169    pub fn deliver(&mut self, from: Ieee, out: Outgoing, delay: Duration) {
170        let Some(nwk) = self.nwk_of(from) else {
171            return;
172        };
173        let (lqi, rssi) = self
174            .devices
175            .get(&from)
176            .map(|d| (d.lqi, d.rssi))
177            .unwrap_or((200, -50));
178        if let Some(n) = self.network.as_mut() {
179            n.frame_counter = n.frame_counter.wrapping_add(1);
180        }
181        let aps_seq = self.next_aps_seq();
182        self.schedule(
183            delay,
184            Scheduled::Mesh(MeshEvent::Incoming {
185                nwk,
186                ieee: from,
187                lqi,
188                rssi,
189                aps_seq,
190                out,
191            }),
192        );
193    }
194
195    pub fn permit_open(&self) -> bool {
196        self.permit_until.is_some_and(|t| Instant::now() < t)
197    }
198
199    /// Open (seconds > 0) or close joining; devices in pairing mode join.
200    pub fn permit(&mut self, seconds: u16) {
201        if seconds == 0 {
202            self.permit_until = None;
203        } else {
204            self.permit_until = Some(Instant::now() + Duration::from_secs(u64::from(seconds)));
205            self.schedule_joins();
206        }
207    }
208
209    fn may_join(&self, device: &SimDevice) -> bool {
210        if !self.up || !self.permit_open() || !self.allow_joins {
211            return false;
212        }
213        match device.install_code_key {
214            Some(key) => self.join_keys.get(&device.ieee) == Some(&key),
215            None => !self.install_code_only && self.well_known_ok,
216        }
217    }
218
219    pub fn schedule_joins(&self) {
220        for d in self.devices.values() {
221            if d.pairing && !self.joined.contains_key(&d.ieee) {
222                self.schedule(self.join_delay, Scheduled::Join(d.ieee));
223            }
224        }
225    }
226
227    pub fn join(&mut self, ieee: Ieee) {
228        let Some(device) = self.devices.get(&ieee).cloned() else {
229            return;
230        };
231        if self.joined.contains_key(&ieee) || !self.may_join(&device) {
232            return;
233        }
234        let nwk = self.next_nwk;
235        self.next_nwk = self.next_nwk.wrapping_add(0x1111);
236        self.joined.insert(
237            ieee,
238            Joined {
239                nwk,
240                state: DeviceState::default(),
241            },
242        );
243        tracing::info!(%ieee, nwk = format!("{nwk:#06x}"), "sim: device joined");
244        self.schedule(
245            Duration::ZERO,
246            Scheduled::Mesh(MeshEvent::Joined {
247                nwk,
248                ieee,
249                end_device: (!device.router).then_some(device.sleepy),
250                key_exchange: !device.legacy,
251            }),
252        );
253        let announce = device.announce(nwk);
254        self.deliver(ieee, announce, Duration::from_millis(30));
255    }
256
257    pub fn leave_device(&mut self, ieee: Ieee) {
258        if let Some(j) = self.joined.remove(&ieee) {
259            self.schedule(
260                Duration::from_millis(5),
261                Scheduled::Mesh(MeshEvent::Left { nwk: j.nwk, ieee }),
262            );
263        }
264    }
265
266    /// A unicast from the coordinator. Returns whether a device took it.
267    pub fn unicast(&mut self, destination: NodeId, out: &Outgoing) -> bool {
268        let Some(ieee) = self.ieee_of(destination) else {
269            return false;
270        };
271        let coordinator = self.ieee();
272        let delay = self.reply_delay;
273        let Some(mut device) = self.devices.get(&ieee).cloned() else {
274            return false;
275        };
276        let Some(joined) = self.joined.get_mut(&ieee) else {
277            return false;
278        };
279        let reaction = if out.profile == zigbee_zdo::PROFILE_ID && out.destination_endpoint == 0 {
280            device.handle_zdo(
281                destination,
282                &mut joined.state,
283                out.cluster,
284                &out.payload,
285                coordinator,
286            )
287        } else {
288            device.handle_zcl(
289                &mut joined.state,
290                out.destination_endpoint,
291                out.cluster,
292                out.source_endpoint,
293                &out.payload,
294            )
295        };
296        self.devices.insert(ieee, device);
297        for reply in reaction.replies {
298            self.deliver(ieee, reply, delay);
299        }
300        if reaction.leave {
301            self.leave_device(ieee);
302        }
303        true
304    }
305
306    /// Form (or restore) a network.
307    pub fn form(&mut self, network: SimNetwork) {
308        self.network = Some(network);
309        self.up = true;
310    }
311
312    /// Leave the stored network; every device is gone with it.
313    pub fn leave(&mut self) -> bool {
314        self.up = false;
315        self.joined.clear();
316        self.network.take().is_some()
317    }
318
319    /// Move the network to another channel (a network update); every
320    /// device follows. Returns false without a network.
321    pub fn change_channel(&mut self, channel: u8) -> bool {
322        match self.network.as_mut() {
323            Some(n) => {
324                n.channel = channel;
325                n.nwk_update_id = n.nwk_update_id.wrapping_add(1);
326                true
327            }
328            None => false,
329        }
330    }
331
332    /// A Mgmt_NWK_Update_req the coordinator handles itself (`data` is the
333    /// request after its sequence number): a channel change (duration
334    /// 0xFE) moves the network; an energy scan (duration 0 to 5) returns
335    /// the Mgmt_NWK_Update_notify payload, energies in 802.15.4 ED units.
336    pub fn network_update(&mut self, data: &[u8]) -> Option<Vec<u8>> {
337        let mask = u32::from_le_bytes(data.get(..4)?.try_into().ok()?);
338        let duration = *data.get(4)?;
339        if duration == 0xFE {
340            if let Some(channel) = (11..=26u8).find(|c| mask & (1 << c) != 0) {
341                self.change_channel(channel);
342            }
343            return None;
344        }
345        if duration > 5 {
346            return None;
347        }
348        let energies = Mesh::energy(mask);
349        let mut notify = vec![0];
350        notify.extend_from_slice(&100u16.to_le_bytes());
351        notify.extend_from_slice(&0u16.to_le_bytes());
352        notify.extend_from_slice(&mask.to_le_bytes());
353        notify.push(energies.len() as u8);
354        for (_, dbm) in energies {
355            notify.push(((i16::from(dbm) + 100).clamp(0, 40) * 255 / 40) as u8);
356        }
357        Some(notify)
358    }
359
360    /// Energy per channel in the mask, dBm.
361    pub fn energy(channel_mask: u32) -> Vec<(u8, i8)> {
362        (11..=26u8)
363            .filter(|c| channel_mask & (1 << c) != 0)
364            .map(|c| (c, -95 + ((c * 7) % 30) as i8))
365            .collect()
366    }
367}