Skip to main content

industrial_protocols_kernel/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # Industrial Protocols Kernel
3//!
4//! 工业通信协议集的微内核。内核只定义「协议是什么」(通过 6 个 SDK trait),
5//! 不包含任何具体协议实现。
6//!
7//! ## 核心组件
8//!
9//! - [`ProtocolRegistry`] — 协议注册表,按名称或分类查找协议
10//! - [`ConnectionManager`] — 设备连接管理器,支持 3 种连接策略
11//! - [`ConfigRepository`] — TOML 配置加载与运行时覆盖
12//! - [`EventBus`] — 事件发布/订阅总线
13//! - [`CircuitBreaker`] — 熔断保护器
14//! - [`RetryConfig`] — 重试配置(固定/指数/线性/无)
15//! - [`GatewayEngine`] — 协议间数据转发引擎
16//!
17//! ## 使用示例
18//!
19//! ```rust,ignore
20//! use industrial_protocols_kernel::*;
21//! use industrial_protocols_kernel::sdk::*;
22//!
23//! let mut kernel = Kernel::builder()
24//!     .config_from_str(r#"
25//!         [devices.plc-001]
26//!         protocol = "modbus"
27//!         host = "192.168.1.10"
28//!         port = 502
29//!     "#)
30//!     .with_protocol(Box::new(MyProtocol))
31//!     .build();
32//!
33//! kernel.boot()?;
34//! // ... 使用协议读写设备 ...
35//! kernel.shutdown()?;
36//! ```
37
38pub mod bridge;
39pub mod circuit;
40pub mod config;
41pub mod connection;
42pub mod error;
43pub mod event;
44pub mod gateway;
45pub mod registry;
46pub mod retry;
47pub mod sdk;
48
49use config::ConfigRepository;
50use connection::{ConnectionManager, ConnectionStrategy};
51use event::EventBus;
52use gateway::GatewayEngine;
53use registry::ProtocolRegistry;
54use sdk::Protocol;
55use std::io;
56
57/// 内核结构体,是工业协议应用的入口点。
58///
59/// 通过 [`KernelBuilder`] 构建,使用 Builder 模式配置协议、连接策略等参数,
60/// 然后调用 [`boot`](Kernel::boot) 启动,使用完毕后调用 [`shutdown`](Kernel::shutdown) 关闭。
61pub struct Kernel {
62    registry: ProtocolRegistry,
63    conn_manager: ConnectionManager,
64    config: Option<ConfigRepository>,
65    config_error: Option<String>,
66    events: EventBus,
67    gateway: GatewayEngine,
68}
69
70impl Kernel {
71    /// 创建内核构建器。
72    pub fn builder() -> KernelBuilder {
73        KernelBuilder::new()
74    }
75
76    /// 启动内核,校验所有配置文件中的设备均有对应协议注册。
77    pub fn boot(&mut self) -> io::Result<()> {
78        if let Some(ref err) = self.config_error {
79            return Err(io::Error::new(io::ErrorKind::InvalidData, err.clone()));
80        }
81        if let Some(ref config) = self.config {
82            for device_id in config.device_ids() {
83                let dev = config.get_device(&device_id).unwrap();
84                if self.registry.get(&dev.protocol).is_none() {
85                    return Err(io::Error::new(
86                        io::ErrorKind::NotFound,
87                        format!(
88                            "protocol '{}' not registered (needed by device '{device_id}')",
89                            dev.protocol
90                        ),
91                    ));
92                }
93            }
94        }
95        Ok(())
96    }
97
98    /// 关闭内核,断开所有设备连接并停止网关引擎。
99    pub fn shutdown(&mut self) -> io::Result<()> {
100        self.gateway.stop();
101        self.conn_manager.shutdown()
102    }
103
104    /// 获取协议注册表的只读引用。
105    pub fn protocol_registry(&self) -> &ProtocolRegistry {
106        &self.registry
107    }
108
109    /// 获取连接管理器的只读引用。
110    pub fn connection_manager(&self) -> &ConnectionManager {
111        &self.conn_manager
112    }
113
114    /// 获取配置仓库的只读引用。
115    ///
116    /// # Panics
117    /// 如果未通过 builder 加载配置(即 `config_from_str` 或 `config_from_file` 未被调用)。
118    pub fn config(&self) -> &ConfigRepository {
119        self.config.as_ref().expect("config not loaded")
120    }
121
122    /// 获取事件总线的只读引用。
123    pub fn event_bus(&self) -> &EventBus {
124        &self.events
125    }
126
127    /// 获取网关引擎的只读引用。
128    pub fn gateway(&self) -> &GatewayEngine {
129        &self.gateway
130    }
131
132    /// 获取网关引擎的可变引用。
133    pub fn gateway_mut(&mut self) -> &mut GatewayEngine {
134        &mut self.gateway
135    }
136}
137
138/// 内核构建器,使用 Builder 模式配置内核参数。
139///
140/// # 示例
141///
142/// ```rust,ignore
143/// let kernel = Kernel::builder()
144///     .config_from_str(toml_str)
145///     .with_protocol(Box::new(protocol))
146///     .with_connection_strategy(ConnectionStrategy::Persistent)
147///     .build();
148/// ```
149pub struct KernelBuilder {
150    config: Option<ConfigRepository>,
151    config_error: Option<String>,
152    protocols: Vec<Box<dyn Protocol>>,
153    connection_strategy: ConnectionStrategy,
154    event_capacity: usize,
155    gateway_interval_ms: u64,
156}
157
158impl KernelBuilder {
159    fn new() -> Self {
160        KernelBuilder {
161            config: None,
162            config_error: None,
163            protocols: Vec::new(),
164            connection_strategy: ConnectionStrategy::Persistent,
165            event_capacity: 64,
166            gateway_interval_ms: 100,
167        }
168    }
169
170    /// 从 TOML 字符串加载设备配置。
171    ///
172    /// 配置解析错误会保存到内核,并由 [`Kernel::boot`] 返回。
173    pub fn config_from_str(mut self, toml_str: &str) -> Self {
174        match ConfigRepository::parse(toml_str) {
175            Ok(config) => self.config = Some(config),
176            Err(e) => self.config_error = Some(format!("invalid TOML config: {e}")),
177        }
178        self
179    }
180
181    /// 从 TOML 文件加载设备配置。
182    ///
183    /// 配置加载错误会保存到内核,并由 [`Kernel::boot`] 返回。
184    pub fn config_from_file(mut self, path: impl AsRef<std::path::Path>) -> Self {
185        match ConfigRepository::load(path) {
186            Ok(config) => self.config = Some(config),
187            Err(e) => self.config_error = Some(format!("failed to load config file: {e}")),
188        }
189        self
190    }
191
192    /// 注册一个协议实例。
193    pub fn with_protocol(mut self, protocol: Box<dyn Protocol>) -> Self {
194        self.protocols.push(protocol);
195        self
196    }
197
198    /// 设置设备连接策略。
199    pub fn with_connection_strategy(mut self, strategy: ConnectionStrategy) -> Self {
200        self.connection_strategy = strategy;
201        self
202    }
203
204    /// 设置事件总线通道缓冲区大小。
205    pub fn with_event_capacity(mut self, cap: usize) -> Self {
206        self.event_capacity = cap;
207        self
208    }
209
210    /// 设置网关引擎的轮询间隔(毫秒)。
211    pub fn with_gateway_interval(mut self, ms: u64) -> Self {
212        self.gateway_interval_ms = ms;
213        self
214    }
215
216    /// 构建内核实例。
217    pub fn build(self) -> Kernel {
218        let mut registry = ProtocolRegistry::new();
219        for p in self.protocols {
220            registry.register(p);
221        }
222        Kernel {
223            registry,
224            conn_manager: ConnectionManager::new(self.connection_strategy),
225            config: self.config,
226            config_error: self.config_error,
227            events: EventBus::new(self.event_capacity),
228            gateway: GatewayEngine::new(self.gateway_interval_ms),
229        }
230    }
231}