Skip to main content

industrial_protocols_kernel/
event.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # 事件总线
3//!
4//! 发布/订阅模式的事件系统。内核内部和协议实现可通过事件总线通信,
5//! 无需直接耦合。
6//!
7//! ## 事件主题
8//!
9//! - **Connection** — 设备连接/断开、读写完成
10//! - **Error** — 协议错误、熔断触发
11//! - **Health** — 设备健康状态变更
12
13use std::sync::{Arc, Mutex};
14
15pub type EventHandler = Arc<dyn Fn(ProtocolEvent) + Send + Sync + 'static>;
16
17pub struct EventBus {
18    handlers: Arc<Mutex<Vec<(EventTopic, EventHandler)>>>,
19}
20
21impl EventBus {
22    pub fn new(_capacity: usize) -> Self {
23        EventBus {
24            handlers: Arc::new(Mutex::new(Vec::new())),
25        }
26    }
27
28    pub fn subscribe(
29        &self,
30        topic: EventTopic,
31        handler: impl Fn(ProtocolEvent) + Send + Sync + 'static,
32    ) {
33        self.handlers
34            .lock()
35            .unwrap()
36            .push((topic, Arc::new(handler)));
37    }
38
39    pub fn publish(&self, event: ProtocolEvent) {
40        let topic = event.topic();
41        // Clone the matching handlers before invoking them so a handler that
42        // subscribes or publishes again cannot deadlock on this mutex.
43        let handlers: Vec<EventHandler> = {
44            let handlers = self.handlers.lock().unwrap();
45            handlers
46                .iter()
47                .filter(|(t, _)| *t == topic)
48                .map(|(_, h)| Arc::clone(h))
49                .collect()
50        };
51        for handler in handlers {
52            handler(event.clone());
53        }
54    }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum EventTopic {
59    Connection,
60    Error,
61    Health,
62}
63
64#[derive(Debug, Clone)]
65pub enum HealthState {
66    Healthy,
67    Degraded,
68    Unhealthy,
69    Unknown,
70}
71
72#[derive(Debug, Clone)]
73pub enum Severity {
74    Info,
75    Warning,
76    Error,
77    Critical,
78}
79
80#[derive(Debug, Clone)]
81pub enum ProtocolEvent {
82    Connected {
83        device_id: String,
84        protocol: String,
85        timestamp: std::time::Instant,
86    },
87    Disconnected {
88        device_id: String,
89        reason: String,
90    },
91    ReadCompleted {
92        device_id: String,
93        address: String,
94        latency_ms: u64,
95    },
96    WriteCompleted {
97        device_id: String,
98        address: String,
99        latency_ms: u64,
100    },
101    Error {
102        device_id: String,
103        error: String,
104        severity: Severity,
105    },
106    HealthChanged {
107        device_id: String,
108        from: HealthState,
109        to: HealthState,
110    },
111    CircuitBreakerTriggered {
112        device_id: String,
113        failures: u32,
114    },
115}
116
117impl ProtocolEvent {
118    pub fn topic(&self) -> EventTopic {
119        match self {
120            ProtocolEvent::Connected { .. }
121            | ProtocolEvent::Disconnected { .. }
122            | ProtocolEvent::ReadCompleted { .. }
123            | ProtocolEvent::WriteCompleted { .. } => EventTopic::Connection,
124            ProtocolEvent::Error { .. } | ProtocolEvent::CircuitBreakerTriggered { .. } => {
125                EventTopic::Error
126            }
127            ProtocolEvent::HealthChanged { .. } => EventTopic::Health,
128        }
129    }
130}