blob: cd48a8cb8f64e7a964f9bdef54b395eb794a37f5 [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>
8#include <phosphor-logging/log.hpp>
9
10#include <filesystem>
11#include <fstream>
12
13// Register class version with Cereal
14CEREAL_CLASS_VERSION(phosphor::led::Serialize, CLASS_VERSION);
15
16namespace phosphor
17{
18namespace led
19{
20
21namespace fs = std::filesystem;
22
23bool Serialize::getGroupSavedState(const std::string& objPath) const
24{
25 return savedGroups.find(objPath) == savedGroups.end() ? false : true;
26}
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{
58 using namespace phosphor::logging;
59
60 if (!fs::exists(path))
61 {
62 log<level::INFO>("File does not exist",
63 entry("FILE_PATH=%s", path.c_str()));
64 return;
65 }
66
67 try
68 {
69 std::ifstream is(path.c_str(), std::ios::in | std::ios::binary);
70 cereal::JSONInputArchive iarchive(is);
71 iarchive(savedGroups);
72 }
73 catch (cereal::Exception& e)
74 {
75 log<level::ERR>(e.what());
76 fs::remove(path);
77 }
78}
79
80} // namespace led
81} // namespace phosphor