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> |
Krzysztof Grobelny | 41fa80d | 2022-06-09 13:27:16 +0200 | [diff] [blame] | 21 | static typename ThresholdType::ThresholdDetail& |
Szymon Dompke | 94f71c5 | 2021-12-10 07:16:33 +0100 | [diff] [blame] | 22 | getDetails(ThresholdType* thresholdPtr, |
| 23 | const interfaces::Sensor& sensor) |
| 24 | { |
Patrick Williams | c7935fa | 2023-10-20 11:19:30 -0500 | [diff] [blame] | 25 | auto it = std::find_if( |
| 26 | thresholdPtr->sensorDetails.begin(), |
| 27 | thresholdPtr->sensorDetails.end(), |
| 28 | [&sensor](const auto& x) { return &sensor == x.first.get(); }); |
Szymon Dompke | 94f71c5 | 2021-12-10 07:16:33 +0100 | [diff] [blame] | 29 | return *it->second; |
| 30 | } |
| 31 | |
| 32 | template <typename ThresholdType> |
Krzysztof Grobelny | 41fa80d | 2022-06-09 13:27:16 +0200 | [diff] [blame] | 33 | static void updateSensors(ThresholdType* thresholdPtr, Sensors newSensors) |
Szymon Dompke | 94f71c5 | 2021-12-10 07:16:33 +0100 | [diff] [blame] | 34 | { |
| 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 | }; |