industrial_protocols_kernel/
connection.rs1use std::collections::HashMap;
13use std::io;
14use std::sync::Mutex;
15use std::time::Instant;
16
17pub trait Connection: Send {
18 fn send(&mut self, data: &[u8]) -> io::Result<Vec<u8>>;
19 fn close(&mut self) -> io::Result<()>;
20 fn is_alive(&self) -> bool;
21}
22
23pub type ConnectionFactory = Box<dyn Fn() -> io::Result<Box<dyn Connection>> + Send + Sync>;
24
25#[derive(Debug, Clone)]
26pub enum ConnectionStrategy {
27 Simple,
28 Persistent,
29 Pooled {
30 min: usize,
31 max: usize,
32 timeout_ms: u64,
33 },
34}
35
36struct ManagedConn {
37 conn: Box<dyn Connection>,
38}
39
40pub struct ConnectionManager {
41 strategy: ConnectionStrategy,
42 connections: Mutex<HashMap<String, ManagedConn>>,
43}
44
45pub struct HealthInfo {
46 pub connected: bool,
47 pub latency_ms: u64,
48}
49
50impl ConnectionManager {
51 pub fn new(strategy: ConnectionStrategy) -> Self {
52 ConnectionManager {
53 strategy,
54 connections: Mutex::new(HashMap::new()),
55 }
56 }
57
58 pub fn connect(&self, device_id: &str, factory: ConnectionFactory) -> io::Result<String> {
59 let mut conns = self.connections.lock().unwrap();
60 match self.strategy {
61 ConnectionStrategy::Simple => {
62 let mut conn = factory()?;
63 conn.close()?;
64 Ok(device_id.to_string())
65 }
66 ConnectionStrategy::Persistent | ConnectionStrategy::Pooled { .. } => {
67 if conns.contains_key(device_id) {
68 return Ok(device_id.to_string());
69 }
70 conns.insert(device_id.to_string(), ManagedConn { conn: factory()? });
71 Ok(device_id.to_string())
72 }
73 }
74 }
75
76 pub fn disconnect(&self, device_id: &str) -> io::Result<()> {
77 let mut conns = self.connections.lock().unwrap();
78 if let Some(mut m) = conns.remove(device_id) {
79 m.conn.close()
80 } else {
81 Ok(())
82 }
83 }
84
85 pub fn is_connected(&self, device_id: &str) -> bool {
86 self.connections
87 .lock()
88 .unwrap()
89 .get(device_id)
90 .map(|c| c.conn.is_alive())
91 .unwrap_or(false)
92 }
93
94 pub fn health(&self, device_id: &str) -> Option<HealthInfo> {
95 let mut conns = self.connections.lock().unwrap();
96 let managed = conns.get_mut(device_id)?;
97 let start = Instant::now();
98 let connected = managed.conn.is_alive();
99 Some(HealthInfo {
100 connected,
101 latency_ms: start.elapsed().as_millis() as u64,
102 })
103 }
104
105 pub fn send(&self, device_id: &str, data: &[u8]) -> io::Result<Vec<u8>> {
106 let mut conns = self.connections.lock().unwrap();
107 conns
108 .get_mut(device_id)
109 .ok_or_else(|| {
110 io::Error::new(
111 io::ErrorKind::NotFound,
112 format!("device not connected: {device_id}"),
113 )
114 })?
115 .conn
116 .send(data)
117 }
118
119 pub fn shutdown(&self) -> io::Result<()> {
120 for (_, mut m) in self.connections.lock().unwrap().drain() {
121 let _ = m.conn.close();
122 }
123 Ok(())
124 }
125}