Skip to main content

industrial_protocols_kernel/
gateway.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # 网关引擎
3//!
4//! 规则驱动的协议间数据转发引擎。通过后台线程周期性轮询,
5//! 将源设备的数据经变换后转发到目标设备。
6//!
7//! ## 转发规则
8//!
9//! 每条规则定义:
10//! - **source** — 源设备 + 地址(从哪读数据)
11//! - **target** — 目标设备 + 地址(写到哪去)
12//! - **transform** — 数据变换(透传 / 缩放 / 偏移 / 缩放+偏移)
13//!
14//! ## 适配器
15//!
16//! 协议通过实现 [`GatewayAdapter`] trait 来支持网关转发。
17//! 引擎负责调度和错误计数,适配器负责协议特定的读写逻辑。
18
19use crate::error::Result;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::{Arc, Mutex};
22use std::thread::{self, JoinHandle};
23use std::time::Duration;
24
25/// Adapter that protocols implement to support gateway forwarding.
26pub trait GatewayAdapter: Send + Sync {
27    /// Forward a value from source endpoint to target, applying the transform.
28    fn forward(
29        &self,
30        source_device: &str,
31        source_address: &str,
32        target_device: &str,
33        target_address: &str,
34        transform: &Transform,
35    ) -> Result<()>;
36}
37
38#[derive(Debug, Clone)]
39pub enum Transform {
40    Passthrough,
41    Scale(f64),
42    Offset(f64),
43    ScaleAndOffset { scale: f64, offset: f64 },
44}
45
46#[derive(Debug, Clone)]
47pub struct GatewayEndpoint {
48    pub device: String,
49    pub address: String,
50}
51
52#[derive(Debug, Clone)]
53pub struct GatewayRule {
54    pub name: String,
55    pub source: GatewayEndpoint,
56    pub target: GatewayEndpoint,
57    pub transform: Transform,
58}
59
60pub struct GatewayEngine {
61    rules: Vec<GatewayRule>,
62    interval_ms: u64,
63    adapters: Vec<Box<dyn GatewayAdapter>>,
64    running: Arc<AtomicBool>,
65    handle: Mutex<Option<JoinHandle<()>>>,
66    error_count: Arc<Mutex<u64>>,
67}
68
69impl GatewayEngine {
70    pub fn new(interval_ms: u64) -> Self {
71        GatewayEngine {
72            rules: Vec::new(),
73            interval_ms,
74            adapters: Vec::new(),
75            running: Arc::new(AtomicBool::new(false)),
76            handle: Mutex::new(None),
77            error_count: Arc::new(Mutex::new(0)),
78        }
79    }
80
81    pub fn add_rule(&mut self, rule: GatewayRule) {
82        self.rules.push(rule);
83    }
84
85    pub fn add_adapter(&mut self, adapter: Box<dyn GatewayAdapter>) {
86        self.adapters.push(adapter);
87    }
88
89    pub fn rule_count(&self) -> usize {
90        self.rules.len()
91    }
92
93    pub fn error_count(&self) -> u64 {
94        *self.error_count.lock().unwrap()
95    }
96
97    pub fn is_running(&self) -> bool {
98        self.running.load(Ordering::SeqCst)
99    }
100
101    /// Start the gateway polling loop on a background thread.
102    pub fn start(&mut self) {
103        if self.running.swap(true, Ordering::SeqCst) {
104            return; // already running
105        }
106
107        let running = self.running.clone();
108        let error_count = self.error_count.clone();
109        let rules: Vec<_> = self.rules.clone();
110        let adapters: Vec<Arc<dyn GatewayAdapter>> = std::mem::take(&mut self.adapters)
111            .into_iter()
112            .map(Arc::from)
113            .collect();
114        let interval = Duration::from_millis(self.interval_ms);
115
116        let handle = thread::spawn(move || {
117            while running.load(Ordering::SeqCst) {
118                for rule in &rules {
119                    for adapter in &adapters {
120                        if let Err(_e) = adapter.forward(
121                            &rule.source.device,
122                            &rule.source.address,
123                            &rule.target.device,
124                            &rule.target.address,
125                            &rule.transform,
126                        ) {
127                            *error_count.lock().unwrap() += 1;
128                        }
129                    }
130                }
131                thread::sleep(interval);
132            }
133        });
134
135        *self.handle.lock().unwrap() = Some(handle);
136    }
137
138    /// Stop the gateway polling loop.
139    pub fn stop(&mut self) {
140        self.running.store(false, Ordering::SeqCst);
141        if let Some(handle) = self.handle.lock().unwrap().take() {
142            let _ = handle.join();
143        }
144    }
145}
146
147impl Drop for GatewayEngine {
148    fn drop(&mut self) {
149        self.stop();
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use std::sync::atomic::AtomicU32;
157
158    struct TestAdapter {
159        call_count: Arc<AtomicU32>,
160    }
161
162    impl TestAdapter {
163        fn new() -> (Self, Arc<AtomicU32>) {
164            let count = Arc::new(AtomicU32::new(0));
165            (
166                TestAdapter {
167                    call_count: count.clone(),
168                },
169                count,
170            )
171        }
172    }
173
174    impl GatewayAdapter for TestAdapter {
175        fn forward(
176            &self,
177            src_dev: &str,
178            _src_addr: &str,
179            tgt_dev: &str,
180            _tgt_addr: &str,
181            _transform: &Transform,
182        ) -> Result<()> {
183            // Verify endpoints are passed correctly
184            assert_eq!(src_dev, "plc-001");
185            assert_eq!(tgt_dev, "mqtt-broker");
186            self.call_count.fetch_add(1, Ordering::SeqCst);
187            Ok(())
188        }
189    }
190
191    #[test]
192    fn test_add_rule() {
193        let mut engine = GatewayEngine::new(1000);
194        engine.add_rule(GatewayRule {
195            name: "test".into(),
196            source: GatewayEndpoint {
197                device: "plc-001".into(),
198                address: "40001".into(),
199            },
200            target: GatewayEndpoint {
201                device: "mqtt".into(),
202                address: "topic/plc".into(),
203            },
204            transform: Transform::Passthrough,
205        });
206        assert_eq!(engine.rule_count(), 1);
207    }
208
209    #[test]
210    fn test_start_stop() {
211        let mut engine = GatewayEngine::new(10);
212        engine.add_rule(GatewayRule {
213            name: "t".into(),
214            source: GatewayEndpoint {
215                device: "plc-001".into(),
216                address: "40001".into(),
217            },
218            target: GatewayEndpoint {
219                device: "mqtt-broker".into(),
220                address: "t".into(),
221            },
222            transform: Transform::Passthrough,
223        });
224
225        let (adapter, count) = TestAdapter::new();
226        engine.add_adapter(Box::new(adapter));
227        engine.start();
228
229        // Wait for a few poll cycles
230        thread::sleep(Duration::from_millis(50));
231        engine.stop();
232
233        assert!(count.load(Ordering::SeqCst) > 0);
234        assert!(!engine.is_running());
235    }
236
237    #[test]
238    fn test_double_start_noop() {
239        let mut engine = GatewayEngine::new(100);
240        engine.add_rule(GatewayRule {
241            name: "t".into(),
242            source: GatewayEndpoint {
243                device: "plc-001".into(),
244                address: "40001".into(),
245            },
246            target: GatewayEndpoint {
247                device: "mqtt-broker".into(),
248                address: "t".into(),
249            },
250            transform: Transform::Passthrough,
251        });
252
253        let (adapter, _count) = TestAdapter::new();
254        engine.add_adapter(Box::new(adapter));
255        engine.start();
256        engine.start(); // second start should be noop
257        engine.stop();
258        assert!(!engine.is_running());
259    }
260
261    #[test]
262    fn test_scale_transform() {
263        let t = Transform::Scale(2.5);
264        assert!(matches!(t, Transform::Scale(2.5)));
265    }
266
267    #[test]
268    fn test_offset_transform() {
269        let t = Transform::Offset(-10.0);
270        assert!(matches!(t, Transform::Offset(-10.0)));
271    }
272
273    #[test]
274    fn test_scale_and_offset_transform() {
275        let t = Transform::ScaleAndOffset {
276            scale: 1.8,
277            offset: 32.0,
278        };
279        assert!(matches!(
280            t,
281            Transform::ScaleAndOffset {
282                scale: 1.8,
283                offset: 32.0
284            }
285        ));
286    }
287}