1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum SimNcp {
20 Ezsp {
23 protocol: u8,
25 },
26 Znp {
28 product: u8,
30 },
31 Deconz,
33}
34
35impl Default for SimNcp {
36 fn default() -> Self {
37 SimNcp::Ezsp { protocol: 13 }
38 }
39}
40
41#[derive(Debug, Clone)]
43pub struct SimConfig {
44 pub ncp: SimNcp,
46 pub ieee: Ieee,
48 pub devices: Vec<SimDevice>,
50 pub join_delay: Duration,
52 pub reply_delay: Duration,
54 pub key_table_size: u16,
56 pub neighbors: Vec<SimNeighbor>,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct SimNeighbor {
63 pub channel: u8,
65 pub pan_id: u16,
67 pub extended_pan_id: zigbee_primitives::ExtPanId,
69 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#[derive(Debug, Clone)]
89pub struct SimSnapshot {
90 pub network: Option<SimNetwork>,
92 pub joined: Vec<(Ieee, NodeId)>,
94 pub bindings: Vec<(Ieee, u8, u16)>,
96 pub reporting: Vec<(Ieee, u8, u16, u16)>,
98 pub permit_join: bool,
100 pub ieee: Ieee,
102 pub key_table: Vec<(Ieee, Key)>,
104 pub ias_enrolled: Vec<Ieee>,
106 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#[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#[derive(Debug, thiserror::Error)]
168pub enum SimError {
169 #[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 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 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 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 pub fn send_from(&self, ieee: Ieee, out: Outgoing) {
282 lock(&self.state).mesh.deliver(ieee, out, Duration::ZERO);
283 }
284
285 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 pub fn leave(&self, ieee: Ieee) {
298 lock(&self.state).mesh.leave_device(ieee);
299 }
300
301 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}