presence: Parse JSON input file
Load, parse, and store the JSON configuration data to be used in
populating the fan presence policies.
Tested:
Valid json file is parsed without error
Invalid json file throws exception
Change-Id: Ib5e28533177ece31620877a6e146ce61025b4fb3
Signed-off-by: Matthew Barth <msbarth@us.ibm.com>
diff --git a/presence/json_config.cpp b/presence/json_config.cpp
index 5bb7c3c..4a9d493 100644
--- a/presence/json_config.cpp
+++ b/presence/json_config.cpp
@@ -14,6 +14,10 @@
* limitations under the License.
*/
#include <string>
+#include <filesystem>
+#include <fstream>
+#include <nlohmann/json.hpp>
+#include <phosphor-logging/log.hpp>
#include "json_config.hpp"
@@ -24,11 +28,39 @@
namespace presence
{
+using json = nlohmann::json;
+namespace fs = std::filesystem;
+using namespace phosphor::logging;
+
policies JsonConfig::_policies;
JsonConfig::JsonConfig(const std::string& jsonFile)
{
+ fs::path confFile{jsonFile};
+ std::ifstream file;
+ json jsonConf;
+ if (fs::exists(confFile))
+ {
+ file.open(confFile);
+ try
+ {
+ jsonConf = json::parse(file);
+ }
+ catch (std::exception& e)
+ {
+ log<level::ERR>("Failed to parse JSON config file",
+ entry("JSON_FILE=%s", jsonFile.c_str()),
+ entry("JSON_ERROR=%s", e.what()));
+ throw std::runtime_error("Failed to parse JSON config file");
+ }
+ }
+ else
+ {
+ log<level::ERR>("Unable to open JSON config file",
+ entry("JSON_FILE=%s", jsonFile.c_str()));
+ throw std::runtime_error("Unable to open JSON config file");
+ }
}
const policies& JsonConfig::get()