blob: db45b05c8c35fc7aaf3d587af658eb84194dd8d6 [file] [log] [blame]
Patrick Venture02e32372019-08-16 10:50:18 -07001#include "entity_map_json.hpp"
2
3#include <exception>
4#include <ipmid/types.hpp>
5#include <nlohmann/json.hpp>
6#include <string>
7#include <utility>
8
9namespace ipmi
10{
11namespace sensor
12{
13
14EntityInfoMap buildJsonEntityMap(const nlohmann::json& data)
15{
16 EntityInfoMap builtMap;
17
18 if (data.type() != nlohmann::json::value_t::array)
19 {
20 return builtMap;
21 }
22
23 try
24 {
25 for (const auto& entry : data)
26 {
27 /* It's an array entry with the following fields: id,
28 * containerEntityId, containerEntityInstance, isList, isLinked,
29 * entities[4]
30 */
31 EntityInfo obj;
32 Id recordId = entry.at("id").get<Id>();
33 obj.containerEntityId =
34 entry.at("containerEntityId").get<uint8_t>();
35 obj.containerEntityInstance =
36 entry.at("containerEntityInstance").get<uint8_t>();
37 obj.isList = entry.at("isList").get<bool>();
38 obj.isLinked = entry.at("isLinked").get<bool>();
39
40 auto jsonEntities = entry.at("entities");
41
42 if (jsonEntities.type() != nlohmann::json::value_t::array)
43 {
44 throw std::runtime_error(
45 "Invalid type for entities entry, must be array");
46 }
47 if (jsonEntities.size() != obj.containedEntities.size())
48 {
49 throw std::runtime_error(
50 "Entities must be in pairs of " +
51 std::to_string(obj.containedEntities.size()));
52 }
53
54 for (std::size_t i = 0; i < obj.containedEntities.size(); i++)
55 {
56 obj.containedEntities[i] = std::make_pair(
57 jsonEntities[i].at("id").get<uint8_t>(),
58 jsonEntities[i].at("instance").get<uint8_t>());
59 }
60
61 builtMap.insert({recordId, obj});
62 }
63 }
64 catch (const std::exception& e)
65 {
66 /* If any entry is invalid, the entire file cannot be trusted. */
67 builtMap.clear();
68 }
69
70 return builtMap;
71}
72
73} // namespace sensor
74} // namespace ipmi