Skip to main content

zwave_sim/
node.rs

1//! Simulated end nodes: their command classes, their side of S0 and S2,
2//! sleeping and SmartStart.
3
4use std::collections::BTreeMap;
5use zwave_cc::{
6    association, basic, battery, binary_switch, configuration, firmware_update_md,
7    manufacturer_specific, meter, multilevel_sensor, notification, security, security_2,
8    supervision, version, wake_up, zwave_plus_info, Command, Value,
9};
10use zwave_security::dsk::Dsk;
11use zwave_security::kex::{bootstrap_keys, KeyPair, ECDH_CURVE25519, KEX_SCHEME_1};
12use zwave_security::s0::{S0Manager, S0Payload, TEMP_KEY};
13use zwave_security::s2::{EncryptOptions, KeyId, S2Manager};
14use zwave_security::SecurityClass;
15use zwave_serial::message::{NodeInfo, NodeProtocolInfo};
16
17/// How a simulated node is secured.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Security {
20    /// No security.
21    None,
22    /// Security 0.
23    S0,
24    /// Security 2, requesting these classes.
25    S2(Vec<SecurityClass>),
26}
27
28/// What a simulated node is.
29#[derive(Debug, Clone)]
30pub struct NodeSpec {
31    /// A name to address it by.
32    pub name: String,
33    /// Always listening, or sleeping.
34    pub listening: bool,
35    /// Security.
36    pub security: Security,
37    /// Joins by SmartStart instead of a button press.
38    pub smartstart: bool,
39    /// A Z-Wave Long Range node (SmartStart only, 16-bit node id).
40    pub long_range: bool,
41    /// Generic device class.
42    pub generic: u8,
43    /// Specific device class.
44    pub specific: u8,
45    /// Command classes and their versions.
46    pub ccs: Vec<(u16, u8)>,
47    /// Command classes only available with security (subset of `ccs`).
48    pub secure_only: Vec<u16>,
49    /// Product id reported by Manufacturer Specific.
50    pub product_id: u16,
51    /// The node's private key (S2), fixed so tests can derive its DSK.
52    pub private_key: [u8; 32],
53}
54
55impl NodeSpec {
56    /// A mains-powered switch with an energy meter, no security.
57    pub fn switch(name: &str) -> Self {
58        NodeSpec {
59            name: name.into(),
60            listening: true,
61            security: Security::None,
62            smartstart: false,
63            long_range: false,
64            generic: 0x10,
65            specific: 0x01,
66            ccs: vec![
67                (0x5e, 2),
68                (0x25, 2),
69                (0x32, 3),
70                (0x72, 2),
71                (0x86, 3),
72                (0x85, 2),
73                (0x6c, 1),
74                (0x20, 2),
75                (0x70, 4),
76                (0x7a, 5),
77            ],
78            secure_only: vec![],
79            product_id: 1,
80            private_key: [0x11; 32],
81        }
82    }
83
84    /// A battery multisensor that sleeps between wake-ups, with S0.
85    pub fn sleeping_sensor(name: &str) -> Self {
86        NodeSpec {
87            name: name.into(),
88            listening: false,
89            security: Security::S0,
90            smartstart: false,
91            long_range: false,
92            generic: 0x21,
93            specific: 0x01,
94            ccs: vec![
95                (0x5e, 2),
96                (0x98, 1),
97                (0x31, 11),
98                (0x80, 1),
99                (0x84, 2),
100                (0x72, 2),
101                (0x86, 3),
102                (0x85, 2),
103            ],
104            secure_only: vec![0x31, 0x80, 0x84, 0x72, 0x86, 0x85],
105            product_id: 2,
106            private_key: [0x22; 32],
107        }
108    }
109
110    /// A mains-powered multisensor (temperature, humidity, motion) with S2.
111    pub fn s2_sensor(name: &str, requested: Vec<SecurityClass>) -> Self {
112        NodeSpec {
113            name: name.into(),
114            listening: true,
115            security: Security::S2(requested),
116            smartstart: false,
117            long_range: false,
118            generic: 0x21,
119            specific: 0x01,
120            ccs: vec![
121                (0x5e, 2),
122                (0x9f, 1),
123                (0x6c, 2),
124                (0x55, 2),
125                (0x31, 11),
126                (0x71, 8),
127                (0x72, 2),
128                (0x86, 3),
129                (0x85, 2),
130                (0x7a, 5),
131            ],
132            secure_only: vec![0x31, 0x71, 0x72, 0x86, 0x85, 0x7a],
133            product_id: 3,
134            private_key: [0x33; 32],
135        }
136    }
137
138    /// An S2 node that joins by SmartStart.
139    pub fn smartstart_sensor(name: &str) -> Self {
140        let mut s = Self::s2_sensor(name, vec![SecurityClass::S2Authenticated]);
141        s.smartstart = true;
142        s.product_id = 4;
143        s.private_key = [0x44; 32];
144        s
145    }
146
147    /// A Long Range sensor that joins by SmartStart with S2 Authenticated.
148    pub fn long_range_sensor(name: &str) -> Self {
149        let mut s = Self::s2_sensor(name, vec![SecurityClass::S2Authenticated]);
150        s.smartstart = true;
151        s.long_range = true;
152        s.product_id = 5;
153        s.private_key = [0x55; 32];
154        s
155    }
156
157    /// The node's DSK.
158    pub fn dsk(&self) -> Dsk {
159        Dsk::from_public_key(KeyPair::from_private(self.private_key).public())
160    }
161
162    fn version_of(&self, cc: u16) -> u8 {
163        self.ccs
164            .iter()
165            .find(|(c, _)| *c == cc)
166            .map(|(_, v)| *v)
167            .unwrap_or(0)
168    }
169
170    /// The node information frame: insecure command classes only, as nodes send it.
171    pub fn nif(&self) -> NodeInfo {
172        NodeInfo {
173            basic: 0x04,
174            generic: self.generic,
175            specific: self.specific,
176            supported: self
177                .ccs
178                .iter()
179                .map(|(c, _)| *c)
180                .filter(|c| !self.secure_only.contains(c))
181                .collect(),
182            controlled: vec![],
183        }
184    }
185
186    /// Protocol information as the controller reports it.
187    pub fn protocol_info(&self) -> NodeProtocolInfo {
188        NodeProtocolInfo {
189            listening: self.listening,
190            routing: self.listening,
191            flirs_1000: false,
192            flirs_250: false,
193            beaming: true,
194            controller: false,
195            security: !matches!(self.security, Security::None),
196            protocol_version: 3,
197            speeds: 0b111,
198            basic: 0x04,
199            generic: self.generic,
200            specific: self.specific,
201        }
202    }
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206enum Sec {
207    Plain,
208    S2(KeyId),
209    S0,
210}
211
212struct Kex {
213    granted: Vec<SecurityClass>,
214    controller_pub: Option<[u8; 32]>,
215    requested_report: security_2::KexReport,
216    pending: Vec<SecurityClass>,
217    current: Option<SecurityClass>,
218}
219
220/// A simulated node's state.
221pub struct SimNode {
222    /// What it is.
223    pub spec: NodeSpec,
224    /// Its node id once included.
225    pub id: Option<u16>,
226    /// Awake (sleeping nodes).
227    pub awake: bool,
228    /// Powered; a node without power answers nothing.
229    pub powered: bool,
230    /// Classes it holds keys for after inclusion.
231    pub granted: Vec<SecurityClass>,
232    /// Sensor readings by type.
233    pub sensors: BTreeMap<u8, f64>,
234    /// Switch state.
235    pub switch_on: bool,
236    /// Lifeline (association group 1).
237    pub lifeline: Vec<u8>,
238    /// Configured wake-up interval.
239    pub wake_interval: u32,
240    /// The installed firmware image.
241    pub firmware: Vec<u8>,
242    fw_rx: Option<(u16, u16, Vec<u8>, u16)>,
243    /// Configuration parameters: size and value.
244    pub params: BTreeMap<u8, (u8, i32)>,
245    /// Every command received, decrypted, for tests to inspect.
246    pub received: Vec<Vec<u8>>,
247    keypair: KeyPair,
248    s2: S2Manager,
249    s0: S0Manager,
250    s0_keyed: bool,
251    kex: Option<Kex>,
252    pending_s2: Vec<(Vec<u8>, KeyId)>,
253    pending_s0: Vec<Vec<u8>>,
254    last_s2: Option<(Vec<u8>, KeyId)>,
255}
256
257const CTRL: u16 = 1;
258
259impl SimNode {
260    /// A node out of any network.
261    pub fn new(spec: NodeSpec) -> Self {
262        let keypair = KeyPair::from_private(spec.private_key);
263        let mut sensors = BTreeMap::new();
264        if spec.version_of(0x31) > 0 {
265            sensors.insert(1, 22.5);
266            sensors.insert(5, 41.0);
267        }
268        SimNode {
269            spec,
270            id: None,
271            awake: true,
272            powered: true,
273            granted: vec![],
274            sensors,
275            switch_on: false,
276            lifeline: vec![],
277            wake_interval: 3600,
278            firmware: b"simulated firmware 1.2".to_vec(),
279            fw_rx: None,
280            params: BTreeMap::new(),
281            received: vec![],
282            keypair,
283            s2: S2Manager::new(0, 0),
284            s0: S0Manager::new(0, &TEMP_KEY),
285            s0_keyed: false,
286            kex: None,
287            pending_s2: vec![],
288            pending_s0: vec![],
289            last_s2: None,
290        }
291    }
292
293    /// Joins a network as `id`.
294    pub fn join(&mut self, id: u16, home_id: u32) {
295        self.id = Some(id);
296        self.s2 = S2Manager::new(id, home_id);
297        self.s0 = S0Manager::new(id, &TEMP_KEY);
298        self.s0_keyed = false;
299        self.granted.clear();
300        self.lifeline.clear();
301        self.awake = true;
302    }
303
304    /// Leaves the network (excluded or reset).
305    pub fn leave(&mut self) {
306        self.id = None;
307        self.granted.clear();
308        self.kex = None;
309    }
310
311    /// Whether frames reach it now.
312    pub fn reachable(&self) -> bool {
313        self.powered && self.id.is_some() && (self.spec.listening || self.awake)
314    }
315
316    fn highest(&self) -> Sec {
317        if let Some(c) = self.granted.iter().copied().filter(|c| c.is_s2()).max() {
318            Sec::S2(KeyId::Class(c))
319        } else if self.granted.contains(&SecurityClass::S0Legacy) {
320            Sec::S0
321        } else {
322            Sec::Plain
323        }
324    }
325
326    fn send(&mut self, plaintext: Vec<u8>, sec: Sec) -> Vec<Vec<u8>> {
327        match sec {
328            Sec::Plain => vec![plaintext],
329            Sec::S2(key) => match self.s2.encrypt(
330                CTRL,
331                &plaintext,
332                &EncryptOptions {
333                    key: Some(key),
334                    ..Default::default()
335                },
336            ) {
337                Ok(f) => {
338                    self.last_s2 = Some((plaintext, key));
339                    vec![f]
340                }
341                Err(_) => {
342                    self.pending_s2.push((plaintext, key));
343                    vec![self.s2.nonce_get(CTRL).expect("rng")]
344                }
345            },
346            Sec::S0 => {
347                self.pending_s0.push(plaintext);
348                if self.pending_s0.len() == 1 {
349                    vec![S0Manager::nonce_get()]
350                } else {
351                    vec![]
352                }
353            }
354        }
355    }
356
357    /// Something the node sends on its own (a report to its lifeline).
358    pub fn unsolicited(&mut self, cmd: Command) -> Vec<Vec<u8>> {
359        if self.id.is_none() {
360            return vec![];
361        }
362        let sec = self.highest();
363        self.send(cmd.encode(), sec)
364    }
365
366    /// A Wake Up Notification.
367    pub fn wake(&mut self) -> Vec<Vec<u8>> {
368        self.awake = true;
369        self.unsolicited(wake_up::Notification {}.into())
370    }
371
372    /// Handles a frame from the controller; returns frames to send back.
373    pub fn receive(&mut self, frame: &[u8]) -> Vec<Vec<u8>> {
374        match (frame.first(), frame.get(1)) {
375            (Some(0x9f), Some(0x01)) => vec![self.s2.nonce_report(CTRL, false).expect("rng")],
376            (Some(0x9f), Some(0x02)) => {
377                if self.s2.handle_nonce_report(CTRL, frame).is_err() {
378                    return vec![];
379                }
380                let mut pending = std::mem::take(&mut self.pending_s2);
381                if pending.is_empty() {
382                    // Our last frame did not decrypt: send it again on the new SPAN.
383                    pending.extend(self.last_s2.take());
384                }
385                let mut out = vec![];
386                for (p, key) in pending {
387                    match self.s2.encrypt(
388                        CTRL,
389                        &p,
390                        &EncryptOptions {
391                            key: Some(key),
392                            ..Default::default()
393                        },
394                    ) {
395                        Ok(f) => out.push(f),
396                        Err(_) => self.pending_s2.push((p, key)),
397                    }
398                }
399                out
400            }
401            (Some(0x9f), Some(0x03)) => match self.s2.decrypt(CTRL, frame) {
402                Ok(d) => self.application(&d.command, Sec::S2(d.key)),
403                Err(zwave_security::Error::Duplicate) => vec![],
404                Err(_) => vec![self.s2.nonce_report(CTRL, false).expect("rng")],
405            },
406            (Some(0x98), Some(0x40)) => vec![self.s0.nonce_report(CTRL).expect("rng")],
407            (Some(0x98), Some(0x80)) => {
408                if self.s0.handle_nonce_report(CTRL, frame).is_err() || self.pending_s0.is_empty() {
409                    return vec![];
410                }
411                let p = self.pending_s0.remove(0);
412                let temp = !self.s0_keyed;
413                let mut out = vec![self.s0.encapsulate(CTRL, &p, temp).expect("fits")];
414                if !self.pending_s0.is_empty() {
415                    out.push(S0Manager::nonce_get());
416                }
417                out
418            }
419            (Some(0x98), Some(0x81 | 0xc1)) => {
420                let temp = !self.s0_keyed;
421                match self.s0.decapsulate(CTRL, frame, temp) {
422                    Ok(S0Payload::Complete(cmd)) => self.application(&cmd, Sec::S0),
423                    _ => vec![],
424                }
425            }
426            _ => self.application(frame, Sec::Plain),
427        }
428    }
429
430    fn supports(&self, cc: u16, sec: Sec) -> bool {
431        self.spec.version_of(cc) > 0
432            && (sec != Sec::Plain
433                || !self.spec.secure_only.contains(&cc)
434                || self.granted.is_empty())
435    }
436
437    fn application(&mut self, frame: &[u8], sec: Sec) -> Vec<Vec<u8>> {
438        self.received.push(frame.to_vec());
439        if frame.starts_with(&[0x7a, 0x06]) && self.supports(0x7a, sec) {
440            return self.firmware_fragment(frame, sec);
441        }
442        if frame.starts_with(&[0x7a, 0x03]) && self.supports(0x7a, sec) {
443            if let Ok(Command::FirmwareUpdateMd(firmware_update_md::Command::RequestGet(r))) =
444                Command::parse(frame)
445            {
446                let size = r.fragment_size.unwrap_or(32);
447                self.fw_rx = Some((r.checksum, size, Vec::new(), 1));
448                let mut out = self.send(
449                    Command::from(firmware_update_md::RequestReport {
450                        status: 0xff,
451                        resume: Some(false),
452                        non_secure: Some(false),
453                    })
454                    .encode(),
455                    sec,
456                );
457                out.extend(
458                    self.send(
459                        Command::from(firmware_update_md::Get {
460                            count: 2,
461                            report: 1,
462                        })
463                        .encode(),
464                        sec,
465                    ),
466                );
467                return out;
468            }
469        }
470        let Ok(cmd) = Command::parse(frame) else {
471            return vec![];
472        };
473        if let Command::Supervision(supervision::Command::Get(g)) = &cmd {
474            let mut out = self.application(&g.command, sec);
475            let rep: Command = supervision::Report {
476                more_status_updates: false,
477                wake_up_request: false,
478                session_id: g.session_id,
479                status: 0xff,
480                duration: Some(0),
481            }
482            .into();
483            out.extend(self.send(rep.encode(), sec));
484            return out;
485        }
486        let reply: Option<Command> = match cmd {
487            Command::Security2(c) => return self.kex(c, sec),
488            Command::Security(c) => return self.s0_kex(c, sec),
489            _ if !self.supports(cmd.cc(), sec) => None,
490            Command::Version(version::Command::Get(_)) => Some(
491                version::Report {
492                    library_type: 3,
493                    protocol_version: 7,
494                    protocol_sub_version: 18,
495                    firmware_version: 1,
496                    firmware_sub_version: 2,
497                    hardware_version: Some(1),
498                    firmware_targets: Some(0),
499                    target_versions: vec![],
500                }
501                .into(),
502            ),
503            Command::Version(version::Command::CommandClassGet(g)) => Some(
504                version::CommandClassReport {
505                    requested_cc: g.requested_cc,
506                    version: self.spec.version_of(u16::from(g.requested_cc)),
507                }
508                .into(),
509            ),
510            Command::ManufacturerSpecific(manufacturer_specific::Command::Get(_)) => Some(
511                manufacturer_specific::Report {
512                    manufacturer_id: 0xfffe,
513                    product_type: 0x5349,
514                    product_id: self.spec.product_id,
515                }
516                .into(),
517            ),
518            Command::ZwavePlusInfo(zwave_plus_info::Command::Get(_)) => Some(
519                zwave_plus_info::Report {
520                    zwave_plus_version: 2,
521                    role_type: if self.spec.listening { 5 } else { 6 },
522                    node_type: 0,
523                    installer_icon: 0x0c07,
524                    user_icon: 0x0c07,
525                }
526                .into(),
527            ),
528            Command::MultilevelSensor(multilevel_sensor::Command::SupportedSensorGet(_)) => Some(
529                multilevel_sensor::SupportedSensorReport {
530                    sensor_types: self.sensors.keys().map(|&k| u16::from(k)).collect(),
531                }
532                .into(),
533            ),
534            Command::MultilevelSensor(multilevel_sensor::Command::SupportedScaleGet(g)) => Some(
535                multilevel_sensor::SupportedScaleReport {
536                    sensor_type: g.sensor_type,
537                    scales: 0b01,
538                }
539                .into(),
540            ),
541            Command::MultilevelSensor(multilevel_sensor::Command::Get(g)) => {
542                let t = g.sensor_type.unwrap_or(1);
543                self.sensors.get(&t).map(|v| {
544                    multilevel_sensor::Report {
545                        sensor_type: t,
546                        value: Value::from_f64(*v, 1, 0),
547                    }
548                    .into()
549                })
550            }
551            Command::Notification(notification::Command::SupportedGet(_)) => Some(
552                notification::SupportedReport {
553                    v1_alarm: false,
554                    types: vec![7],
555                }
556                .into(),
557            ),
558            Command::Notification(notification::Command::EventSupportedGet(g)) => Some(
559                notification::EventSupportedReport {
560                    notification_type: g.notification_type,
561                    events: vec![8],
562                }
563                .into(),
564            ),
565            Command::Battery(battery::Command::Get(_)) => Some(
566                battery::Report {
567                    level: 87,
568                    ..Default::default()
569                }
570                .into(),
571            ),
572            Command::WakeUp(wake_up::Command::IntervalCapabilitiesGet(_)) => Some(
573                wake_up::IntervalCapabilitiesReport {
574                    minimum: 300,
575                    maximum: 86_400,
576                    default: 3600,
577                    step: 60,
578                    on_demand: Some(false),
579                }
580                .into(),
581            ),
582            Command::WakeUp(wake_up::Command::IntervalSet(s)) => {
583                self.wake_interval = s.seconds;
584                None
585            }
586            Command::WakeUp(wake_up::Command::IntervalGet(_)) => Some(
587                wake_up::IntervalReport {
588                    seconds: self.wake_interval,
589                    node_id: CTRL as u8,
590                }
591                .into(),
592            ),
593            Command::WakeUp(wake_up::Command::NoMoreInformation(_)) => {
594                self.awake = false;
595                None
596            }
597            Command::Association(association::Command::GroupingsGet(_)) => {
598                Some(association::GroupingsReport { groups: 1 }.into())
599            }
600            Command::Association(association::Command::Set(s)) => {
601                if s.group == 1 {
602                    self.lifeline = s.nodes;
603                }
604                None
605            }
606            Command::Association(association::Command::Get(g)) => Some(
607                association::Report {
608                    group: g.group,
609                    max_nodes: 5,
610                    reports_to_follow: 0,
611                    nodes: self.lifeline.clone(),
612                }
613                .into(),
614            ),
615            Command::BinarySwitch(binary_switch::Command::Get(_)) => Some(self.switch_report()),
616            Command::BinarySwitch(binary_switch::Command::Set(s)) => {
617                self.switch_on = s.target != 0;
618                None
619            }
620            Command::Basic(basic::Command::Set(s)) => {
621                self.switch_on = s.value != 0;
622                None
623            }
624            Command::FirmwareUpdateMd(firmware_update_md::Command::MetaDataGet(_)) => Some(
625                firmware_update_md::MetaDataReport {
626                    manufacturer_id: 0xfffe,
627                    firmware_id: 0x0001,
628                    checksum: zwave_cc::crc16::checksum(&self.firmware),
629                    upgradable: Some(0xff),
630                    additional_targets: Some(0),
631                    max_fragment_size: Some(36),
632                    rest: vec![],
633                }
634                .into(),
635            ),
636            Command::Configuration(configuration::Command::Set(s)) => {
637                self.params.insert(s.parameter, (s.size, s.value));
638                None
639            }
640            Command::Configuration(configuration::Command::Get(g)) => {
641                let (size, value) = self.params.get(&g.parameter).copied().unwrap_or((1, 0));
642                Some(
643                    configuration::Report {
644                        parameter: g.parameter,
645                        size,
646                        value,
647                    }
648                    .into(),
649                )
650            }
651            Command::Basic(basic::Command::Get(_)) => Some(
652                basic::Report {
653                    current: if self.switch_on { 0xff } else { 0 },
654                    target: None,
655                    duration: None,
656                }
657                .into(),
658            ),
659            Command::Meter(meter::Command::SupportedGet(_)) => Some(
660                meter::SupportedReport {
661                    meter_reset: true,
662                    rate_type: 1,
663                    meter_type: 1,
664                    more_scale_types: false,
665                    scales: 0b101,
666                    extra_scales: vec![],
667                }
668                .into(),
669            ),
670            Command::Meter(meter::Command::Get(g)) => {
671                let scale = g.scale.unwrap_or(0);
672                let v = if scale == 2 { 12.5 } else { 1.234 };
673                Some(
674                    meter::Report {
675                        scale_bit2: scale & 4 != 0,
676                        rate_type: 1,
677                        meter_type: 1,
678                        value: Value {
679                            scale: scale & 3,
680                            ..Value::from_f64(v, 3, 0)
681                        },
682                        delta_time: Some(0),
683                        previous_value: None,
684                        scale2: None,
685                    }
686                    .into(),
687                )
688            }
689            _ => None,
690        };
691        match reply {
692            Some(r) => self.send(r.encode(), sec),
693            None => vec![],
694        }
695    }
696
697    fn firmware_fragment(&mut self, frame: &[u8], sec: Sec) -> Vec<Vec<u8>> {
698        let Some((checksum, _size, data, next)) = self.fw_rx.as_mut() else {
699            return vec![];
700        };
701        if frame.len() < 6 {
702            return vec![];
703        }
704        let (body, crc) = frame.split_at(frame.len() - 2);
705        if zwave_cc::crc16::checksum(body) != u16::from_be_bytes([crc[0], crc[1]]) {
706            // A corrupt fragment: ask for it again.
707            let again = *next;
708            return self.send(
709                Command::from(firmware_update_md::Get {
710                    count: 1,
711                    report: again,
712                })
713                .encode(),
714                sec,
715            );
716        }
717        let header = u16::from_be_bytes([body[2], body[3]]);
718        let (number, last) = (header & 0x7fff, header & 0x8000 != 0);
719        if number != *next {
720            return vec![];
721        }
722        data.extend_from_slice(&body[4..]);
723        *next += 1;
724        if last {
725            let ok = zwave_cc::crc16::checksum(data) == *checksum;
726            let image = std::mem::take(data);
727            self.fw_rx = None;
728            if ok {
729                self.firmware = image;
730            }
731            let status = if ok { 0xff } else { 0x00 };
732            return self.send(
733                Command::from(firmware_update_md::StatusReport {
734                    status,
735                    wait_time: Some(5),
736                })
737                .encode(),
738                sec,
739            );
740        }
741        if (*next - 1) % 2 == 0 {
742            let n = *next;
743            return self.send(
744                Command::from(firmware_update_md::Get {
745                    count: 2,
746                    report: n,
747                })
748                .encode(),
749                sec,
750            );
751        }
752        vec![]
753    }
754
755    fn switch_report(&self) -> Command {
756        let v = if self.switch_on { 0xff } else { 0 };
757        binary_switch::Report {
758            current: v,
759            target: Some(v),
760            duration: Some(0),
761        }
762        .into()
763    }
764
765    /// A multilevel sensor report for `sensor_type`, as the node would send it.
766    pub fn sensor_report(&self, sensor_type: u8) -> Option<Command> {
767        self.sensors.get(&sensor_type).map(|v| {
768            multilevel_sensor::Report {
769                sensor_type,
770                value: Value::from_f64(*v, 1, 0),
771            }
772            .into()
773        })
774    }
775
776    fn kex(&mut self, c: security_2::Command, sec: Sec) -> Vec<Vec<u8>> {
777        let Security::S2(requested) = self.spec.security.clone() else {
778            return vec![];
779        };
780        match c {
781            security_2::Command::KexGet(_) if sec == Sec::Plain => {
782                let report = security_2::KexReport {
783                    request_csa: false,
784                    echo: false,
785                    schemes: KEX_SCHEME_1,
786                    curves: ECDH_CURVE25519,
787                    keys: SecurityClass::to_key_bits(&requested),
788                };
789                self.kex = Some(Kex {
790                    granted: vec![],
791                    controller_pub: None,
792                    requested_report: report.clone(),
793                    pending: vec![],
794                    current: None,
795                });
796                self.send(Command::from(report).encode(), Sec::Plain)
797            }
798            security_2::Command::KexSet(s) if !s.echo && sec == Sec::Plain => {
799                let Some(k) = self.kex.as_mut() else {
800                    return vec![];
801                };
802                k.granted = SecurityClass::from_key_bits(s.keys);
803                // Lowest first, as nodes ask for them.
804                let mut pending = k.granted.clone();
805                pending.reverse();
806                k.pending = pending;
807                let mut key = self.keypair.public().to_vec();
808                if k.granted.iter().any(|c| c.needs_pin()) {
809                    key[0] = 0;
810                    key[1] = 0;
811                }
812                self.send(
813                    Command::from(security_2::PublicKeyReport {
814                        including_node: false,
815                        public_key: key,
816                    })
817                    .encode(),
818                    Sec::Plain,
819                )
820            }
821            security_2::Command::PublicKeyReport(p) if p.including_node && sec == Sec::Plain => {
822                let Some(k) = self.kex.as_mut() else {
823                    return vec![];
824                };
825                let Ok(cpub) = <[u8; 32]>::try_from(p.public_key.as_slice()) else {
826                    return vec![];
827                };
828                k.controller_pub = Some(cpub);
829                let granted = SecurityClass::to_key_bits(&k.granted);
830                let Ok(shared) = self.keypair.shared_secret(&cpub) else {
831                    return vec![];
832                };
833                let tk = bootstrap_keys(&shared, &cpub, self.keypair.public());
834                self.s2.begin_bootstrap(CTRL, tk);
835                let echo = security_2::KexSet {
836                    request_csa: false,
837                    echo: true,
838                    scheme: KEX_SCHEME_1,
839                    curve: ECDH_CURVE25519,
840                    keys: granted,
841                };
842                self.send(Command::from(echo).encode(), Sec::S2(KeyId::Temporary))
843            }
844            security_2::Command::KexReport(r) if r.echo && sec == Sec::S2(KeyId::Temporary) => {
845                let Some(k) = self.kex.as_mut() else {
846                    return vec![];
847                };
848                if r.keys != k.requested_report.keys {
849                    return vec![];
850                }
851                self.next_key_get()
852            }
853            security_2::Command::NetworkKeyReport(r) if sec == Sec::S2(KeyId::Temporary) => {
854                let Some(k) = self.kex.as_mut() else {
855                    return vec![];
856                };
857                let Some(class) = SecurityClass::from_key_bit(r.granted_key) else {
858                    return vec![];
859                };
860                let Ok(key) = <[u8; 16]>::try_from(r.network_key.as_slice()) else {
861                    return vec![];
862                };
863                k.current = Some(class);
864                self.s2.set_network_key(class, &key);
865                if class == SecurityClass::S0Legacy {
866                    self.s0.set_network_key(&key);
867                    self.s0_keyed = true;
868                }
869                self.s2.set_peer_classes(CTRL, &[class]);
870                self.send(
871                    Command::from(security_2::NetworkKeyVerify {}).encode(),
872                    Sec::S2(KeyId::Class(class)),
873                )
874            }
875            security_2::Command::TransferEnd(t)
876                if t.key_verified && sec == Sec::S2(KeyId::Temporary) =>
877            {
878                let Some(k) = self.kex.as_mut() else {
879                    return vec![];
880                };
881                if let Some(c) = k.current.take() {
882                    self.granted.push(c);
883                }
884                if k.pending.is_empty() {
885                    let out = self.send(
886                        Command::from(security_2::TransferEnd {
887                            key_verified: false,
888                            key_request_complete: true,
889                        })
890                        .encode(),
891                        Sec::S2(KeyId::Temporary),
892                    );
893                    self.s2.end_bootstrap(CTRL);
894                    self.s2.set_peer_classes(CTRL, &self.granted.clone());
895                    self.kex = None;
896                    out
897                } else {
898                    self.next_key_get()
899                }
900            }
901            security_2::Command::KexFail(_) => {
902                self.kex = None;
903                self.s2.end_bootstrap(CTRL);
904                vec![]
905            }
906            security_2::Command::CommandsSupportedGet(_)
907                if matches!(sec, Sec::S2(KeyId::Class(_))) =>
908            {
909                let list = self.spec.secure_only.clone();
910                self.send(
911                    Command::from(security_2::CommandsSupportedReport {
912                        command_classes: list,
913                    })
914                    .encode(),
915                    sec,
916                )
917            }
918            _ => vec![],
919        }
920    }
921
922    fn next_key_get(&mut self) -> Vec<Vec<u8>> {
923        let Some(k) = self.kex.as_mut() else {
924            return vec![];
925        };
926        let Some(class) = k.pending.first().copied() else {
927            return vec![];
928        };
929        k.pending.remove(0);
930        self.send(
931            Command::from(security_2::NetworkKeyGet {
932                requested_key: class.key_bit(),
933            })
934            .encode(),
935            Sec::S2(KeyId::Temporary),
936        )
937    }
938
939    fn s0_kex(&mut self, c: security::Command, sec: Sec) -> Vec<Vec<u8>> {
940        match c {
941            security::Command::SchemeGet(_)
942                if sec == Sec::Plain && self.spec.security == Security::S0 =>
943            {
944                self.send(
945                    Command::from(security::SchemeReport { schemes: 0 }).encode(),
946                    Sec::Plain,
947                )
948            }
949            security::Command::NetworkKeySet(s) if sec == Sec::S0 && !self.s0_keyed => {
950                let Ok(key) = <[u8; 16]>::try_from(s.network_key.as_slice()) else {
951                    return vec![];
952                };
953                self.s0.set_network_key(&key);
954                self.s0_keyed = true;
955                self.granted = vec![SecurityClass::S0Legacy];
956                self.send(
957                    Command::from(security::NetworkKeyVerify {}).encode(),
958                    Sec::S0,
959                )
960            }
961            security::Command::CommandsSupportedGet(_) if sec == Sec::S0 => {
962                let list = self.spec.secure_only.clone();
963                self.send(
964                    Command::from(security::CommandsSupportedReport {
965                        reports_to_follow: 0,
966                        command_classes: list,
967                    })
968                    .encode(),
969                    Sec::S0,
970                )
971            }
972            _ => vec![],
973        }
974    }
975}