blob: f75c12ae7e4927b856b88d9a40d42d445ed03b0f [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>
Patrick Williams583ba442025-02-03 14:28:19 -050021 static typename ThresholdType::ThresholdDetail& getDetails(
22 ThresholdType* thresholdPtr, const interfaces::Sensor& sensor)
Szymon Dompke94f71c52021-12-10 07:16:33 +010023 {
Patrick Williamsc7935fa2023-10-20 11:19:30 -050024 auto it = std::find_if(
25 thresholdPtr->sensorDetails.begin(),
26 thresholdPtr->sensorDetails.end(),
27 [&sensor](const auto& x) { return &sensor == x.first.get(); });
Szymon Dompke94f71c52021-12-10 07:16:33 +010028 return *it->second;
29 }
30
31 template <typename ThresholdType>
Krzysztof Grobelny41fa80d2022-06-09 13:27:16 +020032 static void updateSensors(ThresholdType* thresholdPtr, Sensors newSensors)
Szymon Dompke94f71c52021-12-10 07:16:33 +010033 {
34 typename ThresholdType::SensorDetails newSensorDetails;
35 typename ThresholdType::SensorDetails oldSensorDetails =
36 thresholdPtr->sensorDetails;
37
38 for (const auto& sensor : newSensors)
39 {
40 auto it = std::find_if(
41 oldSensorDetails.begin(), oldSensorDetails.end(),
42 [&sensor](const auto& sd) { return sensor == sd.first; });
43 if (it != oldSensorDetails.end())
44 {
45 newSensorDetails.emplace(*it);
46 oldSensorDetails.erase(it);
47 continue;
48 }
49
50 newSensorDetails.emplace(
51 sensor, thresholdPtr->makeDetails(sensor->getName()));
52 if (thresholdPtr->initialized)
53 {
54 sensor->registerForUpdates(thresholdPtr->weak_from_this());
55 }
56 }
57
58 if (thresholdPtr->initialized)
59 {
60 for ([[maybe_unused]] auto& [sensor, detail] : oldSensorDetails)
61 {
62 sensor->unregisterFromUpdates(thresholdPtr->weak_from_this());
63 }
64 }
65
66 thresholdPtr->sensorDetails = std::move(newSensorDetails);
67 }
68};