#include "Application.h" #include "common/Utils.h" #include "Config.h" #include "app/Device.h" #include "database/DaoEntity.h" #include "database/Dao.h" #include "app/Station.h" #include "app/Device.h" #include "protocol/HttpEntity.h" #include "common/Spdlogger.h" #include "protocol/MqttEntity.h" void Application::init() { // 初始化系统配置,读取配置文件 Config::init("assets/config/app.json"); // MQTT 数据结构 MqttClient::loadDataStruct("assets/config/registeraddr.json"); // 设备读取寄存器的地址定义 Device::loadParamAddr("assets/config/monitoraddr.json"); // 设置数据库配置 DaoEntity::setOption(Config::option.database.host, Config::option.database.port, Config::option.database.user, Config::option.database.passwd, Config::option.database.dbname); spdlog::info("[app] set database option: host={}, port={}, user={}, dbname={}", Config::option.database.host, Config::option.database.port, Config::option.database.user, Config::option.database.dbname); // 连接数据库,读取基础信息 // 初始化系统基础数据 this->isInit = appdata.init(); // 创建设备处理线程 std::thread([=]() { runThreadDevice(); }).detach(); // 创建HTTP服务线程 std::thread([=]() { while (!isQuit) { HttpEntity http; http.listen("0.0.0.0", Config::option.http.port); // 阻塞 } }).detach(); // 统计分析 std::thread([=]() { runThreadStat(); }).detach(); // 创建主业务循环线程 std::thread([=]() { runThreadMain(); }).detach(); } void Application::runThreadDevice() { while (!isQuit) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } void Application::runThreadMain() { std::string addr = "tcp://localhost:1883"; //mqttCli = std::make_shared(); //mqttCli->init(addr, "ESS", "", "", {}); while (!isQuit) { if (!this->isInit) // 初始化失败 { std::this_thread::sleep_for(std::chrono::milliseconds(10000)); this->isInit = appdata.init(); if (!this->isInit) { continue; } } static TimeTick ttMqtt; // 检查 场站的 MQTT 连接 if (ttMqtt.elapse(10)) { auto& optionMqtt = Config::option.mqtt; if (!optionMqtt.host.empty()) { for (auto& item : appdata.mapStation) { if (item.second) { item.second->initMqtt(); //item.second->polling(); } } } } /////////////////////////////////////////////////////////////////////////////////////////// /// 召测 static TimeTick tt1; if (tt1.elapse(10)) { } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void Application::runThreadStat() { int nCachePos = 0; while (!isQuit) { int64_t tTime = Utils::time(); int64_t tDate = Utils::date(); int64_t delta = tTime-tDate; int n = delta / 600; int offset = delta % 600; bool flagStore = (delta >=0 && delta < 86400 && offset <= 10 && n != nCachePos); if (flagStore) { nCachePos = n; std::string dt = Utils::dateStr(tDate); for (auto item: appdata.mapStation) { item.second->writeRuntimeData(dt, nCachePos); } } else { //spdlog::info("保存历史数据倒计时: {}", 600 - offset); } for (auto& station : appdata.mapStation) { } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } }