1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
//! Model management API
//!
//! This module provides a high-level API for managing device models.
//! It allows users to list, create, edit, validate, and apply models to devices.
use crate::error::{PoKeysError, Result};
use crate::models::{
DeviceModel, PinModel, copy_default_models_to_user_dir, get_default_model_dir,
};
use log::{info, warn};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
/// Model manager for device models
pub struct ModelManager {
/// Directory containing model files
model_dir: PathBuf,
/// Loaded models
models: HashMap<String, DeviceModel>,
}
impl ModelManager {
/// Create a new model manager
///
/// # Arguments
///
/// * `model_dir` - Optional custom directory for model files
///
/// # Returns
///
/// * `Result<ModelManager>` - The new model manager or an error
pub fn new(model_dir: Option<PathBuf>) -> Result<Self> {
let dir = model_dir.unwrap_or_else(get_default_model_dir);
// Create the directory if it doesn't exist
if !dir.exists() {
fs::create_dir_all(&dir).map_err(|e| {
PoKeysError::ModelDirCreateError(dir.to_string_lossy().to_string(), e.to_string())
})?;
}
// Copy default models to the user's directory
copy_default_models_to_user_dir(Some(&dir))?;
let mut manager = Self {
model_dir: dir,
models: HashMap::new(),
};
// Load all models from the directory
manager.reload_models()?;
Ok(manager)
}
/// Reload all models from the model directory
///
/// # Returns
///
/// * `Result<()>` - Ok if models were loaded successfully, an error otherwise
pub fn reload_models(&mut self) -> Result<()> {
self.models.clear();
// Read all YAML files in the directory
let entries = fs::read_dir(&self.model_dir).map_err(|e| {
PoKeysError::ModelDirReadError(
self.model_dir.to_string_lossy().to_string(),
e.to_string(),
)
})?;
for entry in entries {
let entry = entry.map_err(|e| {
PoKeysError::ModelDirReadError(
self.model_dir.to_string_lossy().to_string(),
e.to_string(),
)
})?;
let path = entry.path();
if path.extension().is_some_and(|ext| ext == "yaml") {
if let Some(file_name) = path.file_stem() {
let model_name = file_name.to_string_lossy().to_string();
match DeviceModel::from_file(&path) {
Ok(model) => {
self.models.insert(model_name, model);
}
Err(e) => {
warn!("Failed to load model from {}: {}", path.display(), e);
}
}
}
}
}
info!(
"Loaded {} models from {}",
self.models.len(),
self.model_dir.display()
);
Ok(())
}
/// Get a model by name
///
/// # Arguments
///
/// * `name` - The name of the model
///
/// # Returns
///
/// * `Option<&DeviceModel>` - The model if found, None otherwise
pub fn get_model(&self, name: &str) -> Option<&DeviceModel> {
self.models.get(name)
}
/// Get a mutable model by name
///
/// # Arguments
///
/// * `name` - The name of the model
///
/// # Returns
///
/// * `Option<&mut DeviceModel>` - The model if found, None otherwise
pub fn get_model_mut(&mut self, name: &str) -> Option<&mut DeviceModel> {
self.models.get_mut(name)
}
/// Get all loaded models
///
/// # Returns
///
/// * `&HashMap<String, DeviceModel>` - Map of model names to models
pub fn get_all_models(&self) -> &HashMap<String, DeviceModel> {
&self.models
}
/// Create a new model
///
/// # Arguments
///
/// * `name` - The name of the model
/// * `pins` - Map of pin numbers to pin models
///
/// # Returns
///
/// * `Result<()>` - Ok if the model was created successfully, an error otherwise
pub fn create_model(&mut self, name: &str, pins: HashMap<u8, PinModel>) -> Result<()> {
// Create the model
let model = DeviceModel {
name: name.to_string(),
pins,
};
// Validate the model
model.validate()?;
// Save the model to a file
self.save_model(&model)?;
// Add the model to the map
self.models.insert(name.to_string(), model);
Ok(())
}
/// Save a model to a file
///
/// # Arguments
///
/// * `model` - The model to save
///
/// # Returns
///
/// * `Result<()>` - Ok if the model was saved successfully, an error otherwise
pub fn save_model(&self, model: &DeviceModel) -> Result<()> {
let file_path = self.model_dir.join(format!("{}.yaml", model.name));
// Serialize the model to YAML
let yaml = serde_yaml::to_string(model).map_err(|e| {
PoKeysError::ModelParseError(file_path.to_string_lossy().to_string(), e.to_string())
})?;
// Write the YAML to a file
fs::write(&file_path, yaml).map_err(|e| {
PoKeysError::ModelLoadError(file_path.to_string_lossy().to_string(), e.to_string())
})?;
info!("Saved model {} to {}", model.name, file_path.display());
Ok(())
}
/// Delete a model
///
/// # Arguments
///
/// * `name` - The name of the model
///
/// # Returns
///
/// * `Result<()>` - Ok if the model was deleted successfully, an error otherwise
pub fn delete_model(&mut self, name: &str) -> Result<()> {
// Remove the model from the map
self.models.remove(name);
// Delete the model file
let file_path = self.model_dir.join(format!("{}.yaml", name));
if file_path.exists() {
fs::remove_file(&file_path).map_err(|e| {
PoKeysError::ModelLoadError(file_path.to_string_lossy().to_string(), e.to_string())
})?;
info!("Deleted model {}", name);
}
Ok(())
}
/// Create a copy of a model with a new name
///
/// # Arguments
///
/// * `source_name` - The name of the source model
/// * `target_name` - The name of the target model
///
/// # Returns
///
/// * `Result<()>` - Ok if the model was copied successfully, an error otherwise
pub fn copy_model(&mut self, source_name: &str, target_name: &str) -> Result<()> {
// Get the source model
let source_model = self.get_model(source_name).ok_or_else(|| {
PoKeysError::ModelLoadError(source_name.to_string(), "Model not found".to_string())
})?;
// Create a copy of the model with the new name
let mut target_model = source_model.clone();
target_model.name = target_name.to_string();
// Save the target model
self.save_model(&target_model)?;
// Add the target model to the map
self.models.insert(target_name.to_string(), target_model);
Ok(())
}
/// Validate a model
///
/// # Arguments
///
/// * `name` - The name of the model
///
/// # Returns
///
/// * `Result<()>` - Ok if the model is valid, an error otherwise
pub fn validate_model(&self, name: &str) -> Result<()> {
// Get the model
let model = self.get_model(name).ok_or_else(|| {
PoKeysError::ModelLoadError(name.to_string(), "Model not found".to_string())
})?;
// Validate the model
model.validate()
}
/// Get the model directory
///
/// # Returns
///
/// * `&Path` - The model directory
pub fn get_model_dir(&self) -> &Path {
&self.model_dir
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn test_model_manager() {
// Create a temporary directory for the test
let dir = tempdir().unwrap();
// Create a model manager
let mut manager = ModelManager::new(Some(dir.path().to_path_buf())).unwrap();
// Create a model
let mut pins = HashMap::new();
pins.insert(
1,
PinModel {
capabilities: vec!["DigitalInput".to_string(), "DigitalOutput".to_string()],
active: true,
},
);
pins.insert(
2,
PinModel {
capabilities: vec!["DigitalInput".to_string(), "AnalogInput".to_string()],
active: true,
},
);
// Create the model
assert!(manager.create_model("TestModel", pins).is_ok());
// Get the model
let model = manager.get_model("TestModel");
assert!(model.is_some());
let model = model.unwrap();
assert_eq!(model.name, "TestModel");
assert_eq!(model.pins.len(), 2);
// Copy the model
assert!(manager.copy_model("TestModel", "TestModel2").is_ok());
// Get the copied model
let model = manager.get_model("TestModel2");
assert!(model.is_some());
let model = model.unwrap();
assert_eq!(model.name, "TestModel2");
assert_eq!(model.pins.len(), 2);
// Delete the model
assert!(manager.delete_model("TestModel").is_ok());
// Check that the model was deleted
assert!(manager.get_model("TestModel").is_none());
// Check that the copied model still exists
assert!(manager.get_model("TestModel2").is_some());
// Reload models
assert!(manager.reload_models().is_ok());
// Check that the copied model was reloaded
assert!(manager.get_model("TestModel2").is_some());
}
}