1 #include "on_change_threshold.hpp"
2 
3 #include <phosphor-logging/log.hpp>
4 
5 OnChangeThreshold::OnChangeThreshold(
6     const std::string& triggerIdIn, Sensors sensorsIn,
7     std::vector<std::unique_ptr<interfaces::TriggerAction>> actionsIn,
8     std::unique_ptr<interfaces::Clock> clockIn) :
9     triggerId(triggerIdIn),
10     sensors(std::move(sensorsIn)), actions(std::move(actionsIn)),
11     clock(std::move(clockIn))
12 {}
13 
14 void OnChangeThreshold::initialize()
15 {
16     for (auto& sensor : sensors)
17     {
18         sensor->registerForUpdates(weak_from_this());
19     }
20     initialized = true;
21 }
22 
23 void OnChangeThreshold::updateSensors(Sensors newSensors)
24 {
25     Sensors oldSensors = sensors;
26 
27     for (const auto& sensor : newSensors)
28     {
29         auto it =
30             std::find_if(oldSensors.begin(), oldSensors.end(),
31                          [&sensor](const auto& s) { return sensor == s; });
32         if (it != oldSensors.end())
33         {
34             oldSensors.erase(it);
35             continue;
36         }
37 
38         if (initialized)
39         {
40             sensor->registerForUpdates(weak_from_this());
41         }
42     }
43 
44     if (initialized)
45     {
46         for (auto& sensor : oldSensors)
47         {
48             sensor->unregisterFromUpdates(weak_from_this());
49         }
50     }
51 
52     sensors = std::move(newSensors);
53 }
54 
55 void OnChangeThreshold::sensorUpdated(interfaces::Sensor& sensor,
56                                       Milliseconds timestamp, double value)
57 {
58     if (isFirstReading)
59     {
60         isFirstReading = false;
61         return;
62     }
63 
64     commit(sensor.getName(), value);
65 }
66 
67 void OnChangeThreshold::commit(const std::string& sensorName, double value)
68 {
69     Milliseconds timestamp = clock->systemTimestamp();
70     for (const auto& action : actions)
71     {
72         action->commit(triggerId, std::nullopt, sensorName, timestamp, value);
73     }
74 }
75 
76 LabeledThresholdParam OnChangeThreshold::getThresholdParam() const
77 {
78     return {};
79 }
80