Add deserialization logic

This commit is contained in:
2022-09-24 17:23:12 +02:00
parent 61923121f0
commit d3cd6857d0
8 changed files with 79 additions and 17 deletions

View File

@@ -2,12 +2,15 @@
#include <fstream>
#include <iostream>
#include <memory>
#include <Serializer.h>
#include <fan/HwmonFan.h>
#include <fan/PwmControl.h>
#include <sensor/HwmonSensor.h>
namespace fs = std::filesystem;
#define SERIALIZATION_DIR "/etc/fantasize"
#define FANS_JSON_FILENAME "fans.json"
using namespace std;
namespace fs = filesystem;
Serializer::Serializer() {
if (!fs::exists(SERIALIZATION_DIR)) {
@@ -15,24 +18,52 @@ Serializer::Serializer() {
}
}
void Serializer::Serialize(std::vector<std::shared_ptr<Fan>> fans) {
void Serializer::Serialize(vector<shared_ptr<Fan>> fans) {
json fansArr;
for (auto f : fans) {
fansArr.push_back(f->toJson());
fansArr.emplace_back(f->toJson());
}
json obj;
obj["fans"] = fansArr;
std::cout << "Json obj: " << obj.dump(2) << std::endl;
cout << "Json obj: " << obj.dump(2) << endl;
WriteJson(obj);
}
vector<shared_ptr<Fan>>
Serializer::Deserialize(vector<shared_ptr<Sensor>> availableSensors) {
vector<shared_ptr<Fan>> mapping;
// Create a for the sensors first, then searching becomes cheaper
map<string, shared_ptr<Sensor>> sensorMap;
for (auto s : availableSensors) {
sensorMap[s->toString()] = s;
}
auto data = ReadJson();
try {
for (auto &el : data["fans"].items()) {
auto pwmControl = make_shared<PwmControl>(el.value()["PwmControl"]);
auto rpmSensor = sensorMap[el.value()["HwmonSensor"]];
mapping.push_back(make_shared<HwmonFan>(pwmControl, rpmSensor));
}
} catch (const std::exception &e) {
std::cout << "Deserialization error! Message: " << e.what() << std::endl;
}
return mapping;
}
void Serializer::WriteJson(json o) {
std::ofstream ostrm(fs::path(SERIALIZATION_DIR) / FANS_JSON_FILENAME,
std::ios::trunc);
ofstream ostrm(fs::path(SERIALIZATION_DIR) / FANS_JSON_FILENAME, ios::trunc);
ostrm << o.dump(2) << "\n";
}
json Serializer::ReadJson() {
ifstream istrm(fs::path(SERIALIZATION_DIR) / FANS_JSON_FILENAME);
return json::parse(istrm);
}