1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use futures_time::future::FutureExt;
use thiserror::Error;
use tokio::net::TcpStream;
use tokio_modbus::{
  client::{Context, Writer},
  prelude::Reader,
  slave::SlaveContext,
  Slave,
};
use tokio_serial::SerialPortBuilderExt;

use super::{record::SimpleRecord, span::SimpleSpan};

#[expect(
  clippy::allow_attributes_without_reason,
  reason = "generated by derivative"
)]
mod __device {
  use derivative::Derivative;
  use std::net::SocketAddr;

  #[derive(Derivative)]
  #[derivative(Clone, Debug, Hash, Eq, PartialEq)]
  pub(crate) enum Device {
    Tcp(SocketAddr),
    Rtu {
      path: String,
      // NOTE: Eq is just a marker trait and works through PartialEq
      #[derivative(Hash = "ignore", PartialEq = "ignore")]
      baud_rate: u32,
    },
  }
}

pub(crate) use __device::*;

#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub(crate) struct Destination {
  pub(crate) device: Device,
  pub(crate) slave: Option<u8>,
}

impl Destination {
  pub(crate) fn slaves_for(
    device: Device,
    max_slave: Option<u8>,
  ) -> impl Iterator<Item = Destination> {
    let device = device.clone();
    (Slave::min_device().0..(max_slave.unwrap_or(Slave::max_device().0))).map(
      move |slave| {
        let device = device.clone();
        Destination {
          device,
          slave: Some(slave),
        }
      },
    )
  }

  pub(crate) fn standalone_for(device: Device) -> Destination {
    Destination {
      device,
      slave: None,
    }
  }
}

pub(crate) type ReadResponse = Vec<u16>;
pub(crate) type WriteResponse = ();

#[derive(Debug)]
pub(crate) struct Connection {
  device: Device,
  ctx: Option<Context>,
  slave: Option<u8>,
}

impl Connection {
  pub(crate) fn new(device: Device) -> Self {
    Self {
      device,
      ctx: None,
      slave: None,
    }
  }

  pub(crate) async fn ensure_connected(
    &mut self,
    slave: Option<u8>,
  ) -> Result<(), ConnectError> {
    if self.ctx.is_none() || self.slave != slave {
      let _ = self.reconnect(slave).await?;
    }

    Ok(())
  }
}

#[derive(Debug, Error)]
pub(crate) enum ReadError {
  #[error("Failed connecting")]
  Connection(#[from] ConnectError),

  #[error("Failed reading")]
  Read(std::io::Error),

  #[error("Connection timed out")]
  Timeout(std::io::Error),
}

#[derive(Debug, Error)]
pub(crate) enum WriteError {
  #[error("Failed connecting")]
  Connection(#[from] ConnectError),

  #[error("Failed reading")]
  Read(std::io::Error),

  #[error("Connection timed out")]
  Timeout(std::io::Error),
}

impl Connection {
  #[tracing::instrument(skip(self), fields(address = ?self.device))]
  pub(crate) async fn read(
    &mut self,
    slave: Option<u8>,
    span: SimpleSpan,
    timeout: chrono::Duration,
  ) -> Result<ReadResponse, ReadError> {
    let response = self
      .simple_read_impl(slave, span, timeout_from_chrono(timeout))
      .await?;

    tracing::trace!("Simple read successful");

    Ok(response)
  }

  #[tracing::instrument(skip(self), fields(address = ?self.device))]
  pub(crate) async fn write(
    &mut self,
    slave: Option<u8>,
    record: SimpleRecord,
    timeout: chrono::Duration,
  ) -> Result<WriteResponse, WriteError> {
    self
      .simple_write_impl(slave, record, timeout_from_chrono(timeout))
      .await?;

    tracing::trace!("Simple read successful");

    Ok(())
  }

  async fn simple_read_impl(
    &mut self,
    slave: Option<u8>,
    span: SimpleSpan,
    timeout: futures_time::time::Duration,
  ) -> Result<ReadResponse, ReadError> {
    let response = match &mut self.ctx {
      Some(ctx) => {
        let ctx = if self.slave != slave {
          self.reconnect(slave).await?
        } else {
          ctx
        };
        Self::simple_read_impl_connected(ctx, slave, span, timeout).await
      }
      None => {
        let ctx = self.reconnect(slave).await?;
        Self::simple_read_impl_connected(ctx, slave, span, timeout).await
      }
    };

    if matches!(response, Err(ReadError::Connection(_) | ReadError::Read(_))) {
      self.ctx = None;
    }

    response
  }

