rust-ethernet-ip 1.2.1

High-performance EtherNet/IP communication library for Allen-Bradley CompactLogix and ControlLogix PLCs
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
use crate::error::{EtherNetIpError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::time::Duration;

/// Production configuration for EtherNet/IP library
#[derive(Debug, Clone, Serialize, Deserialize)]
#[deprecated(
    since = "1.2.0",
    note = "ProductionConfig is not consumed by EipClient and implies unsupported enforcement; configure EipClient/Client/Fleet directly. The type will be removed in 2.0."
)]
pub struct ProductionConfig {
    /// Connection settings
    pub connection: ConnectionConfig,
    /// Performance settings
    pub performance: PerformanceConfig,
    /// Monitoring settings
    pub monitoring: MonitoringConfig,
    /// Security settings
    pub security: SecurityConfig,
    /// Logging settings
    pub logging: LoggingConfig,
    /// PLC-specific settings
    pub plc_settings: HashMap<String, PlcSpecificConfig>,
}

/// Network timeouts, retry behavior, and connection limits.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionConfig {
    /// Default connection timeout
    pub connection_timeout: Duration,
    /// Default read timeout
    pub read_timeout: Duration,
    /// Default write timeout
    pub write_timeout: Duration,
    /// Maximum number of concurrent connections
    pub max_connections: u32,
    /// Connection retry attempts
    pub retry_attempts: u32,
    /// Retry delay between attempts
    pub retry_delay: Duration,
    /// Keep-alive interval
    pub keep_alive_interval: Duration,
}

/// Packet, batching, pooling, and memory settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Maximum packet size
    pub max_packet_size: usize,
    /// Batch operation configuration
    pub batch_config: BatchConfig,
    /// Connection pool settings
    pub connection_pool: ConnectionPoolConfig,
    /// Memory limits
    pub memory_limits: MemoryLimits,
}

/// Legacy batch execution configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchConfig {
    /// Maximum operations per batch
    pub max_operations_per_batch: usize,
    /// Batch timeout
    pub batch_timeout: Duration,
    /// Continue on error
    pub continue_on_error: bool,
    /// Optimize packet packing
    pub optimize_packet_packing: bool,
}

/// Legacy connection-pool sizing and cleanup settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionPoolConfig {
    /// Initial pool size
    pub initial_size: u32,
    /// Maximum pool size
    pub max_size: u32,
    /// Pool growth increment
    pub growth_increment: u32,
    /// Connection idle timeout
    pub idle_timeout: Duration,
    /// Pool cleanup interval
    pub cleanup_interval: Duration,
}

/// Advisory process memory thresholds.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryLimits {
    /// Maximum memory usage in MB
    pub max_memory_mb: usize,
    /// Memory warning threshold in MB
    pub warning_threshold_mb: usize,
    /// Enable memory monitoring
    pub enable_monitoring: bool,
}

/// Diagnostic collection and health-check settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    /// Enable production monitoring
    pub enabled: bool,
    /// Metrics collection interval
    pub collection_interval: Duration,
    /// Health check interval
    pub health_check_interval: Duration,
    /// Metrics retention period
    pub retention_period: Duration,
    /// Enable performance profiling
    pub enable_profiling: bool,
    /// Alert thresholds
    pub alert_thresholds: AlertThresholds,
}

/// Thresholds used to raise monitoring alerts.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertThresholds {
    /// Error rate threshold (0.0 to 1.0)
    pub error_rate_threshold: f64,
    /// Latency threshold in milliseconds
    pub latency_threshold_ms: f64,
    /// Memory usage threshold in MB
    pub memory_threshold_mb: usize,
    /// Connection failure threshold
    pub connection_failure_threshold: u32,
}

/// Input validation, rate limiting, and reserved encryption settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// Enable connection encryption (if supported by PLC)
    pub enable_encryption: bool,
    /// Connection validation
    pub validate_connections: bool,
    /// Input validation
    pub validate_inputs: bool,
    /// Rate limiting
    pub rate_limiting: RateLimitingConfig,
}

/// Request-rate limiter settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitingConfig {
    /// Enable rate limiting
    pub enabled: bool,
    /// Maximum requests per second
    pub max_requests_per_second: u32,
    /// Burst capacity
    pub burst_capacity: u32,
}

/// Log level, format, destination, and rotation settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Log level (trace, debug, info, warn, error)
    pub level: LogLevel,
    /// Log format (json, text)
    pub format: LogFormat,
    /// Log file path
    pub file_path: Option<String>,
    /// Enable console logging
    pub enable_console: bool,
    /// Enable structured logging
    pub enable_structured: bool,
    /// Log rotation settings
    pub rotation: LogRotationConfig,
}

/// Rotating log-file policy.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogRotationConfig {
    /// Enable log rotation
    pub enabled: bool,
    /// Maximum file size in MB
    pub max_file_size_mb: usize,
    /// Maximum number of files
    pub max_files: usize,
    /// Rotation schedule (daily, weekly, monthly)
    pub schedule: LogRotationSchedule,
}

/// Minimum severity emitted by configured logging.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    /// Very detailed diagnostic events.
    Trace,
    /// Debugging events.
    Debug,
    /// Normal informational events.
    Info,
    /// Potential problems that do not stop operation.
    Warn,
    /// Operation failures.
    Error,
}

/// Log record serialization format.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LogFormat {
    /// Structured JSON records.
    Json,
    /// Human-readable text records.
    Text,
}

/// Calendar interval for log rotation.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LogRotationSchedule {
    /// Rotate once per day.
    Daily,
    /// Rotate once per week.
    Weekly,
    /// Rotate once per month.
    Monthly,
}

