WaterLevelSensor/configinterface.cpp

108 lines
2.8 KiB
C++
Raw Normal View History

2026-04-01 18:33:19 +05:30
#include "configinterface.h"
ConfigInterface::ConfigInterface(QObject *parent)
: QObject{parent}
{
auto paths = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
qDebug() << "Got writable path as: " << paths;
std::filesystem::path dir = paths.toStdString();
if(!QDir(dir).exists()) {
QDir().mkpath(paths);
}
std::filesystem::path path = dir / "config.json";
QFile config(path);
if(config.exists()) {
qDebug() << "Loading config file....";
bool ok = config.open(QFile::ReadOnly);
if(!ok) {
qDebug() << config.errorString();
return;
}
auto data = config.readAll();
config.close();
QJsonObject top = QJsonDocument::fromJson(data).object();
QString max, min, alert;
max = top["max_threshold"].toString();
min = top["min_threshold"].toString();
alert = top["alert_threshold"].toString();
setMax(max);
setMin(min);
setAlert(alert);
}
else {
qDebug() << "File does not exist creating one...";
QJsonObject top;
top["max_threshold"] = "125";
top["min_threshold"] = "25";
top["alert_threshold"] = "100";
QByteArray data = QJsonDocument(top).toJson();
bool ok = config.open(QFile::WriteOnly);
if(!ok) {
qDebug() << config.errorString();
return;
}
config.write(data);
config.flush();
config.close();
}
}
void ConfigInterface::saveConfig(QString max, QString min, QString alert)
{
auto paths = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
qDebug() << "Got writable path as: " << paths;
std::filesystem::path path = paths.toStdString();
QFile config(path / "config.json");
qDebug() << "Writing to config file..." << max << min << alert;
QJsonObject top;
top["max_threshold"] = max;
top["min_threshold"] = min;
top["alert_threshold"] = alert;
setMax(max);
setMin(min);
setAlert(alert);
QByteArray data = QJsonDocument(top).toJson();
config.open(QIODevice::WriteOnly);
config.write(data);
config.flush();
config.close();
}
QString ConfigInterface::alert() const
{
return m_alert;
}
void ConfigInterface::setAlert(const QString &newAlert)
{
if (m_alert == newAlert)
return;
m_alert = newAlert;
emit alertChanged();
}
QString ConfigInterface::max() const
{
return m_max;
}
void ConfigInterface::setMax(const QString &newMax)
{
if (m_max == newMax)
return;
m_max = newMax;
emit maxChanged();
}
QString ConfigInterface::min() const
{
return m_min;
}
void ConfigInterface::setMin(const QString &newMin)
{
if (m_min == newMin)
return;
m_min = newMin;
emit minChanged();
}