soundboard/src/config.cpp

79 lines
1.7 KiB
C++
Raw Normal View History

2021-12-13 14:48:43 +01:00
#include "config.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <stdlib.h> // realpath
#include <libgen.h> // dirname
2021-12-13 14:48:43 +01:00
#include <nlohmann/json.hpp>
using json = nlohmann::json;
2021-12-20 21:59:20 +01:00
#include <iomanip>
#include <Log.h>
2021-12-20 21:59:20 +01:00
#include "config_json.cpp" // json parsing in diffrent file
2021-12-13 14:48:43 +01:00
2022-02-26 16:00:02 +01:00
const uint8_t Config::ButtonConfig::DEFAULTWIDTH = 6;
Config::Config(const std::string binaryArgument) {
2022-02-26 16:00:02 +01:00
#if __unix__
char* buff = realpath(binaryArgument.c_str(), NULL); // buff needs free !
//ssize_t read = readlink(binaryArgument.c_str(), buf, MAXBUF);
if(buff) {
// success
char* binPath = dirname(buff);
binaryPath = std::string(binPath) + '/';
free(buff);
} else {
// error
Log::error << "unable to read path of the binaryFile";
}
2022-02-26 16:00:02 +01:00
#else
(void) binaryArgument;
binaryPath = "./";
#endif
2021-12-13 14:48:43 +01:00
}
Config::~Config() {
}
2021-12-19 15:53:57 +01:00
bool Config::SampleConfig::isValid() const {
2021-12-13 14:48:43 +01:00
return !file.empty();
}
2021-12-19 15:53:57 +01:00
bool Config::ButtonConfig::isValid() const {
bool validfound = std::any_of(samples.begin(), samples.end(), [](const SampleConfig& sc){ return sc.isValid(); });
return !samples.empty() && !name.empty() && validfound;
}
2021-12-13 14:48:43 +01:00
void Config::load() {
std::ifstream stream(binaryPath + file);
2021-12-13 14:48:43 +01:00
json json;
if(stream) {
try {
stream >> json;
rootConfig = json;
2021-12-13 14:48:43 +01:00
} catch(nlohmann::detail::parse_error& pe) {
std::cout << "json error: " << pe.what() << std::endl;
return;
}
} else {
Log::error << "config File not found";
2021-12-21 20:19:24 +01:00
// just save the current config to create a file
save();
2021-12-13 14:48:43 +01:00
}
}
2021-12-20 21:59:20 +01:00
void Config::save() {
std::ofstream stream(binaryPath + file);
if(stream) {
json j = rootConfig;
stream << j.dump(1, '\t');
} else {
Log::error << "could not write configfile";
}
2022-02-26 16:00:02 +01:00
}