Skip to content

Commit fc308e8

Browse files
committed
Refactor FileConfig.
1 parent fceb152 commit fc308e8

File tree

10 files changed

+134
-82
lines changed

10 files changed

+134
-82
lines changed

sources/config.cpp

Lines changed: 0 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -27,60 +27,6 @@ spdlog::level::level_enum parseLogLevel(const std::string& level) {
2727
}
2828

2929
Config::Config(const ArgConfig& argConfig, const FileConfig& fileConfig) : m_id(!argConfig.id.empty() ? argConfig.id : randomHex(8)), m_argConfig(argConfig), m_fileConfig(fileConfig) {}
30-
31-
Config Config::loadFromFile(const std::string& path, const ArgConfig& argConfig) {
32-
std::ifstream stream(path);
33-
if (stream) {
34-
try {
35-
auto json = nlohmann::json::parse(stream);
36-
ConfigMigrator::update(json);
37-
FileConfig fileConfig(json);
38-
SdrDeviceReader::updateDevices(fileConfig.devices);
39-
return Config(argConfig, fileConfig);
40-
} catch (const nlohmann::json::parse_error& exception) {
41-
Logger::info(LABEL, "config parse error, creating default");
42-
FileConfig fileConfig;
43-
SdrDeviceReader::updateDevices(fileConfig.devices);
44-
Config::saveToFile(path, static_cast<nlohmann::json>(fileConfig));
45-
return Config(argConfig, fileConfig);
46-
}
47-
} else {
48-
Logger::info(LABEL, "config not found, creating default");
49-
FileConfig fileConfig;
50-
SdrDeviceReader::updateDevices(fileConfig.devices);
51-
Config::saveToFile(path, static_cast<nlohmann::json>(fileConfig));
52-
return Config(argConfig, fileConfig);
53-
}
54-
}
55-
56-
void Config::saveToFile(const std::string& path, const nlohmann::json& json) {
57-
std::ofstream stream(path);
58-
if (stream) {
59-
auto tmp = json;
60-
SdrDeviceReader::clearDevices(tmp);
61-
ConfigMigrator::sort(tmp);
62-
stream << std::setw(4) << tmp << std::endl;
63-
} else {
64-
Logger::warn(LABEL, "save new config failed");
65-
}
66-
}
67-
68-
nlohmann::json Config::hideSensitiveData(const nlohmann::json& json) {
69-
nlohmann::json config(json);
70-
try {
71-
if (!config["api_key"].empty()) {
72-
config["api_key"] = "******";
73-
}
74-
std::regex regex(R"(^(\d+)\.\d+)");
75-
config["position"]["latitude"] = std::regex_replace(config["position"]["latitude"].get<std::string>(), regex, "$1.********");
76-
config["position"]["longitude"] = std::regex_replace(config["position"]["longitude"].get<std::string>(), regex, "$1.********");
77-
} catch (const std::exception& exception) {
78-
Logger::warn(LABEL, "hide sensitive data exception: {}", colored(RED, "{}", exception.what()));
79-
}
80-
return config;
81-
}
82-
83-
nlohmann::json Config::json() const { return static_cast<nlohmann::json>(m_fileConfig); }
8430
std::string Config::mqtt() const { return fmt::format("{}@{}", m_argConfig.mqttUser, m_argConfig.mqttUrl); };
8531

8632
std::string Config::getId() const { return m_id; }

sources/config.h

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,7 @@ constexpr auto SPECTROGRAM_SEND_INTERVAL = std::chrono::milliseconds(1000); //
3838

