oxirs_modbus/
config.rs

1use serde::{Deserialize, Serialize};
2use std::time::Duration;
3
4/// Modbus client configuration
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct ModbusConfig {
7    /// Protocol type (TCP or RTU)
8    pub protocol: ModbusProtocol,
9
10    /// TCP host address (TCP only)
11    pub host: Option<String>,
12
13    /// TCP port number (TCP only, default: 502)
14    pub port: Option<u16>,
15
16    /// Serial port path (RTU only)
17    pub serial_port: Option<String>,
18
19    /// Baud rate (RTU only, default: 9600)
20    pub baud_rate: Option<u32>,
21
22    /// Modbus unit ID (slave address)
23    pub unit_id: u8,
24
25    /// Polling interval (in seconds)
26    #[serde(default = "default_polling_interval")]
27    pub polling_interval_secs: u64,
28
29    /// Connection timeout (in seconds)
30    #[serde(default = "default_connection_timeout")]
31    pub connection_timeout_secs: u64,
32
33    /// Retry attempts on failure
34    pub retry_attempts: usize,
35}
36
37/// Modbus protocol type
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39pub enum ModbusProtocol {
40    /// Modbus TCP (port 502, Ethernet)
41    TCP,
42    /// Modbus RTU (serial RS-232/RS-485)
43    RTU,
44}
45
46fn default_polling_interval() -> u64 {
47    1
48}
49
50fn default_connection_timeout() -> u64 {
51    5
52}
53
54impl Default for ModbusConfig {
55    fn default() -> Self {
56        Self {
57            protocol: ModbusProtocol::TCP,
58            host: Some("127.0.0.1".to_string()),
59            port: Some(502),
60            serial_port: None,
61            baud_rate: None,
62            unit_id: 1,
63            polling_interval_secs: 1,
64            connection_timeout_secs: 5,
65            retry_attempts: 3,
66        }
67    }
68}
69
70impl ModbusConfig {
71    /// Get polling interval as Duration
72    pub fn polling_interval(&self) -> Duration {
73        Duration::from_secs(self.polling_interval_secs)
74    }
75
76    /// Get connection timeout as Duration
77    pub fn connection_timeout(&self) -> Duration {
78        Duration::from_secs(self.connection_timeout_secs)
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn test_default_config() {
88        let config = ModbusConfig::default();
89        assert_eq!(config.protocol, ModbusProtocol::TCP);
90        assert_eq!(config.port, Some(502));
91        assert_eq!(config.unit_id, 1);
92    }
93}