mabi-modbus 1.6.2

Mabinogion - Modbus TCP/RTU 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
//! Configuration update utilities and helpers.

use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};

use super::{ConfigUpdate, RuntimeState};

/// Builder for creating configuration updates.
#[derive(Default)]
pub struct UpdateBuilder {
    updates: Vec<ConfigUpdate>,
}

impl UpdateBuilder {
    /// Create a new update builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum connections.
    pub fn max_connections(mut self, max: usize) -> Self {
        self.updates.push(ConfigUpdate::MaxConnections(max));
        self
    }

    /// Set idle timeout.
    pub fn idle_timeout(mut self, duration: Duration) -> Self {
        self.updates.push(ConfigUpdate::IdleTimeout(duration));
        self
    }

    /// Set request timeout.
    pub fn request_timeout(mut self, duration: Duration) -> Self {
        self.updates.push(ConfigUpdate::RequestTimeout(duration));
        self
    }

    /// Enable/disable a unit.
    pub fn unit_enabled(mut self, unit_id: u8, enabled: bool) -> Self {
        self.updates
            .push(ConfigUpdate::UnitEnabled { unit_id, enabled });
        self
    }

    /// Enable TCP nodelay.
    pub fn tcp_nodelay(mut self, enabled: bool) -> Self {
        self.updates.push(ConfigUpdate::TcpNoDelay(enabled));
        self
    }

    /// Set keepalive interval.
    pub fn keepalive(mut self, interval: Option<Duration>) -> Self {
        self.updates.push(ConfigUpdate::KeepaliveInterval(interval));
        self
    }

    /// Enable/disable metrics.
    pub fn metrics_enabled(mut self, enabled: bool) -> Self {
        self.updates.push(ConfigUpdate::MetricsEnabled(enabled));
        self
    }

    /// Enable/disable debug logging.
    pub fn debug_logging(mut self, enabled: bool) -> Self {
        self.updates.push(ConfigUpdate::DebugLogging(enabled));
        self
    }

    /// Set a register value.
    pub fn set_register(mut self, unit_id: u8, address: u16, value: u16) -> Self {
        self.updates.push(ConfigUpdate::SetRegister {
            unit_id,
            address,
            value,
        });
        self
    }

    /// Set multiple registers.
    pub fn set_registers(mut self, unit_id: u8, start_address: u16, values: Vec<u16>) -> Self {
        self.updates.push(ConfigUpdate::SetRegisters {
            unit_id,
            start_address,
            values,
        });
        self
    }

    /// Set a coil value.
    pub fn set_coil(mut self, unit_id: u8, address: u16, value: bool) -> Self {
        self.updates.push(ConfigUpdate::SetCoil {
            unit_id,
            address,
            value,
        });
        self
    }

    /// Add a custom setting.
    pub fn custom(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.updates.push(ConfigUpdate::Custom {
            key: key.into(),
            value: value.into(),
        });
        self
    }

    /// Add any update.
    pub fn update(mut self, update: ConfigUpdate) -> Self {
        self.updates.push(update);
        self
    }

    /// Build the list of updates.
    pub fn build(self) -> Vec<ConfigUpdate> {
        self.updates
    }

    /// Get the number of updates.
    pub fn len(&self) -> usize {
        self.updates.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.updates.is_empty()
    }
}

/// Record of a configuration update for auditing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateRecord {
    /// Unique ID for this update.
    pub id: u64,

    /// The update that was applied.
    pub update: ConfigUpdate,

    /// When the update was applied.
    pub timestamp: SystemTime,

    /// Whether the update was successful.
    pub success: bool,

    /// Error message if the update failed.
    pub error: Option<String>,

    /// Who initiated the update (if known).
    pub source: Option<String>,
}

impl UpdateRecord {
    /// Create a successful update record.
    pub fn success(id: u64, update: ConfigUpdate) -> Self {
        Self {
            id,
            update,
            timestamp: SystemTime::now(),
            success: true,
            error: None,
            source: None,
        }
    }