3939
class Config {
4040
public:
41-
static Config loadFromFile(const std::string& path, const ArgConfig& argConfig);
42-
static void saveToFile(const std::string& path, const nlohmann::json& json);
43-
static nlohmann::json hideSensitiveData(const nlohmann::json& json);
44-
nlohmann::json json() const;
41+
Config(const ArgConfig& argConfig, const FileConfig& fileConfig);
4542
std::string mqtt() const;
4643

4744
std::string getId() const;
@@ -68,9 +65,7 @@ class Config {
6865
int altitude() const;
6966

7067
private:
71-
Config(const ArgConfig& argConfig, const FileConfig& fileConfig);
72-
7368
const std::string m_id;
7469
const ArgConfig& m_argConfig;
75-
const FileConfig m_fileConfig;
70+
const FileConfig& m_fileConfig;
7671
};

sources/file_config.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include "file_config.h"
2+
3+
#include <config_migrator.h>
4+
#include <logger.h>
5+
#include <radio/sdr_device_reader.h>
6+
7+
#include <regex>
8+
9+
constexpr auto LABEL = "config";
10+
11+
FileConfig FileConfig::fromJson(nlohmann::json json) {
12+
ConfigMigrator::update(json);
13+
FileConfig fileConfig(json);
14+
SdrDeviceReader::updateDevices(fileConfig.devices);
15+
return fileConfig;
16+
}
17+
18+
nlohmann::json FileConfig::toSave(nlohmann::json json) {
19+
SdrDeviceReader::clearDevices(json);
20+
ConfigMigrator::sort(json);
21+
return json;
22+
}
23+
24+
nlohmann::json FileConfig::toPrint(nlohmann::json json) {
25+
try {
26+
if (!json["api_key"].empty()) {
27+
json["api_key"] = "******";
28+
}
29+
std::regex regex(R"(^(\d+)\.\d+)");
30+
json["position"]["latitude"] = std::regex_replace(json["position"]["latitude"].get<std::string>(), regex, "$1.********");
31+
json["position"]["longitude"] = std::regex_replace(json["position"]["longitude"].get<std::string>(), regex, "$1.********");
32+
} catch (const std::exception& exception) {
33+
Logger::warn(LABEL, "hide sensitive data exception: {}", colored(RED, "{}", exception.what()));
34+
}
35+
return json;
36+
}

sources/file_config.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,5 +43,9 @@ struct FileConfig {
4343
RecordingConfig recording;
4444
int version = 1;
4545
int workers = 0;
46+
47+
static FileConfig fromJson(nlohmann::json json);
48+
static nlohmann::json toSave(nlohmann::json json);
49+
static nlohmann::json toPrint(nlohmann::json json);
4650
};
4751
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(FileConfig, api_key, devices, ignored_frequencies, output, position, recording, version, workers)

sources/main.cpp

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <network/remote_controller.h>
66
#include <scanner.h>
77
#include <signal.h>
8+
#include <utils/file_utils.h>
89

910
#include <CLI/CLI.hpp>
1011
#include <memory>
@@ -43,20 +44,50 @@ int main(int argc, char** argv) {
4344
Logger::configure(spdlog::level::info, spdlog::level::info, argConfig.logFileName, argConfig.logFileSize, argConfig.logFileCount, true);
4445
Logger::info(LABEL, "{}", colored(GREEN, "{}", "starting"));
4546

47+
nlohmann::json tmpJson;
4648
while (isRunning) {
4749
bool reload = false;
48-
const Config config = Config::loadFromFile(argConfig.configFile, argConfig);
50+
const auto fileJson = tmpJson.empty() ? readFromFile(argConfig.configFile, static_cast<nlohmann::json>(FileConfig())) : tmpJson;
51+
const auto fileConfig = FileConfig::fromJson(fileJson);
52+
const Config config(argConfig, fileConfig);
4953
Logger::configure(config.consoleLogLevel(), config.fileLogLevel(), argConfig.logFileName, argConfig.logFileSize, argConfig.logFileCount, config.isColorLogEnabled());
50-
Logger::info(LABEL, "config: {}", colored(GREEN, "{}", Config::hideSensitiveData(config.json()).dump()));
54+
Logger::info(LABEL, "config: {}", colored(GREEN, "{}", FileConfig::toPrint(fileJson).dump()));
5155
Logger::info(LABEL, "mqtt: {}", colored(GREEN, "{}", config.mqtt()));
5256

5357
Mqtt mqtt(config);
5458
RemoteController remoteController(config, mqtt);
55-
remoteController.reloadConfigCallback([&reload, &argConfig, &remoteController](const nlohmann::json& json) {
56-
Logger::info(LABEL, "reload config: {}", colored(GREEN, "{}", Config::hideSensitiveData(json).dump()));
57-
Config::saveToFile(argConfig.configFile, json);
58-
remoteController.reloadConfigStatus(true);
59+
remoteController.setConfigQuery([&reload, &argConfig, &remoteController, &tmpJson](const nlohmann::json& json) {
60+
try {
61+
Logger::info(LABEL, "set config: {}", colored(GREEN, "{}", FileConfig::toPrint(json).dump()));
62+
saveToFile(argConfig.configFile, FileConfig::toSave(json));
63+
reload = true;
64+
tmpJson.clear();
65+
remoteController.setConfigResponse(true);
66+
} catch (const std::runtime_error& exception) {
67+
Logger::warn(LABEL, "set config exception: {}", exception.what());
68+
remoteController.setConfigResponse(false);
69+
}
70+
});
71+
remoteController.resetTmpConfigQuery([&reload, &argConfig, &remoteController, &tmpJson](const std::string&) {
72+
Logger::info(LABEL, "reset tmp config");
5973
reload = true;
74+
tmpJson.clear();
75+
remoteController.resetTmpConfigResponse(true);
76+
});
77+
remoteController.setTmpConfigQuery([&reload, &argConfig, &remoteController, &tmpJson](const nlohmann::json& json) {
78+
try {
79+
Logger::info(LABEL, "set tmp config: {}", colored(GREEN, "{}", FileConfig::toPrint(json).dump()));
80+
reload = true;
81+
tmpJson = json;
82+
remoteController.setConfigResponse(true);
83+
} catch (const std::runtime_error& exception) {
84+
Logger::warn(LABEL, "set tmp config exception: {}", exception.what());
85+
remoteController.setConfigResponse(false);
86+
}
87+
});
88+
remoteController.getConfigQuery([&remoteController, &fileConfig](const std::string&) {
89+
Logger::info(LABEL, "get config");
90+
remoteController.getConfigResponse(static_cast<nlohmann::json>(fileConfig).dump());
6091
});
6192
std::vector<std::unique_ptr<Scanner>> scanners;
6293
for (const auto& device : config.devices()) {

sources/network/mqtt.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
class Mqtt {
1616
public:
17-
using RawCallback = std::function<void(const nlohmann::json&)>;
17+
using RawCallback = std::function<void(const std::string&)>;
1818
using JsonCallback = std::function<void(const nlohmann::json&)>;
1919

2020
Mqtt(const Config& config);

sources/network/remote_controller.cpp

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,30 @@
77
constexpr auto LIST = "list";
88
constexpr auto STATUS = "status";
99
constexpr auto CONFIG = "config";
10+
constexpr auto TMP_CONFIG = "tmp_config";
11+
constexpr auto RESET_TMP_CONFIG = "reset_tmp_config";
1012
constexpr auto SCHEDULER = "scheduler";
1113
constexpr auto SUCCESS = "success";
1214
constexpr auto FAILED = "failed";
1315
constexpr auto LABEL = "remote";
1416

1517
using namespace std::placeholders;
1618

17-
RemoteController::RemoteController(const Config& config, Mqtt& mqtt) : m_config(config), m_mqtt(mqtt) {
18-
mqtt.setRawMessageCallback(fmt::format("sdr/{}", LIST), std::bind(&RemoteController::listCallback, this, _1));
19-
Logger::info(LABEL, "started, id: {}", colored(GREEN, "{}", m_config.getId()));
20-
}
19+
RemoteController::RemoteController(const Config& config, Mqtt& mqtt) : m_config(config), m_mqtt(mqtt) { Logger::info(LABEL, "started, id: {}", colored(GREEN, "{}", m_config.getId())); }
2120

22-
void RemoteController::reloadConfigCallback(const Mqtt::JsonCallback& callback) { m_mqtt.setJsonMessageCallback(fmt::format("sdr/{}/{}", CONFIG, m_config.getId()), callback); }
21+
void RemoteController::getConfigQuery(const Mqtt::RawCallback& callback) { m_mqtt.setRawMessageCallback(fmt::format("sdr/{}", LIST), callback); }
22+
void RemoteController::getConfigResponse(const std::string& data) { m_mqtt.publish(fmt::format("sdr/{}/{}", STATUS, m_config.getId()), data, 2); }
2323

24-
void RemoteController::reloadConfigStatus(const bool& success) { m_mqtt.publish(fmt::format("sdr/{}/{}/{}", CONFIG, m_config.getId(), success ? SUCCESS : FAILED), "", 2); }
24+
void RemoteController::setConfigQuery(const Mqtt::JsonCallback& callback) { m_mqtt.setJsonMessageCallback(fmt::format("sdr/{}/{}", CONFIG, m_config.getId()), callback); }
25+
void RemoteController::setConfigResponse(const bool& success) { m_mqtt.publish(fmt::format("sdr/{}/{}/{}", CONFIG, m_config.getId(), success ? SUCCESS : FAILED), "", 2); }
2526

26-
void RemoteController::schedulerQuery(const std::string& device, const std::string& query) { m_mqtt.publish(fmt::format("sdr/{}/{}/{}/get", SCHEDULER, m_config.getId(), device), query, 2); }
27+
void RemoteController::resetTmpConfigQuery(const Mqtt::RawCallback& callback) { m_mqtt.setRawMessageCallback(fmt::format("sdr/{}/{}", RESET_TMP_CONFIG, m_config.getId()), callback); }
28+
void RemoteController::resetTmpConfigResponse(const bool& success) { m_mqtt.publish(fmt::format("sdr/{}/{}/{}", RESET_TMP_CONFIG, m_config.getId(), success ? SUCCESS : FAILED), "", 2); }
29+
30+
void RemoteController::setTmpConfigQuery(const Mqtt::JsonCallback& callback) { m_mqtt.setJsonMessageCallback(fmt::format("sdr/{}/{}", TMP_CONFIG, m_config.getId()), callback); }
31+
void RemoteController::setTmpConfigResponse(const bool& success) { m_mqtt.publish(fmt::format("sdr/{}/{}/{}", TMP_CONFIG, m_config.getId(), success ? SUCCESS : FAILED), "", 2); }
2732

33+
void RemoteController::schedulerQuery(const std::string& device, const std::string& query) { m_mqtt.publish(fmt::format("sdr/{}/{}/{}/get", SCHEDULER, m_config.getId(), device), query, 2); }
2834
void RemoteController::schedulerCallback(const std::string& device, const Mqtt::JsonCallback& callback) {
2935
m_mqtt.setJsonMessageCallback(fmt::format("sdr/{}/{}/{}/set", SCHEDULER, m_config.getId(), device), callback);
3036
}
31-
32-
void RemoteController::listCallback(const std::string&) {
33-
Logger::info(LABEL, "received list");
34-
m_mqtt.publish(fmt::format("sdr/{}/{}", STATUS, m_config.getId()), m_config.json().dump(), 2);
35-
}

sources/network/remote_controller.h

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,17 @@ class RemoteController {
1010
public:
1111
RemoteController(const Config& config, Mqtt& mqtt);
1212

13-
void reloadConfigCallback(const Mqtt::JsonCallback& callback);
14-
void reloadConfigStatus(const bool& success);
13+
void getConfigQuery(const Mqtt::RawCallback& callback);
14+
void getConfigResponse(const std::string& data);
15+
16+
void setConfigQuery(const Mqtt::JsonCallback& callback);
17+
void setConfigResponse(const bool& success);
18+
19+
void resetTmpConfigQuery(const Mqtt::RawCallback& callback);
20+
void resetTmpConfigResponse(const bool& success);
21+
22+
void setTmpConfigQuery(const Mqtt::JsonCallback& callback);
23+
void setTmpConfigResponse(const bool& success);
1524

1625
void schedulerQuery(const std::string& device, const std::string& query);
1726
void schedulerCallback(const std::string& device, const Mqtt::JsonCallback& callback);

sources/utils/file_utils.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include "file_utils.h"
2+
3+
#include <fstream>
4+
5+
nlohmann::json readFromFile(const std::string& path, const nlohmann::json& defaultValue) {
6+
std::ifstream stream(path);
7+
if (stream) {
8+
try {
9+
return nlohmann::json::parse(stream);
10+
} catch (const std::runtime_error&) {
11+
return defaultValue;
12+
}
13+
} else {
14+
return defaultValue;
15+
}
16+
}
17+
18+
void saveToFile(const std::string& path, const nlohmann::json& json) {
19+
std::ofstream stream(path);
20+
if (stream) {
21+
stream << std::setw(4) << json << std::endl;
22+
}
23+
}

sources/utils/file_utils.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#pragma once
2+
3+
#include <nlohmann/json.hpp>
4+
5+
nlohmann::json readFromFile(const std::string& path, const nlohmann::json& defaultValue = {});
6+
7+
void saveToFile(const std::string& path, const nlohmann::json& json);

0 commit comments

Comments
 (0)