soundboard/src/config.cpp

104 lines
2.3 KiB
C++

#include "config.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <stdlib.h> // realpath
#include <libgen.h> // dirname
#include <nlohmann/json.hpp>
using json = nlohmann::json;
#include <iomanip>
#include <Log.h>
#include "config_json.cpp" // json parsing in diffrent file
const uint8_t Config::ButtonConfig::DEFAULTWIDTH = 6;
Config::Config(const std::string binaryArgument) {
#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";
}
#else
(void) binaryArgument;
binaryPath = "./";
#endif
}
Config::~Config() {
}
bool Config::SampleConfig::isValid() const {
return !file.empty();
}
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;
}
void Config::load() {
std::ifstream stream(binaryPath + file);
json json;
if(stream) {
try {
stream >> json;
rootConfig = json;
assignIDs();
} catch(nlohmann::detail::parse_error& pe) {
std::cout << "json error: " << pe.what() << std::endl;
return;
}
} else {
Log::error << "config File not found";
// just save the current config to create a file
save();
}
}
void Config::save() {
std::ofstream stream(binaryPath + file);
if(stream) {
json j = rootConfig;
stream << j.dump(1, '\t');
assignIDs();
} else {
Log::error << "could not write configfile";
}
}
void Config::assignIDs() {
for(uint32_t row = 0; row < rootConfig.buttons.size(); ++row) {
auto& r = rootConfig.buttons.at(row);
for(uint32_t col = 0; col < r.size(); ++col) {
auto& btn = r.at(col);
btn.id = ((row+1) * 100) + (col+1); // TODO: problems when more than 99 colums in one row but should be fine for now
}
}
}
const Config::ButtonConfig* Config::getButtonByID(uint32_t btnid) const {
uint32_t row = (btnid / 100) -1;
uint32_t col = (btnid % 100) -1;
if(row >= rootConfig.buttons.size()) return nullptr;
const auto& rowref = rootConfig.buttons.at(row);
if(col >= rowref.size()) return nullptr;
return &rowref.at(col);
}