1 /**
2  * Copyright © 2022 IBM Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17 
18 #include "../zone.hpp"
19 #include "action.hpp"
20 #include "group.hpp"
21 
22 #include <nlohmann/json.hpp>
23 
24 namespace phosphor::fan::control::json
25 {
26 
27 using json = nlohmann::json;
28 
29 /**
30  * @class MappedFloor - Action to set a fan floor based on ranges of
31  *                      multiple sensor values.
32  * For example, consider the following config:
33  *
34  *    {
35  *    "name": "mapped_floor",
36  *    "key_group": "ambient_temp",
37  *    "default_floor": 2000,
38  *    "fan_floors": [
39  *        {
40  *        "key": 27,
41  *        "floor_offset_parameter": "floor_27_offset",
42  *        "default_floor": 3000,
43  *        "floors": [
44  *          {
45  *            "group": "altitude",
46  *            "floors": [
47  *               {
48  *                 "value": 5000,
49  *                 "floor": 4500
50  *               }
51  *            ]
52  *          },
53  *          {
54  *            "group": "power_mode",
55  *            "floors": [
56  *               {
57  *                 "value": "MaximumPerformance",
58  *                 "floor": 5000
59  *               }
60  *            ]
61  *          }
62  *        ]
63  *        }
64  *      ]
65  *    }
66  *
67  * When it runs, it will:
68  *
69  * 1. Evaluate the key_group
70  *   - Find the max D-Bus property value (if numeric) of the member properties
71  *     in this group.
72  *   - Check it against each 'key' value in the fan_floor entries until
73  *     the key_group property value < key value, so:
74  *        max ambient temp < 27.
75  *   - If the above check passes, the rest of that entry will be evaluated
76  *     and then the action will be done.
77  *
78  * 2. Evaluate the group values in each floors array entry for this key value.
79  *   - Find the max D-Bus property value (if numeric) of the member properties
80  *     of this group - in this case 'altitude'.
81  *   - Depending on the data type of that group, compare to the 'value' entry:
82  *     - If numeric, check if the group's value is <= the 'value' one
83  *     - Otherwise, check if it is ==
84  *   - If that passes, save the value from the 'floor' entry and continue to
85  *     the next entry in the floors array, which, if present, would specify
86  *     another group to check.  In this case, 'power_mode'.  Repeat the above
87  *     step.
88  *   - After all the group compares are done, choose the largest floor value
89  *     to set the fan floor to, but first apply the floor offset provided
90  *     by the parameter in the 'floor_offset_parameter' field, if it present.
91  *   - If any group check results doesn't end in a match being found, then
92  *     the default floor will be set.
93  *
94  * There are up to 3 default value values that may be used when a regular
95  * floor value can't be calculated:
96  *   1. Optional default floor at the key group level
97  *     - Chosen when a floor wasn't found in any floor groups
98  *   2. Optional default floor at the action level
99  *     - Chosen when there isn't a key table found for the key value,
100  *       or 1. above occurred but that default floor wasn't supplied.
101  *   3. The default floor in the zone config
102  *     - Chosen when when 2. would be used, but it wasn't supplied
103  *
104  * This action can also have a condition specified where a group property
105  * must either match or not match a given value to determine if the
106  * action should run or not.  This requires the following in the JSON:
107  *    "condition_group": The group name
108  *       - As of now, group must just have a single member.
109  *    "condition_op": Either "equal" or "not_equal"
110  *    "condition_value": The value to check against
111  *
112  * This allows completely separate mapped_floor actions to run based on
113  * the value of a D-bus property - i.e. it allows multiple floor tables.
114  *
115  * Other notes:
116  *  - If a group has multiple members, they must be numeric or else
117  *    the code will throw an exception.
118  *
119  *  - The group inside the floors array can also be a Manager parameter, so that
120  *    this action can operate on a parameter value set by another action.
121  *
122  *    So instead of
123  *            "group": "altitude",
124  *    it can be:
125  *            "parameter": "some_parameter"
126  */
127 class MappedFloor : public ActionBase, public ActionRegister<MappedFloor>
128 {
129   public:
130     /* Name of this action */
131     static constexpr auto name = "mapped_floor";
132 
133     MappedFloor() = delete;
134     MappedFloor(const MappedFloor&) = delete;
135     MappedFloor(MappedFloor&&) = delete;
136     MappedFloor& operator=(const MappedFloor&) = delete;
137     MappedFloor& operator=(MappedFloor&&) = delete;
138     ~MappedFloor() = default;
139 
140     /**
141      * @brief Parse the JSON to set the members
142      *
143      * @param[in] jsonObj - JSON configuration of this action
144      * @param[in] groups - Groups of dbus objects the action uses
145      */
146     MappedFloor(const json& jsonObj, const std::vector<Group>& groups);
147 
148     /**
149      * @brief Run the action.  See description above.
150      *
151      * @param[in] zone - Zone to run the action on
152      */
153     void run(Zone& zone) override;
154 
155   private:
156     /**
157      * @brief Parse and set the key group
158      *
159      * @param[in] jsonObj - JSON object for the action
160      */
161     void setKeyGroup(const json& jsonObj);
162 
163     /**
164      * @brief Parse and set the default floor value
165      *
166      * @param[in] jsonObj - JSON object for the action
167      */
168     void setDefaultFloor(const json& jsonObj);
169 
170     /**
171      * @brief Parses and sets the floor group data members
172      *
173      * @param[in] jsonObj - JSON object for the action
174      */
175     void setFloorTable(const json& jsonObj);
176 
177     /**
178      * @brief Parse and set the conditions
179      *
180      * @param jsonObj - JSON object for the action
181      */
182     void setCondition(const json& jsonObj);
183 
184     /**
185      * @brief Applies the offset in offsetParameter to the
186      *        value passed in.
187      *
188      * If offsetParameter is empty then no offset will be
189      * applied.
190      *
191      * Note: The offset may be negative.
192      *
193      * @param[in] floor - The floor to apply offset to
194      * @param[in] offsetParameter - The floor offset parameter
195      *
196      * @return uint64_t - The new floor value
197      */
198     uint64_t applyFloorOffset(uint64_t floor,
199                               const std::string& offsetParameter) const;
200 
201     /**
202      * @brief Determines the maximum value of the property specified
203      *        for the group of all members in the group.
204      *
205      * If not numeric, and more than one member, will throw an exception.
206      * Converts numeric values to doubles so they can be compared later.
207      *
208      * If cannot get at least one valid value, returns std::nullopt.
209      *
210      * @param[in] group - The group to get the max value of
211      *
212      * @return optional<PropertyVariantType> - The value, or std::nullopt
213      */
214     std::optional<PropertyVariantType> getMaxGroupValue(const Group& group);
215 
216     /**
217      * @brief Returns a pointer to the group object specified
218      *
219      * Throws ActionParseError if no group found
220      *
221      * @param[in] name - The group name
222      *
223      * @return const Group* - Pointer to the group
224      */
225     const Group* getGroup(const std::string& name);
226 
227     /**
228      * @brief Checks if the condition is met, if there is one.
229      *
230      * @return bool - False if there is a condition and it
231      *                isn't met, true otherwise.
232      */
233     bool meetsCondition();
234 
235     /* Key group pointer */
236     const Group* _keyGroup;
237 
238     /* condition group pointer */
239     const Group* _conditionGroup = nullptr;
240 
241     /* Condition value */
242     PropertyVariantType _conditionValue;
243 
244     /* Condition operation */
245     std::string _conditionOp;
246 
247     /* Optional default floor value for the action */
248     std::optional<uint64_t> _defaultFloor;
249 
250     using FloorEntry = std::tuple<PropertyVariantType, uint64_t>;
251 
252     struct FloorGroup
253     {
254         std::variant<const Group*, std::string> groupOrParameter;
255         std::vector<FloorEntry> floorEntries;
256     };
257 
258     struct FanFloors
259     {
260         PropertyVariantType keyValue;
261         std::string offsetParameter;
262         std::optional<uint64_t> defaultFloor;
263         std::vector<FloorGroup> floorGroups;
264     };
265 
266     /* The fan floors action data, loaded from JSON */
267     std::vector<FanFloors> _fanFloors;
268 };
269 
270 } // namespace phosphor::fan::control::json
271