blob: e11bb95ec145fb1e6eac9ea87755e86d59410bce [file] [log] [blame]
George Liu2098aa62020-05-09 11:26:35 +08001#include "config.h"
2
3#include "serialize.hpp"
4
5#include <cereal/archives/json.hpp>
6#include <cereal/types/set.hpp>
7#include <cereal/types/string.hpp>
George Liue9fb5c62021-07-01 14:05:32 +08008#include <phosphor-logging/lg2.hpp>
George Liu2098aa62020-05-09 11:26:35 +08009
10#include <filesystem>
11#include <fstream>
12
13// Register class version with Cereal
George Liu4b062012020-10-13 15:26:58 +080014CEREAL_CLASS_VERSION(phosphor::led::Serialize, CLASS_VERSION)
George Liu2098aa62020-05-09 11:26:35 +080015
16namespace phosphor
17{
18namespace led
19{
20
21namespace fs = std::filesystem;
22
23bool Serialize::getGroupSavedState(const std::string& objPath) const
24{
George Liu7f53a032021-05-04 11:18:21 +080025 return savedGroups.contains(objPath);
George Liu2098aa62020-05-09 11:26:35 +080026}
27
28void Serialize::storeGroups(const std::string& group, bool asserted)
29{
30 // If the name of asserted group does not exist in the archive and the
31 // Asserted property is true, it is inserted into archive.
32 // If the name of asserted group exist in the archive and the Asserted
33 // property is false, entry is removed from the archive.
34 auto iter = savedGroups.find(group);
George Liu349d22e2024-08-23 09:09:56 +080035 if (iter != savedGroups.end() && !asserted)
George Liu2098aa62020-05-09 11:26:35 +080036 {
37 savedGroups.erase(iter);
38 }
39
40 if (iter == savedGroups.end() && asserted)
41 {
42 savedGroups.emplace(group);
43 }
44
45 auto dir = path.parent_path();
46 if (!fs::exists(dir))
47 {
48 fs::create_directories(dir);
49 }
50
51 std::ofstream os(path.c_str(), std::ios::binary);
52 cereal::JSONOutputArchive oarchive(os);
53 oarchive(savedGroups);
54}
55
56void Serialize::restoreGroups()
57{
George Liu2098aa62020-05-09 11:26:35 +080058 if (!fs::exists(path))
59 {
George Liue9fb5c62021-07-01 14:05:32 +080060 lg2::info("File does not exist, FILE_PATH = {PATH}", "PATH", path);
George Liu2098aa62020-05-09 11:26:35 +080061 return;
62 }
63
64 try
65 {
66 std::ifstream is(path.c_str(), std::ios::in | std::ios::binary);
67 cereal::JSONInputArchive iarchive(is);
68 iarchive(savedGroups);
69 }
Patrick Williamsfb56fde2021-10-06 12:27:15 -050070 catch (const cereal::Exception& e)
George Liu2098aa62020-05-09 11:26:35 +080071 {
George Liue9fb5c62021-07-01 14:05:32 +080072 lg2::error("Failed to restore groups, ERROR = {ERROR}", "ERROR", e);
George Liu2098aa62020-05-09 11:26:35 +080073 fs::remove(path);
74 }
75}
76
77} // namespace led
78} // namespace phosphor