1use serde::{Deserialize, Serialize};
2use std::time::Duration;
3
4#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct ModbusConfig {
7 pub protocol: ModbusProtocol,
9
10 pub host: Option<String>,
12
13 pub port: Option<u16>,
15
16 pub serial_port: Option<String>,
18
19 pub baud_rate: Option<u32>,
21
22 pub unit_id: u8,
24
25 #[serde(default = "default_polling_interval")]
27 pub polling_interval_secs: u64,
28
29 #[serde(default = "default_connection_timeout")]
31 pub connection_timeout_secs: u64,
32
33 pub retry_attempts: usize,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39pub enum ModbusProtocol {
40 TCP,
42 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 pub fn polling_interval(&self) -> Duration {
73 Duration::from_secs(self.polling_interval_secs)
74 }
75
76 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}