blob: 42d469e7868b81fc60863c3d26633fe22bca3eee [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 {
Patrick Williams3a1c2972023-05-10 07:51:04 -050025 auto it = std::find_if(thresholdPtr->sensorDetails.begin(),
26 thresholdPtr->sensorDetails.end(),
27 [&sensor](const auto& x) {
28 return &sensor == x.first.get();
29 });
Szymon Dompke94f71c52021-12-10 07:16:33 +010030 return *it->second;
31 }
32
33 template <typename ThresholdType>
Krzysztof Grobelny41fa80d2022-06-09 13:27:16 +020034 static void updateSensors(ThresholdType* thresholdPtr, Sensors newSensors)
Szymon Dompke94f71c52021-12-10 07:16:33 +010035 {
36 typename ThresholdType::SensorDetails newSensorDetails;
37 typename ThresholdType::SensorDetails oldSensorDetails =
38 thresholdPtr->sensorDetails;
39
40 for (const auto& sensor : newSensors)
41 {
42 auto it = std::find_if(
43 oldSensorDetails.begin(), oldSensorDetails.end(),
44 [&sensor](const auto& sd) { return sensor == sd.first; });
45 if (it != oldSensorDetails.end())
46 {
47 newSensorDetails.emplace(*it);
48 oldSensorDetails.erase(it);
49 continue;
50 }
51
52 newSensorDetails.emplace(
53 sensor, thresholdPtr->makeDetails(sensor->getName()));
54 if (thresholdPtr->initialized)
55 {
56 sensor->registerForUpdates(thresholdPtr->weak_from_this());
57 }
58 }
59
60 if (thresholdPtr->initialized)
61 {
62 for ([[maybe_unused]] auto& [sensor, detail] : oldSensorDetails)
63 {
64 sensor->unregisterFromUpdates(thresholdPtr->weak_from_this());
65 }
66 }
67
68 thresholdPtr->sensorDetails = std::move(newSensorDetails);
69 }
70};