/// Per-controller overrides keyed by PLC address.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlcSpecificConfig {
    /// PLC model/type
    pub model: String,
    /// Specific connection settings
    pub connection_settings: HashMap<String, String>,
    /// Tag discovery settings
    pub tag_discovery: TagDiscoveryConfig,
    /// Performance tuning
    pub performance_tuning: HashMap<String, String>,
}

/// Periodic tag-discovery settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TagDiscoveryConfig {
    /// Enable automatic tag discovery
    pub enabled: bool,
    /// Discovery interval
    pub interval: Duration,
    /// Cache discovered tags
    pub cache_tags: bool,
    /// Maximum tags to discover
    pub max_tags: usize,
}

#[expect(
    deprecated,
    reason = "CODEX-AQ keeps ProductionConfig compatibility until 2.0 removal"
)]
impl Default for ProductionConfig {
    fn default() -> Self {
        Self {
            connection: ConnectionConfig {
                connection_timeout: Duration::from_secs(10),
                read_timeout: Duration::from_secs(5),
                write_timeout: Duration::from_secs(5),
                max_connections: 10,
                retry_attempts: 3,
                retry_delay: Duration::from_secs(1),
                keep_alive_interval: Duration::from_secs(30),
            },
            performance: PerformanceConfig {
                max_packet_size: 4000,
                batch_config: BatchConfig {
                    max_operations_per_batch: 50,
                    batch_timeout: Duration::from_secs(10),
                    continue_on_error: true,
                    optimize_packet_packing: true,
                },
                connection_pool: ConnectionPoolConfig {
                    initial_size: 2,
                    max_size: 10,
                    growth_increment: 2,
                    idle_timeout: Duration::from_secs(300),
                    cleanup_interval: Duration::from_secs(60),
                },
                memory_limits: MemoryLimits {
                    max_memory_mb: 100,
                    warning_threshold_mb: 80,
                    enable_monitoring: true,
                },
            },
            monitoring: MonitoringConfig {
                enabled: true,
                collection_interval: Duration::from_secs(30),
                health_check_interval: Duration::from_secs(60),
                retention_period: Duration::from_secs(86400), // 24 hours
                enable_profiling: false,
                alert_thresholds: AlertThresholds {
                    error_rate_threshold: 0.05,
                    latency_threshold_ms: 1000.0,
                    memory_threshold_mb: 80,
                    connection_failure_threshold: 5,
                },
            },
            security: SecurityConfig {
                enable_encryption: false,
                validate_connections: true,
                validate_inputs: true,
                rate_limiting: RateLimitingConfig {
                    enabled: true,
                    max_requests_per_second: 100,
                    burst_capacity: 200,
                },
            },
            logging: LoggingConfig {
                level: LogLevel::Info,
                format: LogFormat::Json,
                file_path: Some("logs/ethernet_ip.log".to_string()),
                enable_console: true,
                enable_structured: true,
                rotation: LogRotationConfig {
                    enabled: true,
                    max_file_size_mb: 100,
                    max_files: 10,
                    schedule: LogRotationSchedule::Daily,
                },
            },
            plc_settings: HashMap::new(),
        }
    }
}

#[expect(
    deprecated,
    reason = "CODEX-AQ keeps ProductionConfig compatibility until 2.0 removal"
)]
impl ProductionConfig {
    /// Load configuration from file
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = fs::read_to_string(path)?;
        let config: ProductionConfig =
            toml::from_str(&content).map_err(|e| EtherNetIpError::Other(e.to_string()))?;
        Ok(config)
    }

    /// Save configuration to file
    pub fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let content =
            toml::to_string_pretty(self).map_err(|e| EtherNetIpError::Other(e.to_string()))?;
        fs::write(path, content)?;
        Ok(())
    }

    /// Validate configuration
    pub fn validate(&self) -> std::result::Result<(), Vec<String>> {
        let mut errors = Vec::new();

        // Validate connection settings
        if self.connection.connection_timeout.as_secs() == 0 {
            errors.push("Connection timeout must be greater than 0".to_string());
        }

        if self.connection.max_connections == 0 {
            errors.push("Maximum connections must be greater than 0".to_string());
        }

        // Validate performance settings
        if self.performance.max_packet_size < 100 {
            errors.push("Maximum packet size must be at least 100 bytes".to_string());
        }

        if self.performance.batch_config.max_operations_per_batch == 0 {
            errors.push("Maximum operations per batch must be greater than 0".to_string());
        }

        // Validate monitoring settings
        if self.monitoring.collection_interval.as_secs() == 0 {
            errors.push("Collection interval must be greater than 0".to_string());
        }

        // Validate security settings
        if self.security.rate_limiting.enabled
            && self.security.rate_limiting.max_requests_per_second == 0
        {
            errors.push(
                "Max requests per second must be greater than 0 when rate limiting is enabled"
                    .to_string(),
            );
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Get PLC-specific configuration
    pub fn get_plc_config(&self, plc_address: &str) -> Option<&PlcSpecificConfig> {
        self.plc_settings.get(plc_address)
    }

    /// Add or update PLC-specific configuration
    pub fn set_plc_config(&mut self, plc_address: String, config: PlcSpecificConfig) {
        self.plc_settings.insert(plc_address, config);
    }

    /// Create a development configuration
    pub fn development() -> Self {
        let mut config = Self::default();
        config.logging.level = LogLevel::Debug;
        config.monitoring.enabled = false;
        config.security.rate_limiting.enabled = false;
        config.performance.memory_limits.enable_monitoring = false;
        config
    }

    /// Create a production configuration
    pub fn production() -> Self {
        let mut config = Self::default();
        config.logging.level = LogLevel::Info;
        config.monitoring.enabled = true;
        config.security.rate_limiting.enabled = true;
        config.performance.memory_limits.enable_monitoring = true;
        config.performance.memory_limits.max_memory_mb = 500;
        config
    }
}