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> |
| 10 | void initialize(ThresholdType* thresholdPtr) |
| 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> |
| 21 | typename ThresholdType::ThresholdDetail& |
| 22 | 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> |
| 33 | void updateSensors(ThresholdType* thresholdPtr, Sensors newSensors) |
| 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 | }; |