Szymon Dompke | 94f71c5 | 2021-12-10 07:16:33 +0100 | [diff] [blame] | 1 | #pragma once |
| 2 | |
| 3 | #include "interfaces/sensor.hpp" |
| 4 | |
| 5 | #include <boost/asio/io_context.hpp> |
| 6 | |
| 7 | struct ThresholdOperations |
| 8 | { |
| 9 | template <typename ThresholdType> |
Krzysztof Grobelny | 41fa80d | 2022-06-09 13:27:16 +0200 | [diff] [blame] | 10 | static void initialize(ThresholdType* thresholdPtr) |
Szymon Dompke | 94f71c5 | 2021-12-10 07:16:33 +0100 | [diff] [blame] | 11 | { |
| 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 Williams | 583ba44 | 2025-02-03 14:28:19 -0500 | [diff] [blame^] | 21 | static typename ThresholdType::ThresholdDetail& getDetails( |
| 22 | ThresholdType* thresholdPtr, const interfaces::Sensor& sensor) |
Szymon Dompke | 94f71c5 | 2021-12-10 07:16:33 +0100 | [diff] [blame] | 23 | { |
Patrick Williams | c7935fa | 2023-10-20 11:19:30 -0500 | [diff] [blame] | 24 | auto it = std::find_if( |
| 25 | thresholdPtr->sensorDetails.begin(), |
| 26 | thresholdPtr->sensorDetails.end(), |
| 27 | [&sensor](const auto& x) { return &sensor == x.first.get(); }); |
Szymon Dompke | 94f71c5 | 2021-12-10 07:16:33 +0100 | [diff] [blame] | 28 | return *it->second; |
| 29 | } |
| 30 | |
| 31 | template <typename ThresholdType> |
Krzysztof Grobelny | 41fa80d | 2022-06-09 13:27:16 +0200 | [diff] [blame] | 32 | static void updateSensors(ThresholdType* thresholdPtr, Sensors newSensors) |
Szymon Dompke | 94f71c5 | 2021-12-10 07:16:33 +0100 | [diff] [blame] | 33 | { |
| 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 | }; |