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 static 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 static typename ThresholdType::ThresholdDetail& 22 getDetails(ThresholdType* thresholdPtr, 23 const interfaces::Sensor& sensor) 24 { 25 auto it = std::find_if(thresholdPtr->sensorDetails.begin(), 26 thresholdPtr->sensorDetails.end(), 27 [&sensor](const auto& x) { 28 return &sensor == x.first.get(); 29 }); 30 return *it->second; 31 } 32 33 template <typename ThresholdType> 34 static void updateSensors(ThresholdType* thresholdPtr, Sensors newSensors) 35 { 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 }; 71