Skip to main content

zwave_host/
node.rs

1//! What the host knows about each node. Persisted in the [`store`](crate::store).
2
3use crate::NodeId;
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6use zwave_security::SecurityClass;
7
8/// Interview progress, persisted so an interrupted interview resumes.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
10#[serde(rename_all = "snake_case")]
11pub enum InterviewStage {
12    /// Nothing known yet.
13    #[default]
14    New,
15    /// Protocol information (listening, routing, device class) known.
16    ProtocolInfo,
17    /// The node information frame (command classes) known.
18    NodeInfo,
19    /// The secure command classes known.
20    Security,
21    /// Manufacturer, product and Z-Wave Plus info known.
22    Identity,
23    /// Command class versions known.
24    Versions,
25    /// Endpoints known.
26    Endpoints,
27    /// Each command class's capabilities known and the node configured.
28    CommandClasses,
29    /// Done.
30    Complete,
31}
32
33/// Runtime status (not persisted).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
35#[serde(rename_all = "snake_case")]
36pub enum NodeStatus {
37    /// Not heard from yet.
38    #[default]
39    Unknown,
40    /// Listening and answering.
41    Alive,
42    /// A sleeping node that is awake now.
43    Awake,
44    /// A sleeping node that is asleep.
45    Asleep,
46    /// Listening but not answering.
47    Dead,
48}
49
50/// Protocol information from the controller.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
52pub struct ProtocolInfo {
53    /// Always listening.
54    pub listening: bool,
55    /// Frequently listening (FLiRS), reachable with a beam.
56    pub flirs: bool,
57    /// A routing node (can repeat).
58    pub routing: bool,
59    /// The node is a controller.
60    pub controller: bool,
61    /// Basic device class.
62    pub basic: u8,
63    /// Generic device class.
64    pub generic: u8,
65    /// Specific device class.
66    pub specific: u8,
67}
68
69impl ProtocolInfo {
70    /// A node that sleeps and is reachable only when it wakes up.
71    pub fn sleeping(&self) -> bool {
72        !self.listening && !self.flirs
73    }
74}
75
76/// One command class on an endpoint.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
78pub struct CcSupport {
79    /// The version the node implements (0 until known).
80    pub version: u8,
81    /// Supported only with security.
82    pub secure: bool,
83}
84
85/// What each command class on an endpoint reported in the interview.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
87pub struct Capabilities {
88    /// Multilevel sensor types and their scales.
89    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
90    pub sensors: BTreeMap<u8, Vec<u8>>,
91    /// Meter type and scales.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub meter: Option<(u8, Vec<u8>)>,
94    /// Notification types and their events.
95    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
96    pub notifications: BTreeMap<u8, Vec<u8>>,
97    /// Binary sensor types.
98    #[serde(default, skip_serializing_if = "Vec::is_empty")]
99    pub binary_sensors: Vec<u8>,
100    /// Multilevel switch primary type.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub switch_type: Option<u8>,
103}
104
105/// An endpoint: the root device (0) or a Multi Channel endpoint.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
107pub struct Endpoint {
108    /// Generic device class (endpoints only).
109    #[serde(default)]
110    pub generic: u8,
111    /// Specific device class (endpoints only).
112    #[serde(default)]
113    pub specific: u8,
114    /// Supported command classes.
115    #[serde(default)]
116    pub ccs: BTreeMap<u16, CcSupport>,
117    /// Capabilities found in the interview.
118    #[serde(default)]
119    pub caps: Capabilities,
120}
121
122impl Endpoint {
123    /// Whether the endpoint supports a command class.
124    pub fn supports(&self, cc: u16) -> bool {
125        self.ccs.contains_key(&cc)
126    }
127
128    /// The version of a command class (1 if supported but unknown, 0 if unsupported).
129    pub fn version(&self, cc: u16) -> u8 {
130        self.ccs.get(&cc).map(|c| c.version.max(1)).unwrap_or(0)
131    }
132}
133
134/// Manufacturer identity.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
136pub struct Manufacturer {
137    /// Manufacturer id.
138    pub manufacturer_id: u16,
139    /// Product type.
140    pub product_type: u16,
141    /// Product id.
142    pub product_id: u16,
143}
144
145/// Everything the host stores about a node.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
147pub struct NodeRecord {
148    /// Node id.
149    pub id: NodeId,
150    /// Protocol information.
151    #[serde(default)]
152    pub protocol: ProtocolInfo,
153    /// Interview progress.
154    #[serde(default)]
155    pub stage: InterviewStage,
156    /// Granted security classes, highest first (empty: insecure).
157    #[serde(default)]
158    pub security: Vec<SecurityClass>,
159    /// Whether the secure command class list is known.
160    #[serde(default)]
161    pub secure_ccs_known: bool,
162    /// Manufacturer identity.
163    #[serde(default)]
164    pub manufacturer: Option<Manufacturer>,
165    /// Firmware version (`major.minor`).
166    #[serde(default)]
167    pub firmware: Option<String>,
168    /// Z-Wave Plus role and node type, and the icons.
169    #[serde(default)]
170    pub zwave_plus: Option<(u8, u8, u16, u16)>,
171    /// Endpoints, `0` being the root device.
172    #[serde(default)]
173    pub endpoints: BTreeMap<u8, Endpoint>,
174    /// Wake-up interval configured, seconds.
175    #[serde(default)]
176    pub wake_up_interval: Option<u32>,
177    /// Neighbors from the controller's routing table.
178    #[serde(default)]
179    pub neighbors: Vec<NodeId>,
180    /// A name given by people.
181    #[serde(default)]
182    pub name: Option<String>,
183    /// A location given by people.
184    #[serde(default)]
185    pub location: Option<String>,
186    /// The DSK the node was included with (S2).
187    #[serde(default)]
188    pub dsk: Option<String>,
189}
190
191impl NodeRecord {
192    /// A record for a new node.
193    pub fn new(id: NodeId) -> Self {
194        let mut r = NodeRecord {
195            id,
196            ..Default::default()
197        };
198        r.endpoints.insert(0, Endpoint::default());
199        r
200    }
201
202    /// The root endpoint.
203    pub fn root(&self) -> &Endpoint {
204        static EMPTY: std::sync::OnceLock<Endpoint> = std::sync::OnceLock::new();
205        self.endpoints
206            .get(&0)
207            .unwrap_or_else(|| EMPTY.get_or_init(Endpoint::default))
208    }
209
210    /// The root endpoint, mutable.
211    pub fn root_mut(&mut self) -> &mut Endpoint {
212        self.endpoints.entry(0).or_default()
213    }
214
215    /// The highest granted S2 class.
216    pub fn highest_s2(&self) -> Option<SecurityClass> {
217        self.security.iter().copied().filter(|c| c.is_s2()).max()
218    }
219
220    /// Whether the node was included with S0 only.
221    pub fn s0_only(&self) -> bool {
222        self.highest_s2().is_none() && self.security.contains(&SecurityClass::S0Legacy)
223    }
224
225    /// Whether a command class must be sent with security to this endpoint.
226    pub fn needs_security(&self, endpoint: u8, cc: u16) -> bool {
227        if self.security.is_empty() {
228            return false;
229        }
230        // The security classes' own commands go plain or are handled by the stack.
231        if matches!(cc, 0x98 | 0x9f) {
232            return false;
233        }
234        match self.endpoints.get(&endpoint).and_then(|e| e.ccs.get(&cc)) {
235            Some(s) => s.secure || !self.secure_ccs_known,
236            // Unknown to us: secure until the secure list says otherwise.
237            None => !self.secure_ccs_known || endpoint != 0,
238        }
239    }
240}