blob: 598209318c92d2a544ef10ccbd48cf6946f06bc6 [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);
35 if (iter != savedGroups.end() && asserted == false)
36 {
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
59 if (!fs::exists(path))
60 {
George Liue9fb5c62021-07-01 14:05:32 +080061 lg2::info("File does not exist, FILE_PATH = {PATH}", "PATH", path);
George Liu2098aa62020-05-09 11:26:35 +080062 return;
63 }
64
65 try
66 {
67 std::ifstream is(path.c_str(), std::ios::in | std::ios::binary);
68 cereal::JSONInputArchive iarchive(is);
69 iarchive(savedGroups);
70 }
Patrick Williamsfb56fde2021-10-06 12:27:15 -050071 catch (const cereal::Exception& e)
George Liu2098aa62020-05-09 11:26:35 +080072 {
George Liue9fb5c62021-07-01 14:05:32 +080073 lg2::error("Failed to restore groups, ERROR = {ERROR}", "ERROR", e);
George Liu2098aa62020-05-09 11:26:35 +080074 fs::remove(path);
75 }
76}
77
78} // namespace led
79} // namespace phosphor