    /// Create a failed update record.
    pub fn failure(id: u64, update: ConfigUpdate, error: String) -> Self {
        Self {
            id,
            update,
            timestamp: SystemTime::now(),
            success: false,
            error: Some(error),
            source: None,
        }
    }

    /// Set the source of the update.
    pub fn with_source(mut self, source: impl Into<String>) -> Self {
        self.source = Some(source.into());
        self
    }
}

/// Audit log for configuration updates.
pub struct UpdateAuditLog {
    records: Vec<UpdateRecord>,
    max_records: usize,
    next_id: u64,
}

impl UpdateAuditLog {
    /// Create a new audit log.
    pub fn new(max_records: usize) -> Self {
        Self {
            records: Vec::with_capacity(max_records.min(1000)),
            max_records,
            next_id: 1,
        }
    }

    /// Record a successful update.
    pub fn record_success(&mut self, update: ConfigUpdate) -> &UpdateRecord {
        let id = self.next_id;
        self.next_id += 1;

        self.add_record(UpdateRecord::success(id, update))
    }

    /// Record a failed update.
    pub fn record_failure(&mut self, update: ConfigUpdate, error: String) -> &UpdateRecord {
        let id = self.next_id;
        self.next_id += 1;

        self.add_record(UpdateRecord::failure(id, update, error))
    }

    fn add_record(&mut self, record: UpdateRecord) -> &UpdateRecord {
        // Remove oldest if at capacity
        while self.records.len() >= self.max_records {
            self.records.remove(0);
        }

        self.records.push(record);
        self.records.last().unwrap()
    }

    /// Get all records.
    pub fn records(&self) -> &[UpdateRecord] {
        &self.records
    }

    /// Get recent records (last N).
    pub fn recent(&self, n: usize) -> &[UpdateRecord] {
        let start = self.records.len().saturating_sub(n);
        &self.records[start..]
    }

    /// Get failed updates only.
    pub fn failures(&self) -> Vec<&UpdateRecord> {
        self.records.iter().filter(|r| !r.success).collect()
    }

    /// Clear all records.
    pub fn clear(&mut self) {
        self.records.clear();
    }

    /// Get total update count.
    pub fn total_count(&self) -> u64 {
        self.next_id - 1
    }

    /// Get success rate.
    pub fn success_rate(&self) -> f64 {
        if self.records.is_empty() {
            return 1.0;
        }
        let successes = self.records.iter().filter(|r| r.success).count();
        successes as f64 / self.records.len() as f64
    }
}

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

/// Diff between two runtime states.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateDiff {
    /// Fields that changed.
    pub changes: Vec<FieldChange>,
}

/// A single field change.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldChange {
    /// Field name.
    pub field: String,
    /// Old value (as string).
    pub old: String,
    /// New value (as string).
    pub new: String,
}

impl StateDiff {
    /// Calculate diff between two states.
    pub fn diff(old: &RuntimeState, new: &RuntimeState) -> Self {
        let mut changes = Vec::new();

        if old.max_connections != new.max_connections {
            changes.push(FieldChange {
                field: "max_connections".into(),
                old: old.max_connections.to_string(),
                new: new.max_connections.to_string(),
            });
        }

        if old.idle_timeout != new.idle_timeout {
            changes.push(FieldChange {
                field: "idle_timeout".into(),
                old: format!("{:?}", old.idle_timeout),
                new: format!("{:?}", new.idle_timeout),
            });
        }

        if old.request_timeout != new.request_timeout {
            changes.push(FieldChange {
                field: "request_timeout".into(),
                old: format!("{:?}", old.request_timeout),
                new: format!("{:?}", new.request_timeout),
            });
        }

        if old.tcp_nodelay != new.tcp_nodelay {
            changes.push(FieldChange {
                field: "tcp_nodelay".into(),
                old: old.tcp_nodelay.to_string(),
                new: new.tcp_nodelay.to_string(),
            });
        }

        if old.metrics_enabled != new.metrics_enabled {
            changes.push(FieldChange {
                field: "metrics_enabled".into(),
                old: old.metrics_enabled.to_string(),
                new: new.metrics_enabled.to_string(),
            });
        }

        if old.debug_logging != new.debug_logging {
            changes.push(FieldChange {
                field: "debug_logging".into(),
                old: old.debug_logging.to_string(),
                new: new.debug_logging.to_string(),
            });
        }

        if old.enabled_units != new.enabled_units {
            changes.push(FieldChange {
                field: "enabled_units".into(),
                old: format!("{:?}", old.enabled_units),
                new: format!("{:?}", new.enabled_units),
            });
        }

        Self { changes }
    }

