Skip to main content

zwave_sim/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5pub mod node;
6
7use futures_util::{SinkExt, StreamExt};
8use node::{NodeSpec, SimNode};
9use std::time::Duration;
10use tokio::io::{AsyncRead, AsyncWrite};
11use tokio::sync::{mpsc, oneshot};
12use tokio_util::codec::Framed;
13use tracing::debug;
14use zwave_cc::Command;
15use zwave_security::SecurityClass;
16use zwave_serial::frame::{DataFrame, Frame, FrameCodec, FrameType};
17use zwave_serial::message::{
18    add_mode, AddNodeStatus, ApplicationCommand, ApplicationUpdate, ControllerId,
19    ControllerVersion, InitData, NvmResponse, RemoveNodeStatus, RxStatus, SerialApiCapabilities,
20    TxReport,
21};
22use zwave_serial::FunctionId as F;
23
24/// A byte stream the simulator serves.
25pub trait Port: AsyncRead + AsyncWrite + Send + Unpin + 'static {}
26impl<T: AsyncRead + AsyncWrite + Send + Unpin + 'static> Port for T {}
27
28/// The simulated controller's identity.
29#[derive(Debug, Clone)]
30pub struct SimConfig {
31    /// Home id.
32    pub home_id: u32,
33    /// Size of the simulated NVM image.
34    pub nvm_size: usize,
35    /// Pause between frames the simulator sends, so a host reads them one by one.
36    pub frame_gap: Duration,
37    /// Accept 16-bit node ids (and so Long Range), as 700 and 800 series sticks with Long Range do.
38    pub long_range: bool,
39    /// The NVM image to start with (by default `nvm_size` bytes of a pattern).
40    pub nvm: Option<Vec<u8>>,
41}
42
43impl Default for SimConfig {
44    fn default() -> Self {
45        SimConfig {
46            home_id: 0xc0ff_ee01,
47            nvm_size: 4096,
48            frame_gap: Duration::from_millis(2),
49            long_range: true,
50            nvm: None,
51        }
52    }
53}
54
55enum Mode {
56    Idle,
57    Adding {
58        cb: u8,
59    },
60    AddingDsk {
61        cb: u8,
62        nwi: [u8; 4],
63        long_range: bool,
64    },
65    Listening,
66    Removing {
67        cb: u8,
68    },
69    Replacing {
70        cb: u8,
71        node: u16,
72    },
73}
74
75type Inspector = Box<dyn FnOnce(Option<&SimNode>) + Send>;
76
77enum Cmd {
78    Press(String, oneshot::Sender<Option<u16>>),
79    PowerOn(String, oneshot::Sender<bool>),
80    Wake(String, oneshot::Sender<bool>),
81    SetSensor(String, u8, f64, oneshot::Sender<bool>),
82    Motion(String, oneshot::Sender<bool>),
83    Inspect(String, Inspector),
84    Nvm(oneshot::Sender<Vec<u8>>),
85    PowerOff(String, oneshot::Sender<bool>),
86    Attach(Box<dyn PortBox>),
87}
88
89/// A boxed port.
90pub trait PortBox: AsyncRead + AsyncWrite + Send + Unpin + 'static {}
91impl<T: AsyncRead + AsyncWrite + Send + Unpin + 'static> PortBox for T {}
92
93/// A simulated controller with its nodes.
94pub struct Simulator {
95    cfg: SimConfig,
96    nodes: Vec<SimNode>,
97    mode: Mode,
98    next_id: u16,
99    suc: u16,
100    nvm: Vec<u8>,
101    last_added: u16,
102    /// Bytes per node id on the Serial API (2 after SetNodeIDType Long).
103    nid: usize,
104    /// RF region code (USA Long Range by default).
105    region: u8,
106    next_lr_id: u16,
107}
108
109/// Controls a running simulator.
110#[derive(Clone)]
111pub struct SimHandle {
112    tx: mpsc::Sender<Cmd>,
113}
114
115impl Simulator {
116    /// A controller with no nodes in its network.
117    pub fn new(cfg: SimConfig) -> Self {
118        let nvm = cfg
119            .nvm
120            .clone()
121            .unwrap_or_else(|| (0..cfg.nvm_size).map(|i| (i * 7 + 3) as u8).collect());
122        Simulator {
123            cfg,
124            nodes: vec![],
125            mode: Mode::Idle,
126            next_id: 2,
127            suc: 0,
128            nvm,
129            last_added: 0,
130            nid: 1,
131            next_lr_id: 256,
132            region: 0x09,
133        }
134    }
135
136    /// Adds a node that is not in the network yet.
137    pub fn with_node(mut self, spec: NodeSpec) -> Self {
138        self.nodes.push(SimNode::new(spec));
139        self
140    }
141
142    /// Adds a node that is already in the network (insecure), as if included earlier.
143    pub fn with_joined_node(mut self, spec: NodeSpec) -> Self {
144        let mut n = SimNode::new(spec);
145        n.join(self.next_id, self.cfg.home_id);
146        n.lifeline = vec![1];
147        self.next_id += 1;
148        self.nodes.push(n);
149        self
150    }
151
152    /// Serves `port` until it closes; control the simulation with the handle.
153    pub fn spawn<P: Port>(self, port: P) -> SimHandle {
154        let (tx, rx) = mpsc::channel(64);
155        tokio::spawn(self.run(Box::new(port), rx));
156        SimHandle { tx }
157    }
158
159    fn node_mut(&mut self, id: u16) -> Option<&mut SimNode> {
160        self.nodes.iter_mut().find(|n| n.id == Some(id))
161    }
162
163    fn by_name(&mut self, name: &str) -> Option<&mut SimNode> {
164        self.nodes.iter_mut().find(|n| n.spec.name == name)
165    }
166
167    fn included(&self) -> Vec<u16> {
168        self.nodes.iter().filter_map(|n| n.id).collect()
169    }
170
171    async fn run(mut self, port: Box<dyn PortBox>, mut rx: mpsc::Receiver<Cmd>) {
172        let mut framed = Framed::new(port, FrameCodec::default());
173        // Without a handle the simulator still serves its port.
174        let mut commands_open = true;
175        loop {
176            let out: Vec<DataFrame> = tokio::select! {
177                f = framed.next() => match f {
178                    Some(Ok(Frame::Data(df))) => {
179                        if framed.send(Frame::Ack).await.is_err() { return; }
180                        self.handle(df)
181                    }
182                    Some(Ok(Frame::Invalid)) => { let _ = framed.send(Frame::Nak).await; vec![] }
183                    Some(Ok(_)) => vec![],
184                    Some(Err(_)) | None => {
185                        // Wait for a new port, as a stick does when the host reconnects.
186                        loop {
187                            match rx.recv().await {
188                                Some(Cmd::Attach(p)) => { framed = Framed::new(p, FrameCodec::default()); break; }
189                                Some(other) => { let _ = self.command(other); }
190                                None => return,
191                            }
192                        }
193                        vec![]
194                    }
195                },
196                c = rx.recv(), if commands_open => match c {
197                    Some(Cmd::Attach(p)) => { framed = Framed::new(p, FrameCodec::default()); vec![] }
198                    Some(c) => self.command(c),
199                    None => { commands_open = false; vec![] }
200                },
201            };
202            for f in out {
203                if framed.send(Frame::Data(f)).await.is_err() {
204                    break;
205                }
206                // Let the host read and acknowledge before the next frame.
207                if self.cfg.frame_gap.is_zero() {
208                    tokio::task::yield_now().await;
209                } else {
210                    tokio::time::sleep(self.cfg.frame_gap).await;
211                }
212            }
213        }
214    }
215
216    fn app_frames(&self, id: u16, frames: Vec<Vec<u8>>) -> Vec<DataFrame> {
217        frames
218            .into_iter()
219            .map(|c| {
220                ApplicationCommand {
221                    rx_status: RxStatus(0),
222                    source: id,
223                    destination: None,
224                    command: c,
225                    rssi: Some(-58),
226                }
227                .to_frame(self.nid)
228            })
229            .collect()
230    }
231
232    fn command(&mut self, c: Cmd) -> Vec<DataFrame> {
233        match c {
234            Cmd::Press(name, reply) => {
235                let (frames, id) = self.press(&name);
236                let _ = reply.send(id);
237                frames
238            }
239            Cmd::PowerOn(name, reply) => {
240                let listening = matches!(self.mode, Mode::Listening);
241                let Some(n) = self.by_name(&name) else {
242                    let _ = reply.send(false);
243                    return vec![];
244                };
245                if !n.spec.smartstart || n.id.is_some() || !listening {
246                    let _ = reply.send(false);
247                    return vec![];
248                }
249                let nwi = n.spec.dsk().nwi_home_id();
250                let info = n.spec.nif();
251                let long_range = n.spec.long_range;
252                let _ = reply.send(true);
253                vec![ApplicationUpdate::SmartStartHomeIdReceived {
254                    nwi_home_id: nwi,
255                    long_range,
256                    info,
257                }
258                .to_frame(self.nid)]
259            }
260            Cmd::Wake(name, reply) => {
261                let Some(n) = self.by_name(&name) else {
262                    let _ = reply.send(false);
263                    return vec![];
264                };
265                let Some(id) = n.id else {
266                    let _ = reply.send(false);
267                    return vec![];
268                };
269                let f = n.wake();
270                let _ = reply.send(true);
271                self.app_frames(id, f)
272            }
273            Cmd::SetSensor(name, t, v, reply) => {
274                let Some(n) = self.by_name(&name) else {
275                    let _ = reply.send(false);
276                    return vec![];
277                };
278                n.sensors.insert(t, v);
279                let (Some(id), Some(r)) = (n.id, n.sensor_report(t)) else {
280                    let _ = reply.send(false);
281                    return vec![];
282                };
283                let ok = !n.lifeline.is_empty() && n.reachable();
284                let _ = reply.send(ok);
285                if ok {
286                    let f = n.unsolicited(r);
287                    self.app_frames(id, f)
288                } else {
289                    vec![]
290                }
291            }
292            Cmd::Motion(name, reply) => {
293                let Some(n) = self.by_name(&name) else {
294                    let _ = reply.send(false);
295                    return vec![];
296                };
297                let Some(id) = n.id else {
298                    let _ = reply.send(false);
299                    return vec![];
300                };
301                let r: Command = zwave_cc::notification::Report {
302                    v1_alarm_type: 0,
303                    v1_alarm_level: 0,
304                    zensor_net_source: Some(0),
305                    status: Some(0xff),
306                    notification_type: Some(7),
307                    event: Some(8),
308                    sequence: Some(false),
309                    params: vec![],
310                    sequence_number: None,
311                }
312                .into();
313                let _ = reply.send(true);
314                let f = n.unsolicited(r);
315                self.app_frames(id, f)
316            }
317            Cmd::Inspect(name, f) => {
318                f(self.nodes.iter().find(|n| n.spec.name == name));
319                vec![]
320            }
321            Cmd::PowerOff(name, reply) => {
322                let found = self.by_name(&name).map(|n| n.powered = false).is_some();
323                let _ = reply.send(found);
324                vec![]
325            }
326            Cmd::Nvm(reply) => {
327                let _ = reply.send(self.nvm.clone());
328                vec![]
329            }
330            Cmd::Attach(_) => vec![],
331        }
332    }
333
334    fn press(&mut self, name: &str) -> (Vec<DataFrame>, Option<u16>) {
335        let home = self.cfg.home_id;
336        match self.mode {
337            Mode::Adding { cb } => {
338                let next = self.next_id;
339                let Some(n) = self.by_name(name) else {
340                    return (vec![], None);
341                };
342                if n.id.is_some() {
343                    return (vec![], None);
344                }
345                n.join(next, home);
346                let info = n.spec.nif();
347                self.next_id += 1;
348                self.last_added = next;
349                self.mode = Mode::Idle;
350                (
351                    vec![
352                        AddNodeStatus::NodeFound.to_frame(cb, self.nid),
353                        AddNodeStatus::AddingEndNode { node: next, info }.to_frame(cb, self.nid),
354                        AddNodeStatus::ProtocolDone.to_frame(cb, self.nid),
355                    ],
356                    Some(next),
357                )
358            }
359            Mode::Replacing { cb, node } => {
360                let Some(n) = self.by_name(name) else {
361                    return (vec![], None);
362                };
363                if n.id.is_some() {
364                    return (vec![], None);
365                }
366                n.join(node, home);
367                self.mode = Mode::Idle;
368                (
369                    vec![DataFrame::request(F::REPLACE_FAILED_NODE, vec![cb, 0x04])],
370                    Some(node),
371                )
372            }
373            Mode::Removing { cb } => {
374                let Some(n) = self.by_name(name) else {
375                    return (vec![], None);
376                };
377                let id = n.id.unwrap_or(0);
378                n.leave();
379                self.mode = Mode::Idle;
380                (
381                    vec![
382                        RemoveNodeStatus::NodeFound.to_frame(cb, self.nid),
383                        RemoveNodeStatus::RemovingEndNode { node: id }.to_frame(cb, self.nid),
384                        RemoveNodeStatus::Done { node: id }.to_frame(cb, self.nid),
385                    ],
386                    Some(id),
387                )
388            }
389            _ => (vec![], None),
390        }
391    }
392
393    fn response(f: F, payload: Vec<u8>) -> DataFrame {
394        DataFrame::response(f, payload)
395    }
396
397    fn handle(&mut self, df: DataFrame) -> Vec<DataFrame> {
398        if df.kind != FrameType::Request {
399            return vec![];
400        }
401        let p = &df.payload;
402        let home = self.cfg.home_id;
403        match F(df.function) {
404            F::GET_SERIAL_API_CAPABILITIES => {
405                let functions = SerialApiCapabilities::mask(&[
406                    F::GET_INIT_DATA,
407                    F::APPLICATION_COMMAND_HANDLER,
408                    F::GET_CONTROLLER_CAPABILITIES,
409                    F::GET_SERIAL_API_CAPABILITIES,
410                    F::SERIAL_API_SETUP,
411                    F::SEND_DATA,
412                    F::GET_CONTROLLER_VERSION,
413                    F::GET_CONTROLLER_ID,
414                    F::GET_NODE_PROTOCOL_INFO,
415                    F::APPLICATION_UPDATE,
416                    F::ADD_NODE_TO_NETWORK,
417                    F::REMOVE_NODE_FROM_NETWORK,
418                    F::SET_SUC_NODE_ID,
419                    F::GET_SUC_NODE_ID,
420                    F::REQUEST_NODE_INFO,
421                    F::REMOVE_FAILED_NODE,
422                    F::REPLACE_FAILED_NODE,
423                    F::SET_DEFAULT,
424                    F::GET_ROUTING_INFO,
425                    F::EXTENDED_NVM_OPERATIONS,
426                    F::GET_LONG_RANGE_NODES,
427                ]);
428                let c = SerialApiCapabilities {
429                    firmware_major: 7,
430                    firmware_minor: 22,
431                    manufacturer_id: 0x0000,
432                    product_type: 0x0004,
433                    product_id: 0x0004,
434                    functions,
435                };
436                vec![Self::response(F::GET_SERIAL_API_CAPABILITIES, c.encode())]
437            }
438            F::GET_CONTROLLER_VERSION => vec![Self::response(
439                F::GET_CONTROLLER_VERSION,
440                ControllerVersion {
441                    version: "Z-Wave 7.22".into(),
442                    library_type: 7,
443                }
444                .encode(),
445            )],
446            F::GET_CONTROLLER_ID => vec![Self::response(
447                F::GET_CONTROLLER_ID,
448                ControllerId {
449                    home_id: home,
450                    node_id: 1,
451                }
452                .encode(self.nid),
453            )],
454            F::GET_INIT_DATA => {
455                let mut nodes = vec![1];
456                nodes.extend(self.included().into_iter().filter(|&n| n <= 255));
457                let caps = if self.suc == 1 { 0x08 } else { 0 };
458                vec![Self::response(
459                    F::GET_INIT_DATA,
460                    InitData {
461                        api_version: 9,
462                        capabilities: caps,
463                        nodes,
464                        chip_type: Some(8),
465                        chip_version: Some(0),
466                    }
467                    .encode(),
468                )]
469            }
470            F::GET_CONTROLLER_CAPABILITIES => {
471                vec![Self::response(F::GET_CONTROLLER_CAPABILITIES, vec![0x1c])]
472            }
473            F::SERIAL_API_SETUP => match p.first() {
474                Some(&0x02) => vec![Self::response(F::SERIAL_API_SETUP, vec![0x02, 0x01])],
475                Some(&0x20) => vec![Self::response(F::SERIAL_API_SETUP, vec![0x20, self.region])],
476                Some(&0x40) => {
477                    self.region = p.get(1).copied().unwrap_or(self.region);
478                    vec![Self::response(F::SERIAL_API_SETUP, vec![0x40, 0x01])]
479                }
480                Some(&0x80) if self.cfg.long_range => {
481                    self.nid = if p.get(1) == Some(&0x02) { 2 } else { 1 };
482                    vec![Self::response(F::SERIAL_API_SETUP, vec![0x80, 0x01])]
483                }
484                _ => vec![Self::response(F::SERIAL_API_SETUP, vec![0x00])],
485            },
486            F::GET_SUC_NODE_ID => {
487                let mut v = Vec::new();
488                zwave_serial::message::node_bytes(self.suc, self.nid, &mut v);
489                vec![Self::response(F::GET_SUC_NODE_ID, v)]
490            }
491            F::GET_LONG_RANGE_NODES => {
492                let lr: Vec<u16> = self.included().into_iter().filter(|&n| n > 255).collect();
493                let seg = p.first().copied().unwrap_or(0);
494                vec![Self::response(
495                    F::GET_LONG_RANGE_NODES,
496                    zwave_serial::message::encode_long_range_nodes(false, seg, &lr),
497                )]
498            }
499            F::SET_SUC_NODE_ID => {
500                self.suc = zwave_serial::message::parse_node_id(p, self.nid).unwrap_or(0);
501                vec![Self::response(F::SET_SUC_NODE_ID, vec![0x01])]
502            }
503            F::GET_NODE_PROTOCOL_INFO => {
504                let id = zwave_serial::message::parse_node_id(p, self.nid).unwrap_or(0);
505                let info = self
506                    .node_mut(id)
507                    .map(|n| n.spec.protocol_info().encode())
508                    .unwrap_or(vec![0; 6]);
509                vec![Self::response(F::GET_NODE_PROTOCOL_INFO, info)]
510            }
511            F::GET_ROUTING_INFO => {
512                let id = zwave_serial::message::parse_node_id(p, self.nid).unwrap_or(0);
513                let mut neighbors: Vec<u16> = vec![1];
514                neighbors.extend(
515                    self.nodes
516                        .iter()
517                        .filter(|n| n.spec.listening)
518                        .filter_map(|n| n.id)
519                        .filter(|&n| n != id),
520                );
521                vec![Self::response(
522                    F::GET_ROUTING_INFO,
523                    zwave_serial::message::encode_node_mask(&neighbors, 29),
524                )]
525            }
526            F::REQUEST_NODE_INFO => {
527                let id = zwave_serial::message::parse_node_id(p, self.nid).unwrap_or(0);
528                let mut out = vec![Self::response(F::REQUEST_NODE_INFO, vec![0x01])];
529                match self.node_mut(id) {
530                    Some(n) if n.reachable() => out.push(
531                        ApplicationUpdate::NodeInfoReceived {
532                            node: id,
533                            info: n.spec.nif(),
534                        }
535                        .to_frame(self.nid),
536                    ),
537                    _ => out.push(ApplicationUpdate::NodeInfoRequestFailed.to_frame(self.nid)),
538                }
539                out
540            }
541            F::SEND_DATA => self.send_data(p),
542            F::ADD_NODE_TO_NETWORK => {
543                let mode = p.first().copied().unwrap_or(0) & 0x0f;
544                let cb = p.get(1).copied().unwrap_or(0);
545                match mode {
546                    add_mode::ANY => {
547                        self.mode = Mode::Adding { cb };
548                        vec![AddNodeStatus::Ready.to_frame(cb, self.nid)]
549                    }
550                    add_mode::SMART_START_LISTEN => {
551                        self.mode = Mode::Listening;
552                        vec![]
553                    }
554                    add_mode::SMART_START_DSK => {
555                        let nwi: [u8; 4] = p
556                            .get(2..6)
557                            .and_then(|s| s.try_into().ok())
558                            .unwrap_or([0; 4]);
559                        let long_range = p
560                            .first()
561                            .is_some_and(|f| f & add_mode::PROTOCOL_LONG_RANGE != 0);
562                        self.mode = Mode::AddingDsk {
563                            cb,
564                            nwi,
565                            long_range,
566                        };
567                        self.include_smartstart()
568                    }
569                    add_mode::STOP => {
570                        let was_listening = matches!(self.mode, Mode::Listening);
571                        self.mode = Mode::Idle;
572                        if cb != 0 && !was_listening {
573                            vec![AddNodeStatus::Done {
574                                node: self.last_added,
575                            }
576                            .to_frame(cb, self.nid)]
577                        } else {
578                            vec![]
579                        }
580                    }
581                    _ => vec![],
582                }
583            }
584            F::REMOVE_NODE_FROM_NETWORK => {
585                let mode = p.first().copied().unwrap_or(0) & 0x0f;
586                let cb = p.get(1).copied().unwrap_or(0);
587                match mode {
588                    add_mode::ANY => {
589                        self.mode = Mode::Removing { cb };
590                        vec![RemoveNodeStatus::Ready.to_frame(cb, self.nid)]
591                    }
592                    _ => {
593                        self.mode = Mode::Idle;
594                        vec![]
595                    }
596                }
597            }
598            F::SET_DEFAULT => {
599                // Factory defaults: every node forgotten, a new home id.
600                for n in &mut self.nodes {
601                    n.leave();
602                }
603                self.cfg.home_id = self.cfg.home_id.rotate_left(8) ^ 0x5a5a_0001;
604                self.next_id = 2;
605                self.next_lr_id = 256;
606                self.suc = 0;
607                let cb = p.first().copied().unwrap_or(0);
608                vec![DataFrame::request(F::SET_DEFAULT, vec![cb])]
609            }
610            F::REPLACE_FAILED_NODE => {
611                let id = zwave_serial::message::parse_node_id(p, self.nid).unwrap_or(0);
612                let cb = p.get(self.nid).copied().unwrap_or(0);
613                match self.node_mut(id).map(|n| n.reachable()) {
614                    None => vec![Self::response(F::REPLACE_FAILED_NODE, vec![0x01])],
615                    Some(true) => vec![
616                        Self::response(F::REPLACE_FAILED_NODE, vec![0x00]),
617                        DataFrame::request(F::REPLACE_FAILED_NODE, vec![cb, 0x00]),
618                    ],
619                    Some(false) => {
620                        if let Some(n) = self.node_mut(id) {
621                            n.leave();
622                        }
623                        self.mode = Mode::Replacing { cb, node: id };
624                        vec![
625                            Self::response(F::REPLACE_FAILED_NODE, vec![0x00]),
626                            DataFrame::request(F::REPLACE_FAILED_NODE, vec![cb, 0x03]),
627                        ]
628                    }
629                }
630            }
631            F::REMOVE_FAILED_NODE => {
632                let id = zwave_serial::message::parse_node_id(p, self.nid).unwrap_or(0);
633                let cb = p.get(self.nid).copied().unwrap_or(0);
634                let failed = self.node_mut(id).map(|n| !n.reachable()).unwrap_or(true);
635                let mut out = vec![Self::response(F::REMOVE_FAILED_NODE, vec![0x00])];
636                if failed {
637                    if let Some(n) = self.node_mut(id) {
638                        n.leave();
639                    }
640                    out.push(DataFrame::request(F::REMOVE_FAILED_NODE, vec![cb, 0x01]));
641                } else {
642                    out.push(DataFrame::request(F::REMOVE_FAILED_NODE, vec![cb, 0x02]));
643                }
644                out
645            }
646            F::EXTENDED_NVM_OPERATIONS => {
647                let op = p.first().copied().unwrap_or(0xff);
648                let r = match op {
649                    0x00 => NvmResponse {
650                        status: 0,
651                        offset_or_size: self.nvm.len() as u32,
652                        data: vec![],
653                    },
654                    0x01 => {
655                        let len = usize::from(p.get(1).copied().unwrap_or(0));
656                        let off = p
657                            .get(2..6)
658                            .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
659                            .unwrap_or(0) as usize;
660                        let end = (off + len).min(self.nvm.len());
661                        let data = self.nvm.get(off..end).unwrap_or(&[]).to_vec();
662                        NvmResponse {
663                            status: if end >= self.nvm.len() { 0xff } else { 0 },
664                            offset_or_size: off as u32,
665                            data,
666                        }
667                    }
668                    0x02 => {
669                        let len = usize::from(p.get(1).copied().unwrap_or(0));
670                        let off = p
671                            .get(2..6)
672                            .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
673                            .unwrap_or(0) as usize;
674                        match p.get(6..6 + len) {
675                            Some(data) if off + len <= self.nvm.len() => {
676                                self.nvm[off..off + len].copy_from_slice(data);
677                                NvmResponse {
678                                    status: 0,
679                                    offset_or_size: off as u32,
680                                    data: vec![],
681                                }
682                            }
683                            _ => NvmResponse {
684                                status: 0x01,
685                                offset_or_size: off as u32,
686                                data: vec![],
687                            },
688                        }
689                    }
690                    0x03 => NvmResponse {
691                        status: 0,
692                        offset_or_size: 0,
693                        data: vec![],
694                    },
695                    _ => NvmResponse {
696                        status: 0x04,
697                        offset_or_size: 0,
698                        data: vec![],
699                    },
700                };
701                vec![Self::response(F::EXTENDED_NVM_OPERATIONS, r.encode(true))]
702            }
703            other => {
704                debug!("simulator ignores {other}");
705                vec![]
706            }
707        }
708    }
709
710    fn include_smartstart(&mut self) -> Vec<DataFrame> {
711        let Mode::AddingDsk {
712            cb,
713            nwi,
714            long_range,
715        } = self.mode
716        else {
717            return vec![];
718        };
719        // A Long Range node only joins over Long Range, with a 16-bit id.
720        if long_range && self.nid != 2 {
721            return vec![AddNodeStatus::Failed.to_frame(cb, self.nid)];
722        }
723        let next = if long_range {
724            self.next_lr_id
725        } else {
726            self.next_id
727        };
728        let home = self.cfg.home_id;
729        let Some(n) = self.nodes.iter_mut().find(|n| {
730            n.spec.smartstart
731                && n.spec.long_range == long_range
732                && n.id.is_none()
733                && n.spec.dsk().nwi_home_id() == nwi
734        }) else {
735            return vec![AddNodeStatus::Failed.to_frame(cb, self.nid)];
736        };
737        n.join(next, home);
738        let info = n.spec.nif();
739        if long_range {
740            self.next_lr_id += 1;
741        } else {
742            self.next_id += 1;
743        }
744        self.last_added = next;
745        self.mode = Mode::Idle;
746        vec![
747            AddNodeStatus::Ready.to_frame(cb, self.nid),
748            AddNodeStatus::NodeFound.to_frame(cb, self.nid),
749            AddNodeStatus::AddingEndNode { node: next, info }.to_frame(cb, self.nid),
750            AddNodeStatus::ProtocolDone.to_frame(cb, self.nid),
751        ]
752    }
753
754    fn send_data(&mut self, p: &[u8]) -> Vec<DataFrame> {
755        let id = zwave_serial::message::parse_node_id(p, self.nid).unwrap_or(0);
756        let at = self.nid;
757        let len = usize::from(p.get(at).copied().unwrap_or(0));
758        let Some(data) = p.get(at + 1..at + 1 + len).map(<[u8]>::to_vec) else {
759            return vec![Self::response(F::SEND_DATA, vec![0x00])];
760        };
761        let cb = p.get(at + 2 + len).copied().unwrap_or(0);
762        let mut out = vec![Self::response(F::SEND_DATA, vec![0x01])];
763        let reply = match self.node_mut(id) {
764            Some(n) if n.reachable() => Some(n.receive(&data)),
765            _ => None,
766        };
767        let status = if reply.is_some() { 0x00 } else { 0x01 };
768        if cb != 0 {
769            let report = TxReport {
770                ticks: 2,
771                repeaters: vec![],
772                ack_rssi: Some(-55),
773                repeater_rssi: vec![],
774                ack_channel: Some(0),
775                tx_channel: 0,
776                route_scheme: 0,
777                speed: 3,
778                attempts: 1,
779                failed_from: None,
780                failed_to: None,
781            };
782            let mut cbp = vec![cb, status];
783            cbp.extend_from_slice(&report.encode());
784            out.push(DataFrame::request(F::SEND_DATA, cbp));
785        }
786        if let Some(frames) = reply {
787            out.extend(self.app_frames(id, frames));
788        }
789        out
790    }
791}
792
793impl SimHandle {
794    async fn ask<T>(&self, make: impl FnOnce(oneshot::Sender<T>) -> Cmd) -> Option<T> {
795        let (tx, rx) = oneshot::channel();
796        self.tx.send(make(tx)).await.ok()?;
797        rx.await.ok()
798    }
799
800    /// Presses a node's button: it joins while inclusion runs, leaves while exclusion runs.
801    /// Returns its node id (new or former).
802    pub async fn press(&self, name: &str) -> Option<u16> {
803        self.ask(|tx| Cmd::Press(name.into(), tx)).await.flatten()
804    }
805
806    /// Powers on a SmartStart node: it asks for inclusion while the controller listens.
807    pub async fn power_on(&self, name: &str) -> bool {
808        self.ask(|tx| Cmd::PowerOn(name.into(), tx))
809            .await
810            .unwrap_or(false)
811    }
812
813    /// Wakes a sleeping node: it sends a Wake Up Notification.
814    pub async fn wake_up(&self, name: &str) -> bool {
815        self.ask(|tx| Cmd::Wake(name.into(), tx))
816            .await
817            .unwrap_or(false)
818    }
819
820    /// Changes a sensor reading; a node with a lifeline reports it.
821    pub async fn set_sensor(&self, name: &str, sensor_type: u8, value: f64) -> bool {
822        self.ask(|tx| Cmd::SetSensor(name.into(), sensor_type, value, tx))
823            .await
824            .unwrap_or(false)
825    }
826
827    /// The node detects motion and sends a Notification Report.
828    pub async fn motion(&self, name: &str) -> bool {
829        self.ask(|tx| Cmd::Motion(name.into(), tx))
830            .await
831            .unwrap_or(false)
832    }
833
834    /// Reads something from a node's state.
835    pub async fn inspect<T: Send + 'static>(
836        &self,
837        name: &str,
838        f: impl FnOnce(&SimNode) -> T + Send + 'static,
839    ) -> Option<T> {
840        let (tx, rx) = oneshot::channel();
841        let cmd = Cmd::Inspect(
842            name.into(),
843            Box::new(move |n| {
844                let _ = tx.send(n.map(f));
845            }),
846        );
847        self.tx.send(cmd).await.ok()?;
848        rx.await.ok().flatten()
849    }
850
851    /// The node's id, if included.
852    pub async fn node_id(&self, name: &str) -> Option<u16> {
853        self.inspect(name, |n| n.id).await.flatten()
854    }
855
856    /// The classes the node holds keys for.
857    pub async fn granted(&self, name: &str) -> Vec<SecurityClass> {
858        self.inspect(name, |n| n.granted.clone())
859            .await
860            .unwrap_or_default()
861    }
862
863    /// Cuts a node's power: it stops answering, so the controller sees it fail.
864    pub async fn power_off(&self, name: &str) -> bool {
865        self.ask(|tx| Cmd::PowerOff(name.into(), tx))
866            .await
867            .unwrap_or(false)
868    }
869
870    /// The simulated NVM image.
871    pub async fn nvm(&self) -> Vec<u8> {
872        self.ask(Cmd::Nvm).await.unwrap_or_default()
873    }
874
875    /// Serves a new connection (the host reconnected).
876    pub async fn attach<P: Port>(&self, port: P) {
877        let _ = self.tx.send(Cmd::Attach(Box::new(port))).await;
878    }
879}