1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5mod controller;
6pub mod device_config;
7pub mod firmware;
8mod inclusion;
9mod interview;
10pub mod node;
11mod nvm;
12pub mod nvm3;
13pub mod store;
14pub mod values;
15
16pub use controller::{
17 Controller, ControllerInfo, Events, HostConfig, Topology, TopologyNode, MAX_PENDING_EVENTS,
18};
19pub use inclusion::{GrantPolicy, InclusionOptions, InclusionResult};
20pub use node::{NodeRecord, NodeStatus};
21pub use values::{ValueId, ValueKind, ValueUpdate};
22pub use zwave_security::SecurityClass;
23pub use zwave_serial::NodeId;
24
25use zwave_security::provisioning::Entry as ProvisioningEntry;
26
27pub fn is_long_range(node: NodeId) -> bool {
29 node > 255
30}
31
32#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37pub struct NetworkKeys {
38 #[serde(with = "hex_key")]
40 pub s0: [u8; 16],
41 #[serde(with = "hex_key")]
43 pub s2_unauthenticated: [u8; 16],
44 #[serde(with = "hex_key")]
46 pub s2_authenticated: [u8; 16],
47 #[serde(with = "hex_key")]
49 pub s2_access_control: [u8; 16],
50 #[serde(with = "hex_key")]
52 pub ecdh_private: [u8; 32],
53 #[serde(default, with = "hex_key_opt", skip_serializing_if = "Option::is_none")]
55 pub lr_s2_authenticated: Option<[u8; 16]>,
56 #[serde(default, with = "hex_key_opt", skip_serializing_if = "Option::is_none")]
58 pub lr_s2_access_control: Option<[u8; 16]>,
59}
60
61impl std::fmt::Debug for NetworkKeys {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 f.write_str("NetworkKeys(..)")
64 }
65}
66
67impl NetworkKeys {
68 pub fn generate() -> Result<Self, zwave_security::Error> {
70 use zwave_security::random_bytes;
71 Ok(NetworkKeys {
72 s0: random_bytes()?,
73 s2_unauthenticated: random_bytes()?,
74 s2_authenticated: random_bytes()?,
75 s2_access_control: random_bytes()?,
76 ecdh_private: random_bytes()?,
77 lr_s2_authenticated: Some(random_bytes()?),
78 lr_s2_access_control: Some(random_bytes()?),
79 })
80 }
81
82 pub fn fill_long_range(&mut self) -> Result<bool, zwave_security::Error> {
84 let mut added = false;
85 if self.lr_s2_authenticated.is_none() {
86 self.lr_s2_authenticated = Some(zwave_security::random_bytes()?);
87 added = true;
88 }
89 if self.lr_s2_access_control.is_none() {
90 self.lr_s2_access_control = Some(zwave_security::random_bytes()?);
91 added = true;
92 }
93 Ok(added)
94 }
95
96 pub fn long_range_key(&self, class: SecurityClass) -> Option<&[u8; 16]> {
98 match class {
99 SecurityClass::S2Authenticated => self.lr_s2_authenticated.as_ref(),
100 SecurityClass::S2AccessControl => self.lr_s2_access_control.as_ref(),
101 _ => None,
102 }
103 }
104
105 pub fn key(&self, class: SecurityClass) -> &[u8; 16] {
107 match class {
108 SecurityClass::S0Legacy => &self.s0,
109 SecurityClass::S2Unauthenticated => &self.s2_unauthenticated,
110 SecurityClass::S2Authenticated => &self.s2_authenticated,
111 SecurityClass::S2AccessControl => &self.s2_access_control,
112 }
113 }
114
115 pub fn controller_dsk(&self) -> zwave_security::dsk::Dsk {
117 let kp = zwave_security::kex::KeyPair::from_private(self.ecdh_private);
118 zwave_security::dsk::Dsk::from_public_key(kp.public())
119 }
120}
121
122mod hex_key_opt {
123 use serde::{Deserialize, Deserializer, Serializer};
124
125 pub fn serialize<S: Serializer>(k: &Option<[u8; 16]>, s: S) -> Result<S::Ok, S::Error> {
126 match k {
127 Some(k) => s.serialize_str(&hex::encode(k)),
128 None => s.serialize_none(),
129 }
130 }
131
132 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<[u8; 16]>, D::Error> {
133 let s: Option<String> = Option::deserialize(d)?;
134 match s {
135 None => Ok(None),
136 Some(s) => {
137 let v = hex::decode(s.trim()).map_err(serde::de::Error::custom)?;
138 v.try_into()
139 .map(Some)
140 .map_err(|_| serde::de::Error::custom("expected 16 bytes"))
141 }
142 }
143 }
144}
145
146mod hex_key {
147 use serde::{Deserialize, Deserializer, Serializer};
148
149 pub fn serialize<S: Serializer, const N: usize>(k: &[u8; N], s: S) -> Result<S::Ok, S::Error> {
150 s.serialize_str(&hex::encode(k))
151 }
152
153 pub fn deserialize<'de, D: Deserializer<'de>, const N: usize>(
154 d: D,
155 ) -> Result<[u8; N], D::Error> {
156 let s = String::deserialize(d)?;
157 let v = hex::decode(s.trim()).map_err(serde::de::Error::custom)?;
158 v.try_into()
159 .map_err(|_| serde::de::Error::custom(format!("expected {N} bytes")))
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
165pub enum Error {
166 #[error("serial: {0}")]
168 Serial(#[from] zwave_serial::SerialError),
169 #[error("controller: {0}")]
171 Controller(String),
172 #[error("node {0} did not acknowledge")]
174 NoAck(NodeId),
175 #[error("transmission to node {0} failed: {1}")]
177 TransmitFailed(NodeId, String),
178 #[error("node {0} did not answer in time")]
180 Timeout(NodeId),
181 #[error("security: {0}")]
183 Security(String),
184 #[error("no node {0}")]
186 UnknownNode(NodeId),
187 #[error("the controller is busy with another inclusion or exclusion")]
189 Busy,
190 #[error("{0}")]
192 Inclusion(String),
193 #[error("store: {0}")]
195 Store(String),
196 #[error("controller stopped")]
198 Stopped,
199}
200
201#[derive(Debug, Clone, PartialEq)]
203pub enum Event {
204 Ready(ControllerInfo),
206 InclusionStarted,
208 InclusionStopped,
210 ExclusionStarted,
212 ExclusionStopped,
214 NodeAdded {
216 node: NodeId,
218 },
219 NodeRemoved {
221 node: NodeId,
223 },
224 GrantSecurityClasses {
226 node: NodeId,
228 requested: Vec<SecurityClass>,
230 },
231 ValidateDsk {
233 node: NodeId,
235 dsk: String,
237 },
238 SecurityBootstrapped {
240 node: NodeId,
242 classes: Vec<SecurityClass>,
244 },
245 SecurityFailed {
247 node: NodeId,
249 reason: String,
251 },
252 InterviewStage {
254 node: NodeId,
256 stage: node::InterviewStage,
258 },
259 InterviewCompleted {
261 node: NodeId,
263 },
264 InterviewFailed {
266 node: NodeId,
268 reason: String,
270 },
271 NodeUpdated {
273 node: NodeId,
275 },
276 NodeStatus {
278 node: NodeId,
280 status: NodeStatus,
282 },
283 Value(ValueUpdate),
285 Route {
287 node: NodeId,
289 repeaters: Vec<NodeId>,
291 rssi: Option<i8>,
293 },
294 Command {
296 node: NodeId,
298 endpoint: u8,
300 command: zwave_cc::Command,
302 },
303 FirmwareUpdateProgress {
305 node: NodeId,
307 sent: u16,
309 total: u16,
311 },
312 FirmwareUpdateFinished {
314 node: NodeId,
316 status: u8,
318 success: bool,
320 },
321 ProvisioningChanged {
323 entries: Vec<ProvisioningEntry>,
325 },
326}
327
328#[cfg(doctest)]
330#[doc = include_str!("../../../README.md")]
331struct ReadmeDoctests;