Willy Tu | 6c71b0f | 2021-10-10 13:34:41 -0700 | [diff] [blame] | 1 | // 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 | |
| 20 | #include <charconv> |
| 21 | #include <filesystem> |
| 22 | #include <fstream> |
| 23 | #include <nlohmann/json.hpp> |
| 24 | #include <optional> |
| 25 | #include <string_view> |
| 26 | #include <vector> |
| 27 | |
| 28 | namespace google |
| 29 | { |
| 30 | namespace ipmi |
| 31 | { |
| 32 | |
| 33 | BifurcationStatic::BifurcationStatic() : |
| 34 | BifurcationStatic(STATIC_BIFURCATION_CONFIG) |
| 35 | { |
| 36 | } |
| 37 | |
| 38 | BifurcationStatic::BifurcationStatic(std::string_view bifurcationFile) : |
| 39 | bifurcationFile(bifurcationFile) |
| 40 | { |
| 41 | } |
| 42 | |
| 43 | std::optional<std::vector<uint8_t>> |
| 44 | BifurcationStatic::getBifurcation(uint8_t index) noexcept |
| 45 | { |
| 46 | // Example valid data: |
| 47 | // { |
| 48 | // "1": [8,8], |
| 49 | // "2": [4, 4, 12] |
| 50 | // } |
| 51 | std::ifstream jsonFile(bifurcationFile.c_str()); |
| 52 | if (!jsonFile.is_open()) |
| 53 | { |
| 54 | fmt::print(stderr, "Unable to open file {} for bifurcation.\n", |
| 55 | bifurcationFile.data()); |
| 56 | return std::nullopt; |
| 57 | } |
| 58 | |
| 59 | nlohmann::json jsonData; |
| 60 | try |
| 61 | { |
| 62 | jsonData = nlohmann::json::parse(jsonFile, nullptr, false); |
| 63 | } |
| 64 | catch (const nlohmann::json::parse_error& ex) |
| 65 | { |
| 66 | fmt::print( |
| 67 | stderr, |
| 68 | "Failed to parse the static config. Parse error at byte {}\n", |
| 69 | ex.byte); |
| 70 | return std::nullopt; |
| 71 | } |
| 72 | |
| 73 | std::vector<uint8_t> vec; |
| 74 | try |
| 75 | { |
| 76 | std::string key = std::to_string(index); |
| 77 | auto value = jsonData[key]; |
| 78 | value.get_to(vec); |
| 79 | } |
| 80 | catch (std::exception const& e) |
| 81 | { |
| 82 | fmt::print(stderr, |
| 83 | "Failed to convert bifurcation value to vec[uin8_t]\n"); |
| 84 | return std::nullopt; |
| 85 | } |
| 86 | |
| 87 | return vec; |
| 88 | } |
| 89 | |
| 90 | } // namespace ipmi |
| 91 | } // namespace google |