Skip to main content

zigbee_sim/
ncp.rs

1//! The simulator: one simulated network behind the NCP family of your
2//! choice.
3
4use std::sync::{Arc, Mutex, MutexGuard};
5use std::time::Duration;
6
7use tokio::io::{AsyncRead, AsyncWrite};
8use zigbee_primitives::{Ieee, Key, NodeId};
9use zigbee_zcl::Value;
10
11use crate::deconz::DeconzFront;
12use crate::device::{DeviceState, Outgoing, SimDevice};
13use crate::ezsp::EzspFront;
14use crate::mesh::{Mesh, SimNetwork};
15use crate::znp::ZnpFront;
16
17/// Which coordinator family the simulator plays.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum SimNcp {
20    /// Silicon Labs EmberZNet over EZSP and ASH. `protocol` 13 is EmberZNet
21    /// 7.4; 14 to 19 are 8.x.
22    Ezsp {
23        /// EZSP protocol version.
24        protocol: u8,
25    },
26    /// Texas Instruments Z-Stack over ZNP.
27    Znp {
28        /// Product: 1 for Z-Stack 3.x.0 (CC2652), 2 for 3.0.x (CC2531).
29        product: u8,
30    },
31    /// dresden elektronik deCONZ (a ConBee II).
32    Deconz,
33}
34
35impl Default for SimNcp {
36    fn default() -> Self {
37        SimNcp::Ezsp { protocol: 13 }
38    }
39}
40
41/// Simulator settings.
42#[derive(Debug, Clone)]
43pub struct SimConfig {
44    /// The coordinator family and version.
45    pub ncp: SimNcp,
46    /// The coordinator's factory IEEE address.
47    pub ieee: Ieee,
48    /// The simulated devices.
49    pub devices: Vec<SimDevice>,
50    /// Delay before a device in pairing mode joins an open network.
51    pub join_delay: Duration,
52    /// Delay of every device reply.
53    pub reply_delay: Duration,
54    /// Key table entries (EZSP).
55    pub key_table_size: u16,
56    /// Other networks in range, which an active scan hears.
57    pub neighbors: Vec<SimNeighbor>,
58}
59
60/// Another network in range of the simulated coordinator.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct SimNeighbor {
63    /// Channel.
64    pub channel: u8,
65    /// PAN id.
66    pub pan_id: u16,
67    /// Extended PAN id.
68    pub extended_pan_id: zigbee_primitives::ExtPanId,
69    /// Accepting joins.
70    pub permit_joining: bool,
71}
72
73impl Default for SimConfig {
74    fn default() -> Self {
75        SimConfig {
76            ncp: SimNcp::default(),
77            ieee: Ieee(0x00_0D_6F_FF_FE_00_00_01),
78            devices: Vec::new(),
79            join_delay: Duration::from_millis(200),
80            reply_delay: Duration::from_millis(20),
81            key_table_size: 12,
82            neighbors: Vec::new(),
83        }
84    }
85}
86
87/// A point-in-time view for tests.
88#[derive(Debug, Clone)]
89pub struct SimSnapshot {
90    /// The stored network, if any.
91    pub network: Option<SimNetwork>,
92    /// Joined devices and their network addresses.
93    pub joined: Vec<(Ieee, NodeId)>,
94    /// Bindings: (device, endpoint, cluster).
95    pub bindings: Vec<(Ieee, u8, u16)>,
96    /// Reporting configurations: (device, endpoint, cluster, attribute).
97    pub reporting: Vec<(Ieee, u8, u16, u16)>,
98    /// Joining is open.
99    pub permit_join: bool,
100    /// The IEEE address the NCP reports (factory or written).
101    pub ieee: Ieee,
102    /// Link keys the NCP holds for individual devices.
103    pub key_table: Vec<(Ieee, Key)>,
104    /// IAS-enrolled devices.
105    pub ias_enrolled: Vec<Ieee>,
106    /// Firmware of the devices that take OTA upgrades.
107    pub firmware: Vec<(Ieee, crate::device::SimFirmware)>,
108}
109
110pub(crate) enum Front {
111    Ezsp(EzspFront),
112    Znp(ZnpFront),
113    Deconz(DeconzFront),
114}
115
116impl Front {
117    pub fn ezsp(&mut self) -> Option<&mut EzspFront> {
118        match self {
119            Front::Ezsp(f) => Some(f),
120            _ => None,
121        }
122    }
123
124    pub fn znp(&mut self) -> Option<&mut ZnpFront> {
125        match self {
126            Front::Znp(f) => Some(f),
127            _ => None,
128        }
129    }
130
131    pub fn deconz(&mut self) -> Option<&mut DeconzFront> {
132        match self {
133            Front::Deconz(f) => Some(f),
134            _ => None,
135        }
136    }
137
138    fn link_keys(&self) -> Vec<(Ieee, Key)> {
139        match self {
140            Front::Ezsp(f) => f.key_table.values().copied().collect(),
141            Front::Znp(f) => f.link_keys.iter().map(|(i, k)| (*i, *k)).collect(),
142            Front::Deconz(f) => f.link_keys.iter().map(|(i, k)| (*i, *k)).collect(),
143        }
144    }
145}
146
147pub(crate) struct SimState {
148    pub mesh: Mesh,
149    pub front: Front,
150}
151
152/// An NCP simulator. State (the stored network, joined devices, bindings)
153/// survives host reconnects, as an NCP's non-volatile memory survives
154/// resets.
155#[derive(Clone)]
156pub struct Simulator {
157    pub(crate) state: Arc<Mutex<SimState>>,
158}
159
160impl std::fmt::Debug for Simulator {
161    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        f.debug_struct("Simulator").finish_non_exhaustive()
163    }
164}
165
166/// The simulator could not run.
167#[derive(Debug, thiserror::Error)]
168pub enum SimError {
169    /// The host's link ended.
170    #[error("host link closed: {0}")]
171    Closed(String),
172}
173
174pub(crate) fn lock(m: &Mutex<SimState>) -> MutexGuard<'_, SimState> {
175    m.lock().unwrap_or_else(|e| e.into_inner())
176}
177
178impl Simulator {
179    /// A simulator with `config`'s devices, all powered on.
180    pub fn new(config: SimConfig) -> Simulator {
181        let mut mesh = Mesh::new(
182            config.ieee,
183            &config.devices,
184            config.join_delay,
185            config.reply_delay,
186        );
187        mesh.neighbors = config.neighbors.clone();
188        let front = match config.ncp {
189            SimNcp::Ezsp { protocol } => {
190                Front::Ezsp(EzspFront::new(protocol, config.key_table_size))
191            }
192            SimNcp::Znp { product } => Front::Znp(ZnpFront::new(product)),
193            SimNcp::Deconz => Front::Deconz(DeconzFront::new()),
194        };
195        Simulator {
196            state: Arc::new(Mutex::new(SimState { mesh, front })),
197        }
198    }
199
200    /// Everything the simulator holds, for assertions.
201    pub fn snapshot(&self) -> SimSnapshot {
202        let s = lock(&self.state);
203        let mut bindings = Vec::new();
204        let mut reporting = Vec::new();
205        for (ieee, j) in &s.mesh.joined {
206            bindings.extend(
207                j.state
208                    .bindings
209                    .iter()
210                    .map(|b| (*ieee, b.source_endpoint, b.cluster)),
211            );
212            reporting.extend(
213                j.state
214                    .reporting
215                    .keys()
216                    .map(|(e, c, a)| (*ieee, *e, *c, *a)),
217            );
218        }
219        reporting.sort_unstable();
220        SimSnapshot {
221            network: s.mesh.network.clone(),
222            joined: s.mesh.joined.iter().map(|(i, j)| (*i, j.nwk)).collect(),
223            bindings,
224            reporting,
225            permit_join: s.mesh.permit_open(),
226            ieee: s.mesh.ieee(),
227            key_table: s.front.link_keys(),
228            ias_enrolled: s
229                .mesh
230                .joined
231                .iter()
232                .filter(|(_, j)| j.state.ias_enrolled)
233                .map(|(i, _)| *i)
234                .collect(),
235            firmware: s
236                .mesh
237                .devices
238                .iter()
239                .filter_map(|(i, d)| d.firmware.clone().map(|f| (*i, f)))
240                .collect(),
241        }
242    }
243
244    /// Set a device attribute, reporting it if the device was configured to.
245    /// Returns how many reports were sent.
246    pub fn set_attribute(
247        &self,
248        ieee: Ieee,
249        endpoint: u8,
250        cluster: u16,
251        attribute: u16,
252        value: Value,
253    ) -> usize {
254        let mut s = lock(&self.state);
255        let mesh = &mut s.mesh;
256        let Some(mut device) = mesh.devices.get(&ieee).cloned() else {
257            return 0;
258        };
259        let reports = match mesh.joined.get_mut(&ieee) {
260            Some(j) => device.set_attribute(&mut j.state, endpoint, cluster, attribute, value),
261            None => {
262                device.set_attribute(
263                    &mut DeviceState::default(),
264                    endpoint,
265                    cluster,
266                    attribute,
267                    value,
268                );
269                Vec::new()
270            }
271        };
272        mesh.devices.insert(ieee, device);
273        let n = reports.len();
274        for r in reports {
275            mesh.deliver(ieee, r, Duration::ZERO);
276        }
277        n
278    }
279
280    /// A device sends a cluster command frame (a button press, an alarm).
281    pub fn send_from(&self, ieee: Ieee, out: Outgoing) {
282        lock(&self.state).mesh.deliver(ieee, out, Duration::ZERO);
283    }
284
285    /// Add a device (it joins the next time the network opens).
286    pub fn add_device(&self, device: SimDevice) {
287        let mut s = lock(&self.state);
288        let ieee = device.ieee;
289        s.mesh.devices.insert(ieee, device);
290        if s.mesh.permit_open() {
291            let delay = s.mesh.join_delay;
292            s.mesh.schedule(delay, crate::mesh::Scheduled::Join(ieee));
293        }
294    }
295
296    /// A device leaves the network by itself.
297    pub fn leave(&self, ieee: Ieee) {
298        lock(&self.state).mesh.leave_device(ieee);
299    }
300
301    /// Serve one host connection over `io` until it ends.
302    pub async fn serve<T>(&self, io: T) -> Result<(), SimError>
303    where
304        T: AsyncRead + AsyncWrite + Send + 'static,
305    {
306        let kind = match lock(&self.state).front {
307            Front::Ezsp(_) => 0,
308            Front::Znp(_) => 1,
309            Front::Deconz(_) => 2,
310        };
311        match kind {
312            0 => crate::ezsp::serve(self, io).await,
313            1 => crate::znp::serve(self, io).await,
314            _ => crate::deconz::serve(self, io).await,
315        }
316    }
317}