1 #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/lg2.hpp>
9 
10 #include <filesystem>
11 #include <fstream>
12 
13 // Register class version with Cereal
14 CEREAL_CLASS_VERSION(phosphor::led::Serialize, CLASS_VERSION)
15 
16 namespace phosphor
17 {
18 namespace led
19 {
20 
21 namespace fs = std::filesystem;
22 
getGroupSavedState(const std::string & objPath) const23 bool Serialize::getGroupSavedState(const std::string& objPath) const
24 {
25     return savedGroups.contains(objPath);
26 }
27 
storeGroups(const std::string & group,bool asserted)28 void 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)
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 
restoreGroups()56 void Serialize::restoreGroups()
57 {
58     if (!fs::exists(path))
59     {
60         lg2::info("File does not exist, FILE_PATH = {PATH}", "PATH", path);
61         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     }
70     catch (const cereal::Exception& e)
71     {
72         lg2::error("Failed to restore groups, ERROR = {ERROR}", "ERROR", e);
73         fs::remove(path);
74     }
75 }
76 
77 } // namespace led
78 } // namespace phosphor
79