    /// Check if there are any changes.
    pub fn has_changes(&self) -> bool {
        !self.changes.is_empty()
    }

    /// Get number of changes.
    pub fn change_count(&self) -> usize {
        self.changes.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_update_builder() {
        let updates = UpdateBuilder::new()
            .max_connections(200)
            .idle_timeout(Duration::from_secs(600))
            .metrics_enabled(false)
            .build();

        assert_eq!(updates.len(), 3);
    }

    #[test]
    fn test_update_builder_empty() {
        let builder = UpdateBuilder::new();
        assert!(builder.is_empty());
    }

    #[test]
    fn test_update_builder_registers() {
        let updates = UpdateBuilder::new()
            .set_register(1, 100, 1234)
            .set_registers(1, 200, vec![1, 2, 3])
            .set_coil(1, 50, true)
            .build();

        assert_eq!(updates.len(), 3);
    }

    #[test]
    fn test_update_record() {
        let record =
            UpdateRecord::success(1, ConfigUpdate::MaxConnections(100)).with_source("test_user");

        assert!(record.success);
        assert_eq!(record.source, Some("test_user".to_string()));
    }

    #[test]
    fn test_update_record_failure() {
        let record =
            UpdateRecord::failure(2, ConfigUpdate::MaxConnections(0), "Invalid value".into());

        assert!(!record.success);
        assert!(record.error.is_some());
    }

    #[test]
    fn test_audit_log() {
        let mut log = UpdateAuditLog::new(10);

        log.record_success(ConfigUpdate::MaxConnections(100));
        log.record_success(ConfigUpdate::MaxConnections(200));
        log.record_failure(ConfigUpdate::MaxConnections(0), "Invalid".into());

        assert_eq!(log.records().len(), 3);
        assert_eq!(log.failures().len(), 1);
        assert_eq!(log.total_count(), 3);
    }

    #[test]
    fn test_audit_log_capacity() {
        let mut log = UpdateAuditLog::new(5);

        for i in 0..10 {
            log.record_success(ConfigUpdate::MaxConnections(i));
        }

        assert_eq!(log.records().len(), 5);
        assert_eq!(log.total_count(), 10);
    }

    #[test]
    fn test_audit_log_success_rate() {
        let mut log = UpdateAuditLog::new(10);

        log.record_success(ConfigUpdate::MaxConnections(100));
        log.record_success(ConfigUpdate::MaxConnections(100));
        log.record_failure(ConfigUpdate::MaxConnections(0), "Error".into());

        let rate = log.success_rate();
        assert!((rate - 0.6666).abs() < 0.01);
    }

    #[test]
    fn test_state_diff() {
        let old = RuntimeState::default();
        let mut new = RuntimeState::default();
        new.max_connections = 200;
        new.metrics_enabled = false;

        let diff = StateDiff::diff(&old, &new);

        assert!(diff.has_changes());
        assert_eq!(diff.change_count(), 2);
    }

    #[test]
    fn test_state_diff_no_changes() {
        let state = RuntimeState::default();
        let diff = StateDiff::diff(&state, &state);

        assert!(!diff.has_changes());
    }
}