mbus_async/runtime/
network_client.rs1use std::ops::Deref;
9use super::*;
10
11pub struct AsyncTcpClient<const N: usize = 9> {
20 core: AsyncClientCore,
21}
22
23impl<const N: usize> Deref for AsyncTcpClient<N> {
24 type Target = AsyncClientCore;
25
26 fn deref(&self) -> &Self::Target {
27 &self.core
28 }
29}
30
31impl AsyncTcpClient<9> {
34 #[cfg(feature = "tcp")]
38 pub fn connect(host: &str, port: u16) -> Result<Self, AsyncError> {
39 Self::connect_with_pipeline(host, port)
40 }
41
42 #[cfg(feature = "tcp")]
47 pub fn connect_with_poll_interval(
48 host: &str,
49 port: u16,
50 poll_interval: Duration,
51 ) -> Result<Self, AsyncError> {
52 Self::connect_with_pipeline_and_poll_interval(host, port, poll_interval)
53 }
54}
55
56impl<const N: usize> AsyncTcpClient<N> {
59 #[cfg(feature = "tcp")]
63 pub fn connect_with_pipeline(host: &str, port: u16) -> Result<Self, AsyncError> {
64 let transport = StdTcpTransport::new();
65 let config = ModbusConfig::Tcp(ModbusTcpConfig::new(host, port)?);
66 Self::from_transport_config(transport, config, Duration::from_millis(20))
67 }
68
69 #[cfg(feature = "tcp")]
72 pub fn connect_with_pipeline_and_poll_interval(
73 host: &str,
74 port: u16,
75 poll_interval: Duration,
76 ) -> Result<Self, AsyncError> {
77 let transport = StdTcpTransport::new();
78 let config = ModbusConfig::Tcp(ModbusTcpConfig::new(host, port)?);
79 Self::from_transport_config(transport, config, poll_interval)
80 }
81
82 #[cfg(feature = "tcp")]
86 fn from_transport_config(
87 transport: StdTcpTransport,
88 config: ModbusConfig,
89 poll_interval: Duration,
90 ) -> Result<Self, AsyncError> {
91 let pending = Arc::new(Mutex::new(HashMap::new()));
92 let app = AsyncApp {
93 pending: pending.clone(),
94 };
95
96 let client = ClientServices::<_, _, N>::new(transport, app, config)?;
97 let (sender, receiver) = mpsc::channel();
98
99 thread::spawn(move || run_worker(client, pending, receiver, poll_interval));
100
101 Ok(Self {
102 core: AsyncClientCore::new(sender),
103 })
104 }
105}