1use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14
15use crate::fsutil::{read_json, write_atomic};
16use crate::Error;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20pub struct DeviceType {
21 pub id: u32,
23 pub revision: u16,
25}
26
27#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Endpoint {
30 pub device_types: Vec<DeviceType>,
32 pub server_clusters: Vec<u32>,
34 pub client_clusters: Vec<u32>,
36 pub parts: Vec<u16>,
38}
39
40#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
42pub struct BasicInfo {
43 pub vendor_id: Option<u16>,
45 pub vendor_name: Option<String>,
47 pub product_id: Option<u16>,
49 pub product_name: Option<String>,
51 pub node_label: Option<String>,
53 pub hardware_version: Option<String>,
55 pub software_version: Option<String>,
57 pub serial_number: Option<String>,
59 pub unique_id: Option<String>,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65pub struct Node {
66 pub node_id: u64,
68 pub name: String,
70 #[serde(default)]
72 pub basic: BasicInfo,
73 #[serde(default)]
75 pub endpoints: BTreeMap<u16, Endpoint>,
76 #[serde(default)]
78 pub interviewed: bool,
79 pub commissioned_at: u64,
81}
82
83impl Node {
84 pub fn default_name(node_id: u64) -> String {
86 format!("node_{node_id}")
87 }
88}
89
90#[derive(Default, Serialize, Deserialize)]
91struct StoreFile {
92 version: u32,
93 nodes: Vec<Node>,
94}
95
96pub struct NodeStore {
98 path: PathBuf,
99 nodes: BTreeMap<u64, Node>,
100}
101
102impl NodeStore {
103 const VERSION: u32 = 1;
104
105 pub fn open(path: &Path) -> Result<Self, Error> {
107 let file = read_json::<StoreFile>(path)?.unwrap_or_default();
108 if file.version > Self::VERSION {
109 return Err(Error::Store(format!(
110 "{}: version {} is newer than this build reads ({})",
111 path.display(),
112 file.version,
113 Self::VERSION
114 )));
115 }
116 Ok(Self {
117 path: path.to_path_buf(),
118 nodes: file.nodes.into_iter().map(|n| (n.node_id, n)).collect(),
119 })
120 }
121
122 fn save(&self) -> Result<(), Error> {
123 let file = StoreFile {
124 version: Self::VERSION,
125 nodes: self.nodes.values().cloned().collect(),
126 };
127 write_atomic(&self.path, &serde_json::to_vec_pretty(&file)?, false)
128 }
129
130 pub fn nodes(&self) -> impl Iterator<Item = &Node> {
132 self.nodes.values()
133 }
134
135 pub fn get(&self, node_id: u64) -> Option<&Node> {
137 self.nodes.get(&node_id)
138 }
139
140 pub fn find(&self, name: &str) -> Option<&Node> {
142 self.nodes.values().find(|n| n.name == name).or_else(|| {
143 let id = match name.strip_prefix("0x") {
144 Some(hex) => u64::from_str_radix(hex, 16).ok(),
145 None => name.parse().ok(),
146 }?;
147 self.nodes.get(&id)
148 })
149 }
150
151 pub fn put(&mut self, node: Node) -> Result<(), Error> {
153 if let Some(other) = self
154 .nodes
155 .values()
156 .find(|n| n.name == node.name && n.node_id != node.node_id)
157 {
158 return Err(Error::Invalid(format!(
159 "the name `{}` is taken by node {}",
160 node.name, other.node_id
161 )));
162 }
163 if self.nodes.get(&node.node_id) == Some(&node) {
164 return Ok(());
165 }
166 self.nodes.insert(node.node_id, node);
167 self.save()
168 }
169
170 pub fn remove(&mut self, node_id: u64) -> Result<Option<Node>, Error> {
172 let node = self.nodes.remove(&node_id);
173 if node.is_some() {
174 self.save()?;
175 }
176 Ok(node)
177 }
178
179 pub fn unique_name(&self, base: &str) -> String {
181 if !self.nodes.values().any(|n| n.name == base) {
182 return base.to_string();
183 }
184 (2..)
185 .map(|i| format!("{base}_{i}"))
186 .find(|name| !self.nodes.values().any(|n| &n.name == name))
187 .unwrap()
188 }
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 fn node(id: u64, name: &str) -> Node {
196 Node {
197 node_id: id,
198 name: name.into(),
199 basic: BasicInfo::default(),
200 endpoints: BTreeMap::new(),
201 interviewed: false,
202 commissioned_at: 0,
203 }
204 }
205
206 #[test]
207 fn persists_and_finds() {
208 let dir = tempfile::tempdir().unwrap();
209 let path = dir.path().join("nodes.json");
210 let mut store = NodeStore::open(&path).unwrap();
211 store.put(node(5, "lamp")).unwrap();
212 store.put(node(6, "plug")).unwrap();
213 assert!(store.put(node(7, "lamp")).is_err());
214 assert_eq!(store.unique_name("lamp"), "lamp_2");
215
216 let store = NodeStore::open(&path).unwrap();
217 assert_eq!(store.find("lamp").unwrap().node_id, 5);
218 assert_eq!(store.find("6").unwrap().name, "plug");
219 assert_eq!(store.find("0x6").unwrap().name, "plug");
220 assert!(store.find("nope").is_none());
221 }
222
223 #[test]
224 fn unchanged_put_does_not_write() {
225 let dir = tempfile::tempdir().unwrap();
226 let path = dir.path().join("nodes.json");
227 let mut store = NodeStore::open(&path).unwrap();
228 store.put(node(1, "a")).unwrap();
229 let before = std::fs::metadata(&path).unwrap().modified().unwrap();
230 std::fs::remove_file(&path).unwrap();
231 store.put(node(1, "a")).unwrap();
232 assert!(!path.exists(), "an unchanged node was written again");
233 let _ = before;
234 }
235
236 #[test]
237 fn rejects_a_newer_version() {
238 let dir = tempfile::tempdir().unwrap();
239 let path = dir.path().join("nodes.json");
240 std::fs::write(&path, br#"{"version": 99, "nodes": []}"#).unwrap();
241 assert!(NodeStore::open(&path).is_err());
242 }
243}