mabi-core 1.6.2

Mabinogion - Core abstractions and utilities for industrial protocol simulator
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Device factory and plugin system for extensibility.
//!
//! This module provides abstractions for creating devices dynamically
//! and registering protocol plugins at runtime.

use std::collections::HashMap;
use std::sync::Arc;

use parking_lot::RwLock;

use crate::config::DeviceConfig;
use crate::device::BoxedDevice;
use crate::error::{Error, Result};
use crate::protocol::Protocol;
use crate::version::RELEASE_VERSION;

/// A factory trait for creating devices.
///
/// Implement this trait to add support for new protocols or device types.
///
/// # Example
///
/// ```ignore
/// struct ModbusDeviceFactory;
///
/// impl DeviceFactory for ModbusDeviceFactory {
///     fn protocol(&self) -> Protocol {
///         Protocol::ModbusTcp
///     }
///
///     fn create(&self, config: DeviceConfig) -> Result<BoxedDevice> {
///         Ok(Box::new(ModbusDevice::new(config)?))
///     }
/// }
/// ```
pub trait DeviceFactory: Send + Sync {
    /// Get the protocol this factory handles.
    fn protocol(&self) -> Protocol;

    /// Create a device from configuration.
    fn create(&self, config: DeviceConfig) -> Result<BoxedDevice>;

    /// Create multiple devices from configurations.
    fn create_batch(&self, configs: Vec<DeviceConfig>) -> Result<Vec<BoxedDevice>> {
        configs.into_iter().map(|c| self.create(c)).collect()
    }

    /// Validate device configuration without creating the device.
    fn validate(&self, config: &DeviceConfig) -> Result<()> {
        if config.id.is_empty() {
            return Err(Error::Config("Device ID cannot be empty".into()));
        }
        if config.name.is_empty() {
            return Err(Error::Config("Device name cannot be empty".into()));
        }
        if config.protocol != self.protocol() {
            return Err(Error::Config(format!(
                "Protocol mismatch: expected {:?}, got {:?}",
                self.protocol(),
                config.protocol
            )));
        }
        Ok(())
    }

    /// Get factory metadata.
    fn metadata(&self) -> FactoryMetadata {
        FactoryMetadata {
            protocol: self.protocol(),
            version: RELEASE_VERSION.to_string(),
            description: format!("{:?} device factory", self.protocol()),
            capabilities: Vec::new(),
        }
    }
}

/// Metadata about a device factory.
#[derive(Debug, Clone)]
pub struct FactoryMetadata {
    /// Protocol this factory handles.
    pub protocol: Protocol,
    /// Factory version.
    pub version: String,
    /// Description.
    pub description: String,
    /// Supported capabilities.
    pub capabilities: Vec<String>,
}

/// A type-erased device factory.
pub type BoxedFactory = Box<dyn DeviceFactory>;

/// Registry for device factories.
///
/// This allows registering factories for different protocols at runtime,
/// enabling a plugin-like architecture.
///
/// # Example
///
/// ```ignore
/// let mut registry = FactoryRegistry::new();
/// registry.register(ModbusDeviceFactory)?;
///
/// let config = DeviceConfig { /* ... */ };
/// let device = registry.create_device(config)?;
/// ```
pub struct FactoryRegistry {
    factories: RwLock<HashMap<Protocol, Arc<BoxedFactory>>>,
}

impl FactoryRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self {
            factories: RwLock::new(HashMap::new()),
        }
    }

    /// Register a device factory.
    pub fn register<F: DeviceFactory + 'static>(&self, factory: F) -> Result<()> {
        let protocol = factory.protocol();
        let mut factories = self.factories.write();

        if factories.contains_key(&protocol) {
            return Err(Error::Config(format!(
                "Factory already registered for protocol {:?}",
                protocol
            )));
        }

        factories.insert(protocol, Arc::new(Box::new(factory)));
        Ok(())
    }

    /// Register a boxed factory.
    pub fn register_boxed(&self, factory: BoxedFactory) -> Result<()> {
        let protocol = factory.protocol();
        let mut factories = self.factories.write();

        if factories.contains_key(&protocol) {
            return Err(Error::Config(format!(
                "Factory already registered for protocol {:?}",
                protocol
            )));
        }

        factories.insert(protocol, Arc::new(factory));
        Ok(())
    }

    /// Unregister a factory for a protocol.
    pub fn unregister(&self, protocol: Protocol) -> bool {
        self.factories.write().remove(&protocol).is_some()
    }

    /// Get a factory for a protocol.
    pub fn get(&self, protocol: Protocol) -> Option<Arc<BoxedFactory>> {
        self.factories.read().get(&protocol).cloned()
    }

    /// Check if a factory is registered for a protocol.
    pub fn has(&self, protocol: Protocol) -> bool {
        self.factories.read().contains_key(&protocol)
    }

    /// Get all registered protocols.
    pub fn protocols(&self) -> Vec<Protocol> {
        self.factories.read().keys().copied().collect()
    }

    /// Get metadata for all registered factories.
    pub fn all_metadata(&self) -> Vec<FactoryMetadata> {
        self.factories
            .read()
            .values()
            .map(|f| f.metadata())
            .collect()
    }

    /// Create a device using the appropriate factory.
    pub fn create_device(&self, config: DeviceConfig) -> Result<BoxedDevice> {
        let factory = self
            .get(config.protocol)
            .ok_or_else(|| Error::NotSupported(format!("Protocol {:?}", config.protocol)))?;

        factory.validate(&config)?;
        factory.create(config)
    }

    /// Create multiple devices.
    pub fn create_devices(&self, configs: Vec<DeviceConfig>) -> Result<Vec<BoxedDevice>> {
        configs.into_iter().map(|c| self.create_device(c)).collect()
    }
}

