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
use futures::future::join_all;
use futures_time::future::FutureExt;

#[allow(unused_imports, reason = "services")]
use crate::{service::*, *};

// TODO: use destination to send request because the device might not be discovered

pub(crate) struct Process {
  #[allow(dead_code, reason = "process")]
  config: config::Manager,

  #[allow(dead_code, reason = "process")]
  services: service::Container,
}

impl Process {
  pub(crate) fn new(
    config: config::Manager,
    services: service::Container,
  ) -> Self {
    Self { config, services }
  }
}

impl super::Process for Process {}

#[async_trait::async_trait]
impl process::Recurring for Process {
  #[tracing::instrument(skip(self))]
  async fn execute(&self) -> anyhow::Result<()> {
    let config = self.config.values().await;

    let devices = self.services.db().get_devices().await?;

    let pinged_devices = join_all(
      devices
        .iter()
        .cloned()
        .map(|device| self.ping_device(&config, device)),
    )
    .await;
    let pinged_devices_len = pinged_devices.len();
    let healthy_count = pinged_devices.iter().filter(|pinged| **pinged).count();
    let unreachable_count =
      pinged_devices.iter().filter(|pinged| !**pinged).count();
    tracing::info!(
      "Pinged {:?} devices of which {:?} are healthy and {:?} unreachable",
      pinged_devices_len,
      healthy_count,
      unreachable_count,
    );

    let consolidated_devices = join_all(
      pinged_devices
        .into_iter()
        .zip(devices)
        .map(|(pinged, device)| self.consolidate(&config, device, pinged)),
    )
    .await;
    let consolidated_devices_len = consolidated_devices.len();
    let healthy_count = consolidated_devices
      .iter()
      .filter(|consolidated| {
        matches!(**consolidated, Ok((_, db::DeviceStatus::Healthy)))
      })
      .count();
    let unreachable_count = consolidated_devices
      .iter()
      .filter(|consolidated| {
        matches!(**consolidated, Ok((_, db::DeviceStatus::Unreachable)))
      })
      .count();
    let inactive_count = consolidated_devices
      .iter()
      .filter(|consolidated| {
        matches!(**consolidated, Ok((_, db::DeviceStatus::Inactive)))
      })
      .count();
    let failed_count = consolidated_devices
      .iter()
      .filter(|consolidated| consolidated.is_err())
      .count();

    tracing::info!(
      "Consolidated {:?} D {:?} H {:?} U {:?} I {:?} F",
      consolidated_devices_len,
      healthy_count,
      unreachable_count,
      inactive_count,
      failed_count
    );

    Ok(())
  }
}

impl Process {
  #[tracing::instrument(skip(self, config))]
  async fn ping_device(
    &self,
    config: &config::Values,
    device: db::Device,
  ) -> bool {
    match config
      .modbus
      .devices
      .values()
      .find(|device_config| device_config.kind == device.kind)
    {
      Some(device_config) => {
        match self
          .services
          .modbus()
          .read_from_id(&device.id, device_config.id.clone())
          .timeout(timeout_from_chrono(config.modbus.ping_timeout))
          .await
        {
          Err(error) => {
            tracing::warn!("Getting id timed out {}", error);
            return false;
          }
          Ok(Err(error)) => {
            tracing::warn!("Getting id failed {}", error);
            return false;
          }
          Ok(Ok(id_registers)) => {
            if modbus::make_id(device.kind, id_registers) == device.id {
              tracing::debug!("Id match");
            } else {
              tracing::debug!("Id mismatch");
              return false;
            }
          }
        }
      }
      None => {
        tracing::debug!("Config not found");
        return false;
      }
    }

    true
  }

  #[tracing::instrument(skip(self, config, device), fields(id = ?device.id))]
  async fn consolidate(
    &self,
    config: &config::Values,
    device: db::Device,
    pinged: bool,
  ) -> anyhow::Result<(db::Device, db::DeviceStatus)> {
    let now = chrono::Utc::now();
    let status = if pinged {
      db::DeviceStatus::Healthy
    } else if now.signed_duration_since(device.seen)
      > config.modbus.inactive_timeout
    {
      db::DeviceStatus::Inactive
    } else {
      db::DeviceStatus::Unreachable
    };
    let seen = if pinged { now } else { device.seen };
    let update = device.status != status;
    let remove = (status == db::DeviceStatus::Inactive)
      && (device.status != db::DeviceStatus::Inactive);

    if let Err(error) = self
      .services
      .db()
      .update_device_status(&device.id, status, seen, now)
      .await
    {
      tracing::error!("Failed updating device status {}", error);
      return Err(error.into());
    };

    if remove {
      self.services.modbus().stop_from_id(&device.id).await;
    } else {
      self
        .services
        .modbus()
        .bind(
          device.id.clone(),
          modbus::Destination {
            device: match &device.address {
              Some(address) => modbus::connection::Device::Tcp(
                self.services.net().to_socket(db::to_address(*address)),
              ),
              None => match (&device.path, &device.baud_rate) {
                (Some(path), Some(baud_rate)) => {
                  modbus::connection::Device::Rtu {
                    path: path.clone(),
                    baud_rate: (*baud_rate as u32),
                  }
                }
                _ => {
                  return Err(anyhow::anyhow!(format!(
                    "Device {device:?} missing appropriate server details"
                  )))
                }
              },
            },
            slave: db::to_slave(device.slave),
          },
        )
        .await;
    }

    if update {
      if let Err(error) = self
        .services
        .db()
        .insert_health(db::Health {
          id: 0,
          source: device.id.clone(),
          timestamp: seen,
          status,
          data: serde_json::Value::Object(serde_json::Map::new()),
        })
        .await
      {
        tracing::error!("Failed inserting health {}", error);
      }
    }

    tracing::debug!("Updated device status and health");

    Ok((device, status))
  }
}

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