Skip to main content

industrial_protocols_kernel/
config.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # 配置管理
3//!
4//! 通过 TOML 文件加载设备配置,支持运行时覆盖。
5//!
6//! ## 配置格式
7//!
8//! ```toml
9//! [devices.plc-001]
10//! protocol = "modbus"
11//! variant = "tcp"
12//! host = "192.168.1.10"
13//! port = 502
14//! unit_id = 1
15//! timeout_ms = 3000
16//! retry = { max = 3, strategy = "exponential", base_ms = 100, max_ms = 5000 }
17//! connection_strategy = "persistent"
18//! ```
19//!
20//! 协议特定字段(如 BACnet 的 `device_instance`)通过 `#[serde(flatten)]` 捕获到 `extras` 中。
21
22use serde::Deserialize;
23use std::collections::HashMap;
24use std::fs;
25use std::path::Path;
26
27fn default_defaults() -> DefaultsConfig {
28    DefaultsConfig {
29        timeout_ms: default_timeout(),
30        retry_max: default_retry_max(),
31        retry_strategy: default_retry_strategy(),
32        health_check_interval_s: default_health_interval(),
33        circuit_breaker_threshold: default_cb_threshold(),
34        circuit_breaker_cooldown_s: default_cb_cooldown(),
35    }
36}
37
38#[derive(Debug, Clone, Deserialize)]
39pub struct ConfigFile {
40    #[serde(default)]
41    pub devices: HashMap<String, DeviceConfigRaw>,
42    #[serde(default = "default_defaults")]
43    pub defaults: DefaultsConfig,
44}
45
46#[derive(Debug, Clone, Deserialize)]
47pub struct DeviceConfigRaw {
48    pub protocol: String,
49    #[serde(default)]
50    pub variant: String,
51    pub host: Option<String>,
52    pub port: Option<u16>,
53    pub serial_port: Option<String>,
54    pub baud_rate: Option<u32>,
55    pub timeout_ms: Option<u64>,
56    pub unit_id: Option<u16>,
57    pub retry: Option<RetryConfigRaw>,
58    pub connection_strategy: Option<ConnectionStrategyConfig>,
59    pub health_check: Option<bool>,
60    #[serde(flatten)]
61    pub extras: HashMap<String, toml::Value>,
62}
63
64#[derive(Debug, Clone, Deserialize)]
65pub struct RetryConfigRaw {
66    pub max: u32,
67    pub strategy: String,
68    #[serde(default)]
69    pub base_ms: u64,
70    #[serde(default)]
71    pub max_ms: u64,
72    #[serde(default)]
73    pub step_ms: u64,
74}
75
76#[derive(Debug, Clone, Deserialize, PartialEq)]
77#[serde(rename_all = "snake_case")]
78pub enum ConnectionStrategyConfig {
79    Simple,
80    Persistent,
81    Pooled {
82        min: usize,
83        max: usize,
84        timeout_ms: u64,
85    },
86}
87
88#[derive(Debug, Clone, Deserialize, Default)]
89pub struct DefaultsConfig {
90    #[serde(default = "default_timeout")]
91    pub timeout_ms: u64,
92    #[serde(default = "default_retry_max")]
93    pub retry_max: u32,
94    #[serde(default = "default_retry_strategy")]
95    pub retry_strategy: String,
96    #[serde(default = "default_health_interval")]
97    pub health_check_interval_s: u64,
98    #[serde(default = "default_cb_threshold")]
99    pub circuit_breaker_threshold: u32,
100    #[serde(default = "default_cb_cooldown")]
101    pub circuit_breaker_cooldown_s: u64,
102}
103
104fn default_timeout() -> u64 {
105    5000
106}
107fn default_retry_max() -> u32 {
108    3
109}
110fn default_retry_strategy() -> String {
111    "exponential".into()
112}
113fn default_health_interval() -> u64 {
114    30
115}
116fn default_cb_threshold() -> u32 {
117    5
118}
119fn default_cb_cooldown() -> u64 {
120    30
121}
122
123#[derive(Debug, Clone)]
124pub struct DeviceConfig {
125    pub protocol: String,
126    pub variant: String,
127    pub host: Option<String>,
128    pub port: Option<u16>,
129    pub serial_port: Option<String>,
130    pub baud_rate: Option<u32>,
131    pub timeout_ms: u64,
132    pub unit_id: u16,
133    pub retry: RetryConfigResolved,
134    pub connection_strategy: ConnectionStrategyConfig,
135    pub health_check: bool,
136    pub extras: HashMap<String, toml::Value>,
137}
138
139#[derive(Debug, Clone)]
140pub struct RetryConfigResolved {
141    pub max: u32,
142    pub strategy: String,
143    pub base_ms: u64,
144    pub max_ms: u64,
145    pub step_ms: u64,
146}
147
148pub struct ConfigRepository {
149    raw: ConfigFile,
150    overrides: HashMap<String, HashMap<String, toml::Value>>,
151}
152
153impl ConfigRepository {
154    pub fn load(path: impl AsRef<Path>) -> std::io::Result<Self> {
155        let content = fs::read_to_string(path)?;
156        let raw: ConfigFile = toml::from_str(&content)
157            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
158        Ok(ConfigRepository {
159            raw,
160            overrides: HashMap::new(),
161        })
162    }
163
164    pub fn parse(toml_str: &str) -> std::io::Result<Self> {
165        let raw: ConfigFile = toml::from_str(toml_str)
166            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
167        Ok(ConfigRepository {
168            raw,
169            overrides: HashMap::new(),
170        })
171    }
172
173    pub fn get_device(&self, id: &str) -> Option<DeviceConfig> {
174        let raw = self.raw.devices.get(id)?;
175        let overrides = self.overrides.get(id);
176        let timeout_ms = overrides
177            .and_then(|o| o.get("timeout_ms"))
178            .and_then(|v| v.as_integer())
179            .map(|v| v as u64)
180            .unwrap_or(raw.timeout_ms.unwrap_or(self.raw.defaults.timeout_ms));
181        let retry = raw.retry.clone().unwrap_or(RetryConfigRaw {
182            max: self.raw.defaults.retry_max,
183            strategy: self.raw.defaults.retry_strategy.clone(),
184            base_ms: 100,
185            max_ms: 5000,
186            step_ms: 50,
187        });
188        Some(DeviceConfig {
189            protocol: raw.protocol.clone(),
190            variant: raw.variant.clone(),
191            host: raw.host.clone(),
192            port: raw.port,
193            serial_port: raw.serial_port.clone(),
194            baud_rate: raw.baud_rate,
195            timeout_ms,
196            unit_id: overrides
197                .and_then(|o| o.get("unit_id"))
198                .and_then(|v| v.as_integer())
199                .map(|v| v as u16)
200                .unwrap_or(raw.unit_id.unwrap_or(1)),
201            retry: RetryConfigResolved {
202                max: retry.max,
203                strategy: retry.strategy,
204                base_ms: retry.base_ms,
205                max_ms: retry.max_ms,
206                step_ms: retry.step_ms,
207            },
208            connection_strategy: raw
209                .connection_strategy
210                .clone()
211                .unwrap_or(ConnectionStrategyConfig::Persistent),
212            health_check: raw.health_check.unwrap_or(true),
213            extras: raw.extras.clone(),
214        })
215    }
216
217    pub fn device_ids(&self) -> Vec<String> {
218        self.raw.devices.keys().cloned().collect()
219    }
220    pub fn defaults(&self) -> &DefaultsConfig {
221        &self.raw.defaults
222    }
223
224    pub fn set_override(&mut self, device_id: &str, key: &str, value: toml::Value) {
225        self.overrides
226            .entry(device_id.to_string())
227            .or_default()
228            .insert(key.to_string(), value);
229    }
230
231    pub fn clear_overrides(&mut self, device_id: &str) {
232        self.overrides.remove(device_id);
233    }
234}