industrial_protocols_async_layer/
lib.rs1use industrial_protocols_kernel::Kernel;
29use industrial_protocols_kernel::connection::Connection;
30use industrial_protocols_kernel::error::Result;
31use industrial_protocols_kernel::sdk::{ProtocolRead, ProtocolWrite};
32use std::sync::Arc;
33use tokio::sync::Mutex;
34
35pub struct AsyncKernel {
36 kernel: Arc<Mutex<Kernel>>,
37}
38
39impl AsyncKernel {
40 pub fn new(kernel: Kernel) -> Self {
41 AsyncKernel {
42 kernel: Arc::new(Mutex::new(kernel)),
43 }
44 }
45
46 pub async fn boot(&self) -> std::io::Result<()> {
47 let mut k = self.kernel.lock().await;
48 k.boot()
49 }
50
51 pub async fn shutdown(&self) -> std::io::Result<()> {
52 let mut k = self.kernel.lock().await;
53 k.shutdown()
54 }
55
56 pub async fn read<P: ProtocolRead + ?Sized>(
57 &self,
58 protocol: &P,
59 conn: &mut (dyn Connection + Send),
60 addr: &P::Address,
61 ) -> Result<P::Value> {
62 protocol.read(conn, addr)
63 }
64
65 pub async fn write<P: ProtocolWrite + ?Sized>(
66 &self,
67 protocol: &P,
68 conn: &mut (dyn Connection + Send),
69 addr: &P::Address,
70 value: &P::Value,
71 ) -> Result<()> {
72 protocol.write(conn, addr, value)
73 }
74
75 pub fn kernel(&self) -> &Arc<Mutex<Kernel>> {
76 &self.kernel
77 }
78}
79
80pub struct AsyncEventStream {
81 receiver: tokio::sync::mpsc::Receiver<industrial_protocols_kernel::event::ProtocolEvent>,
82}
83
84impl AsyncEventStream {
85 pub fn from_channel(
86 receiver: tokio::sync::mpsc::Receiver<industrial_protocols_kernel::event::ProtocolEvent>,
87 ) -> Self {
88 AsyncEventStream { receiver }
89 }
90
91 pub fn subscribe(
92 kernel: &Kernel,
93 topic: industrial_protocols_kernel::event::EventTopic,
94 ) -> Self {
95 let (tx, rx) = tokio::sync::mpsc::channel(1024);
98 kernel.event_bus().subscribe(topic, move |event| {
99 let _ = tx.try_send(event);
100 });
101 AsyncEventStream { receiver: rx }
102 }
103
104 pub async fn recv(&mut self) -> Option<industrial_protocols_kernel::event::ProtocolEvent> {
105 self.receiver.recv().await
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112 use industrial_protocols_kernel::connection::Connection;
113 use industrial_protocols_kernel::event::{EventTopic, ProtocolEvent};
114 use industrial_protocols_kernel::sdk::*;
115 use std::io;
116
117 struct TestProtocol;
118 impl Protocol for TestProtocol {
119 fn name(&self) -> &'static str {
120 "test"
121 }
122 fn version(&self) -> &'static str {
123 "1.0"
124 }
125 fn category(&self) -> ProtocolCategory {
126 ProtocolCategory::IndustrialEthernet
127 }
128 fn supported_variants(&self) -> &'static [&'static str] {
129 &["tcp"]
130 }
131 }
132 impl ProtocolRead for TestProtocol {
133 type Address = u16;
134 type Value = u16;
135 fn read(&self, _c: &mut dyn Connection, a: &Self::Address) -> Result<Self::Value> {
136 Ok(*a * 2)
137 }
138 fn read_batch(
139 &self,
140 _c: &mut dyn Connection,
141 a: &[Self::Address],
142 ) -> Result<Vec<Self::Value>> {
143 Ok(a.iter().map(|x| x * 2).collect())
144 }
145 fn read_range(
146 &self,
147 _c: &mut dyn Connection,
148 s: &Self::Address,
149 n: u16,
150 ) -> Result<Vec<Self::Value>> {
151 Ok((*s..*s + n).map(|x| x * 2).collect())
152 }
153 }
154
155 struct TestConn;
156 impl Connection for TestConn {
157 fn send(&mut self, _: &[u8]) -> io::Result<Vec<u8>> {
158 Ok(vec![42])
159 }
160 fn close(&mut self) -> io::Result<()> {
161 Ok(())
162 }
163 fn is_alive(&self) -> bool {
164 true
165 }
166 }
167
168 struct TestWriteProtocol;
169 impl Protocol for TestWriteProtocol {
170 fn name(&self) -> &'static str {
171 "write-test"
172 }
173 fn version(&self) -> &'static str {
174 "1.0"
175 }
176 fn category(&self) -> ProtocolCategory {
177 ProtocolCategory::IndustrialEthernet
178 }
179 fn supported_variants(&self) -> &'static [&'static str] {
180 &["tcp"]
181 }
182 }
183 impl ProtocolWrite for TestWriteProtocol {
184 type Address = u16;
185 type Value = u16;
186 fn write(
187 &self,
188 _c: &mut dyn Connection,
189 addr: &Self::Address,
190 value: &Self::Value,
191 ) -> Result<()> {
192 assert_eq!(*addr, 1);
193 assert_eq!(*value, 42);
194 Ok(())
195 }
196 fn write_batch(
197 &self,
198 _c: &mut dyn Connection,
199 _items: &[(Self::Address, Self::Value)],
200 ) -> Result<()> {
201 Ok(())
202 }
203 }
204
205 #[tokio::test]
206 async fn test_async_read() {
207 let kernel = Kernel::builder()
208 .with_protocol(Box::new(TestProtocol))
209 .build();
210 let ak = AsyncKernel::new(kernel);
211 let mut conn = TestConn;
212 let val = ak.read(&TestProtocol, &mut conn, &21).await.unwrap();
213 assert_eq!(val, 42);
214 }
215
216 #[tokio::test]
217 async fn test_async_boot_shutdown() {
218 let kernel = Kernel::builder()
219 .with_protocol(Box::new(TestProtocol))
220 .build();
221 let ak = AsyncKernel::new(kernel);
222 assert!(ak.boot().await.is_ok());
223 assert!(ak.shutdown().await.is_ok());
224 }
225
226 #[tokio::test]
227 async fn test_event_stream() {
228 let kernel = Kernel::builder()
230 .with_protocol(Box::new(TestProtocol))
231 .build();
232
233 let mut stream = AsyncEventStream::subscribe(
234 &kernel,
235 industrial_protocols_kernel::event::EventTopic::Connection,
236 );
237
238 kernel.event_bus().publish(
240 industrial_protocols_kernel::event::ProtocolEvent::Connected {
241 device_id: "test".into(),
242 protocol: "test".into(),
243 timestamp: std::time::Instant::now(),
244 },
245 );
246
247 let event = stream.recv().await;
248 assert!(event.is_some());
249 }
250
251 #[tokio::test]
252 async fn test_async_write() {
253 let kernel = Kernel::builder().build();
254 let ak = AsyncKernel::new(kernel);
255 let mut conn = TestConn;
256 ak.write(&TestWriteProtocol, &mut conn, &1, &42)
257 .await
258 .unwrap();
259 }
260
261 #[tokio::test]
262 async fn test_async_kernel_accessor() {
263 let kernel = Kernel::builder()
264 .with_protocol(Box::new(TestProtocol))
265 .build();
266 let ak = AsyncKernel::new(kernel);
267 let guard = ak.kernel().lock().await;
268 assert!(guard.protocol_registry().get("test").is_some());
269 }
270
271 #[tokio::test]
272 async fn test_async_shutdown_idempotent() {
273 let kernel = Kernel::builder().build();
274 let ak = AsyncKernel::new(kernel);
275 assert!(ak.boot().await.is_ok());
276 assert!(ak.shutdown().await.is_ok());
277 assert!(ak.shutdown().await.is_ok());
278 }
279
280 #[tokio::test]
281 async fn test_event_stream_from_channel() {
282 let (tx, rx) = tokio::sync::mpsc::channel(8);
283 let mut stream = AsyncEventStream::from_channel(rx);
284 tx.send(ProtocolEvent::Disconnected {
285 device_id: "d".into(),
286 reason: "gone".into(),
287 })
288 .await
289 .unwrap();
290 let event = stream.recv().await.unwrap();
291 assert!(matches!(
292 event,
293 ProtocolEvent::Disconnected { device_id, .. } if device_id == "d"
294 ));
295 }
296
297 #[tokio::test]
298 async fn test_event_stream_recv_none_when_channel_closed() {
299 let (tx, rx) = tokio::sync::mpsc::channel(1);
300 drop(tx);
301 let mut stream = AsyncEventStream::from_channel(rx);
302 assert!(stream.recv().await.is_none());
303 }
304
305 #[tokio::test]
306 async fn test_event_stream_multiple_events_in_order() {
307 let kernel = Kernel::builder().build();
308 let mut stream = AsyncEventStream::subscribe(&kernel, EventTopic::Connection);
309 kernel.event_bus().publish(ProtocolEvent::Connected {
310 device_id: "a".into(),
311 protocol: "p".into(),
312 timestamp: std::time::Instant::now(),
313 });
314 kernel.event_bus().publish(ProtocolEvent::Connected {
315 device_id: "b".into(),
316 protocol: "p".into(),
317 timestamp: std::time::Instant::now(),
318 });
319 let first = stream.recv().await.unwrap();
320 let second = stream.recv().await.unwrap();
321 assert!(matches!(
322 first,
323 ProtocolEvent::Connected { device_id, .. } if device_id == "a"
324 ));
325 assert!(matches!(
326 second,
327 ProtocolEvent::Connected { device_id, .. } if device_id == "b"
328 ));
329 }
330}