  async fn simple_write_impl(
    &mut self,
    slave: Option<u8>,
    record: SimpleRecord,
    timeout: futures_time::time::Duration,
  ) -> Result<WriteResponse, WriteError> {
    let response = match &mut self.ctx {
      Some(ctx) => {
        let ctx = if self.slave != slave {
          self.reconnect(slave).await?
        } else {
          ctx
        };
        Self::simple_write_impl_connected(ctx, slave, record, timeout).await
      }
      None => {
        let ctx = self.reconnect(slave).await?;
        Self::simple_write_impl_connected(ctx, slave, record, timeout).await
      }
    };

    if matches!(
      response,
      Err(WriteError::Connection(_) | WriteError::Read(_))
    ) {
      self.ctx = None;
    }

    response
  }

  async fn simple_read_impl_connected(
    ctx: &mut Context,
    slave: Option<u8>,
    span: SimpleSpan,
    timeout: futures_time::time::Duration,
  ) -> Result<ReadResponse, ReadError> {
    if let Some(slave) = slave {
      if slave < Slave::min_device().0 || slave > Slave::max_device().0 {
        return Err(ReadError::Connection(ConnectError::Slave));
      }

      ctx.set_slave(Slave(slave))
    } else {
      ctx.set_slave(Slave::tcp_device())
    }

    match ctx
      .read_holding_registers(span.address, span.quantity)
      .timeout(timeout)
      .await
    {
      Err(timeout_error) => Err(ReadError::Timeout(timeout_error)),
      Ok(Err(connection_error)) => Err(ReadError::Read(connection_error)),
      Ok(Ok(response)) => Ok(response),
    }
  }

  async fn simple_write_impl_connected(
    ctx: &mut Context,
    slave: Option<u8>,
    record: SimpleRecord,
    timeout: futures_time::time::Duration,
  ) -> Result<WriteResponse, WriteError> {
    if let Some(slave) = slave {
      if slave < Slave::min_device().0 || slave > Slave::max_device().0 {
        return Err(WriteError::Connection(ConnectError::Slave));
      }

      ctx.set_slave(Slave(slave))
    } else {
      ctx.set_slave(Slave::tcp_device())
    }

    match ctx
      .write_multiple_registers(record.address, &record.values)
      .timeout(timeout)
      .await
    {
      Err(timeout_error) => Err(WriteError::Timeout(timeout_error)),
      Ok(Err(connection_error)) => Err(WriteError::Read(connection_error)),
      Ok(Ok(_)) => Ok(()),
    }
  }
}

#[derive(Debug, thiserror::Error)]
pub(crate) enum ConnectError {
  #[error("Failed to connect TCP")]
  TcpConnect(#[from] std::io::Error),

  #[error("Failed to connect RTU")]
  RtuConnect(#[from] serialport::Error),

  #[error("Wrong slave number")]
  Slave,
}

impl Connection {
  async fn reconnect(
    &mut self,
    slave: Option<u8>,
  ) -> Result<&mut Context, ConnectError> {
    if let Some(ctx) = &mut self.ctx {
      ctx.disconnect().await?;
      self.ctx = None;
    }

    let mut ctx = match &self.device {
      Device::Tcp(socket) => {
        let stream = TcpStream::connect(socket).await?;
        tokio_modbus::prelude::tcp::attach(stream)
      }
      Device::Rtu { path, baud_rate } => {
        let stream = tokio_serial::new(path, *baud_rate).open_native_async()?;
        tokio_modbus::prelude::rtu::attach(stream)
      }
    };
    if let Some(slave) = slave {
      ctx.set_slave(Slave(slave))
    } else {
      ctx.set_slave(Slave::tcp_device())
    }

    tracing::trace!("Connected");

    self.ctx = Some(ctx);
    self.slave = slave;

    #[allow(clippy::unwrap_used, reason = "it was just put in")]
    Ok(self.ctx.as_mut().unwrap())
  }
}

fn timeout_from_chrono(
  timeout: chrono::Duration,
) -> futures_time::time::Duration {
  futures_time::time::Duration::from_millis(timeout.num_milliseconds() as u64)
}