1use crate::node::NodeRecord;
6use crate::NodeId;
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10use zwave_security::provisioning::ProvisioningList;
11
12pub const VERSION: u32 = 1;
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub struct StoreData {
18 pub version: u32,
20 pub home_id: Option<u32>,
22 pub nodes: BTreeMap<NodeId, NodeRecord>,
24 #[serde(default)]
26 pub provisioning: ProvisioningList,
27}
28
29impl Default for StoreData {
30 fn default() -> Self {
31 StoreData {
32 version: VERSION,
33 home_id: None,
34 nodes: BTreeMap::new(),
35 provisioning: ProvisioningList::default(),
36 }
37 }
38}
39
40pub fn load(path: &Path) -> Result<StoreData, String> {
42 match std::fs::read(path) {
43 Ok(bytes) => {
44 let d: StoreData =
45 serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
46 if d.version > VERSION {
47 return Err(format!(
48 "{}: store version {} is newer than this build",
49 path.display(),
50 d.version
51 ));
52 }
53 Ok(d)
54 }
55 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(StoreData::default()),
56 Err(e) => Err(format!("{}: {e}", path.display())),
57 }
58}
59
60pub fn save(path: &Path, data: &StoreData) -> Result<(), String> {
63 let json = serde_json::to_vec_pretty(data).map_err(|e| e.to_string())?;
64 let tmp: PathBuf = path.with_extension("json.tmp");
65 if let Some(dir) = path.parent() {
66 if !dir.as_os_str().is_empty() {
67 std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
68 }
69 }
70 {
71 use std::io::Write;
72 let mut f = std::fs::File::create(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
73 f.write_all(&json).map_err(|e| e.to_string())?;
74 f.sync_all().map_err(|e| e.to_string())?;
75 }
76 std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn roundtrip_and_missing() {
85 let dir = std::env::temp_dir().join(format!("zwave-store-{}", std::process::id()));
86 let path = dir.join("nodes.json");
87 assert_eq!(load(&path).unwrap(), StoreData::default());
88 let mut d = StoreData {
89 home_id: Some(0xc0ffee01),
90 ..Default::default()
91 };
92 d.nodes.insert(5, NodeRecord::new(5));
93 save(&path, &d).unwrap();
94 assert_eq!(load(&path).unwrap(), d);
95 std::fs::remove_dir_all(dir).unwrap();
96 }
97}