diff --git a/src/app/AppData.cpp b/src/app/AppData.cpp index e2e265f..1468c92 100644 --- a/src/app/AppData.cpp +++ b/src/app/AppData.cpp @@ -11,19 +11,19 @@ void ElectPeriod::parse(std::string jsonstr) { - NJsonNode jsonroot; - NJson::parse(jsonstr, jsonroot); + njson jsonroot; + JSON::parse(jsonstr, jsonroot); - NJson::read(jsonroot, "price_super_peak", this->priceSuperPeak); - NJson::read(jsonroot, "price_peak", this->pricePeak); - NJson::read(jsonroot, "price_shoulder", this->priceShoulder); - NJson::read(jsonroot, "price_off_peak", this->priceOffPeak); - NJson::read>>(jsonroot, "periods", this->vecPeriods); + JSON::read(jsonroot, "price_super_peak", this->priceSuperPeak); + JSON::read(jsonroot, "price_peak", this->pricePeak); + JSON::read(jsonroot, "price_shoulder", this->priceShoulder); + JSON::read(jsonroot, "price_off_peak", this->priceOffPeak); + JSON::read>>(jsonroot, "periods", this->vecPeriods); } std::string ElectPeriod::dump() { - NJsonNode jsonroot; + njson jsonroot; jsonroot["price_super_peak"] = this->priceSuperPeak; jsonroot["price_peak"] = this->pricePeak; jsonroot["price_shoulder"] = this->priceShoulder; @@ -130,8 +130,6 @@ void AppData::initFromDB() if (station) { auto device = Device::create(fields); - auto deviceTypeDef = this->getDeviceTypeDef(device->type); - device->group = deviceTypeDef->group; station->addDevice(deviceId, device); } else diff --git a/src/app/Config.cpp b/src/app/Config.cpp index da13feb..8d6ba2d 100644 --- a/src/app/Config.cpp +++ b/src/app/Config.cpp @@ -10,8 +10,8 @@ AppOption Config::option; bool Config::init(std::string filename) { - NJsonNode jsonroot; - bool ret = NJson::load(filename, jsonroot); + njson jsonroot; + bool ret = JSON::load(filename, jsonroot); if (!ret) { spdlog::error("[config] load config file failed, filename={}", filename); @@ -21,7 +21,7 @@ bool Config::init(std::string filename) if (jsonroot.contains("database")) { - NJsonNode json = jsonroot.at("database"); + njson json = jsonroot.at("database"); option.database.host = json.contains("host") ? json.at("host") : ""; option.database.port = json.contains("port") ? json.at("port") : 0; option.database.user = json.contains("user") ? json.at("user") : ""; @@ -37,11 +37,11 @@ bool Config::init(std::string filename) if (jsonroot.contains("http")) { - NJsonNode json = jsonroot.at("http"); + njson json = jsonroot.at("http"); std:string token; - NJson::read(json, "token", token); + JSON::read(json, "token", token); option.http.useToken = !token.empty(); - NJson::read(json, "port", option.http.port); + JSON::read(json, "port", option.http.port); } else { @@ -50,10 +50,10 @@ bool Config::init(std::string filename) if (jsonroot.contains("mqtt")) { - NJsonNode json = jsonroot.at("mqtt"); - NJson::read(json, "host", option.mqtt.host); - NJson::read(json, "username", option.mqtt.username); - NJson::read(json, "password", option.mqtt.password); + njson json = jsonroot.at("mqtt"); + JSON::read(json, "host", option.mqtt.host); + JSON::read(json, "username", option.mqtt.username); + JSON::read(json, "password", option.mqtt.password); } else { diff --git a/src/app/DataStruct.cpp b/src/app/DataStruct.cpp index e9f0c79..de57163 100644 --- a/src/app/DataStruct.cpp +++ b/src/app/DataStruct.cpp @@ -2,37 +2,37 @@ void EMSYX::fromJson(const std::string& str) { - NJsonNode jsonroot; - auto ret = NJson::parse(str, jsonroot); + njson jsonroot; + auto ret = JSON::parse(str, jsonroot); if (!ret) { return; } - NJson::read(jsonroot, "mcu", mcu); - NJson::read(jsonroot, "pcs", pcs); - NJson::read(jsonroot, "electMeterMainPoint", electMeterMainPoint); - NJson::read(jsonroot, "electMeter", electMeter); - NJson::read(jsonroot, "fireSystem", fireSystem); - NJson::read(jsonroot, "ups", ups); - NJson::read(jsonroot, "temHumMainPoint", temHumMainPoint); - NJson::read(jsonroot, "temHum", temHum); - NJson::read(jsonroot, "aircMainPoint", aircMainPoint); - NJson::read(jsonroot, "airc", airc); - NJson::read(jsonroot, "controlDryContact", controlDryContact); - NJson::read(jsonroot, "statusDryContact", statusDryContact); - NJson::read(jsonroot, "bcuMain", bcuMain); - NJson::read(jsonroot, "pcuMain", pcuMain); - NJson::read(jsonroot, "electMeterMain", electMeterMain); - NJson::read(jsonroot, "fireSystemMain", fireSystemMain); - NJson::read(jsonroot, "upsMain", upsMain); - NJson::read(jsonroot, "temHumMain", temHumMain); - NJson::read(jsonroot, "aircMain", aircMain); - NJson::read(jsonroot, "emu", emu); - NJson::read(jsonroot, "chillerMain", chillerMain); - NJson::read(jsonroot, "chillerMainPoint", chillerMainPoint); - NJson::read(jsonroot, "chiller", chiller); + JSON::read(jsonroot, "mcu", mcu); + JSON::read(jsonroot, "pcs", pcs); + JSON::read(jsonroot, "electMeterMainPoint", electMeterMainPoint); + JSON::read(jsonroot, "electMeter", electMeter); + JSON::read(jsonroot, "fireSystem", fireSystem); + JSON::read(jsonroot, "ups", ups); + JSON::read(jsonroot, "temHumMainPoint", temHumMainPoint); + JSON::read(jsonroot, "temHum", temHum); + JSON::read(jsonroot, "aircMainPoint", aircMainPoint); + JSON::read(jsonroot, "airc", airc); + JSON::read(jsonroot, "controlDryContact", controlDryContact); + JSON::read(jsonroot, "statusDryContact", statusDryContact); + JSON::read(jsonroot, "bcuMain", bcuMain); + JSON::read(jsonroot, "pcuMain", pcuMain); + JSON::read(jsonroot, "electMeterMain", electMeterMain); + JSON::read(jsonroot, "fireSystemMain", fireSystemMain); + JSON::read(jsonroot, "upsMain", upsMain); + JSON::read(jsonroot, "temHumMain", temHumMain); + JSON::read(jsonroot, "aircMain", aircMain); + JSON::read(jsonroot, "emu", emu); + JSON::read(jsonroot, "chillerMain", chillerMain); + JSON::read(jsonroot, "chillerMainPoint", chillerMainPoint); + JSON::read(jsonroot, "chiller", chiller); } std::string EMSYX::toJson() { - NJsonNode jsonroot; + njson jsonroot; jsonroot["bms"] = bms; jsonroot["bcu"] = bcu; jsonroot["mcu"] = mcu; diff --git a/src/app/Device.cpp b/src/app/Device.cpp index fec753a..35983e8 100644 --- a/src/app/Device.cpp +++ b/src/app/Device.cpp @@ -1,6 +1,6 @@ #include "Device.h" -#include "common/Logger.h" +#include "common/Spdlogger.h" #include "common/Utils.h" #include "protocol/CommEntity.h" #include "common/JsonN.h" @@ -44,26 +44,66 @@ int Device::startComm() return 0; } - // 从属性列表中获取通讯方式和通讯地址、端口 - std::string commType = attrs.value("commType"); - - // 如果entity的通讯协议类型当前配置不一致,需要关闭连接删除通讯后创建新的通讯 - if (commEntity && commEntity->type != commType) - { - commEntity->close(); - commEntity = nullptr; - } - // 创建新的通讯 - if (!commEntity) - { - commEntity = CommEntity::create(attrs); - if (!commEntity) { return -1; } - } - - commEntity->start(); + //// 从属性列表中获取通讯方式和通讯地址、端口 + //std::string commType = attrs.value("commType"); + // + //// 如果entity的通讯协议类型当前配置不一致,需要关闭连接删除通讯后创建新的通讯 + //if (commEntity && commEntity->type != commType) + //{ + // commEntity->close(); + // commEntity = nullptr; + //} + //// 创建新的通讯 + //if (!commEntity) + //{ + // commEntity = CommEntity::create(attrs); + // if (!commEntity) { return -1; } + //} + //commEntity->start(); return 0; } +void Device::getRuntimeParams(std::vector>& params) +{ + params.push_back({"额定电压", "0.0V"}); + params.push_back({"实时电压", "0.0V"}); + params.push_back({"额定电流", "0.0A"}); + params.push_back({"实时电流", "0.0A"}); + params.push_back({"额定功率", "0.0kW"}); + params.push_back({"实时功率", "0.0A"}); +} + +void Device::getCacheVoltage(std::vector& vec) +{ + vec.resize(mapCacheVoltage.size()); + int i = 0; + for (auto iter = mapCacheVoltage.begin(); iter != mapCacheVoltage.end(); ++iter) + { + vec[i] = Utils::toStr(iter->second); + i++; + } +} +void Device::getCacheCurrent(std::vector& vec) +{ + vec.resize(mapCacheCurrent.size()); + int i = 0; + for (auto iter = mapCacheCurrent.begin(); iter != mapCacheCurrent.end(); ++iter) + { + vec[i] = Utils::toStr(iter->second); + i++; + } +} +void Device::getCachePower(std::vector& vec) +{ + vec.resize(mapCachePower.size()); + int i = 0; + for (auto iter = mapCachePower.begin(); iter != mapCachePower.end(); ++iter) + { + vec[i] = Utils::toStr(iter->second); + i++; + } +} + std::shared_ptr Device::create(Fields& fields) { auto device = std::make_shared(); @@ -73,13 +113,14 @@ std::shared_ptr Device::create(Fields& fields) device->code = fields.value("code"); device->isOpen = fields.get("is_open"); device->attrsJson = fields.value("attrs"); + device->category = fields.get("category"); // 解析属性的JSON字符串,转换成键值对 - NJsonNode jsonroot; - bool ret = NJson::parse(device->attrsJson, jsonroot); + njson jsonroot; + bool ret = JSON::parse(device->attrsJson, jsonroot); if (!ret) // 解析错误 { - XLOGE() << "device attr json parse error, device_id=" << device->deviceId; + spdlog::error("[device] device attr json parse error, device_id={}", device->deviceId); } else { @@ -92,30 +133,23 @@ std::shared_ptr Device::create(Fields& fields) device->attrs.set(key, val.get()); } else { - XLOGE() << key << ": [" << valType << "]"; + spdlog::error("[device] device attr unknown type: key={}, valtype={}", key, valType); } } } + int step = 600; + for (int i = 0; i*600<86400; ++i) + { + double voltage = double(Utils::random(20000, 30000))*0.01; + double current = double(Utils::random(1000, 2000))*0.01; + device->mapCacheVoltage[i*step] = voltage; + device->mapCacheCurrent[i*step] = current; + device->mapCachePower[i*step] = voltage * current; + } + // 启动通讯,该函数中会自动判断isOpen状态,选择是否进行通讯连接 - device->startComm(); + //device->startComm(); return device; } - - - -// -//std::vector> Device::getDeviceByType(int type) -//{ -// std::vector> vecDevice; -// for (auto iter = mapDevices.begin(); iter!=mapDevices.end(); ++iter) -// { -// auto device = iter->second; -// if (device && (type<=0 || device->type == type)) -// { -// vecDevice.push_back(device); -// } -// } -// return vecDevice; -//} \ No newline at end of file diff --git a/src/app/Device.h b/src/app/Device.h index bcaa76e..1711d5c 100644 --- a/src/app/Device.h +++ b/src/app/Device.h @@ -16,13 +16,13 @@ public: int type = -1; std::string name; std::string code; - std::string group; + int category; bool isOpen = false; std::string attrsJson = ""; int err = 0; int online = 0; - int status = 0; + int running = 0; //std::map mapAttrs; Fields attrs; @@ -37,10 +37,16 @@ public: int64_t tsDataDate {}; - std::map mapCacheData; + std::map mapCacheVoltage; + std::map mapCacheCurrent; + std::map mapCachePower; // 启动通讯 int startComm(); + void getRuntimeParams(std::vector>& params); + void getCacheVoltage(std::vector& vec); + void getCacheCurrent(std::vector& vec); + void getCachePower(std::vector& vec); static std::shared_ptr create(Fields& fields); }; diff --git a/src/app/Station.cpp b/src/app/Station.cpp index fa63d52..d662804 100644 --- a/src/app/Station.cpp +++ b/src/app/Station.cpp @@ -42,7 +42,7 @@ void Station::setFields(Fields& fields) void Station::addDevice(int deviceId, std::shared_ptr device) { mapDevice[deviceId] = device; - mapDeviceGroupNum[device->group]++; + mapDeviceGroup[device->category].push_back(device); } std::shared_ptr Station::getDevice(int deviceId) @@ -67,20 +67,17 @@ void Station::getDeviceByType(int typeId, std::vector>& } } -int Station::getDeviceNumByGroup(std::string name) +int Station::getDeviceNumByGroup(int category) { - return mapDeviceGroupNum[name]; + return 0; } -void Station::getDeviceByGroup(std::string name, std::vector>& res) +void Station::getDeviceByGroup(int category, std::vector>& res) { - for (auto iter = mapDevice.begin(); iter!=mapDevice.end(); ++iter) + auto iter = mapDeviceGroup.find(category); + if (iter != mapDeviceGroup.end()) { - auto device = iter->second; - if (device->group == name) - { - res.push_back(device); - } + res = iter->second; } } diff --git a/src/app/Station.h b/src/app/Station.h index 569a45d..044a587 100644 --- a/src/app/Station.h +++ b/src/app/Station.h @@ -98,8 +98,8 @@ public: std::shared_ptr getDevice(int deviceId); void getDeviceByType(int typeId, std::vector>& res); - int getDeviceNumByGroup(std::string name); - void getDeviceByGroup(std::string name, std::vector>& res); + int getDeviceNumByGroup(int category); + void getDeviceByGroup(int category, std::vector>& res); void setWorkMode(int modeId); void setPolicy(int policyId); @@ -169,8 +169,8 @@ public: /////////////////////////////////////////////////////////////////////////////////////////////// /// === 设备信息 === std::unordered_map> mapDevice; + std::map>> mapDeviceGroup; - std::map mapDeviceGroupNum; // 温湿度信息 std::map mapTempHumUnit; @@ -184,4 +184,6 @@ public: /////////////////////////////////////////////////////////////////////////////////////////////// /// === MQTT client std::shared_ptr mqttCli {nullptr}; + + }; \ No newline at end of file diff --git a/src/common/Fields.cpp b/src/common/Fields.cpp index b580ddc..d70deeb 100644 --- a/src/common/Fields.cpp +++ b/src/common/Fields.cpp @@ -182,8 +182,8 @@ string Fields::toSqlUpdate(string tableName, std::vector vecKeys, s void Fields::parseJson(std::string jsonstr) { - NJsonNode jsonroot; - NJson::parse(jsonstr, jsonroot); + njson jsonroot; + JSON::parse(jsonstr, jsonroot); for (auto& item : jsonroot.items()) { this->set(item.key(), item.value()); diff --git a/src/common/JsonN.h b/src/common/JsonN.h index 7b42ca2..d792338 100644 --- a/src/common/JsonN.h +++ b/src/common/JsonN.h @@ -5,7 +5,7 @@ #include #include -using NJsonNode = nlohmann::json; +using njson = nlohmann::json; /// ============================================================================================= /// 使用说明: @@ -48,10 +48,10 @@ using NJsonNode = nlohmann::json; // std::vector v1; // v1 = j.at["data"].get>() -class NJson +class JSON { public: - static bool load(std::string jsonfile, NJsonNode& json) + static bool load(std::string jsonfile, njson& json) { std::ifstream ifs(jsonfile); if (!ifs.is_open()) { return false; } @@ -60,11 +60,11 @@ public: return true; } - static bool parse(std::string jsonstr, NJsonNode& json) + static bool parse(std::string jsonstr, njson& json) { try { - if (!jsonstr.empty()) { json = NJsonNode::parse(jsonstr); } + if (!jsonstr.empty()) { json = njson::parse(jsonstr); } } catch (nlohmann::json::parse_error& e) { @@ -75,7 +75,7 @@ public: } template - static void read(NJsonNode& json, std::string k, T& v) + static void read(njson& json, std::string k, T& v) { try { @@ -89,8 +89,8 @@ public: static void parse(std::string jsonstr, std::vector& vd) { - NJsonNode jsonroot; - if (NJson::parse(jsonstr, jsonroot)) + njson jsonroot; + if (JSON::parse(jsonstr, jsonroot)) { vd = jsonroot.get>(); } diff --git a/src/database/Dao.cpp b/src/database/Dao.cpp index a6716be..0e39fbc 100644 --- a/src/database/Dao.cpp +++ b/src/database/Dao.cpp @@ -111,6 +111,7 @@ static Errcode QueryPagination(std::string sqlFields, std::string sqlCondition, } if (page.index < 1) page.index = 1; + if (page.size <= 0) page.size = 10; page.total = count; std::string sql = "SELECT " + sqlFields + " " + sqlCondition + DAO::sqlPageLimit(page.index -1, page.size); int ret = dao.exec(sql, result); @@ -416,7 +417,7 @@ Errcode DAO::updateStationById(Fields& params) // 查询设备信息列表 Errcode DAO::queryDeviceList(std::shared_ptr dao, vector& result) { - std::string sql = "SELECT * FROM " + DMDevice::TABLENAME; + std::string sql = "SELECT d.*, ddt.category FROM device d LEFT JOIN def_device_type ddt ON d.`type`=ddt.device_type_id;"; return DAO::exec(dao, sql, result); } diff --git a/src/database/DaoEntity.cpp b/src/database/DaoEntity.cpp index 5fdcd27..b97959c 100644 --- a/src/database/DaoEntity.cpp +++ b/src/database/DaoEntity.cpp @@ -12,18 +12,18 @@ DaoEntity::DaoEntity(string tb_name) //opts.password = "123456"; //opts.port = 3306; //opts.dbname = "pvb"; - db_ = make_shared(DaoEntity::option); - if (!db_->isConnected()) + db = make_shared(DaoEntity::option); + if (!db->isConnected()) { //Global::data().status_msg = "数据库连接异常!"; //PvInstance::send_user_event(nullptr, EUserEvent::ALARM_DB, "数据库连接异常!"); } - tableName_ = tb_name; + tableName = tb_name; } DaoEntity::~DaoEntity() { - db_ = nullptr; + db = nullptr; } MysqlOption& DaoEntity::mysqlOption() @@ -58,34 +58,34 @@ bool DaoEntity::execOnce(string sql, vector& result) void DaoEntity::setTableName(string tb_name) { - tableName_ = tb_name; + tableName = tb_name; } bool DaoEntity::isConnected() { - return db_->isConnected(); + return db->isConnected(); } int DaoEntity::exec(string sql) { - return db_->exec(sql); + return db->exec(sql); } int DaoEntity::exec(string sql, vector& result) { - return db_->exec(sql, result); + return db->exec(sql, result); } int DaoEntity::insertFields(Fields& fields) { - string sql = fields.toSqlInsert(tableName_); - return this->db_->exec(sql); + string sql = fields.toSqlInsert(tableName); + return this->db->exec(sql); } int DaoEntity::insertFields(vector& vec_fields) { //"insert into TABLE () values ()"; - string sql = "insert into " + tableName_; + string sql = "insert into " + tableName; bool first = true; string keys; string values; @@ -100,16 +100,10 @@ int DaoEntity::insertFields(vector& vec_fields) const string& v = item.second; if (first) { - if (!keys.empty()) - { - keys += ","; - } + if (!keys.empty()) { keys += ","; } keys += k; } - if (!values.empty()) - { - values += ","; - } + if (!values.empty()) { values += ","; } values += ("'" + v + "'"); } if (first) @@ -124,7 +118,7 @@ int DaoEntity::insertFields(vector& vec_fields) } } sql += ";"; - return this->db_->exec(sql); + return this->db->exec(sql); } int DaoEntity::duplicateUpdate(Fields& fields, const vector& keys) @@ -150,8 +144,8 @@ int DaoEntity::duplicateUpdate(Fields& fields, const vector& keys) } str += (k + "='" + fields.value(k) + "'"); } - string sql = "INSERT INTO " + tableName_ + "(" + key + ") VALUES (" + val + ") ON duplicate KEY UPDATE " + str; - return this->db_->exec(sql); + string sql = "INSERT INTO " + tableName + "(" + key + ") VALUES (" + val + ") ON duplicate KEY UPDATE " + str; + return this->db->exec(sql); } //void DaoEntity::queryFields(const string& condition, DaoPageinfo& pageinfo, vector>& result) @@ -164,18 +158,18 @@ int DaoEntity::duplicateUpdate(Fields& fields, const vector& keys) int DaoEntity::queryFields(string keys, const string& condition, vector& result) { ostringstream oss; - oss << "SELECT " + keys + " FROM " << tableName_ << (" " + condition) << "; "; - return this->db_->exec(oss.str(), result); + oss << "SELECT " + keys + " FROM " << tableName << (" " + condition) << "; "; + return this->db->exec(oss.str(), result); } int DaoEntity::queryFields(string keys, const string& condition, PageInfo& page, vector& result) { int err = 0; ostringstream oss; - oss << "SELECT count(1) total FROM `" << tableName_ << "` " << condition << ";"; + oss << "SELECT count(1) total FROM `" << tableName << "` " << condition << ";"; vector res_total; - if (err = this->db_->exec(oss.str().c_str(), res_total)) + if (err = this->db->exec(oss.str().c_str(), res_total)) { return err; } @@ -192,23 +186,20 @@ int DaoEntity::queryFields(string keys, const string& condition, PageInfo& page, } oss.str(""); - if (page.index <= 0) - { - page.index = 1; - } + if (page.index <= 0) { page.index = 1; } int start = (page.index - 1) * page.size; - oss << "SELECT " << keys << " FROM `" << tableName_ << "` " << condition << " LIMIT " << start << "," << page.size << ";"; - return this->db_->exec(oss.str().c_str(), result); + oss << "SELECT " << keys << " FROM `" << tableName << "` " << condition << " LIMIT " << start << "," << page.size << ";"; + return this->db->exec(oss.str().c_str(), result); } int DaoEntity::updateFields(Fields& fields, const string& condition) { - string sql = fields.toSqlUpdate(tableName_, condition); - return this->db_->exec(sql); + string sql = fields.toSqlUpdate(tableName, condition); + return this->db->exec(sql); } int DaoEntity::updateFields(Fields& fields, vector vecKeys, const string& condition) { - string sql = fields.toSqlUpdate(tableName_, vecKeys, condition); - return this->db_->exec(sql); + string sql = fields.toSqlUpdate(tableName, vecKeys, condition); + return this->db->exec(sql); } \ No newline at end of file diff --git a/src/database/DaoEntity.h b/src/database/DaoEntity.h index 9bc208a..ec41271 100644 --- a/src/database/DaoEntity.h +++ b/src/database/DaoEntity.h @@ -103,10 +103,10 @@ protected: static MysqlOption option; // mysql 数据库操作对象 - std::shared_ptr db_ = nullptr; + std::shared_ptr db = nullptr; // 数据库表名称 - string tableName_; + string tableName; }; #endif // !!! _DaoBase_H_ diff --git a/src/protocol/HttpEntity.cpp b/src/protocol/HttpEntity.cpp index c1c3034..be8d803 100644 --- a/src/protocol/HttpEntity.cpp +++ b/src/protocol/HttpEntity.cpp @@ -7,15 +7,16 @@ #include "app/AppData.h" #include "app/Config.h" #include "app/Station.h" +#include "app/Device.h" -static void FieldsToJson(Fields& fields, NJsonNode& json) +static void FieldsToJson(Fields& fields, njson& json) { for (auto& item : fields.map()) { json[item.first] = item.second; } } -static void JsonToFields(NJsonNode& json, std::vector vecKeys, Fields& fields) +static void JsonToFields(njson& json, std::vector vecKeys, Fields& fields) { if (vecKeys.empty()) { @@ -32,16 +33,16 @@ static void JsonToFields(NJsonNode& json, std::vector vecKeys, Fiel switch (json[key].type()) { - case NJsonNode::value_t::string: { fields.set(key, json[key].get()); } break; - case NJsonNode::value_t::boolean: { fields.set(key, json[key].get()); } break; - case NJsonNode::value_t::number_integer: { fields.set(key, json[key].get()); } break; - case NJsonNode::value_t::number_unsigned: { fields.set(key, json[key].get()); } break; - case NJsonNode::value_t::number_float: { fields.set(key, json[key].get()); } break; - case NJsonNode::value_t::null: {} break; - case NJsonNode::value_t::object: {} break; - case NJsonNode::value_t::array: {} break; - case NJsonNode::value_t::binary: {} break; - case NJsonNode::value_t::discarded: {} break; + case njson::value_t::string: { fields.set(key, json[key].get()); } break; + case njson::value_t::boolean: { fields.set(key, json[key].get()); } break; + case njson::value_t::number_integer: { fields.set(key, json[key].get()); } break; + case njson::value_t::number_unsigned: { fields.set(key, json[key].get()); } break; + case njson::value_t::number_float: { fields.set(key, json[key].get()); } break; + case njson::value_t::null: {} break; + case njson::value_t::object: {} break; + case njson::value_t::array: {} break; + case njson::value_t::binary: {} break; + case njson::value_t::discarded: {} break; default: break; } @@ -50,12 +51,12 @@ static void JsonToFields(NJsonNode& json, std::vector vecKeys, Fiel } } -static NJsonNode FieldsToJsonArray(std::vector& vecFields) +static njson FieldsToJsonArray(std::vector& vecFields) { - NJsonNode jsonnode = NJsonNode::array(); + njson jsonnode = njson::array(); for (auto& fields : vecFields) { - NJsonNode jnode; + njson jnode; for (auto& item : fields.map()) { jnode[item.first] = item.second; @@ -79,8 +80,8 @@ static void GetRequestParam(const httplib::Request& req, const std::vector result, NJsonNode& json) + static void setPagination(PageInfo& pageinfo, std::vector result, njson& json) { json["count"] = pageinfo.total; json["page"] = pageinfo.index; @@ -142,11 +143,16 @@ static std::map g_mapHttpHandlerGet = {"/queryStationInfo", HandlerOptions(&HttpEntity::queryStationInfo, { DMStation::STATION_ID})}, {"/queryStationData", HandlerOptions(&HttpEntity::queryStationData, { DMStation::STATION_ID})}, + {"/queryStationOverview", HandlerOptions(&HttpEntity::queryStationOverview, {DMStation::STATION_ID})}, + {"/queryDeviceList", HandlerOptions(&HttpEntity::queryDeviceList, {})}, {"/deleteDevice", HandlerOptions(&HttpEntity::deleteDevice, { DMDevice::DEVICE_ID})}, {"/queryDevicTypeDef", HandlerOptions(&HttpEntity::queryDevicTypeDef, {})}, + {"/queryDevicByCategory", HandlerOptions(&HttpEntity::queryDevicByCategory, {DMStation::STATION_ID, "category"})}, + {"/queryDevicCharts", HandlerOptions(&HttpEntity::queryDevicCharts, {DMStation::STATION_ID, "device_id"})}, + {"/queryPolicyList", HandlerOptions(&HttpEntity::queryPolicyList, {})}, {"/deletePolicy", HandlerOptions(&HttpEntity::deletePolicy, { DMPolicy::POLICY_ID})}, @@ -248,7 +254,7 @@ void HttpEntity::runHandler(std::string name, const HandlerOptions& handler, con errcode = ret ? Errcode::OK : Errcode::ERR_TOKEN; } - NJsonNode jsonresp; + njson jsonresp; if (errcode == Errcode::OK) { if (!HttpHelper::CheckRequestParam(req, resp, handler.requiredKeys, errmsg)) @@ -257,7 +263,7 @@ void HttpEntity::runHandler(std::string name, const HandlerOptions& handler, con } else { - errcode = (this->*(handler.func))(req, resp, jsonresp); + errcode = (this->*(handler.func))(req, jsonresp, errmsg); } } jsonresp["errcode"] = errcode; @@ -271,7 +277,7 @@ void HttpEntity::registGet(std::string name, void (HttpEntity::* func)(const htt this->httpsvr.Get(name, std::bind(func, this, std::placeholders::_1, std::placeholders::_2)); } -Errcode HttpEntity::login(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::login(const httplib::Request& req, njson& json, std::string& errmsg) { std::string userId; std::string token; @@ -291,10 +297,10 @@ Errcode HttpEntity::login(const httplib::Request& req, httplib::Response& resp, int roleId = fields.get(DMRole::ROLE_ID); DAO::queryRolePermission(dao, roleId, vecPermission); - NJsonNode nodePermission = NJsonNode::array(); + njson nodePermission = njson::array(); for (auto& item : vecPermission) { - NJsonNode node; + njson node; FieldsToJson(item, node); nodePermission.push_back(node); } @@ -305,7 +311,7 @@ Errcode HttpEntity::login(const httplib::Request& req, httplib::Response& resp, return err; } -Errcode HttpEntity::queryUserList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryUserList(const httplib::Request& req, njson& json, std::string& errmsg) { std::string token = req.get_param_value("token"); PageInfo pageinfo; @@ -322,27 +328,27 @@ Errcode HttpEntity::queryUserList(const httplib::Request& req, httplib::Response return err; } -Errcode HttpEntity::insertUser(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::insertUser(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"account", "name", "gender", "age", "phone", "email", "role_id"}, params); return DAO::insertUser(params); } -Errcode HttpEntity::updateUser(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::updateUser(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"user_id", "account", "name", "gender", "age", "phone", "email", "role_id"}, params); return DAO::updateUserById(params); } -Errcode HttpEntity::deleteUser(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::deleteUser(const httplib::Request& req, njson& json, std::string& errmsg) { std::string userId = req.get_param_value("user_id"); return DAO::deleteUserById(userId); } -Errcode HttpEntity::queryPermissionList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryPermissionList(const httplib::Request& req, njson& json, std::string& errmsg) { PageInfo pageinfo; pageinfo.index = Utils::toInt(req.get_param_value("page")); @@ -354,28 +360,28 @@ Errcode HttpEntity::queryPermissionList(const httplib::Request& req, httplib::Re return err; } -Errcode HttpEntity::insertPermission(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::insertPermission(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"name", "describe", "is_open"}, params); return DAO::insertPermission(params); } -Errcode HttpEntity::updatePermission(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::updatePermission(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"permission_id", "name", "describe", "is_open"}, params); return DAO::updatePermissionById(params); } -Errcode HttpEntity::deletePermission(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::deletePermission(const httplib::Request& req, njson& json, std::string& errmsg) { std::string permissionId = req.get_param_value("permission_id"); return DAO::deletePermissionById(permissionId); } -Errcode HttpEntity::queryRoleList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryRoleList(const httplib::Request& req, njson& json, std::string& errmsg) { std::string token = req.get_param_value("page"); PageInfo pageinfo; @@ -394,12 +400,12 @@ Errcode HttpEntity::queryRoleList(const httplib::Request& req, httplib::Response return err; } - std::map> mapPermission; + std::map> mapPermission; for (auto& fields: vecPermission) { std::string roleId = fields.value("role_id"); auto& v = mapPermission[roleId]; - NJsonNode node; + njson node; FieldsToJson(fields, node); v.push_back(node); } @@ -417,19 +423,19 @@ Errcode HttpEntity::queryRoleList(const httplib::Request& req, httplib::Response return err; } -Errcode HttpEntity::insertRole(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::insertRole(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"name", "describe", "is_open", "permission"}, params); return DAO::insertRole(params); }; -Errcode HttpEntity::updateRole(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::updateRole(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; //GetRequestParam(req, {"role_id", "name", "describe", "is_open", "permission"}, params); - NJsonNode jsonparam; - if (!NJson::parse(req.body, jsonparam)) + njson jsonparam; + if (!JSON::parse(req.body, jsonparam)) { return Errcode::ERR_PARAM; } @@ -459,13 +465,13 @@ Errcode HttpEntity::updateRole(const httplib::Request& req, httplib::Response& r } return err; }; -Errcode HttpEntity::deleteRole(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::deleteRole(const httplib::Request& req, njson& json, std::string& errmsg) { std::string roleId = req.get_param_value(DMRole::ROLE_ID); return DAO::remove(NULL, DMRole::TABLENAME, DMRole::ROLE_ID, roleId); }; -Errcode HttpEntity::queryStationList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryStationList(const httplib::Request& req, njson& json, std::string& errmsg) { PageInfo pageinfo; pageinfo.index = Utils::toInt(req.get_param_value("page")); @@ -477,7 +483,7 @@ Errcode HttpEntity::queryStationList(const httplib::Request& req, httplib::Respo return err; }; -Errcode HttpEntity::insertStation(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::insertStation(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; @@ -485,20 +491,80 @@ Errcode HttpEntity::insertStation(const httplib::Request& req, httplib::Response return DAO::insertStation(params); }; -Errcode HttpEntity::updateStation(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::updateStation(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"station_id", "name", "address", "lon", "lat", "tel", "capacity", "status"}, params); return DAO::updateStationById(params); }; -Errcode HttpEntity::deleteStation(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::deleteStation(const httplib::Request& req, njson& json, std::string& errmsg) { std::string primaryKey = DMStation::STATION_ID; return DAO::remove(NULL, DMStation::TABLENAME, primaryKey, req.get_param_value(primaryKey)); }; -Errcode HttpEntity::queryStationInfo(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryStationOverview(const httplib::Request& req, njson& json, std::string& errmsg) +{ + Fields params; + GetRequestParam(req, {"station_id"}, params); + std::string stationId = params.value("station_id"); + if (stationId.empty()) + { + return Errcode::ERR_PARAM; + } + + auto dao = DaoEntity::create(""); + std::vector result; + + // 运行模式 + std::string sql = "SELECT * FROM station WHERE station_id='" + stationId + "';"; + int ret = dao->exec(sql, result); + if (ret != 0) + { + return Errcode(ret); + } + if (result.size() > 0) + { + json["data"]["work_mode"] = result[0].get("work_mode"); + } + + // 储能设备:总功率,数量 + // 充电设备:总功率,数量 + // 光伏设备:总功率,数量 + sql = R"(SELECT d.`type`, count(1) count, ddt.name typename, ddt.category FROM device d + LEFT JOIN def_device_type ddt ON ddt.device_type_id=d.`type` WHERE d.station_id=')" + stationId + "' GROUP BY `type`;"; + ret = dao->exec(sql, result); + if (ret != 0) + { + return Errcode(ret); + } + njson jsonStorage = njson::parse(R"({"category":1, "count":0, "power":0.0})"); + njson jsonCharge = njson::parse(R"({"category":2, "count":0, "power":0.0})"); + njson jsonSolar = njson::parse(R"({"category":3, "count":0, "power":0.0})"); + njson jsonSecurity = njson::parse(R"({"category":4, "count":0, "power":0.0})"); + for (auto& fields : result) + { + int category = fields.get("category"); + int count = fields.get("count"); + switch (category) + { + case 1: { jsonStorage["count"] = jsonStorage["count"].get() + count; } break; + case 2: { jsonCharge["count"] = jsonCharge["count"].get() + count; } break; + case 3: { jsonSolar["count"] = jsonSolar["count"].get() + count; } break; + case 4: { jsonSecurity["count"] = jsonSecurity["count"].get() + count; } break; + default: + break; + } + } + + // 从运行数据中读取功率信息(待补充) + + json["data"]["device_group"] = {jsonStorage, jsonCharge, jsonSolar, jsonSecurity}; + return Errcode::OK; +} + +Errcode HttpEntity::queryStationInfo(const httplib::Request& req, njson& json, std::string& errmsg) { // 查询场站的基础配置信息 std::string stationId = req.get_param_value("station_id"); @@ -520,9 +586,9 @@ Errcode HttpEntity::queryStationInfo(const httplib::Request& req, httplib::Respo } auto& fields = result[0]; - NJsonNode jsondata; + njson jsondata; std::string attr = fields.remove(DMStation::ATTR); - NJson::parse(attr, jsondata); + JSON::parse(attr, jsondata); FieldsToJson(fields, jsondata); json["data"] = jsondata; @@ -537,10 +603,10 @@ Errcode HttpEntity::queryStationInfo(const httplib::Request& req, httplib::Respo // voltage_rated: 电池额定电压: // power_rated: PCS额定功率 } -Errcode HttpEntity::queryStationData(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryStationData(const httplib::Request& req, njson& json, std::string& errmsg) { // 温度, 电压、电流、功率、功率因数、 - NJsonNode jsondata; + njson jsondata; jsondata["voltage"] = Utils::toStr(200.32); jsondata["current"] = Utils::toStr(20.56); jsondata["power"] = Utils::toStr(200.32); @@ -554,7 +620,7 @@ Errcode HttpEntity::queryStationData(const httplib::Request& req, httplib::Respo return Errcode::OK; } -Errcode HttpEntity::queryDeviceList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryDeviceList(const httplib::Request& req, njson& json, std::string& errmsg) { PageInfo pageinfo; pageinfo.index = Utils::toInt(req.get_param_value("page")); @@ -566,24 +632,24 @@ Errcode HttpEntity::queryDeviceList(const httplib::Request& req, httplib::Respon return err; }; -Errcode HttpEntity::insertDevice(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::insertDevice(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"station_id", "type", "name", "code", "model", "factory", "factory_tel", "is_open", "attrs"}, params); return DAO::insertDevice(params); }; -Errcode HttpEntity::updateDevice(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::updateDevice(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"device_id", "station_id", "type", "name", "code", "model", "factory", "factory_tel", "is_open", "attrs"}, params); return DAO::updateDeviceById(params); }; -Errcode HttpEntity::deleteDevice(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::deleteDevice(const httplib::Request& req, njson& json, std::string& errmsg) { std::string primaryKey = DMDevice::DEVICE_ID; return DAO::remove(NULL, DMDevice::TABLENAME, primaryKey, req.get_param_value(primaryKey)); }; -Errcode HttpEntity::queryDevicTypeDef(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryDevicTypeDef(const httplib::Request& req, njson& json, std::string& errmsg) { std::string sql = "SELECT device_type_id, name FROM def_device_type;"; std::vector result; @@ -591,8 +657,76 @@ Errcode HttpEntity::queryDevicTypeDef(const httplib::Request& req, httplib::Resp json["data"] = FieldsToJsonArray(result); return err; } +Errcode HttpEntity::queryDevicByCategory(const httplib::Request& req, njson& json, std::string& errmsg) +{ + Fields params; + GetRequestParam(req, {"station_id", "category"}, params); + if (!params.contains("station_id")) { errmsg = "缺少参数[station_id]"; return Errcode::ERR_PARAM; } + if (!params.contains("category")) { errmsg = "缺少参数[category]"; return Errcode::ERR_PARAM; } -Errcode HttpEntity::queryPolicyList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) + int stationId = params.get("station_id"); + int category = params.get("category"); + + njson jsondata = njson::array(); + auto station = Application::data().getStation(stationId); + if (station) + { + std::vector> vecDevice; + station->getDeviceByGroup(category, vecDevice); + + for(auto& device: vecDevice) + { + njson jsonnode; + jsonnode["stationId"] = stationId; + jsonnode["category"] = category; + jsonnode["device_id"] = device->deviceId; + jsonnode["name"] = device->name; + jsonnode["code"] = device->code; + jsonnode["type"] = device->type; + + jsonnode["is_online"] = device->online;// ? "在线" : "离线"; + jsonnode["is_error"] = device->err;// ? "故障" : "正常"; + jsonnode["is_running"] = device->running;// ? "工作" : "空闲"; + + njson jsonarrayParams = njson::array(); + VecPairSS vec; + device->getRuntimeParams(vec); + for (auto& item: vec) + { + jsonarrayParams.push_back({{"k", item.first}, {"v", item.second}}); + } + + jsonnode["params"] = jsonarrayParams; + jsondata.push_back(jsonnode); + } + } + json["data"] = jsondata; + return Errcode::OK; +} + +Errcode HttpEntity::queryDevicCharts(const httplib::Request& req, njson& json, std::string& errmsg) +{ + Fields params; + GetRequestParam(req, {"station_id", "device_id"}, params); + if (!params.contains("station_id")) { errmsg = "缺少参数[station_id]"; return Errcode::ERR_PARAM; } + if (!params.contains("device_id")) { errmsg = "缺少参数[device_id]"; return Errcode::ERR_PARAM; } + + int stationId = params.get("station_id"); + int deviceId = params.get("device_id"); + auto device = Application::data().getDevice(stationId, deviceId); + + std::vector vecV, vecI, vecP; + if (device) + { + device->getCacheVoltage(vecV); + device->getCacheCurrent(vecI); + device->getCachePower(vecP); + } + json["data"] = {{"V", vecV}, {"I", vecI}, {"P", vecP}}; + return Errcode::OK; +} + +Errcode HttpEntity::queryPolicyList(const httplib::Request& req, njson& json, std::string& errmsg) { PageInfo pageinfo; pageinfo.index = Utils::toInt(req.get_param_value("page")); @@ -603,26 +737,26 @@ Errcode HttpEntity::queryPolicyList(const httplib::Request& req, httplib::Respon HttpHelper::setPagination(pageinfo, result, json); return err; }; -Errcode HttpEntity::insertPolicy(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::insertPolicy(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"type", "name", "describe", "value", "is_open"}, params); return DAO::insertPolicy(params); }; -Errcode HttpEntity::updatePolicy(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::updatePolicy(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"policy_id", "type", "describe", "value", "is_open"}, params); return DAO::updatePolicyById(params); }; -Errcode HttpEntity::deletePolicy(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::deletePolicy(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"policy_id"}, params); return DAO::deletePolicyById(params.value("policy_id")); }; -Errcode HttpEntity::querySystemLogList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::querySystemLogList(const httplib::Request& req, njson& json, std::string& errmsg) { PageInfo pageinfo; pageinfo.index = Utils::toInt(req.get_param_value("page")); @@ -635,14 +769,14 @@ Errcode HttpEntity::querySystemLogList(const httplib::Request& req, httplib::Res } //Errcode insertSystemLog(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); -Errcode HttpEntity::updateSystemLog(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::updateSystemLog(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"log_id", "status"}, params); return DAO::updateSystemLogById(params); } -Errcode HttpEntity::queryAlertLogList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryAlertLogList(const httplib::Request& req, njson& json, std::string& errmsg) { PageInfo pageinfo; pageinfo.index = Utils::toInt(req.get_param_value("page")); @@ -655,21 +789,21 @@ Errcode HttpEntity::queryAlertLogList(const httplib::Request& req, httplib::Resp } //Errcode insertAlertLog(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); -Errcode HttpEntity::updateAlertLog(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::updateAlertLog(const httplib::Request& req, njson& json, std::string& errmsg) { Fields params; GetRequestParam(req, {"log_id", "status"}, params); return DAO::updateAlertLogById(params); } -Errcode HttpEntity::queryPredictionDetail(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryPredictionDetail(const httplib::Request& req, njson& json, std::string& errmsg) { - NJsonNode jsonData = NJsonNode::array(); + njson jsonData = njson::array(); for (int i = 1; i<=5; i++) { - NJsonNode jnode; + njson jnode; jnode["datatype"] = i; - NJsonNode jsonValues = NJsonNode::array(); + njson jsonValues = njson::array(); for (int i = 0; i<1440; ++i) { jsonValues.push_back(float(Utils::random(50, 100))); @@ -681,11 +815,11 @@ Errcode HttpEntity::queryPredictionDetail(const httplib::Request& req, httplib:: return Errcode::OK; } -Errcode HttpEntity::queryStatSystem(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryStatSystem(const httplib::Request& req, njson& json, std::string& errmsg) { auto& appdata = Application::data(); - NJsonNode jsondata; + njson jsondata; jsondata["launch_date"] = "2025-01-01"; //: 系统上线启用日期,格式:yyyy-mm-dd jsondata["income_total"] = std::to_string(Utils::random(100, 200)); // : 累计收益(元),精度0.01 jsondata["station_num"] = Utils::toStr(appdata.getStationCount()); // : 能源站数量 @@ -700,12 +834,12 @@ Errcode HttpEntity::queryStatSystem(const httplib::Request& req, httplib::Respon json["data"] = jsondata; return Errcode::OK; } -Errcode HttpEntity::queryStatTotal(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryStatTotal(const httplib::Request& req, njson& json, std::string& errmsg) { std::string station_id = req.get_param_value("station_id"); std::string category = req.get_param_value("category"); - NJsonNode jsondata; + njson jsondata; jsondata["station_id"] = "1"; jsondata["launch_date"] = "2025-01-01"; //场站上线日期 jsondata["usage_rate"] = "12"; @@ -726,11 +860,11 @@ Errcode HttpEntity::queryStatTotal(const httplib::Request& req, httplib::Respons json["data"] = jsondata; return Errcode::OK; } -Errcode HttpEntity::queryStatStation(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryStatStation(const httplib::Request& req, njson& json, std::string& errmsg) { std::string station_id = req.get_param_value("station_id"); std::string category = req.get_param_value("category"); - NJsonNode jsondata; + njson jsondata; jsondata["station_id"] = "1"; jsondata["launch_date"] = "2025-01-01"; //场站上线日期 jsondata["usage_rate"] = "12"; @@ -752,7 +886,7 @@ Errcode HttpEntity::queryStatStation(const httplib::Request& req, httplib::Respo return Errcode::OK; } -Errcode HttpEntity::queryStatDayList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryStatDayList(const httplib::Request& req, njson& json, std::string& errmsg) { std::string station_id = req.get_param_value("station_id"); std::string category = req.get_param_value("category"); @@ -763,10 +897,10 @@ Errcode HttpEntity::queryStatDayList(const httplib::Request& req, httplib::Respo int64_t t2 = Utils::time(dt_end)/1000; int64_t tMax = t1+ 86400 * 30; - NJsonNode jsondata = NJsonNode::array(); + njson jsondata = njson::array(); for (int64_t t = t1; t<=t2 && t<=tMax; t += 86400) { - NJsonNode jnode; + njson jnode; jnode["station_id"] = station_id; if (!category.empty()) jnode["category"] = category; jnode["dt"] = Utils::dateStr(t*1000); //日期 @@ -790,7 +924,7 @@ Errcode HttpEntity::queryStatDayList(const httplib::Request& req, httplib::Respo return Errcode::OK; } -Errcode HttpEntity::queryEnvironment(const httplib::Request& req, httplib::Response& resp, NJsonNode& json) +Errcode HttpEntity::queryEnvironment(const httplib::Request& req, njson& json, std::string& errmsg) { std::string stationId = req.get_param_value("station_id"); auto& appdata = Application::data(); @@ -802,15 +936,15 @@ Errcode HttpEntity::queryEnvironment(const httplib::Request& req, httplib::Respo return Errcode::ERR_PARAM; } - NJsonNode jsondata; + njson jsondata; { // 温湿度 auto& mapTempHumUnit = station->mapTempHumUnit; - NJsonNode nodearray = NJsonNode::array(); + njson nodearray = njson::array(); for (auto iter = mapTempHumUnit.begin(); iter!=mapTempHumUnit.end(); iter++) { auto& unit = iter->second; - NJsonNode node; + njson node; node["pos"] = "#" + std::to_string(iter->first); node["temp"] = unit.temp; node["hum"] = unit.hum; @@ -822,10 +956,10 @@ Errcode HttpEntity::queryEnvironment(const httplib::Request& req, httplib::Respo auto& mapAircUnit = station->mapAircUnit; AircUnit unitTmp; AircUnit* unit = (mapAircUnit.size() > 0) ? &(mapAircUnit[0]) : &unitTmp; - NJsonNode nodearray = NJsonNode::array(); + njson nodearray = njson::array(); if (unit) { - NJsonNode node; + njson node; nodearray.push_back({{"pos", "开关"}, {"status", unit->powerOn == 0 ? "关机" : "开机"}}); nodearray.push_back({{"pos", "启动制冷指令"}, {"status", unit->cooling == 0 ? "启动" : "关闭"}}); nodearray.push_back({{"pos", "启动送风指令"}, {"status", unit->airSupply == 0 ? "关闭" : "启动"}}); @@ -845,10 +979,10 @@ Errcode HttpEntity::queryEnvironment(const httplib::Request& req, httplib::Respo static std::map mapFireStatusDef = { {0, "正常"}, {1,"预警"}, {2,"火警"} }; auto& mapFire40Unit = station->mapFire40Unit; - NJsonNode nodearray = NJsonNode::array(); + njson nodearray = njson::array(); for (auto iter = mapFire40Unit.begin(); iter!=mapFire40Unit.end(); ++iter) { - NJsonNode node; + njson node; node["pos"] = "#" + std::to_string(iter->first); node["status"] = mapFireStatusDef[iter->second]; // 0:正常 1:预警 2:火警 nodearray.push_back(node); @@ -859,10 +993,10 @@ Errcode HttpEntity::queryEnvironment(const httplib::Request& req, httplib::Respo auto& mapCoolingUnit = station->mapCoolingUnit; CoolingUnit unitTmp; CoolingUnit* unit = (mapCoolingUnit.size() > 0) ? &(mapCoolingUnit[0]) : &unitTmp; - NJsonNode nodearray = NJsonNode::array(); + njson nodearray = njson::array(); if (unit) { - NJsonNode node; + njson node; nodearray.push_back({{"pos", "开关"}, {"status", unit->powerOn == 0 ? "关机" : "开机"}}); nodearray.push_back({{"pos", "采样模式"}, {"status", unit->mode == 0 ? "出水温度" : "电芯温度"}}); nodearray.push_back({{"pos", "制冷状态"}, {"status", unit->cooling == 0 ? "关闭" : "启动"}}); diff --git a/src/protocol/HttpEntity.h b/src/protocol/HttpEntity.h index 86ab1bc..0e1c9df 100644 --- a/src/protocol/HttpEntity.h +++ b/src/protocol/HttpEntity.h @@ -4,7 +4,7 @@ #include class HttpEntity; -using HandlerFunc = Errcode(HttpEntity::*)(const httplib::Request& req, httplib::Response& resp, NJsonNode& jnode); +using HandlerFunc = Errcode(HttpEntity::*)(const httplib::Request& req, njson& jnode, std::string& errmsg); struct HandlerOptions { @@ -29,57 +29,60 @@ public: //void onGet(const httplib::Request& req, httplib::Response& resp); - Errcode login(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode login(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryUserList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode insertUser(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode updateUser(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode deleteUser(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryUserList(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode insertUser(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode updateUser(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode deleteUser(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryPermissionList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode insertPermission(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode updatePermission(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode deletePermission(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryPermissionList(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode insertPermission(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode updatePermission(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode deletePermission(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryRoleList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode insertRole(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode updateRole(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode deleteRole(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryRoleList(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode insertRole(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode updateRole(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode deleteRole(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryStationList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode insertStation(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode updateStation(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode deleteStation(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryStationList(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode insertStation(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode updateStation(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode deleteStation(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryStationInfo(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode queryStationData(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryStationOverview(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode queryStationInfo(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode queryStationData(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryDeviceList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode insertDevice(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode updateDevice(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode deleteDevice(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode queryDevicTypeDef(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryDeviceList(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode insertDevice(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode updateDevice(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode deleteDevice(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode queryDevicTypeDef(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode queryDevicByCategory(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode queryDevicCharts(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryPolicyList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode insertPolicy(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode updatePolicy(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode deletePolicy(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryPolicyList(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode insertPolicy(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode updatePolicy(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode deletePolicy(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode querySystemLogList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode querySystemLogList(const httplib::Request& req, njson& json, std::string& errmsg); //Errcode insertSystemLog(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode updateSystemLog(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode updateSystemLog(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryAlertLogList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryAlertLogList(const httplib::Request& req, njson& json, std::string& errmsg); //Errcode insertAlertLog(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode updateAlertLog(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode updateAlertLog(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryPredictionDetail(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryPredictionDetail(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryStatSystem(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode queryStatTotal(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode queryStatStation(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); - Errcode queryStatDayList(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryStatSystem(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode queryStatTotal(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode queryStatStation(const httplib::Request& req, njson& json, std::string& errmsg); + Errcode queryStatDayList(const httplib::Request& req, njson& json, std::string& errmsg); - Errcode queryEnvironment(const httplib::Request& req, httplib::Response& resp, NJsonNode& json); + Errcode queryEnvironment(const httplib::Request& req, njson& json, std::string& errmsg); }; \ No newline at end of file diff --git a/src/protocol/MqttEntity.cpp b/src/protocol/MqttEntity.cpp index 506dbff..c5eee1b 100644 --- a/src/protocol/MqttEntity.cpp +++ b/src/protocol/MqttEntity.cpp @@ -10,8 +10,8 @@ static std::map> g_mapRegInfo; void MqttClient::loadDataStruct(std::string filename) { - NJsonNode json; - NJson::load(filename, json); + njson json; + JSON::load(filename, json); // 遍历 JSON 对象 for (auto& jsonitem : json.items()) @@ -321,6 +321,6 @@ void MqttClient::parseTQ(std::string& text) {}; string MQTT::packEquipmentInfo() { - NJsonNode jsonroot; + njson jsonroot; return jsonroot.dump(); } diff --git a/src/pv/pages/MaskPageRunning.cpp b/src/pv/pages/MaskPageRunning.cpp index a01e323..2824bc4 100644 --- a/src/pv/pages/MaskPageRunning.cpp +++ b/src/pv/pages/MaskPageRunning.cpp @@ -245,7 +245,7 @@ void MaskPageRunning::initModule(Module& module, std::string name, int x, int y, { module.name = name; - int deviceNum = activeStation->getDeviceNumByGroup(name); + int deviceNum = activeStation->getDeviceNumByGroup(1); int pid = module.widget = PvApp::label(p, 0, x, y, w, h, "", QSS::LABEL_BOX); PvApp::label(p, module.widget, 10, 20, w, 30, module.name, QSS::LABEL_TITLE); pvSetAlignment(p, module.widget, AlignTop | AlignLeft); @@ -283,7 +283,7 @@ void MaskPageRunning::activeBoxPanel(Module* module) { // 更新卡片: std::vector> vecDevice; - activeStation->getDeviceByGroup(module->name, vecDevice); + activeStation->getDeviceByGroup(1, vecDevice); pvSetText(p, module->labelNum, std::to_string(vecDevice.size()).c_str()); @@ -298,7 +298,7 @@ void MaskPageRunning::activeBoxPanel(Module* module) if (typeDef) { std::vector vecKeys; - NJson::parse(typeDef->fieldsAttr.value("key"), vecKeys); + JSON::parse(typeDef->fieldsAttr.value("key"), vecKeys); card->setCard(typeDef->name, device->name, device->code); card->setParamkeys(vecKeys); } diff --git a/src/pv/pages/PanelPolicy.cpp b/src/pv/pages/PanelPolicy.cpp index 488cec4..24616db 100644 --- a/src/pv/pages/PanelPolicy.cpp +++ b/src/pv/pages/PanelPolicy.cpp @@ -265,14 +265,14 @@ void PanelPolicyPeak::setTimeText(int id, std::string s) void PanelPolicyPeak::parseAttr(std::string str) { - NJsonNode jsonroot; - bool ret = NJson::parse(str, jsonroot); + njson jsonroot; + bool ret = JSON::parse(str, jsonroot); if (!ret) { return; } - NJson::read(jsonroot, "times", data.times); + JSON::read(jsonroot, "times", data.times); // 更新UI (充电策略) if (data.times == 2) { @@ -286,7 +286,7 @@ void PanelPolicyPeak::parseAttr(std::string str) } std::vector> vecTmp; - NJson::read>>(jsonroot, "period", vecTmp); + JSON::read>>(jsonroot, "period", vecTmp); for (int row = 0; row < data.vecPeriods.size(); ++row) { auto& vecRows = data.vecPeriods[row]; @@ -358,13 +358,13 @@ void PanelPolicyPeak::parseAttr(std::string str) std::string PanelPolicyPeak::dumpAttr() { - NJsonNode jsonroot; + njson jsonroot; jsonroot["period"] = data.vecPeriods; jsonroot["times"] = data.times; - NJsonNode nodeCycle = NJsonNode::array(); + njson nodeCycle = njson::array(); - NJsonNode nodeAttr1; + njson nodeAttr1; nodeAttr1["charge_start"] = data.attr1.chargeTimeStart; nodeAttr1["charge_end"] = data.attr1.chargeTimeEnd; nodeAttr1["charge_power"] = data.attr1.chargePower; @@ -374,7 +374,7 @@ std::string PanelPolicyPeak::dumpAttr() nodeCycle.push_back(nodeAttr1); if (data.times > 1) { - NJsonNode nodeAttr2; + njson nodeAttr2; nodeAttr2["charge_start"] = data.attr2.chargeTimeStart; nodeAttr2["charge_end"] = data.attr2.chargeTimeEnd; nodeAttr2["charge_power"] = data.attr2.chargePower; @@ -423,17 +423,17 @@ PanelPolicyRequire::PanelPolicyRequire(PARAM* p, int parent, int ix, int iy, int void PanelPolicyRequire::parseAttr(std::string str) { - NJsonNode jsonroot; - bool ret = NJson::parse(str, jsonroot); + njson jsonroot; + bool ret = JSON::parse(str, jsonroot); if (!ret) { return; } - NJson::read(jsonroot, "charge_soc", data.chargeSoc); - NJson::read(jsonroot, "charge_power", data.chargePower); - NJson::read(jsonroot, "discharge_soc", data.dischargeSoc); - NJson::read(jsonroot, "discharge_power", data.dischargePower); + JSON::read(jsonroot, "charge_soc", data.chargeSoc); + JSON::read(jsonroot, "charge_power", data.chargePower); + JSON::read(jsonroot, "discharge_soc", data.dischargeSoc); + JSON::read(jsonroot, "discharge_power", data.dischargePower); // 更新UI pvSetText(p, ui.chargeSoc, std::to_string(data.chargeSoc).c_str()); @@ -444,7 +444,7 @@ void PanelPolicyRequire::parseAttr(std::string str) std::string PanelPolicyRequire::dumpAttr() { - NJsonNode jsonroot; + njson jsonroot; jsonroot["discharge_soc"] = data.dischargeSoc; jsonroot["discharge_power"] = data.dischargePower; jsonroot["charge_soc"] = data.chargeSoc; @@ -471,17 +471,17 @@ PanelPolicySelf::PanelPolicySelf(PARAM* p, int parent, int ix, int iy, int iw, i void PanelPolicySelf::parseAttr(std::string str) { - NJsonNode jsonroot; - bool ret = NJson::parse(str, jsonroot); + njson jsonroot; + bool ret = JSON::parse(str, jsonroot); if (!ret) { return; } - NJson::read(jsonroot, "used_soc", data.usedSoc); - NJson::read(jsonroot, "grid_soc", data.gridSoc); - NJson::read(jsonroot, "charge_power", data.chargePower); - NJson::read(jsonroot, "discharge_power", data.dischargePower); + JSON::read(jsonroot, "used_soc", data.usedSoc); + JSON::read(jsonroot, "grid_soc", data.gridSoc); + JSON::read(jsonroot, "charge_power", data.chargePower); + JSON::read(jsonroot, "discharge_power", data.dischargePower); // 更新UI pvSetText(p, ui.usedSoc, std::to_string(data.usedSoc).c_str()); @@ -492,7 +492,7 @@ void PanelPolicySelf::parseAttr(std::string str) std::string PanelPolicySelf::dumpAttr() { - NJsonNode jsonroot; + njson jsonroot; jsonroot["used_soc"] = data.usedSoc; jsonroot["grid_soc"] = data.gridSoc; jsonroot["charge_power"] = data.chargePower;