#include "QThreadHttpServer.h" #include "DataManager.h" #include "TaskMNG.h" #include "ElectricityVOC.h" #ifdef Q_OS_WIN #pragma execution_character_set("utf-8") #endif #define NetFrom 0; #define TrainingID DataManager::instance().pRunThread->m_nTrainID; static int nHttpNumber = 0; void* QThreadHttpServer::pFunWnd = nullptr; //UserLoginCallBack QThreadHttpServer::pFunCtrl = nullptr; QThreadHttpServer::QThreadHttpServer(QObject* parent) : QThread(parent) { m_strServerIP = "10.2.2.95"; m_nServerPost = 18080; svr = nullptr; } QThreadHttpServer::~QThreadHttpServer() { StopThread(); } void QThreadHttpServer::InitHttpServer() { if (!svr) { svr = new Server(); } if (!svr) { return; } if (!svr->is_valid()) { printf(" server has an error...\n"); return; } /* svr->Get(".*", [](const httplib::Request& req, httplib::Response& res) { // 注意:这只是一个简单示例,在实际应用中可能需要更精细的路由匹配 std::cout << "[Global Logger] " << req.method << " " << req.path << " from " << req.remote_addr << std::endl; // 注意:这个处理器会捕获所有GET请求,你需要确保它不会干扰其他特定路由 // 更佳实践是为重要的特定路由分别记录,或者使用Server的`set_logger`方法(如果httplib版本支持) });*/ svr->Post("/", [=](const Request& /*req*/, Response& res) { res.set_redirect("/hi"); }); svr->Post("/ServerCtrl/Run", [](const Request& req, Response& res) {//课程运行标记 nHttpNumber = 0; Json::Value pJsonData; Json::Reader pReadJson; std::string jsonData = "{\"code\": 200, \"msg\": \"\", \"data\": \"\"}"; if (pReadJson.parse(req.body, pJsonData)) { SetSystemRun(pJsonData); } else { jsonData = "{\"code\": -1, \"msg\": \"Json Read Error\", \"data\": \"\"}"; } res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body,jsonData, "/ServerCtrl/Run",true); }); svr->Post("/ServerCtrl/Stop", [](const Request& req, Response& res) {//课程运行标记 nHttpNumber=0; SetSystemStop(); std::string jsonData = "{\"code\": 200, \"msg\": \"\", \"data\": \"\"}"; res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body,jsonData,"/ServerCtrl/Stop", true); }); svr->Post("/ServerCtrl/RunStatus", [](const Request& req, Response& res) {//课程运行标记 QString strData = ""; std::string jsonData; auto taskStatus = TaskMNG::instance()->getTaskStatus(); int nTaskStatus = taskStatus; switch (taskStatus) { case TaskMNG::Status_Null: { strData = G2U("结课/未初始化"); } break; case TaskMNG::Status_Init: { strData = G2U("课程初始成功,正在开课"); } break; case TaskMNG::Status_Run: { strData = G2U("课程开课成功"); } break; case TaskMNG::Status_Pass: { strData = G2U("课程暂停"); } break; case TaskMNG::Status_Stop: { strData = G2U("课程已结束,正在释放资源"); } break; case TaskMNG::Status_Error: { strData = QString::fromStdString(TaskMNG::instance()->getTaskText()); } break; default: break; } //double pData = nHttpNumber / 5.0 * 100.0; QString qstrRet = QString("{\"code\": 200, \"msg\": \"\", \"data\": { \"RunStatus\" :\"%1\",\"StatusText\" :\"%2\"} }").arg(nTaskStatus).arg(strData); jsonData = qstrRet.toStdString(); //std::string jsonData = "{\"code\": 200, \"msg\": \"\", \"data\": \"\"}"; res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body,jsonData, "/ServerCtrl/RunStatus", true); }); svr->Post("/ServerCtrl/AllEqpmtList", [](const Request& req, Response& res) {// Json::Value pJsonData; SendAllEqpmtData(pJsonData); Json::FastWriter pJsonW; std::string jsonData = pJsonW.write(pJsonData); res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body,jsonData, "/ServerCtrl/AllEqpmtList", true); }); svr->Post("/ServerCtrl/SetEqpmtOper", [](const Request& req, Response& res) {// Json::Value pJsonData; Json::Reader pReadJson; std::string jsonData = "{\"code\": 200, \"msg\": \"\", \"data\": \"\"}"; if (pReadJson.parse(req.body, pJsonData)) { SetEqpmtData(pJsonData); } else { jsonData = "{\"code\": -1, \"msg\": \"Json Read Error\", \"data\": \"\"}"; } res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body, jsonData, "/ServerCtrl/SetEqpmtOper", true); }); svr->Post("/ServerCtrl/SetEqpmtFault", [](const Request& req, Response& res) {// Json::Value pJsonData; Json::Reader pReadJson; std::string jsonData = "{\"code\": 200, \"msg\": \"\", \"data\": \"\"}"; if (pReadJson.parse(req.body, pJsonData)) { SetEqpmtFault(pJsonData); } else { jsonData = "{\"code\": -1, \"msg\": \"Json Read Error\", \"data\": \"\"}"; } res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body, jsonData, "/ServerCtrl/SetEqpmtFault", true); }); //子系统状态查询 svr->Post("/ServerCtrl/SubSysStatus", [](const Request& req, Response& res) {// Json::Value pJsonData; SendAllSystemData(pJsonData); Json::FastWriter pJsonW; std::string jsonData = pJsonW.write(pJsonData); res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body, jsonData, "/ServerCtrl/SubSysStatus", true); }); //子系统状态查询 svr->Post("/ServerCtrl/SystemCtrl", [](const Request& req, Response& res) {// std::string jsonData = "{\"code\": 200, \"msg\": \"\", \"data\": \"\"}"; res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body, jsonData, "/ServerCtrl/SystemCtrl", true); }); svr->Get("/course/stop", [](const Request& req, Response& res) {//课程运行标记 nHttpNumber=0; std::string jsonData = "{\"code\": 200, \"msg\": \"\", \"data\": \"\"}"; res.status = 200; res.set_content(jsonData, "application/json"); AddLogJson(req.body, jsonData, "/course/stop", true); }); svr->Post("/ServerCtrl/GetEqpmtFault", [](const Request& req, Response& res) {// Json::Value pJsonData; Json::Reader pReadJson; Json::Value pJsonRes; Json::FastWriter pJsonW; std::string jsonData;// = "{\"code\": 200, \"msg\": \"\", \"data\": \"\"}"; if (!req.body.empty()) { if (pReadJson.parse(req.body, pJsonData)) { std::string strEqpmt = pJsonData.get("EqpmtID", "").asString(); GetEqpmtFault(strEqpmt, pJsonRes); } } else { GetEqpmtFault("", pJsonRes); } res.status = 200; jsonData=pJsonW.write(pJsonRes); res.set_content(jsonData, "application/json"); AddLogJson(req.body, jsonData, "/ServerCtrl/GetEqpmtFault", true); }); svr->set_error_handler([](const Request& /*req*/, Response& res) { const char* fmt = "
Error Status: %d
"; char buf[BUFSIZ]; snprintf(buf, sizeof(buf), fmt, res.status); res.set_content(buf, "text/html"); }); } void QThreadHttpServer::run() { if (!svr) { return; } std::string strIp = m_strServerIP.toStdString(); svr->listen(strIp, m_nServerPost); delete svr; svr = nullptr; } std::string QThreadHttpServer::logData(const Request& req, const Response& res) { /* std::string s; char buf[BUFSIZ]; s += "================================\n"; snprintf(buf, sizeof(buf), "%s %s %s", req.method.c_str(), req.version.c_str(), req.path.c_str()); s += buf; std::string query; for (auto it = req.params.begin(); it != req.params.end(); ++it) { const auto& x = *it; snprintf(buf, sizeof(buf), "%c%s=%s", (it == req.params.begin()) ? '?' : '&', x.first.c_str(), x.second.c_str()); query += buf; } snprintf(buf, sizeof(buf), "%s\n", query.c_str()); s += buf; //s += dump_headers(req.headers); s += "--------------------------------\n"; snprintf(buf, sizeof(buf), "%d %s\n", res.status, res.version.c_str()); s += buf; //s += dump_headers(res.headers); s += "\n"; if (!res.body.empty()) { s += res.body; } s += "\n"; return s;*/ return""; } void QThreadHttpServer::StopThread() { if (svr&&svr->is_running()) { svr->stop(); } } void QThreadHttpServer::setIPPost(QString strIp, int nServerPost) { m_strServerIP = strIp; m_nServerPost = nServerPost; } void QThreadHttpServer::InitLink(const Request& req, Response& res) {//接受初始化消息 std::string query; QString strSN = "", strPushOptionsFlag = ""; for (auto it = req.params.begin(); it != req.params.end(); ++it) { if ("SN" == it->first) { strSN = QString::fromStdString(it->second); } else if ("PushOptionsFlag" == it->first) { strPushOptionsFlag = QString::fromStdString(it->second); } } if (strSN.isEmpty() || strPushOptionsFlag.isEmpty()) { return; } QString strOption = initOptions(strSN, strPushOptionsFlag); std::string strSend = strOption.toStdString(); res.headers; res.set_content(strSend, "text/plain"); } QString QThreadHttpServer::initOptions(QString strSN, QString PushOptionsFlag) {//组装返回命令 QString devOptions = ""; devOptions.append("GET OPTION FROM: " + strSN); // + "\nStamp=" + devInfo.devInfoJson.getString("Stamp") devOptions.append("\nATTLOGStamp=0"); devOptions.append("\nOPERLOGStamp=0"); devOptions.append("\nBIODATAStamp=0"); devOptions.append("\nATTPHOTOStamp=0"); devOptions.append("\nErrorDelay=10");//断网重连 devOptions.append("\nDelay=5");//心跳间隔 devOptions.append("\nTimeZone=8");//时区 devOptions.append("\nRealtime=1");//实时上传 devOptions.append("\nServerVer=3.0.1");//这个必须填写 devOptions.append("\nPushProtVer=2.4.1"); // 1 考勤记录 // 2 操作日志 // 3 考勤照片 // 4 登记新指纹 // 5 登记新用户 // 6 指纹图片 // 7 修改用户信息 // 8 修改指纹 // 9 新登记人脸 // 10 用户照片 // 11 工作号码 // 12 比对照片 // devOptions.append("\nTransFlag=111111111111");// 1-12二进制位 分别代表以上含义 devOptions.append("\nTransFlag=100000000001");// 1-12二进制位 分别代表以上含义 if (!PushOptionsFlag.isEmpty() && PushOptionsFlag=="1") { // 支持参数单独获取的才要把需要获取的参数回传给设备 modifeid by max 20170926 devOptions.append("\nPushOptions=RegDeviceType,FingerFunOn,FaceFunOn,FPVersion,FaceVersion,NetworkType,HardwareId3,HardwareId5,HardwareId56,LicenseStatus3,LicenseStatus5,LicenseStatus56"); } devOptions.append("\n"); return devOptions; } void QThreadHttpServer::RtData(const Request& req, Response& res) { logData(req, res); std::string strSN=""; auto iterSN = req.params.find("SN"); if (iterSN == req.params.end()) { strSN = iterSN->second; } auto iterTable = req.params.find("table"); if (iterTable==req.params.end()) { return; } if (iterTable->second == "ATTLOG") { std::string dataArray = req.body; //数据转为数组 int num = dataArray.length(); // if (pFunCtrl) // { // pFunCtrl(pFunWnd, strSN, dataArray); // } } } void QThreadHttpServer::AddLogJson(std::string strRequest, std::string strResponse, std::string nAPIID, bool bStatus,bool ServerData) { std::string strShow = "", strRetrun = ""; // strShow = UTF8_to_string(strRequest); // strRetrun = strResponse; if (!DataManager::JsonToStyled(strRequest, strShow)) { strShow = DataManager::UTF8_to_string(strRequest); } else { strShow = DataManager::UTF8_to_string(strShow); } if (!DataManager::JsonToStyled(strResponse, strRetrun)) { strRetrun = strResponse; } LogJson pData(strShow, strRetrun, nAPIID, bStatus,ServerData); DataManager::instance().AddHttpLog(pData); } void QThreadHttpServer::SendAllEqpmtData(Json::Value& pJson) { ElectricityVOC* pElcVoc = (ElectricityVOC*)TaskMNG::instance()->pGetEleVOC(); if (!pElcVoc) { return; } ELEEQPMTMAP* pEqpmtList= pElcVoc->getElectricEqpmtMap(); if (!pEqpmtList) { return; } //Json::Value pJson; pJson["code"] = 200; QString strSize = QString("Eqpmt Size=%1").arg(pEqpmtList->size()); pJson["msg"] = strSize.toStdString(); for (auto iters =pEqpmtList->begin();iters!=pEqpmtList->end();iters++) { Json::Value pEqpmtJson; pEqpmtJson["EqpmtStrID"]= iters->second->GetEqpmentID(); pEqpmtJson["LineID"] = pElcVoc->m_nRunLineID; pEqpmtJson["EqpmtStdName"] = iters->second->GetEqpmentName(); pEqpmtJson["EqpmtTypeID"] = iters->second->GetBaseType(); pEqpmtJson["CMDType"] = 0; pEqpmtJson["EqpmtStatus"] = iters->second->GetStatus(); pEqpmtJson["CtrlType"] = 1; pEqpmtJson["OpeMark"] = 0; pEqpmtJson["fValue"] = 0.0; pEqpmtJson["nValueType"] = 0; pEqpmtJson["IsReset"] = 0; pJson["data"].append(pEqpmtJson); } } void QThreadHttpServer::SetEqpmtData(Json::Value& InJson) { int nValueType = InJson.get("CMDType", 0).asInt(); string strEqpmtID = InJson.get("EqpmtStrID", "").asString(); OCCCOMMAND occcommand; if (nValueType==0)//设备状态更新 { OCCCOMMAND opercommand; DHEQPMTOPER oper; strcpy(oper.EqpmtStrID, strEqpmtID.c_str()); int nEqpmtCtrlType = InJson.get("CtrlType", 1).asInt(); int nEqpmtStatus = InJson.get("EqpmtStatus", 0).asInt(); switch (nEqpmtCtrlType) { case 1: case 0: { oper.CtrlType = CTRLTYPE_STATUS; oper.EqpmtStatus = nEqpmtStatus; } break; case 2: { oper.CtrlType = CTRLTYPE_CARD; if (nEqpmtStatus==0) { oper.EqpmtStatus = ELC_EQPMTCARDSTATUS_NORMAL;//正常 } else if(nEqpmtStatus == 1) { oper.EqpmtStatus = ELC_EQPMTCARDSTATUS_EARTH;//就地 } else { return; } } break; default: return; break; } oper.OpeMark = OperClient_Tech; occcommand.DesNetID = NetFrom; occcommand.TrainningID = TrainingID; occcommand.DesSysType = OCC_SYS_DD_SVR; occcommand.ScrSysType = OCC_SYS_SERVER_TH; occcommand.setPacketValue(&oper, OCCCOMMAND::eUpdateOper); } else if (nValueType==1) // 值更新 { EQPMTTELEMTRYVALUE oper; strcpy(oper.EqpmtStrID, strEqpmtID.c_str()); oper.nType = InJson.get("nValueType", 1).asInt(); oper.fValue = InJson.get("fValue", 1).asFloat(); oper.IsReset = InJson.get("IsReset", 1).asInt(); occcommand.DesNetID = NetFrom; occcommand.TrainningID = TrainingID; occcommand.DesSysType = OCC_SYS_DD_SVR; occcommand.ScrSysType = OCC_SYS_SERVER_TH; occcommand.setPacketValue(&oper, OCCCOMMAND::eUpdateEqpmtTelemeteryValue); } TaskMNG::instance()->NetComand_Receive(occcommand); } void QThreadHttpServer::SetEqpmtFault(Json::Value& InJson) { string strEqpmtID = InJson.get("EqpmtStrID", "").asString(); int status = InJson.get("EventType", "").asInt(); int nFaultID= InJson.get("EventId", "").asInt(); ELCACCIDENT acci; acci.Eqpmtid = 0; strcpy(acci.EqpmtStrID, strEqpmtID.c_str()); if (status == 1) //故障发生 { acci.EventType = POWER_ERORR_OCCAR; ElectricityVOC* pElcVoc = (ElectricityVOC*)TaskMNG::instance()->pGetEleVOC(); if (!pElcVoc) { return; } ELEEQPMTMAP* pEqpmtList = pElcVoc->getElectricEqpmtMap(); if (pEqpmtList) { auto iterEqpmt = pEqpmtList->find(strEqpmtID); if (iterEqpmt!= pEqpmtList->end()) { DataManager::instance().addEqpmFault(strEqpmtID, iterEqpmt->second->GetBaseType(), nFaultID); } else { DataManager::instance().addEqpmFault(strEqpmtID, 0, nFaultID); } } } if (status == 2) //恢复故障 { acci.EventType = POWER_ERORR_REVERT; DataManager::instance().DeleteEqpmtFault(strEqpmtID, nFaultID); } acci.ClientType = OperClient_Tech; acci.parm = nFaultID; OCCCOMMAND occcommand; occcommand.DesNetID = NetFrom; occcommand.TrainningID = TrainingID; occcommand.DesSysType = OCC_SYS_DD_SVR; occcommand.ScrSysType = OCC_SYS_SERVER_TH; occcommand.setPacketValue(&acci, OCCCOMMAND::eUpdateAccident); TaskMNG::instance()->m_pRecvList.push(occcommand); } void QThreadHttpServer::SendAllSystemData(Json::Value& pJson) { QMap