blob: 641e33be665365fc3d4833625aa440b9d720c020 [file] [log] [blame]
Matthew Barth93341e02021-04-14 13:56:28 -05001/**
2 * Copyright © 2021 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#include "timer.hpp"
17
18#include "../manager.hpp"
19
20#include <fmt/format.h>
21
22#include <nlohmann/json.hpp>
23#include <phosphor-logging/log.hpp>
24
25#include <chrono>
26
27namespace phosphor::fan::control::json::trigger::timer
28{
29
30using json = nlohmann::json;
31using namespace phosphor::logging;
32
33TimerType getType(const json& jsonObj)
34{
35 if (!jsonObj.contains("type"))
36 {
37 log<level::ERR>("Missing required timer trigger type",
38 entry("JSON=%s", jsonObj.dump().c_str()));
39 throw std::runtime_error("Missing required timer trigger type");
40 }
41 auto type = jsonObj["type"].get<std::string>();
42 if (type == "oneshot")
43 {
44 return TimerType::oneshot;
45 }
46 else if (type == "repeating")
47 {
48 return TimerType::repeating;
49 }
50 else
51 {
52 log<level::ERR>(
53 fmt::format("Timer trigger type '{}' is not supported", type)
54 .c_str(),
55 entry("AVAILABLE_TYPES={oneshot, repeating}"));
56 throw std::runtime_error("Unsupported timer trigger type given");
57 }
58}
59
60std::chrono::microseconds getInterval(const json& jsonObj)
61{
62 if (!jsonObj.contains("interval"))
63 {
64 log<level::ERR>("Missing required timer trigger interval",
65 entry("JSON=%s", jsonObj.dump().c_str()));
66 throw std::runtime_error("Missing required timer trigger interval");
67 }
68 return static_cast<std::chrono::microseconds>(
69 jsonObj["interval"].get<uint64_t>());
70}
71
72void triggerTimer(const json& jsonObj, const std::string& eventName,
73 Manager* mgr,
74 std::vector<std::unique_ptr<ActionBase>>& actions)
75{
76 // Get the type and interval of this timer from the JSON
77 auto type = getType(jsonObj);
78 auto interval = getInterval(jsonObj);
79
80 // Create/add event timer
81 auto tpPtr = std::make_unique<TimerPkg>(eventName, std::ref(actions));
82 mgr->addTimer(type, interval, std::move(tpPtr));
83}
84
85} // namespace phosphor::fan::control::json::trigger::timer