|
| 1 | +use crate::api::{ConnCfg, Event, Message}; |
| 2 | +use msr_plugin::MessageLoop; |
| 3 | +use tokio::sync::{broadcast, mpsc}; |
| 4 | + |
| 5 | +#[derive(Default)] |
| 6 | +pub struct Context { |
| 7 | + conn: Connection, |
| 8 | +} |
| 9 | + |
| 10 | +enum Connection { |
| 11 | + Disconnected, |
| 12 | + Connecting, |
| 13 | + Connected(tokio_modbus::client::Context), |
| 14 | +} |
| 15 | + |
| 16 | +impl Default for Connection { |
| 17 | + fn default() -> Self { |
| 18 | + Self::Disconnected |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +pub fn create_message_loop( |
| 23 | + event_tx: broadcast::Sender<Event>, |
| 24 | +) -> (MessageLoop, mpsc::UnboundedSender<Message>) { |
| 25 | + let mut ctx = Context::default(); |
| 26 | + let (message_tx, mut message_rx) = mpsc::unbounded_channel(); |
| 27 | + let message_loop = async move { |
| 28 | + log::debug!("Entering modbus plugin message loop"); |
| 29 | + loop { |
| 30 | + tokio::select! { |
| 31 | + next_msg = message_rx.recv() => { |
| 32 | + if let Some(msg) = next_msg { |
| 33 | + log::debug!("Received message: {:?}", msg); |
| 34 | + match msg { |
| 35 | + Message::Connect(cfg) => { |
| 36 | + match cfg { |
| 37 | + ConnCfg::Tcp(addr) => { |
| 38 | + ctx.conn = Connection::Connecting; |
| 39 | + // TODO send event |
| 40 | + match tokio_modbus::client::tcp::connect(addr).await { |
| 41 | + Ok(mb_ctx) => { |
| 42 | + ctx.conn = Connection::Connected(mb_ctx); |
| 43 | + // TODO send event |
| 44 | + } |
| 45 | + Err(err) => { |
| 46 | + let ev = Event::ConnectionError(err.to_string()); |
| 47 | + if let Err(ev) = event_tx.send(ev) { |
| 48 | + log::debug!("No subscribers, dropping event: {:?}", ev); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + Message::Shutdown => { |
| 56 | + break; |
| 57 | + } |
| 58 | + } |
| 59 | + } else { |
| 60 | + log::debug!("All message senders have been dropped"); |
| 61 | + break; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + log::debug!("Exiting modbus plugin message loop"); |
| 67 | + }; |
| 68 | + (Box::pin(message_loop), message_tx) |
| 69 | +} |
0 commit comments