blob: c4b0f8975f2d7c1fd41c6a06403589052328f403 [file] [log] [blame]
Willy Tu6c71b0f2021-10-10 13:34:41 -07001// Copyright 2022 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14#include "config.h"
15
16#include "bifurcation.hpp"
17
18#include <fmt/format.h>
19
Patrick Williams444b5ea2023-05-19 13:56:42 -050020#include <nlohmann/json.hpp>
21
Willy Tu6c71b0f2021-10-10 13:34:41 -070022#include <charconv>
23#include <filesystem>
24#include <fstream>
Willy Tu6c71b0f2021-10-10 13:34:41 -070025#include <optional>
26#include <string_view>
27#include <vector>
28
29namespace google
30{
31namespace ipmi
32{
33
34BifurcationStatic::BifurcationStatic() :
35 BifurcationStatic(STATIC_BIFURCATION_CONFIG)
Patrick Williams444b5ea2023-05-19 13:56:42 -050036{}
Willy Tu6c71b0f2021-10-10 13:34:41 -070037
38BifurcationStatic::BifurcationStatic(std::string_view bifurcationFile) :
39 bifurcationFile(bifurcationFile)
Patrick Williams444b5ea2023-05-19 13:56:42 -050040{}
Willy Tu6c71b0f2021-10-10 13:34:41 -070041
42std::optional<std::vector<uint8_t>>
43 BifurcationStatic::getBifurcation(uint8_t index) noexcept
44{
45 // Example valid data:
46 // {
47 // "1": [8,8],
48 // "2": [4, 4, 12]
49 // }
50 std::ifstream jsonFile(bifurcationFile.c_str());
51 if (!jsonFile.is_open())
52 {
53 fmt::print(stderr, "Unable to open file {} for bifurcation.\n",
54 bifurcationFile.data());
55 return std::nullopt;
56 }
57
58 nlohmann::json jsonData;
59 try
60 {
61 jsonData = nlohmann::json::parse(jsonFile, nullptr, false);
62 }
63 catch (const nlohmann::json::parse_error& ex)
64 {
65 fmt::print(
66 stderr,
67 "Failed to parse the static config. Parse error at byte {}\n",
68 ex.byte);
69 return std::nullopt;
70 }
71
72 std::vector<uint8_t> vec;
73 try
74 {
75 std::string key = std::to_string(index);
76 auto value = jsonData[key];
77 value.get_to(vec);
78 }
Patrick Williams444b5ea2023-05-19 13:56:42 -050079 catch (const std::exception& e)
Willy Tu6c71b0f2021-10-10 13:34:41 -070080 {
81 fmt::print(stderr,
82 "Failed to convert bifurcation value to vec[uin8_t]\n");
83 return std::nullopt;
84 }
85
86 return vec;
87}
88
89} // namespace ipmi
90} // namespace google