impl Default for FactoryRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Plugin trait for extending the simulator.
///
/// Plugins can register factories, add event handlers, and customize behavior.
pub trait Plugin: Send + Sync {
    /// Get plugin name.
    fn name(&self) -> &str;

    /// Get plugin version.
    fn version(&self) -> &str {
        RELEASE_VERSION
    }

    /// Get plugin description.
    fn description(&self) -> &str {
        ""
    }

    /// Initialize the plugin (called when loaded).
    fn initialize(&mut self) -> Result<()> {
        Ok(())
    }

    /// Register device factories with the registry.
    fn register_factories(&self, _registry: &FactoryRegistry) -> Result<()> {
        Ok(())
    }

    /// Shutdown the plugin (called when unloaded).
    fn shutdown(&mut self) -> Result<()> {
        Ok(())
    }
}

/// A boxed plugin.
pub type BoxedPlugin = Box<dyn Plugin>;

/// Plugin manager for loading and managing plugins.
pub struct PluginManager {
    plugins: RwLock<Vec<BoxedPlugin>>,
    registry: Arc<FactoryRegistry>,
}

impl PluginManager {
    /// Create a new plugin manager.
    pub fn new(registry: Arc<FactoryRegistry>) -> Self {
        Self {
            plugins: RwLock::new(Vec::new()),
            registry,
        }
    }

    /// Load a plugin.
    pub fn load<P: Plugin + 'static>(&self, mut plugin: P) -> Result<()> {
        plugin.initialize()?;
        plugin.register_factories(&self.registry)?;

        self.plugins.write().push(Box::new(plugin));
        Ok(())
    }

    /// Load a boxed plugin.
    pub fn load_boxed(&self, mut plugin: BoxedPlugin) -> Result<()> {
        plugin.initialize()?;
        plugin.register_factories(&self.registry)?;

        self.plugins.write().push(plugin);
        Ok(())
    }

    /// Get the number of loaded plugins.
    pub fn plugin_count(&self) -> usize {
        self.plugins.read().len()
    }

    /// Get information about loaded plugins.
    pub fn plugin_info(&self) -> Vec<PluginInfo> {
        self.plugins
            .read()
            .iter()
            .map(|p| PluginInfo {
                name: p.name().to_string(),
                version: p.version().to_string(),
                description: p.description().to_string(),
            })
            .collect()
    }

    /// Get the factory registry.
    pub fn registry(&self) -> &Arc<FactoryRegistry> {
        &self.registry
    }

    /// Shutdown all plugins.
    pub fn shutdown_all(&self) -> Result<()> {
        for plugin in self.plugins.write().iter_mut() {
            plugin.shutdown()?;
        }
        Ok(())
    }
}

/// Information about a loaded plugin.
#[derive(Debug, Clone)]
pub struct PluginInfo {
    /// Plugin name.
    pub name: String,
    /// Plugin version.
    pub version: String,
    /// Plugin description.
    pub description: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::device::{Device, DeviceInfo, DeviceStatistics};
    use crate::tags::Tags;
    use crate::types::{DataPoint, DataPointDef, DataPointId};
    use crate::value::Value;
    use async_trait::async_trait;

    // Mock device for testing
    struct MockDevice {
        info: DeviceInfo,
    }

    impl MockDevice {
        fn new(id: &str, name: &str) -> Self {
            Self {
                info: DeviceInfo::new(id, name, Protocol::ModbusTcp),
            }
        }
    }

