blob: 99ae4a5414de256700a7fe8556286d229a975d3d [file] [log] [blame]
Szymon Dompke94f71c52021-12-10 07:16:33 +01001#pragma once
2
3#include "interfaces/sensor.hpp"
4
5#include <boost/asio/io_context.hpp>
6
7struct ThresholdOperations
8{
9 template <typename ThresholdType>
Krzysztof Grobelny41fa80d2022-06-09 13:27:16 +020010 static void initialize(ThresholdType* thresholdPtr)
Szymon Dompke94f71c52021-12-10 07:16:33 +010011 {
12 for ([[maybe_unused]] auto& [sensor, detail] :
13 thresholdPtr->sensorDetails)
14 {
15 sensor->registerForUpdates(thresholdPtr->weak_from_this());
16 }
17 thresholdPtr->initialized = true;
18 }
19
20 template <typename ThresholdType>
Krzysztof Grobelny41fa80d2022-06-09 13:27:16 +020021 static typename ThresholdType::ThresholdDetail&
Szymon Dompke94f71c52021-12-10 07:16:33 +010022 getDetails(ThresholdType* thresholdPtr,
23 const interfaces::Sensor& sensor)
24 {
25 auto it = std::find_if(
26 thresholdPtr->sensorDetails.begin(),
27 thresholdPtr->sensorDetails.end(),
28 [&sensor](const auto& x) { return &sensor == x.first.get(); });
29 return *it->second;
30 }
31
32 template <typename ThresholdType>
Krzysztof Grobelny41fa80d2022-06-09 13:27:16 +020033 static void updateSensors(ThresholdType* thresholdPtr, Sensors newSensors)
Szymon Dompke94f71c52021-12-10 07:16:33 +010034 {
35 typename ThresholdType::SensorDetails newSensorDetails;
36 typename ThresholdType::SensorDetails oldSensorDetails =
37 thresholdPtr->sensorDetails;
38
39 for (const auto& sensor : newSensors)
40 {
41 auto it = std::find_if(
42 oldSensorDetails.begin(), oldSensorDetails.end(),
43 [&sensor](const auto& sd) { return sensor == sd.first; });
44 if (it != oldSensorDetails.end())
45 {
46 newSensorDetails.emplace(*it);
47 oldSensorDetails.erase(it);
48 continue;
49 }
50
51 newSensorDetails.emplace(
52 sensor, thresholdPtr->makeDetails(sensor->getName()));
53 if (thresholdPtr->initialized)
54 {
55 sensor->registerForUpdates(thresholdPtr->weak_from_this());
56 }
57 }
58
59 if (thresholdPtr->initialized)
60 {
61 for ([[maybe_unused]] auto& [sensor, detail] : oldSensorDetails)
62 {
63 sensor->unregisterFromUpdates(thresholdPtr->weak_from_this());
64 }
65 }
66
67 thresholdPtr->sensorDetails = std::move(newSensorDetails);
68 }
69};