    #[async_trait]
    impl Device for MockDevice {
        fn info(&self) -> &DeviceInfo {
            &self.info
        }

        async fn initialize(&mut self) -> Result<()> {
            Ok(())
        }

        async fn start(&mut self) -> Result<()> {
            Ok(())
        }

        async fn stop(&mut self) -> Result<()> {
            Ok(())
        }

        async fn tick(&mut self) -> Result<()> {
            Ok(())
        }

        fn point_definitions(&self) -> Vec<&DataPointDef> {
            vec![]
        }

        fn point_definition(&self, _point_id: &str) -> Option<&DataPointDef> {
            None
        }

        async fn read(&self, point_id: &str) -> Result<DataPoint> {
            Ok(DataPoint::new(
                DataPointId::new(&self.info.id, point_id),
                Value::F64(0.0),
            ))
        }

        async fn write(&mut self, _point_id: &str, _value: Value) -> Result<()> {
            Ok(())
        }

        fn statistics(&self) -> DeviceStatistics {
            DeviceStatistics::default()
        }
    }

    // Mock factory for testing
    struct MockFactory;

    impl DeviceFactory for MockFactory {
        fn protocol(&self) -> Protocol {
            Protocol::ModbusTcp
        }

        fn create(&self, config: DeviceConfig) -> Result<BoxedDevice> {
            Ok(Box::new(MockDevice::new(&config.id, &config.name)))
        }
    }

    // Mock plugin for testing
    struct MockPlugin {
        name: String,
    }

    impl MockPlugin {
        fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
            }
        }
    }

    impl Plugin for MockPlugin {
        fn name(&self) -> &str {
            &self.name
        }

        fn description(&self) -> &str {
            "Mock plugin for testing"
        }

        fn register_factories(&self, registry: &FactoryRegistry) -> Result<()> {
            registry.register(MockFactory)
        }
    }

    #[test]
    fn test_factory_registry() {
        let registry = FactoryRegistry::new();

        assert!(!registry.has(Protocol::ModbusTcp));

        registry.register(MockFactory).unwrap();

        assert!(registry.has(Protocol::ModbusTcp));
        assert!(registry.protocols().contains(&Protocol::ModbusTcp));
    }

    #[test]
    fn test_factory_metadata_uses_release_version() {
        let metadata = MockFactory.metadata();
        assert_eq!(metadata.version, RELEASE_VERSION);
    }

    #[test]
    fn test_factory_create_device() {
        let registry = FactoryRegistry::new();
        registry.register(MockFactory).unwrap();

        let config = DeviceConfig {
            id: "test-001".to_string(),
            name: "Test Device".to_string(),
            description: String::new(),
            protocol: Protocol::ModbusTcp,
            address: None,
            points: vec![],
            metadata: Default::default(),
            tags: Tags::new(),
        };

        let device = registry.create_device(config).unwrap();
        assert_eq!(device.id(), "test-001");
    }

    #[test]
    fn test_factory_validation() {
        let factory = MockFactory;

        // Empty ID should fail
        let config = DeviceConfig {
            id: String::new(),
            name: "Test".to_string(),
            description: String::new(),
            protocol: Protocol::ModbusTcp,
            address: None,
            points: vec![],
            metadata: Default::default(),
            tags: Tags::new(),
        };
        assert!(factory.validate(&config).is_err());

        // Wrong protocol should fail
        let config = DeviceConfig {
            id: "test".to_string(),
            name: "Test".to_string(),
            description: String::new(),
            protocol: Protocol::OpcUa,
            address: None,
            points: vec![],
            metadata: Default::default(),
            tags: Tags::new(),
        };
        assert!(factory.validate(&config).is_err());
    }

    #[test]
    fn test_plugin_manager() {
        let registry = Arc::new(FactoryRegistry::new());
        let manager = PluginManager::new(registry.clone());

        assert_eq!(manager.plugin_count(), 0);

        manager.load(MockPlugin::new("test-plugin")).unwrap();

        assert_eq!(manager.plugin_count(), 1);
        assert!(registry.has(Protocol::ModbusTcp));

        let info = manager.plugin_info();
        assert_eq!(info[0].name, "test-plugin");
        assert_eq!(info[0].version, RELEASE_VERSION);
    }

    #[test]
    fn test_duplicate_factory_registration() {
        let registry = FactoryRegistry::new();

        registry.register(MockFactory).unwrap();
        let result = registry.register(MockFactory);

        assert!(result.is_err());
    }
}