LNHandle.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. #include "stdafx.h"
  2. #include "LNHandle.h"
  3. #include <Simplelog.h>
  4. #include "AppService.h"
  5. #include "Device.h"
  6. #include <yyjson.h>
  7. #include "MonitorObject.h"
  8. #include "MGWSServer.h"
  9. #include "ResistAlarm.h"
  10. #include <315ClientManager.h>
  11. #include "AlarmDefine.h"
  12. using namespace rapidjson;
  13. CLNHandle::CLNHandle()
  14. {
  15. m_bWork = true;
  16. m_pThread = new std::thread(ThreadForHandle, (DWORD_PTR)this);
  17. }
  18. CLNHandle::~CLNHandle()
  19. {
  20. }
  21. BOOL CLNHandle::HandlePack(LPBYTE pPack, int nPackLen, SOCKADDR* psa, void* pClientContext /*= NULL*/)
  22. {
  23. CLNContext* pContext = (CLNContext*)pClientContext;
  24. if (pPack == nullptr || nPackLen == 0)
  25. {
  26. if (pContext)
  27. {
  28. pContext->SetIPAdress();
  29. CString strLog;
  30. strLog.Format(_T("CZHGSHandle 有新的链接:%s"), pContext->GetIPAdressNew());
  31. TRACE("%s\r\n", CStringA(strLog));
  32. SPDLOG_INFO(strLog);
  33. }
  34. return TRUE;
  35. }
  36. CString strIp;
  37. if (psa)
  38. {
  39. SOCKADDR_IN* addr = (SOCKADDR_IN*)psa;
  40. strIp.Format("%s:%d", inet_ntoa(addr->sin_addr), ntohs(addr->sin_port));
  41. }
  42. else if (pContext)
  43. {
  44. strIp = pContext->GetIPAdressNew();
  45. }
  46. uint8_t ch_head = (uint8_t)pPack[0];
  47. uint8_t ch_tail = (uint8_t)pPack[nPackLen - 1];
  48. if (ch_head != '{' || ch_tail != '}')
  49. {
  50. CString strLog;
  51. strLog.Format("[%s][%s]数据格式非JSON,丢弃!长度(%d): ", (LPCSTR)strIp, psa ? "UDP" : "TCP", nPackLen);
  52. CSimpleLog::Error(strLog + CSimpleLog::GetHexStringWithNoSpace(pPack, nPackLen));
  53. return FALSE;
  54. }
  55. if (g_bLog)
  56. CSimpleLog::Info("收到(" + strIp + ")(" + to_string(nPackLen).c_str() + "):" + CString((char*)pPack, nPackLen));
  57. lock_guard<mutex> lock(m_mtx);
  58. m_lst.emplace_back(new tagHandlePack(pPack, nPackLen, psa, pContext));
  59. return TRUE;
  60. }
  61. BOOL CLNHandle::ProcessPack(LPBYTE pPack, int nPackLen, SOCKADDR* psa, CLNContext* pClientContext)
  62. {
  63. CLNContext *pContext = (CLNContext*)pClientContext;
  64. Document doc;
  65. if (doc.Parse((char*)pPack, nPackLen).HasParseError() || doc.HasMember("cmd") == false || doc["cmd"].IsString() == false)
  66. {
  67. CString strLog;
  68. strLog.Format("[设备]数据JSON格式解析错误!丢弃.长度(%d):", nPackLen);
  69. CSimpleLog::Error(strLog + CSimpleLog::GetHexString(pPack, nPackLen));
  70. return FALSE;
  71. }
  72. //KEY区分大小写
  73. if (doc.HasMember("IMEI") == false || doc["IMEI"].IsString() == false)
  74. {
  75. CSimpleLog::Error("[设备]IMEI解析出错!");
  76. return FALSE;
  77. }
  78. auto cmd = doc["cmd"].GetString();
  79. auto imei = doc["IMEI"].GetString();
  80. if (strcmp("push_msg", cmd) == 0)
  81. return HandlePushMsg(doc, imei, psa, pContext, pPack, nPackLen);
  82. else if (strcmp("ping", cmd) == 0)
  83. return HandlePingPack(doc, imei, psa, pContext);
  84. else if (strcmp("push_info", cmd) == 0)
  85. return HandlePushInfo(doc, imei, psa, pContext);
  86. else if (strcmp("info_ack", cmd) == 0)
  87. return HandleInfoAck(doc, imei, psa, pContext);
  88. else if (strcmp("time", cmd) == 0)
  89. return HanldeTime(doc, imei, psa, pContext);
  90. else if (strcmp("update", cmd) == 0) //client
  91. return HandleUpdate(doc, imei, psa, pContext);
  92. else if (strcmp("update_ack", cmd) == 0)
  93. return HandleUpdateAck(doc, pPack, nPackLen, imei, psa, pContext);
  94. else if (strcmp("updateinit", cmd) == 0)
  95. return HandleUpdateInit(doc, imei, psa, pContext);
  96. else if (strcmp("updateseq", cmd) == 0)
  97. return HandleUpdateSeq(doc, imei, psa, pContext);
  98. else if (strcmp("updateok", cmd) == 0)
  99. return HandleUpdateOk(doc, imei, psa, pContext);
  100. else if (strcmp("get_online_new", cmd) == 0)
  101. return HandleOnlineDeviceNew(psa, pContext);
  102. else if (strcmp("get_online", cmd) == 0)
  103. return HandleOnlineDevice(doc, imei, psa, pContext);
  104. else if (strcmp("query_msg_ack", cmd) == 0)
  105. return HandleQueryMsgAck(doc, imei, psa, pContext);
  106. else if (strcmp("push_online", cmd) == 0)
  107. return HandlePushOnline(doc, imei, psa, pContext, pPack, nPackLen);
  108. else
  109. CSimpleLog::Error(CString("[设备]命令未解析:") + cmd);
  110. return TRUE;
  111. //throw std::logic_error("The method or operation is not implemented.");
  112. }
  113. BOOL CLNHandle::HandlePingPack(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pContext /*= NULL*/)
  114. {
  115. if (pContext) pContext->m_mapImei[imei]++;
  116. CTime ctNow = CTime::GetCurrentTime();
  117. {
  118. //更新当前设备的心跳时间
  119. auto pDevice = CDeviceMng::Instance()->Insert(imei);
  120. assert(pDevice);
  121. if (pDevice)
  122. {
  123. if (pDevice->m_ctUpdateTime < ctNow)
  124. pDevice->m_ctUpdateTime = ctNow;
  125. }
  126. }
  127. //string mo, mp;
  128. //SYSTEMTIME stNow;
  129. //ctNow.GetAsSystemTime(stNow);
  130. //if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei, 0, mo, mp))
  131. // CResistAlarmMng::Instance()->RecoverAlarm(mo, mp, -1, eZL_ALARMTYPE::EQUIP_OFFLINE, 1, stNow);
  132. //if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei, 1, mo, mp))
  133. // CResistAlarmMng::Instance()->RecoverAlarm(mo, mp, -1, eZL_ALARMTYPE::EQUIP_OFFLINE, 1, stNow);
  134. //if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei, 2, mo, mp))
  135. // CResistAlarmMng::Instance()->RecoverAlarm(mo, mp, -1, eZL_ALARMTYPE::EQUIP_OFFLINE, 1, stNow);
  136. //update
  137. CString strSql;
  138. //strSql.Format("UPDATE rm_deviceinfo SET updatetime='%s' WHERE IMEI = '%s' ", (LPCSTR)ctNow.Format("%Y-%m-%d %H:%M:%S"), imei);
  139. strSql.Format("IF EXISTS (SELECT TOP 1 * FROM rm_deviceinfo WHERE IMEI = '%s') "\
  140. " BEGIN "\
  141. " UPDATE rm_deviceinfo SET updatetime = '%s' WHERE IMEI = '%s' "\
  142. " END "\
  143. " ELSE "\
  144. " BEGIN"\
  145. " INSERT INTO[dbo].[rm_deviceinfo]([IMEI], [CCID]) VALUES('%s', '') "\
  146. " END",
  147. imei, (LPCSTR)ctNow.Format("%Y-%m-%d %H:%M:%S"), imei, imei);
  148. if (!CDBConnectPool::Instance()->DBExecuteSQL(strSql))
  149. {
  150. CSimpleLog::Error(strSql + "执行失败");
  151. }
  152. //response
  153. StringBuffer strBuf;
  154. Writer<StringBuffer> writer(strBuf);
  155. writer.StartObject();
  156. writer.Key("cmd");
  157. writer.String("pong");
  158. writer.Key("IMEI");
  159. writer.String(imei);
  160. writer.EndObject();
  161. string data = strBuf.GetString();
  162. if (pContext)
  163. return pContext->Send(data.c_str(), data.length()) != SOCKET_ERROR;
  164. else if (psa)
  165. return CAppService::Instance()->GetUdpSocket()->SendTo((void*)data.c_str(), data.length(), psa, sizeof(SOCKADDR));
  166. return FALSE;
  167. }
  168. BOOL CLNHandle::HandlePushMsg(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pContext, LPBYTE pPack, int nPackLen)
  169. {
  170. auto start_time = chrono::steady_clock::now();
  171. int code = 200;
  172. string packnum = "0";
  173. if (pContext) pContext->m_mapImei[imei]++;
  174. if (doc.HasMember("packnum") && doc["packnum"].IsString())
  175. packnum = doc["packnum"].GetString();
  176. //response
  177. {
  178. StringBuffer strBuf;
  179. Writer<StringBuffer> writer(strBuf);
  180. writer.StartObject();
  181. writer.Key("cmd");
  182. writer.String("push_msg_ack");
  183. writer.Key("code");
  184. writer.Int(code);
  185. writer.Key("IMEI");
  186. writer.String(imei);
  187. writer.Key("packnum");
  188. writer.String(packnum.c_str());
  189. writer.EndObject();
  190. string data = strBuf.GetString();
  191. if (pContext)
  192. pContext->Send(data.c_str(), data.length()) != SOCKET_ERROR;
  193. else if (psa)
  194. CAppService::Instance()->GetUdpSocket()->SendTo((void*)data.c_str(), data.length(), psa, sizeof(SOCKADDR));
  195. }
  196. do {
  197. //analyze
  198. string szTime;
  199. if (doc.HasMember("time") && doc["time"].IsString())
  200. szTime = doc["time"].GetString();
  201. else
  202. {
  203. code = 401;
  204. break;
  205. }
  206. COleDateTime odt;
  207. try
  208. {
  209. odt.ParseDateTime(szTime.c_str());
  210. }
  211. catch (COleException*)
  212. {
  213. ASSERT(0);
  214. CSimpleLog::Error(("[设备]时间格式错误:" + szTime).c_str());
  215. code = 401;
  216. break;
  217. }
  218. COleDateTime odtNow = COleDateTime::GetCurrentTime();
  219. #ifndef DEBUG_202
  220. if (strcmp(imei, "1234567890") != 0) //测试设备
  221. {
  222. COleDateTimeSpan t(0, 0, 2, 0);
  223. COleDateTimeSpan t2(3, 0, 0, 0);
  224. time_t tmNow;
  225. time(&tmNow);
  226. if ((odtNow - odt > t2 || odtNow - odt > t || odt - odtNow > t) && tmNow - g_stStart > 20) //刚启动不下发同步, 设备有缓存
  227. {
  228. auto doc = yyjson_mut_doc_new(nullptr);
  229. auto root = yyjson_mut_obj(doc);
  230. yyjson_mut_doc_set_root(doc, root);
  231. yyjson_mut_obj_add_str(doc, root, "cmd", "time_ack");
  232. yyjson_mut_obj_add_int(doc, root, "timestamp", tmNow);
  233. yyjson_mut_obj_add_strcpy(doc, root, "IMEI", imei);
  234. size_t len = 0;
  235. auto json = yyjson_mut_write(doc, 0, &len);
  236. if (json)
  237. {
  238. if (pContext)
  239. pContext->Send(json, len) != SOCKET_ERROR;
  240. else if (psa)
  241. CAppService::Instance()->GetUdpSocket()->SendTo(json, len, psa, sizeof(SOCKADDR));
  242. }
  243. yyjson_mut_doc_free(doc);
  244. doc = nullptr;
  245. CString strLog;
  246. strLog.Format("超过服务器的时间六小时:IMEI(%s) 上传时间(%s) 服务器时间(%s) 下发一条time_ack:%s",
  247. imei, (LPCSTR)odt.Format("%Y-%m-%d %H:%M:%S"), (LPCSTR)odtNow.Format("%Y-%m-%d %H:%M:%S"), json);
  248. CSimpleLog::Error(strLog);
  249. if (json)
  250. {
  251. free(json);
  252. json = nullptr;
  253. }
  254. code = 401;
  255. break;
  256. }
  257. }
  258. #endif //
  259. if (odt.m_status != COleDateTime::DateTimeStatus::valid)
  260. {
  261. ASSERT(0);
  262. CSimpleLog::Error(("[设备]收到时间无效:" + szTime).c_str());
  263. code = 401;
  264. break;
  265. }
  266. SYSTEMTIME st;
  267. odt.GetAsSystemTime(st);
  268. CTime ctNow(st);
  269. TIMESTAMP_STRUCT ts;
  270. ts.year = st.wYear;
  271. ts.month = st.wMonth;
  272. ts.day = st.wDay;
  273. ts.hour = st.wHour;
  274. ts.minute = st.wMinute;
  275. ts.second = st.wSecond;
  276. ts.fraction = 0;
  277. string data0, data1, data2, data3, data4, data5, data6, data7, data8;
  278. if (doc.HasMember("data0") && doc["data0"].IsString())
  279. data0 = doc["data0"].GetString();
  280. if (doc.HasMember("data1") && doc["data1"].IsString())
  281. data1 = doc["data1"].GetString();
  282. if (doc.HasMember("data2") && doc["data2"].IsString())
  283. data2 = doc["data2"].GetString();
  284. if (doc.HasMember("data3") && doc["data3"].IsString())
  285. data3 = doc["data3"].GetString();
  286. if (doc.HasMember("data4") && doc["data4"].IsString())
  287. data4 = doc["data4"].GetString();
  288. if (doc.HasMember("data5") && doc["data5"].IsString())
  289. data5 = doc["data5"].GetString();
  290. if (doc.HasMember("data6") && doc["data6"].IsString())
  291. data6 = doc["data6"].GetString();
  292. if (doc.HasMember("data7") && doc["data7"].IsString())
  293. data7 = doc["data7"].GetString();
  294. if (doc.HasMember("data8") && doc["data8"].IsString())
  295. data8 = doc["data8"].GetString();
  296. int temperature = INT_MIN, humidity = INT_MIN;
  297. int bMakeup = 0;
  298. if (doc.HasMember("temperature") && doc["temperature"].IsString())
  299. temperature = atof(doc["temperature"].GetString()) * 100;
  300. if (doc.HasMember("humidity") && doc["humidity"].IsString())
  301. humidity = atof(doc["humidity"].GetString()) * 100;
  302. if (doc.HasMember("make_up") && doc["make_up"].IsInt())
  303. bMakeup = doc["make_up"].GetInt();
  304. //vector<CString> vctData0(ROW_ARRAY_SIZE), vctData1(ROW_ARRAY_SIZE), vctData2(ROW_ARRAY_SIZE), vctData3(ROW_ARRAY_SIZE),
  305. // vctData4(ROW_ARRAY_SIZE), vctData5(ROW_ARRAY_SIZE), vctData6(ROW_ARRAY_SIZE), vctData7(ROW_ARRAY_SIZE), vctData8(ROW_ARRAY_SIZE);
  306. vector<int> vctData0(ROW_ARRAY_SIZE, 0), vctData1(ROW_ARRAY_SIZE, 0), vctData2(ROW_ARRAY_SIZE, 0), vctData3(ROW_ARRAY_SIZE, 0),
  307. vctData4(ROW_ARRAY_SIZE, 0), vctData5(ROW_ARRAY_SIZE, 0), vctData6(ROW_ARRAY_SIZE, 0), vctData7(ROW_ARRAY_SIZE, 0), vctData8(ROW_ARRAY_SIZE, 0);
  308. auto len0 = convertStrToArray(data0, vctData0);
  309. auto len1 = convertStrToArray(data1, vctData1);
  310. auto len2 = convertStrToArray(data2, vctData2);
  311. auto len3 = convertStrToArray(data3, vctData3);
  312. auto len4 = convertStrToArray(data4, vctData4);
  313. auto len5 = convertStrToArray(data5, vctData5);
  314. auto len6 = convertStrToArray(data6, vctData6);
  315. auto len7 = convertStrToArray(data7, vctData7);
  316. auto len8 = convertStrToArray(data8, vctData8);
  317. //转换
  318. string mo_mp;
  319. string imei_idx = imei;
  320. int idx = 0;
  321. if (len3) idx = 1;
  322. else if (len6) idx = 2;
  323. imei_idx += "." + to_string(idx);
  324. auto bMoMp = CMonitorObjectMng::Instance()->IMEI2MOMP(imei_idx, mo_mp);
  325. if (g_strMoMp.compare(mo_mp) == 0)
  326. CSimpleLog::Info(fmt::format("{} recv data:{}", mo_mp, CString((char*)pPack, nPackLen)).c_str());
  327. //实时温湿度分送到客户端
  328. //auto lws_server = CAppService::Instance()->GetLwsServer();
  329. auto mg_server = CAppService::Instance()->GetMgServer();
  330. auto mg_315_server= g_p315ClientManager->GetTcpClient();
  331. if (temperature != INT_MIN && humidity != INT_MIN && humidity > 0 && odt > m_mapIMEI_temp[imei])
  332. {
  333. m_mapIMEI_temp[imei] = odt;
  334. CString strSql;
  335. strSql.Format("INSERT INTO rm_temphumidity_%04d%02d ([IMEI],[acquisitiontime],[temperature],[humidity]) "\
  336. "VALUES('%s' , '%s' , %d , %d); ",
  337. st.wYear, st.wMonth, imei, (LPCSTR)odt.Format("%Y-%m-%d %H:%M:%S"), temperature, humidity);
  338. if (!CDBConnectPool::Instance()->DBExecuteSQL(strSql))
  339. {
  340. CSimpleLog::Error("sql 执行失败:" + strSql);
  341. }
  342. if (mg_server) mg_server->SendHumiTemp(mo_mp, odt, humidity, temperature);
  343. uint8_t* pack = nullptr; int len = 0;
  344. if (CSuperManager::Instance()->GetSuperNum() && bMoMp)
  345. {
  346. auto no = GeneralTempPack(mo_mp, temperature, humidity, ctNow.GetTime(), &pack, &len);
  347. if (no) CSuperManager::Instance()->SendPack(pack, len, no, E_ZL_PROTOCAL::ZL_TEMP_HUMI, false);
  348. delete[] pack;
  349. pack = nullptr;
  350. }
  351. //
  352. }
  353. //#ifdef DEBUG_202
  354. // //针对21号J1-2200以下打0.85折
  355. // if (strcmp(imei, "860588048955283") == 0)
  356. // {
  357. // if (len2 > 0)
  358. // {
  359. // for (int i = 0; i < len2; i++)
  360. // {
  361. // if (vctData2[i] != SHORT_MIN && vctData2[i] < -2200)
  362. // {
  363. // vctData2[i] = vctData2[i] * 0.85;
  364. // }
  365. // }
  366. // }
  367. // }
  368. //
  369. //#endif // DEBUG_202
  370. //三个为一组
  371. if ((len0 != len1 && (len2 != len1))
  372. || (len3 != len4 && (len4 != len5))
  373. || (len6 != len7 && (len8 != len7))
  374. || (len0 == 0 && len3 == 0 && len6 == 0))
  375. {
  376. CSimpleLog::Error("解析Data len 出错");
  377. code = 401;
  378. break;
  379. }
  380. auto pDevice = CDeviceMng::Instance()->Insert(imei);
  381. assert(pDevice != nullptr);
  382. if (pDevice == nullptr)
  383. {
  384. CSimpleLog::Fatal("insert imei fail.");
  385. code = 500;
  386. break;
  387. }
  388. BOOL bIntervalMinute = FALSE;
  389. if (pDevice->m_ctUpdateTime < ctNow)
  390. {
  391. if (ctNow - pDevice->m_ctUpdateTime >= 59)
  392. bIntervalMinute = TRUE; //距离上个数据间隔一分钟.
  393. pDevice->m_ctUpdateTime = ctNow;
  394. }
  395. else if (pDevice->m_ctUpdateTime > ctNow)
  396. pDevice->m_ctUpdateTime = ctNow - CTimeSpan(0, 0, 0, 1);
  397. int nData[3] = { INT_MIN, INT_MIN, INT_MIN };
  398. pDevice->m_nTemperature = temperature;
  399. pDevice->m_nHumidity = humidity;
  400. //时间判断
  401. if (len0)
  402. {
  403. #ifndef DEBUG_202
  404. if (pDevice->m_odt_data0 >= odt)
  405. {
  406. CString strLog;
  407. strLog.Format("[设备]时间错误:上送时间:%s 设备0通道时间:%s", imei, (LPCSTR)odt.Format("%Y-%m-%d %H:%M:%S"), (LPCSTR)pDevice->m_odt_data0.Format("%Y-%m-%d %H:%M:%S"));
  408. CSimpleLog::Error(strLog);
  409. code = 401;
  410. break;
  411. }
  412. #endif // !DEBUG_202
  413. pDevice->m_odt_data0 = odt;
  414. nData[0] = *vctData0.rbegin();
  415. nData[1] = *vctData1.rbegin();
  416. nData[2] = *vctData2.rbegin();
  417. }
  418. else if (len3)
  419. {
  420. #ifndef DEBUG_202
  421. if (pDevice->m_odt_data1 >= odt)
  422. {
  423. CString strLog;
  424. strLog.Format("[设备]时间错误:上送时间:%s 设备1通道时间:%s", imei, (LPCSTR)odt.Format("%Y-%m-%d %H:%M:%S"), (LPCSTR)pDevice->m_odt_data1.Format("%Y-%m-%d %H:%M:%S"));
  425. CSimpleLog::Error(strLog);
  426. code = 401;
  427. break;
  428. }
  429. #endif // !DEBUG_202
  430. pDevice->m_odt_data1 = odt;
  431. nData[0] = *vctData3.rbegin();
  432. nData[1] = *vctData4.rbegin();
  433. nData[2] = *vctData5.rbegin();
  434. }
  435. else if (len6)
  436. {
  437. #ifndef DEBUG_202
  438. if (pDevice->m_odt_data2 >= odt)
  439. {
  440. CString strLog;
  441. strLog.Format("[设备]时间错误:上送时间:%s 设备2通道时间:%s", imei, (LPCSTR)odt.Format("%Y-%m-%d %H:%M:%S"), (LPCSTR)pDevice->m_odt_data2.Format("%Y-%m-%d %H:%M:%S"));
  442. CSimpleLog::Error(strLog);
  443. code = 401;
  444. break;
  445. }
  446. #endif // !DEBUG_202
  447. pDevice->m_odt_data2 = odt;
  448. nData[0] = *vctData6.rbegin();
  449. nData[1] = *vctData7.rbegin();
  450. nData[2] = *vctData8.rbegin();
  451. }
  452. else
  453. {
  454. CString str;
  455. str.Format("len error. %s:%d", __FILE__, __LINE__);
  456. CSimpleLog::Error(str);
  457. code = 401;
  458. break;
  459. }
  460. //insert
  461. auto nNum = max(max(len0, len3), len6);
  462. if (nNum == 0 || nNum > ROW_ARRAY_SIZE)
  463. {
  464. CSimpleLog::Error("Max size zero.");
  465. code = 401;
  466. break;
  467. }
  468. vector<bool> vctResult0(ROW_ARRAY_SIZE, true), vctResult3(ROW_ARRAY_SIZE, true), vctResult6(ROW_ARRAY_SIZE, true);
  469. uint32_t newlen0 = 0, newlen3 = 0, newlen6 = 0;
  470. __time64_t tmNowStart = ctNow.GetTime() * 1000;
  471. SECOND_STAT_INFO tSS1, tSS2, tSS3;
  472. if (len0)
  473. newlen0 = compressArrayNew(vctData0, vctData1, vctData2, len0, vctResult0, tmNowStart, tSS1, tSS2, tSS3);
  474. if (len3)
  475. newlen3 = compressArrayNew(vctData3, vctData4, vctData5, len3, vctResult3, tmNowStart, tSS1, tSS2, tSS3);
  476. if (len6)
  477. newlen6 = compressArrayNew(vctData6, vctData7, vctData8, len6, vctResult6, tmNowStart, tSS1, tSS2, tSS3);
  478. if (bIntervalMinute && (tSS1.dif_val >= 100 || tSS2.dif_val >= 100 || tSS3.dif_val >= 100))
  479. SPDLOG_INFO("波动: ss1:{} ss2:{} ss3:{} {}", tSS1.dif_val, tSS2.dif_val, tSS3.dif_val, CString((char*)pPack, nPackLen));
  480. uint32_t nNewNum = max(max(newlen0, newlen3), newlen6);
  481. //发送315前需要获取转辙机定反位
  482. if (bMoMp && mg_315_server)
  483. {
  484. auto zzjno = CMonitorObjectMng::Instance()->GetZZJNO(mo_mp);
  485. //auto pZZJ = CMonitorObjectMng::Instance()->GetTreeByID(mo_mp);
  486. //if (pZZJ)
  487. if (zzjno > 0)
  488. {
  489. //string direct1, direct2;
  490. //CMonitorObjectMng::Instance()->GetDirectByMoMp(mo_mp, direct1, direct2); //判断0通道是定位还是反位是通过GetNameByMoMp中的name1,和 name2
  491. string name1, name2, name3;
  492. CMonitorObjectMng::Instance()->GetNameByMoMp(mo_mp, name1, name2, name3);
  493. if (name1 == "反位")
  494. {
  495. swap(nData[0], nData[1]);
  496. }
  497. mg_315_server->SendRealDataValue(zzjno, CMonitorObjectMng::Instance()->GetZZJEPOS(mo_mp), true, nData[0], nData[1], nData[2], temperature, humidity, ctNow);
  498. }
  499. }
  500. //实时分送到客户端
  501. if (mg_server)
  502. {
  503. uint8_t* pack = nullptr; int len = 0;
  504. if (len0)
  505. {
  506. //mo_mp 108.J1
  507. mg_server->SendRealResistData(mo_mp, nNum, vctData0, vctData1, vctData2, vctResult0, ctNow);
  508. if (CSuperManager::Instance()->GetSuperNum() && bMoMp)
  509. {
  510. auto no = GeneralResistPack(mo_mp, nNum, vctData0, vctData1, vctData2, vctResult0, ctNow, &pack, &len);
  511. if (no) CSuperManager::Instance()->SendPack(pack, len, no, E_ZL_PROTOCAL::ZL_RESIST_DATA, false);
  512. delete[] pack;
  513. pack = nullptr;
  514. }
  515. }
  516. else if (len3)
  517. {
  518. //mo_mp 108.J2
  519. mg_server->SendRealResistData(mo_mp, nNum, vctData3, vctData4, vctData5, vctResult3, ctNow);
  520. if (CSuperManager::Instance()->GetSuperNum() && bMoMp)
  521. {
  522. auto no = GeneralResistPack(mo_mp, nNum, vctData3, vctData4, vctData5, vctResult3, ctNow, &pack, &len);
  523. if (no) CSuperManager::Instance()->SendPack(pack, len, no, E_ZL_PROTOCAL::ZL_RESIST_DATA, false);
  524. delete[] pack;
  525. pack = nullptr;
  526. }
  527. ///
  528. }
  529. else if (len6)
  530. {
  531. //mo_mp 108.J3
  532. mg_server->SendRealResistData(mo_mp, nNum, vctData6, vctData7, vctData8, vctResult6, ctNow);
  533. if (CSuperManager::Instance()->GetSuperNum() && bMoMp)
  534. {
  535. auto no = GeneralResistPack(mo_mp, nNum, vctData6, vctData7, vctData8, vctResult6, ctNow, &pack, &len);
  536. if (no) CSuperManager::Instance()->SendPack(pack, len, no, E_ZL_PROTOCAL::ZL_RESIST_DATA, false);
  537. delete[] pack;
  538. pack = nullptr;
  539. }
  540. }
  541. }
  542. //放在缓存当中
  543. bool bSave = true;
  544. {
  545. if (len0)
  546. bSave = pDevice->Insert(idx, tmNowStart, 1000 / nNum, vctData0, vctData1, vctData2, vctResult0, nNum, tSS1, tSS2, tSS3, nNewNum, bMakeup);
  547. if (len3)
  548. bSave = pDevice->Insert(idx, tmNowStart, 1000 / nNum, vctData3, vctData4, vctData5, vctResult3, nNum, tSS1, tSS2, tSS3, nNewNum, bMakeup);
  549. if (len6)
  550. bSave =pDevice->Insert(idx, tmNowStart, 1000 / nNum, vctData6, vctData7, vctData8, vctResult6, nNum, tSS1, tSS2, tSS3, nNewNum, bMakeup);
  551. }
  552. if (bSave)
  553. {
  554. //申请内存
  555. LPRESISTANCE p = new RESISTANCE[nNewNum];
  556. if (p == nullptr)
  557. {
  558. CSimpleLog::Fatal("内存分配失败");
  559. code = 401;
  560. break;
  561. }
  562. memset(p, 0, sizeof(RESISTANCE) * nNewNum);
  563. auto db = CDBConnectPool::Instance()->GetConnection();
  564. COdbcStatement stmt(db);
  565. stmt.Create();
  566. stmt.SetAttribute(SQL_ATTR_ROW_BIND_TYPE, (SQLPOINTER)sizeof(RESISTANCE), 0);
  567. stmt.SetAttribute(SQL_ATTR_PARAM_BIND_TYPE, (SQLPOINTER)sizeof(RESISTANCE), SQL_IS_INTEGER);
  568. stmt.SetAttribute(SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER)(DWORD_PTR)nNewNum, SQL_IS_INTEGER);
  569. SQLUSMALLINT ParamStatusArray[ROW_ARRAY_SIZE] = { 0 };
  570. //设定状态数组
  571. stmt.SetAttribute(SQL_ATTR_ROW_STATUS_PTR, ParamStatusArray, 0);
  572. SQLINTEGER nBindOffset = 0;
  573. stmt.SetAttribute(SQL_ATTR_ROW_BIND_OFFSET_PTR, (SQLPOINTER)&nBindOffset, 0);
  574. CString strSql;
  575. strSql.Format("INSERT INTO rm_resistance_%04d%02d%02d ([IMEI],[acquisitiontime],[idx],[data0],[data1],[data2]) "\
  576. "VALUES(? , ? , ? , ? , ? , ? ); ",
  577. st.wYear, st.wMonth, st.wDay);
  578. char* sql = (char*)(LPCSTR)strSql;
  579. int nCol = 1;
  580. stmt.SQLBindCharParam(nCol++, p[0].imei, sizeof(p[0].imei));
  581. stmt.SQLBindCharParam(nCol++, p[0].time, sizeof(p[0].time));
  582. stmt.SQLBindTinyIntParam(nCol++, &p[0].index);
  583. //stmt.SQLBindTimeStampParam(nCol++, &p[0].time);
  584. stmt.SQLBindIntParam(nCol++, &p[0].data0);
  585. stmt.SQLBindIntParam(nCol++, &p[0].data1);
  586. stmt.SQLBindIntParam(nCol++, &p[0].data2);
  587. //prepare
  588. int step = 1000 / nNum;
  589. int j = 0;
  590. {
  591. for (auto i = 0; i < nNum; i++)
  592. {
  593. if (len0)
  594. {
  595. if (vctResult0[i] == false) continue;
  596. p[j].index = 0;
  597. //if (!vctData0[i].IsEmpty()) p[j].data0 = strtol(vctData0[i], NULL, 16) - 0x8000;
  598. //if (!vctData1[i].IsEmpty()) p[j].data1 = strtol(vctData1[i], NULL, 16) - 0x8000;
  599. //if (!vctData2[i].IsEmpty()) p[j].data2 = strtol(vctData2[i], NULL, 16) - 0x8000;
  600. p[j].data0 = vctData0[i];
  601. p[j].data1 = vctData1[i];
  602. p[j].data2 = vctData2[i];
  603. //ASSERT(p[j].data2);
  604. //pDevice->Insert(0, tmNowStart + step * i, vctData0[i], vctData1[i], vctData2[i]);
  605. }
  606. else if (len3)
  607. {
  608. if (vctResult3[i] == false) continue;
  609. p[j].index = 1;
  610. //if (!vctData3[i].IsEmpty()) p[j].data0 = strtol(vctData3[i], NULL, 16) - 0x8000;
  611. //if (!vctData4[i].IsEmpty()) p[j].data1 = strtol(vctData4[i], NULL, 16) - 0x8000;
  612. //if (!vctData5[i].IsEmpty()) p[j].data2 = strtol(vctData5[i], NULL, 16) - 0x8000;
  613. p[j].data0 = vctData3[i];
  614. p[j].data1 = vctData4[i];
  615. p[j].data2 = vctData5[i];
  616. //pDevice->Insert(1, tmNowStart + step * i, vctData3[i], vctData4[i], vctData5[i]);
  617. }
  618. else if (len6)
  619. {
  620. if (vctResult6[i] == false) continue;
  621. p[j].index = 2;
  622. //if (!vctData6[i].IsEmpty()) p[j].data0 = strtol(vctData6[i], NULL, 16) - 0x8000;
  623. //if (!vctData7[i].IsEmpty()) p[j].data1 = strtol(vctData7[i], NULL, 16) - 0x8000;
  624. //if (!vctData8[i].IsEmpty()) p[j].data2 = strtol(vctData8[i], NULL, 16) - 0x8000;
  625. p[j].data0 = vctData6[i];
  626. p[j].data1 = vctData7[i];
  627. p[j].data2 = vctData8[i];
  628. //pDevice->Insert(2, tmNowStart + step * i, vctData6[i], vctData7[i], vctData8[i]);
  629. }
  630. memcpy_s(p[j].imei, sizeof(p[j].imei), imei, strlen(imei));
  631. sprintf_s(p[j].time, sizeof(p[j].time), "%04d-%02d-%02d %02d:%02d:%02d.%03d",
  632. st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, step * i);
  633. j++;
  634. //memcpy(&p[j].time, &ts, sizeof(ts));
  635. //ts.fraction = step * i;
  636. }
  637. assert(j == nNewNum);
  638. }
  639. //exec
  640. //#ifndef _DEBUG
  641. auto iret = db->SetAutoCommit(false);
  642. iret = stmt.Prepare(sql);
  643. if (ISODBCSUCCESS(stmt.Execute()))
  644. {
  645. }
  646. else
  647. {
  648. vector<COdbcError> vct;
  649. GetOdbcError((SQLSMALLINT)SQL_HANDLE_STMT, stmt.GetHandle(), vct);
  650. CString strError;
  651. if (vct.size() > 0) {
  652. COdbcError error = vct.front();
  653. strError.Format("%s %s %d %s %d %s", __FILE__, __FUNCTION__, __LINE__, error.strSQLState, error.nNativeError, error.strMessage);
  654. TRACE("%s\r\n", strError);
  655. }
  656. CSimpleLog::Error(strError);
  657. strError.Format("IMEI:%s time:%s num:%d newnum:%d j:%d", imei, odt.Format("%Y-%m-%d %H:%M:%S"), nNum, nNewNum, j);
  658. CSimpleLog::Error(strError);
  659. code = 500;
  660. }
  661. iret = db->Commit();
  662. db->SetAutoCommit(true);
  663. //#endif // !_DEBUG
  664. CDBConnectPool::Instance()->FreeConnection(db);
  665. if (p) {
  666. delete[] p;
  667. p = nullptr;
  668. }
  669. }
  670. //补偿点
  671. {
  672. string insert_sql;
  673. string str_time;
  674. time_t tTime; int data0, data1, data2;
  675. uint8_t* pack = nullptr; int len = 0;
  676. if (len0)
  677. {
  678. if (pDevice->CalcBInsertData(0, &tTime, &data0, &data1, &data2))
  679. {
  680. str_time = (LPCSTR)CTime(tTime / 1000).Format("%Y-%m-%d %H:%M:%S.") + to_string(tTime % 1000);
  681. insert_sql = fmt::format("INSERT INTO rm_resistance_{}{:0>2}{:0>2} (IMEI,acquisitiontime,idx,data0,data1,data2)VALUES('{}', '{}', {}, {}, {}, {});",
  682. st.wYear, st.wMonth, st.wDay, imei, str_time, 0, data0, data1, data2);
  683. pDevice->Insert(0, tTime, data0, data1, data2);
  684. //mg_315_server->SendRealDataValue(mo_mp, true, data0, data1, data2, ctNow);
  685. }
  686. }
  687. else if (len3)
  688. {
  689. if (pDevice->CalcBInsertData(1, &tTime, &data0, &data1, &data2))
  690. {
  691. str_time = (LPCSTR)CTime(tTime / 1000).Format("%Y-%m-%d %H:%M:%S.") + to_string(tTime % 1000);
  692. insert_sql = fmt::format("INSERT INTO rm_resistance_{}{:0>2}{:0>2} (IMEI,acquisitiontime,idx,data0,data1,data2)VALUES('{}', '{}', {}, {}, {}, {});",
  693. st.wYear, st.wMonth, st.wDay, imei, str_time, 1, data0, data1, data2);
  694. pDevice->Insert(1, tTime, data0, data1, data2);
  695. //mg_315_server->SendRealDataValue(mo_mp, true, data0, data1, data2, ctNow);
  696. }
  697. }
  698. else if (len6)
  699. {
  700. if (pDevice->CalcBInsertData(2, &tTime, &data0, &data1, &data2))
  701. {
  702. str_time = (LPCSTR)CTime(tTime / 1000).Format("%Y-%m-%d %H:%M:%S.") + to_string(tTime % 1000);
  703. insert_sql = fmt::format("INSERT INTO rm_resistance_{}{:0>2}{:0>2} (IMEI,acquisitiontime,idx,data0,data1,data2)VALUES('{}', '{}', {}, {}, {}, {});",
  704. st.wYear, st.wMonth, st.wDay, imei, str_time, 2, data0, data1, data2);
  705. pDevice->Insert(2, tTime, data0, data1, data2);
  706. //mg_315_server->SendRealDataValue(mo_mp, true, data0, data1, data2, ctNow);
  707. }
  708. }
  709. if (insert_sql.length())
  710. {
  711. if (CSuperManager::Instance()->GetSuperNum() && bMoMp)
  712. {
  713. auto no = GeneralResistPack(mo_mp, data0, data1, data2, str_time, &pack, &len);
  714. if (no) CSuperManager::Instance()->SendPack(pack, len, no, E_ZL_PROTOCAL::ZL_RESIST_DATA, false);
  715. delete[] pack;
  716. pack = nullptr;
  717. }
  718. CString sql(insert_sql.c_str());
  719. CSimpleLog::Info("数据补偿:" + sql);
  720. CDBConnectPool::Instance()->DBExecuteSQL(sql);
  721. }
  722. }
  723. }while (false);
  724. auto dif = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count();
  725. if (dif > 500)
  726. CSimpleLog::Info(fmt::format("push msg 处理耗时: {} ms.", dif).c_str());
  727. return TRUE;
  728. }
  729. //实时
  730. uint32_t CLNHandle::GeneralResistPack(const string& momp, const int num,
  731. const std::vector<int>& vctData0, const std::vector<int>& vctData1, const std::vector<int>& vctData2,
  732. const std::vector<bool>& vctResult, const CTime& atime, uint8_t** pack, int* len)
  733. {
  734. auto doc = yyjson_mut_doc_new(nullptr);
  735. auto root = yyjson_mut_obj(doc);
  736. yyjson_mut_doc_set_root(doc, root);
  737. int step = 1000 / num;
  738. //uint64_t utime_t = atime.GetTime() * 1000;
  739. string up, momp_name;
  740. CMonitorObjectMng::Instance()->GetStationNameByMomP(momp, up, momp_name);
  741. string name1, name2, name3;
  742. CMonitorObjectMng::Instance()->GetNameByMoMp(momp, name1, name2, name3);
  743. string mo, mp;
  744. CMonitorObjectMng::spiltByPoint(momp, mo, mp);
  745. yyjson_mut_obj_add_strcpy(doc, root, "station", up.c_str());
  746. yyjson_mut_obj_add_strcpy(doc, root, "mo", mo.c_str());
  747. yyjson_mut_obj_add_strcpy(doc, root, "mp", mp.c_str());
  748. auto time = yyjson_mut_arr(doc);
  749. yyjson_mut_obj_add_val(doc, root, "time", time);
  750. auto fix_data = yyjson_mut_arr(doc);
  751. yyjson_mut_obj_add_val(doc, root, "fix_data", fix_data);
  752. auto invert_data = yyjson_mut_arr(doc);
  753. yyjson_mut_obj_add_val(doc, root, "invert_data", invert_data);
  754. auto convert_data = yyjson_mut_arr(doc);
  755. yyjson_mut_obj_add_val(doc, root, "convert_data", convert_data);
  756. if (name1.find("定位") != -1)
  757. {
  758. for (int i = 0; i < num; i++)
  759. {
  760. if (vctResult[i] == false) continue;
  761. yyjson_mut_arr_add_strcpy(doc, time, fmt::format("{}.{:0>3}", atime.Format("%Y-%m-%d %H:%M:%S"), step*i).c_str());
  762. yyjson_mut_arr_add_int(doc, fix_data, vctData0[i]);
  763. yyjson_mut_arr_add_int(doc, invert_data, vctData1[i]);
  764. yyjson_mut_arr_add_int(doc, convert_data, vctData2[i]);
  765. }
  766. }
  767. else
  768. {
  769. for (int i = 0; i < num; i++)
  770. {
  771. if (vctResult[i] == false) continue;
  772. yyjson_mut_arr_add_strcpy(doc, time, fmt::format("{}.{:0>3}", atime.Format("%Y-%m-%d %H:%M:%S"), step * i).c_str());
  773. yyjson_mut_arr_add_int(doc, invert_data, vctData0[i]);
  774. yyjson_mut_arr_add_int(doc, fix_data, vctData1[i]);
  775. yyjson_mut_arr_add_int(doc, convert_data, vctData2[i]);
  776. }
  777. }
  778. size_t json_len;
  779. auto json = yyjson_mut_write(doc, 0, &json_len);
  780. yyjson_mut_doc_free(doc);
  781. *len = json_len + sizeof(HJDATAHEAD2) + 2;
  782. *pack = new uint8_t[*len];
  783. auto no = CAppService::Instance()->GetPackNo();
  784. CHjDataConver::conver_sendpack(*pack, (LPBYTE)json, json_len, 0, no, E_ZL_PROTOCAL::ZL_RESIST_DATA,
  785. OR_DATA_INFO(0, 0, 1, 2, OPT_TYPE::OPT_ADD));
  786. free(json);
  787. return no;
  788. }
  789. //补传一个点
  790. uint32_t CLNHandle::GeneralResistPack(const string& momp, int data0, int data1, int data2, string str_time, uint8_t** pack, int* len)
  791. {
  792. auto doc = yyjson_mut_doc_new(nullptr);
  793. auto root = yyjson_mut_obj(doc);
  794. yyjson_mut_doc_set_root(doc, root);
  795. string up, momp_name;
  796. CMonitorObjectMng::Instance()->GetStationNameByMomP(momp, up, momp_name);
  797. string name1, name2, name3;
  798. CMonitorObjectMng::Instance()->GetNameByMoMp(momp, name1, name2, name3);
  799. string mo, mp;
  800. CMonitorObjectMng::spiltByPoint(momp, mo, mp);
  801. yyjson_mut_obj_add_strcpy(doc, root, "station", up.c_str());
  802. yyjson_mut_obj_add_strcpy(doc, root, "mo", mo.c_str());
  803. yyjson_mut_obj_add_strcpy(doc, root, "mp", mp.c_str());
  804. auto time = yyjson_mut_arr(doc);
  805. yyjson_mut_obj_add_val(doc, root, "time", time);
  806. auto fix_data = yyjson_mut_arr(doc);
  807. yyjson_mut_obj_add_val(doc, root, "fix_data", fix_data);
  808. auto invert_data = yyjson_mut_arr(doc);
  809. yyjson_mut_obj_add_val(doc, root, "invert_data", invert_data);
  810. auto convert_data = yyjson_mut_arr(doc);
  811. yyjson_mut_obj_add_val(doc, root, "convert_data", convert_data);
  812. yyjson_mut_arr_add_strcpy(doc, time, str_time.c_str());
  813. if (name1.find("定位") != -1)
  814. {
  815. yyjson_mut_arr_add_int(doc, fix_data, data0);
  816. yyjson_mut_arr_add_int(doc, invert_data, data1);
  817. }
  818. else
  819. {
  820. yyjson_mut_arr_add_int(doc, invert_data, data0);
  821. yyjson_mut_arr_add_int(doc, fix_data, data1);
  822. }
  823. yyjson_mut_arr_add_int(doc, convert_data, data2);
  824. size_t json_len;
  825. auto json = yyjson_mut_write(doc, 0, &json_len);
  826. yyjson_mut_doc_free(doc);
  827. *len = json_len + sizeof(HJDATAHEAD2) + 2;
  828. *pack = new uint8_t[*len];
  829. auto no = CAppService::Instance()->GetPackNo();
  830. CHjDataConver::conver_sendpack(*pack, (LPBYTE)json, json_len, 0, no, E_ZL_PROTOCAL::ZL_RESIST_DATA,
  831. OR_DATA_INFO(0, 0, 1, 2, OPT_TYPE::OPT_ADD));
  832. free(json);
  833. return no;
  834. }
  835. uint32_t CLNHandle::GeneralTempPack(const string& momp, int temp, int humi, time_t utime_t, uint8_t** pack, int* len)
  836. {
  837. if (momp.length() <= 3) return 0;
  838. if (utime_t - m_mapTempHumi[momp] < 60) return 0;//温湿度1分钟上送一次
  839. m_mapTempHumi[momp] = utime_t;
  840. string mo, mp;
  841. CMonitorObjectMng::spiltByPoint(momp, mo, mp);
  842. auto doc = yyjson_mut_doc_new(nullptr);
  843. auto root = yyjson_mut_obj(doc);
  844. yyjson_mut_doc_set_root(doc, root);
  845. string up, momp_name;
  846. CMonitorObjectMng::Instance()->GetStationNameByMomP(momp, up, momp_name);
  847. //string name1, name2, name3;
  848. //CMonitorObjectMng::Instance()->GetNameByMoMp(momp, name1, name2, name3);
  849. yyjson_mut_obj_add_strcpy(doc, root, "station", up.c_str());
  850. yyjson_mut_obj_add_strcpy(doc, root, "mo", mo.c_str());
  851. yyjson_mut_obj_add_strcpy(doc, root, "mp", mp.c_str());
  852. yyjson_mut_obj_add_strcpy(doc, root, "time", CTime(utime_t).Format("%Y-%m-%d %H:%M:%S"));
  853. yyjson_mut_obj_add_int(doc, root, "temp", temp);
  854. yyjson_mut_obj_add_int(doc, root, "humi", humi);
  855. size_t json_len;
  856. auto json = yyjson_mut_write(doc, 0, &json_len);
  857. yyjson_mut_doc_free(doc);
  858. *len = json_len + sizeof(HJDATAHEAD2) + 2;
  859. *pack = new uint8_t[*len];
  860. auto no = CAppService::Instance()->GetPackNo();
  861. CHjDataConver::conver_sendpack(*pack, (LPBYTE)json, json_len, 0, no, E_ZL_PROTOCAL::ZL_TEMP_HUMI,
  862. OR_DATA_INFO(0, 0, 1, 2, OPT_TYPE::OPT_ADD));
  863. free(json);
  864. return no;
  865. }
  866. BOOL CLNHandle::HandlePushInfo(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pContext /*= NULL*/)
  867. {
  868. if (pContext) pContext->m_mapImei[imei]++;
  869. string CCID;
  870. if (doc.HasMember("CCID") && doc["CCID"].IsString())
  871. CCID = doc["CCID"].GetString();
  872. string location;
  873. if (doc.HasMember("location") && doc["location"].IsString())
  874. location = doc["location"].GetString();
  875. string type;
  876. if (doc.HasMember("type") && doc["type"].IsString())
  877. type = doc["type"].GetString();
  878. string version;
  879. if (doc.HasMember("version") && doc["version"].IsString())
  880. version = doc["version"].GetString();
  881. vector<CString> vct(2);
  882. auto vctLen = convertStrToArray(location, vct);
  883. //model = 0 代表数据模式 1 代表升级模式
  884. //update
  885. CString strSql;
  886. strSql.Format(" IF EXISTS (SELECT TOP 1 * FROM rm_deviceinfo WHERE IMEI = '%s') " \
  887. " BEGIN "
  888. " UPDATE rm_deviceinfo set CCID = '%s', longitude = %f, latitude = %f, type='%s', version='%s', updatetime = GETDATE(), model = 0 WHERE IMEI = '%s' " \
  889. " END " \
  890. " ELSE " \
  891. " BEGIN " \
  892. " INSERT INTO [dbo].[rm_deviceinfo] ([IMEI],[CCID],[longitude],[latitude],[type],[version],[model]) VALUES ('%s', '%s', %f, %f, '%s', '%s', 0)" \
  893. " END",
  894. imei,
  895. CCID.c_str(), atof(vct[0]), atof(vct[1]), type.c_str(), version.c_str(), imei,
  896. imei, CCID.c_str(), atof(vct[0]), atof(vct[1]), type.c_str(), version.c_str()
  897. );
  898. if (!CDBConnectPool::Instance()->DBExecuteSQL(strSql))
  899. CSimpleLog::Error(strSql + "执行失败");
  900. //response
  901. StringBuffer strBuf;
  902. Writer<StringBuffer> writer(strBuf);
  903. writer.StartObject();
  904. writer.Key("cmd");
  905. writer.String("push_info_ack");
  906. writer.Key("IMEI");
  907. writer.String(imei);
  908. writer.EndObject();
  909. string data = strBuf.GetString();
  910. if (pContext)
  911. return pContext->Send(data.c_str(), data.length()) != SOCKET_ERROR;
  912. else if (psa)
  913. return CAppService::Instance()->GetUdpSocket()->SendTo((void*)data.c_str(), data.length(), psa, sizeof(SOCKADDR));
  914. else
  915. return FALSE;
  916. }
  917. BOOL CLNHandle::HandleInfoAck(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pContext /*= NULL*/)
  918. {
  919. return FALSE;
  920. }
  921. BOOL CLNHandle::HanldeTime(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pContext /*= NULL*/)
  922. {
  923. if (pContext == FALSE) return FALSE;
  924. time_t tmNow;
  925. time(&tmNow);
  926. //response
  927. StringBuffer strBuf;
  928. Writer<StringBuffer> writer(strBuf);
  929. writer.StartObject();
  930. writer.Key("cmd");
  931. writer.String("time_ack");
  932. writer.Key("timestamp");
  933. writer.Uint64(tmNow);
  934. writer.Key("IMEI");
  935. writer.String(imei);
  936. writer.EndObject();
  937. string data = strBuf.GetString();
  938. return pContext->Send(data.c_str(), data.length()) != SOCKET_ERROR;
  939. }
  940. BOOL CLNHandle::SendTimeAckToAllDevice()
  941. {
  942. auto doc = yyjson_mut_doc_new(nullptr);
  943. auto root = yyjson_mut_obj(doc);
  944. yyjson_mut_doc_set_root(doc, root);
  945. yyjson_mut_obj_add_str(doc, root, "cmd", "time_ack");
  946. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  947. pAcceptor->Lock();
  948. for (auto& it : pAcceptor->m_lstClientContext)
  949. {
  950. auto pContext = (CLNContext*)it;
  951. for (auto& ik : pContext->m_mapImei)
  952. {
  953. yyjson_mut_obj_remove_str(root, "IMEI");
  954. yyjson_mut_obj_remove_str(root, "timestamp");
  955. yyjson_mut_obj_add_strcpy(doc, root, "IMEI", ik.first);
  956. auto tt = CTime::GetCurrentTime().GetTime();
  957. yyjson_mut_obj_add_int(doc, root, "timestamp", tt);
  958. size_t l;
  959. auto json = yyjson_mut_write(doc, 0, &l);
  960. if (json)
  961. {
  962. pContext->Send(json, l);
  963. free(json);
  964. }
  965. }
  966. }
  967. pAcceptor->Unlock();
  968. yyjson_mut_doc_free(doc);
  969. return TRUE;
  970. }
  971. //{"cmd":"push_online","IMEI":"002E00404B305009","st0":[0,0],"st1":[0,0],"st2":[1,0],"st3":[0,0],"st4":[0,0],"st5":[1,0],"st6":[0,0],"st7":[0,0],"st8":[1,0]}
  972. //{"cmd":"push_online","IMEI":"1234567890","packnum":"2","st0":[1],"st1":[0],"st2":[0],"st3":[0],"st4":[0],"st5":[0],"st6":[0],"st7":[0],"st8":[0],"dt0":[1],"dt1":[0],"dt2":[0],"dt3":[0],"dt4":[0],"dt5":[0],"dt6":[0],"dt7":[0],"dt8":[0]}
  973. BOOL CLNHandle::HandlePushOnline(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext, LPBYTE pPack, int nPackLen)
  974. {
  975. CSimpleLog::Info(CString((char*)pPack, nPackLen));
  976. if (doc.HasMember("packnum") == FALSE || doc["packnum"].IsString() == FALSE)
  977. return FALSE;
  978. auto packnum = doc["packnum"].GetString();
  979. CString strData;
  980. strData.Format(R"({"cmd":"push_online_ack","IMEI":"%s","packnum":"%s"})", imei, packnum ? packnum : "");
  981. if (pClientContext)
  982. pClientContext->Send(strData, strData.GetLength()) != SOCKET_ERROR;
  983. else if (psa)
  984. CAppService::Instance()->GetUdpSocket()->SendTo((void*)(LPCSTR)strData, strData.GetLength(), psa, sizeof(SOCKADDR));
  985. auto pDevice = CDeviceMng::Instance()->Find(imei);
  986. if (pDevice == nullptr) return FALSE;
  987. SENSOR_STATUS sensor_status[9][2];
  988. memset(&sensor_status, (int)SENSOR_STATUS::UNKONW, sizeof(sensor_status));
  989. char key[10];
  990. for (int i = 0; i < 9; i++)
  991. {
  992. sprintf_s(key, 10, "st%d", i);
  993. if (doc.HasMember(key) == false || doc[key].IsArray() == false)
  994. continue;
  995. auto st = doc[key].GetArray();
  996. for (int j = 0; j < st.Size() && j < 2; j++)
  997. {
  998. if (st[j].IsInt() == false) continue;
  999. if (st[j].GetInt() == 0)
  1000. sensor_status[i][j] = SENSOR_STATUS::ABNORMAL;
  1001. else if (st[j].GetInt() == 1)
  1002. sensor_status[i][j] = SENSOR_STATUS::NORMAL;
  1003. else if (st[j].GetInt() == 2)
  1004. sensor_status[i][j] = SENSOR_STATUS::HFDISTURB;
  1005. else if(st[j].GetInt() == 3)
  1006. sensor_status[i][j] = SENSOR_STATUS::FIXEDVALUE;
  1007. else
  1008. sensor_status[i][j] = SENSOR_STATUS::ABNORMAL; //不认识的状态
  1009. }
  1010. }
  1011. // 获取dt数据
  1012. int sensor_time_chip_status[9][2] = { 0 };
  1013. for (int i = 0; i < 9; i++)
  1014. {
  1015. sprintf_s(key, 10, "dt%d", i);
  1016. if (doc.HasMember(key) == false || doc[key].IsArray() == false)
  1017. continue;
  1018. auto dt = doc[key].GetArray();
  1019. for (int j = 0; j < dt.Size() && j < 2; j++)
  1020. {
  1021. if (dt[j].IsInt() == false) continue;
  1022. sensor_time_chip_status[i][j] = dt[j].GetInt();
  1023. }
  1024. }
  1025. // 写入设备传感器的状态信息
  1026. pDevice->InsertStatus(sensor_status, sensor_time_chip_status);
  1027. for (int i = 0; i < 9; i++)
  1028. {
  1029. for (int j = 0; j < 2; j++)
  1030. {
  1031. const auto& tt = sensor_status[i][j];
  1032. auto& src_tt = pDevice->m_sensor_status[i][j];
  1033. bool bNew = false, bConver = false;
  1034. if (src_tt != SENSOR_STATUS::UNKONW && tt == src_tt) //状态没有变化,不做处理
  1035. continue;
  1036. if (tt == SENSOR_STATUS::NORMAL && src_tt != SENSOR_STATUS::NORMAL) //恢复
  1037. bConver = true;
  1038. else if (tt != SENSOR_STATUS::NORMAL && src_tt == SENSOR_STATUS::NORMAL) //产生
  1039. bNew = true;
  1040. else if (src_tt == SENSOR_STATUS::UNKONW && tt == SENSOR_STATUS::ABNORMAL)
  1041. bNew = true;
  1042. else if (src_tt == SENSOR_STATUS::UNKONW)
  1043. src_tt = tt;
  1044. else if (tt == SENSOR_STATUS::UNKONW) //丢失
  1045. bNew = true;
  1046. else
  1047. ASSERT(FALSE);
  1048. src_tt = tt; //赋值
  1049. if (bConver == false && bNew == false) continue;
  1050. string mo, mp;
  1051. uint8_t idx = i % 3;
  1052. if (false == CMonitorObjectMng::Instance()->IMEI2MOMP(imei, idx, mo, mp)) continue;
  1053. auto pInfo = CMonitorObjectMng::Instance()->GetMoMpInfo(mo + '.' + mp);
  1054. if (pInfo == nullptr)
  1055. {
  1056. ASSERT(FALSE);
  1057. continue;
  1058. }
  1059. //判断是否安装
  1060. switch (idx)
  1061. {
  1062. case 0:
  1063. if (pInfo->binstall_1 == false)
  1064. continue;
  1065. break;
  1066. case 1:
  1067. if (pInfo->binstall_2 == false)
  1068. continue;
  1069. break;
  1070. case 2:
  1071. if (pInfo->binstall_3 == false)
  1072. continue;
  1073. break;
  1074. default:
  1075. ASSERT(FALSE);
  1076. break;
  1077. }
  1078. SYSTEMTIME stNow;
  1079. GetLocalTime(&stNow);
  1080. // 不做报警处理,记录数据库中
  1081. //报警发送
  1082. if (bNew)
  1083. {
  1084. //存入数据库
  1085. //CResistAlarmMng::Instance()->GeneralAlarm(mo, mp, idx, eZL_ALARMTYPE::SENSOR_ABNORMAL, 1, stNow);
  1086. //上送报警 传感器异常暂时屏蔽 等待放开
  1087. g_p315ClientManager->GetTcpClient()->SendAlarmData(CMonitorObjectMng::Instance()->GetZZJNO(mo + '.' + mp), 1, CTime(stNow).GetTime(), 0xFFFFFFFF,
  1088. eZL_ALARMTYPE::SENSOR_ABNORMAL, eDaoChaPosi::DCP_UNKNOWN, 0, eLowHigh::LH_UNKNOWN, TIEDA_ACQ_VALUE(INT_MIN), TIEDA_ACQ_VALUE(INT_MIN), 0);
  1089. }
  1090. else if (bConver)
  1091. {
  1092. //CResistAlarmMng::Instance()->RecoverAlarm(mo, mp, idx, eZL_ALARMTYPE::SENSOR_ABNORMAL, 1, stNow);
  1093. g_p315ClientManager->GetTcpClient()->SendAlarmData(CMonitorObjectMng::Instance()->GetZZJNO(mo + '.' + mp), 2, CTime(stNow).GetTime(), CTime(stNow).GetTime(),
  1094. eZL_ALARMTYPE::SENSOR_ABNORMAL, eDaoChaPosi::DCP_UNKNOWN, 0, eLowHigh::LH_UNKNOWN, TIEDA_ACQ_VALUE(INT_MIN), TIEDA_ACQ_VALUE(INT_MIN), 0);
  1095. }
  1096. }
  1097. }
  1098. return TRUE;
  1099. }
  1100. //client
  1101. BOOL CLNHandle::HandleUpdate(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext /*= NULL*/)
  1102. {
  1103. if (pClientContext == FALSE) return FALSE;
  1104. auto pContext = (CLNContext*)pClientContext;
  1105. pContext->ivuname = imei;
  1106. BOOL bDataRight = TRUE;
  1107. //接收文件数据
  1108. string data;
  1109. if (doc.HasMember("data") && doc["data"].IsString())
  1110. data = doc["data"].GetString();
  1111. else
  1112. bDataRight = FALSE;
  1113. string type;
  1114. if (doc.HasMember("type") && doc["type"].IsString())
  1115. type = doc["type"].GetString();
  1116. else
  1117. bDataRight = FALSE;
  1118. uint32_t filecrc;
  1119. if (doc.HasMember("filecrc") && doc["filecrc"].IsUint())
  1120. filecrc = doc["filecrc"].GetUint();
  1121. else
  1122. bDataRight = FALSE;
  1123. uint32_t filesize;
  1124. if (doc.HasMember("filesize") && doc["filesize"].IsUint())
  1125. filesize = doc["filesize"].GetUint();
  1126. else
  1127. bDataRight = FALSE;
  1128. if (bDataRight)
  1129. {
  1130. auto& mapTypeData = CAppService::Instance()->m_mapTypeData;
  1131. auto it = mapTypeData.find(type.c_str());
  1132. int datalen = data.length();
  1133. if (it != mapTypeData.end())
  1134. {
  1135. it->second->Join();
  1136. it->second = nullptr;
  1137. }
  1138. char* pData = new char[datalen + 2];
  1139. auto pInfo = new UPGRADE_FILE_DATA;
  1140. mapTypeData[type.c_str()] = pInfo;
  1141. pInfo->data = pData;
  1142. pInfo->len = filesize * 2;
  1143. pInfo->crc = filecrc;
  1144. memcpy_s(pData, datalen + 2, data.c_str(), datalen);
  1145. pData[datalen] = 0x00;
  1146. pData[datalen + 1] = 0x00;
  1147. }
  1148. else
  1149. {
  1150. CSimpleLog::Error("HandleUpdate 数据解析错误!");
  1151. }
  1152. //校验文件数据OK
  1153. //response
  1154. StringBuffer strBuf;
  1155. Writer<StringBuffer> writer(strBuf);
  1156. writer.StartObject();
  1157. BOOL bUpdateToDevice = FALSE;
  1158. char ip[30];
  1159. uint16_t port = 0;
  1160. pContext->GetIPAdressNew(ip, 30, port);
  1161. if (bDataRight && SendUpdateToDevice(imei, ip, type))
  1162. {
  1163. //writer.Key("cmd");
  1164. //writer.String("update_ack");
  1165. //writer.Key("result");
  1166. //writer.String("true");
  1167. bUpdateToDevice = TRUE;
  1168. }
  1169. else
  1170. {
  1171. writer.Key("cmd");
  1172. writer.String("update_ack");
  1173. writer.Key("IMEI");
  1174. writer.String(imei);
  1175. writer.Key("result");
  1176. writer.String("false");
  1177. writer.EndObject();
  1178. string senddata = strBuf.GetString();
  1179. #ifdef SEND_LOG
  1180. CSimpleLog::Info(senddata.c_str());
  1181. #endif // SEND_LOG
  1182. bUpdateToDevice &= pContext->Send(senddata.c_str(), senddata.length()) != SOCKET_ERROR;
  1183. }
  1184. return bUpdateToDevice;
  1185. }
  1186. //device
  1187. BOOL CLNHandle::HandleUpdateAck(const rapidjson::Document& doc, LPBYTE pPack, int nPackLen, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext /*= NULL*/)
  1188. {
  1189. CString strLog;
  1190. string result;
  1191. if (doc.HasMember("result") && doc["result"].IsString())
  1192. result = doc["result"].GetString();
  1193. strLog.Format("收到设备升级数据ok包:" + CString(imei) + "result:" + result.c_str());
  1194. TRACE("%s\r\n", strLog);
  1195. CSimpleLog::Info(strLog);
  1196. //根据imei查找TCP链路
  1197. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1198. auto pContext = pAcceptor->FindContextByIVU(imei);
  1199. if (pContext == nullptr) return FALSE;
  1200. auto ret = pContext->Send(pPack, nPackLen) != SOCKET_ERROR;
  1201. pContext->ReleaseSharedPointer();
  1202. return ret;
  1203. }
  1204. //client
  1205. BOOL CLNHandle::HandleOnlineDevice(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext /*= NULL*/)
  1206. {
  1207. if (pClientContext == FALSE) return FALSE;
  1208. auto pContext = (CLNContext*)pClientContext;
  1209. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1210. if (pAcceptor == nullptr) return FALSE;
  1211. std::list<CString> lst;
  1212. pAcceptor->GetAllContextImei(lst);
  1213. //response
  1214. StringBuffer strBuf;
  1215. Writer<StringBuffer> writer(strBuf);
  1216. writer.StartObject();
  1217. writer.Key("cmd");
  1218. writer.String("get_online_ack");
  1219. writer.Key("list");
  1220. writer.StartArray();
  1221. for (const auto& it : lst)
  1222. writer.String(it);
  1223. writer.EndArray();
  1224. writer.EndObject();
  1225. string data = strBuf.GetString();
  1226. return pContext->Send(data.c_str(), data.length()) != SOCKET_ERROR;
  1227. }
  1228. BOOL CLNHandle::HandleOnlineDeviceNew(const SOCKADDR* psa, CLNContext* pContext /*= NULL*/)
  1229. {
  1230. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1231. if (pAcceptor == nullptr) return FALSE;
  1232. std::list<CString> lst;
  1233. pAcceptor->GetAllContextImei(lst);
  1234. auto doc = yyjson_mut_doc_new(nullptr);
  1235. auto root = yyjson_mut_obj(doc);
  1236. yyjson_mut_doc_set_root(doc, root);
  1237. yyjson_mut_obj_add_str(doc, root, "cmd", "get_online_ack");
  1238. auto list = yyjson_mut_arr(doc);
  1239. yyjson_mut_obj_add_val(doc, root, "list", list);
  1240. auto desc_arr = yyjson_mut_arr(doc);
  1241. yyjson_mut_obj_add_val(doc, root, "desc", desc_arr);
  1242. for (auto& it : lst)
  1243. {
  1244. yyjson_mut_arr_add_str(doc, list, it);
  1245. string imei_idx = it + ".0";
  1246. string mo_mp;
  1247. string desc = " ";
  1248. if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei_idx, mo_mp))
  1249. desc += "[" + mo_mp + "]";
  1250. imei_idx = it + ".1";
  1251. if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei_idx, mo_mp))
  1252. desc += "[" + mo_mp + "]";
  1253. imei_idx = it + ".2";
  1254. if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei_idx, mo_mp))
  1255. desc += "[" + mo_mp + "]";
  1256. yyjson_mut_arr_add_strcpy(doc, desc_arr, desc.c_str());
  1257. }
  1258. size_t len;
  1259. auto json = yyjson_mut_write(doc, 0, &len);
  1260. BOOL bRet = FALSE;
  1261. if (pContext)
  1262. bRet = pContext->Send(json, len) != SOCKET_ERROR;
  1263. else if (psa)
  1264. bRet = CAppService::Instance()->GetUdpSocket()->SendTo(json, len, psa, sizeof(SOCKADDR));
  1265. return bRet;
  1266. }
  1267. BOOL CLNHandle::HandleQueryMsgAck(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext /*= NULL*/)
  1268. {
  1269. if (doc.HasMember("result") == FALSE || doc["result"].IsString() == FALSE) return FALSE;
  1270. string result = doc["result"].GetString();
  1271. CString strLog;
  1272. if (result.compare("true") == 0)
  1273. strLog.Format("设备[%s]响应实时数据成功.",imei);
  1274. else if (result.compare("false") == 0)
  1275. strLog.Format("设备[%s]响应实时数据失败.", imei);
  1276. else
  1277. strLog.Format("设备[%s]响应实时数据%s.", result.c_str());
  1278. CSimpleLog::Info(strLog);
  1279. return TRUE;
  1280. }
  1281. BOOL CLNHandle::HandleUpdateInit(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext)
  1282. {
  1283. CAppService::Instance()->m_bHaveDeviceUpgrade = TRUE;
  1284. time(&CAppService::Instance()->m_tDeviceUpgrade);
  1285. //根据type 来发送 filelen 和 filecrc updateinit_ack
  1286. if (psa == nullptr && pClientContext == nullptr)
  1287. return FALSE;
  1288. CString sql;
  1289. sql.Format("UPDATE rm_deviceinfo SET model = 1 WHERE IMEI = '%s';", imei);
  1290. if (CDBConnectPool::Instance()->DBExecuteSQL(sql) == FALSE)
  1291. CSimpleLog::Error(sql);
  1292. uint32_t filesize = 0;
  1293. uint32_t filecrc = 0;
  1294. do
  1295. {
  1296. string type;
  1297. if (doc.HasMember("type") && doc["type"].IsString())
  1298. type = doc["type"].GetString();
  1299. else
  1300. break;
  1301. auto& mapTypeData = CAppService::Instance()->m_mapTypeData;
  1302. const auto it = mapTypeData.find(type.c_str());
  1303. if (it == mapTypeData.end())
  1304. {
  1305. CString strLog;
  1306. strLog.Format("%s %d 未找到文件 IMEI:%s type:%s ", __FUNCTION__, __LINE__, imei, type.c_str());
  1307. CSimpleLog::Error(strLog);
  1308. break;
  1309. }
  1310. if (it->second == nullptr)
  1311. break;
  1312. auto pInfo = it->second;
  1313. filesize = it->second->len / 2;
  1314. filecrc = it->second->crc;
  1315. } while (false);
  1316. //response
  1317. StringBuffer strBuf;
  1318. Writer<StringBuffer> writer(strBuf);
  1319. writer.StartObject();
  1320. writer.Key("cmd");
  1321. writer.String("updateinit_ack");
  1322. writer.Key("IMEI");
  1323. writer.String(imei);
  1324. writer.Key("filesize");
  1325. writer.Uint(filesize);
  1326. writer.Key("filecrc");
  1327. writer.Uint(filecrc);
  1328. writer.EndObject();
  1329. string data = strBuf.GetString();
  1330. #ifdef SEND_LOG
  1331. CSimpleLog::Info(data.c_str());
  1332. #endif // SEND_LOG
  1333. if (psa)
  1334. {
  1335. return CAppService::Instance()->GetUdpSocket()->SendTo(data.c_str(), data.length(), psa, sizeof(SOCKADDR)) != SOCKET_ERROR;
  1336. }
  1337. else if (pClientContext)
  1338. {
  1339. const auto pContext = (CLNContext*)pClientContext;
  1340. return pContext->Send(data.c_str(), data.length()) > 0;
  1341. }
  1342. return false;
  1343. }
  1344. BOOL CLNHandle::HandleUpdateSeq(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext)
  1345. {
  1346. CAppService::Instance()->m_bHaveDeviceUpgrade = TRUE;
  1347. time(&CAppService::Instance()->m_tDeviceUpgrade);
  1348. //根据type 和 seq 来发送 seq datalen data updateseq_ack
  1349. if (psa == nullptr && pClientContext == nullptr)
  1350. return FALSE;
  1351. int datalen = 0;
  1352. char szData[1025] = { 0 };
  1353. int seq = -1;
  1354. do
  1355. {
  1356. string type;
  1357. if (doc.HasMember("type") && doc["type"].IsString())
  1358. type = doc["type"].GetString();
  1359. else
  1360. break;
  1361. if (doc.HasMember("seq") && doc["seq"].IsInt())
  1362. seq = doc["seq"].GetInt();
  1363. else
  1364. break;
  1365. auto& mapTypeData = CAppService::Instance()->m_mapTypeData;
  1366. const auto it = mapTypeData.find(type.c_str());
  1367. if (it == mapTypeData.end())
  1368. {
  1369. CString strLog;
  1370. strLog.Format("%s %d 未找到文件 %s ", __FUNCTION__, __LINE__, imei);
  1371. CSimpleLog::Error(strLog);
  1372. break;
  1373. }
  1374. if (it->second == nullptr)
  1375. break;
  1376. auto pInfo = it->second;
  1377. int start = seq * 512 * 2;
  1378. int end = start + 512;
  1379. if (start > pInfo->len)
  1380. datalen = 0;
  1381. else if (end > pInfo->len)
  1382. datalen = (pInfo->len - start) / 2;
  1383. else
  1384. datalen = 512;
  1385. memcpy_s(szData, 1024, pInfo->data + start, datalen * 2);
  1386. } while (false);
  1387. //response
  1388. StringBuffer strBuf;
  1389. Writer<StringBuffer> writer(strBuf);
  1390. writer.StartObject();
  1391. writer.Key("cmd");
  1392. writer.String("updateseq_ack");
  1393. writer.Key("IMEI");
  1394. writer.String(imei);
  1395. writer.Key("seq");
  1396. writer.Int(seq);
  1397. writer.Key("datalen");
  1398. writer.Int(datalen);
  1399. writer.Key("data");
  1400. writer.String(szData);
  1401. writer.EndObject();
  1402. string data = strBuf.GetString();
  1403. #ifdef SEND_LOG
  1404. CSimpleLog::Info(data.c_str());
  1405. #endif // _DEBUG
  1406. if (psa)
  1407. {
  1408. return CAppService::Instance()->GetUdpSocket()->SendTo(data.c_str(), data.length(), psa, sizeof(SOCKADDR)) != SOCKET_ERROR;
  1409. }
  1410. else if (pClientContext)
  1411. {
  1412. const auto pContext = (CLNContext*)pClientContext;
  1413. return pContext->Send(data.c_str(), data.length()) > 0;
  1414. }
  1415. return false;
  1416. }
  1417. BOOL CLNHandle::HandleUpdateOk(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext)
  1418. {
  1419. CAppService::Instance()->m_bHaveDeviceUpgrade = FALSE;
  1420. time(&CAppService::Instance()->m_tDeviceUpgrade);
  1421. //返回升级成功命令, 删除升级临时数据 type updateok_ack
  1422. string type;
  1423. if (doc.HasMember("type") && doc["type"].IsString())
  1424. type = doc["type"].GetString();
  1425. else
  1426. return FALSE;
  1427. CString strLog;
  1428. strLog.Format("%s %s 升级完成", imei, type.c_str());
  1429. CSimpleLog::Info(strLog);
  1430. if (psa == nullptr && pClientContext == nullptr)
  1431. return FALSE;
  1432. //response
  1433. StringBuffer strBuf;
  1434. Writer<StringBuffer> writer(strBuf);
  1435. writer.StartObject();
  1436. writer.Key("cmd");
  1437. writer.String("updateok_ack");
  1438. writer.Key("IMEI");
  1439. writer.String(imei);
  1440. writer.EndObject();
  1441. string data = strBuf.GetString();
  1442. #ifdef SEND_LOG
  1443. CSimpleLog::Info(data.c_str());
  1444. #endif // _DEBUG
  1445. BOOL ret = FALSE;
  1446. if (psa)
  1447. {
  1448. ret = CAppService::Instance()->GetUdpSocket()->SendTo(data.c_str(), data.length(), psa, sizeof(SOCKADDR)) != SOCKET_ERROR;
  1449. }
  1450. else if (pClientContext)
  1451. {
  1452. const auto pContext = (CLNContext*)pClientContext;
  1453. ret = pContext->Send(data.c_str(), data.length()) > 0;
  1454. }
  1455. //通知websocket
  1456. //auto lwsService = CAppService::Instance()->GetLwsServer();
  1457. //std::map<lws*, per_session_data> m_mapLwsSession;
  1458. //{
  1459. // uint8_t s_data[200];
  1460. // memcpy_s(s_data + LWS_PRE, 200 - LWS_PRE, data.c_str(), data.length());
  1461. // std::lock_guard<std::mutex> lcok(lwsService->m_mtxSession);
  1462. // for (auto& it : lwsService->m_mapLwsSession)
  1463. // {
  1464. // if (m_strUpgradeRemoteAddr.compare(it.second.ip) == 0)
  1465. // {
  1466. // lws_write(it.first, s_data + LWS_PRE, data.length(), lws_write_protocol::LWS_WRITE_TEXT);
  1467. // }
  1468. // }
  1469. //}
  1470. auto mgService = CAppService::Instance()->GetMgServer();
  1471. if (mgService)
  1472. mgService->SendToClient(data.c_str(), data.length(), m_strUpgradeRemoteAddr.c_str());
  1473. return ret;
  1474. }
  1475. //device
  1476. int CLNHandle::SendUpdateToDevice(const char* imei, string remote_addr, string type)
  1477. {
  1478. m_strUpgradeRemoteAddr = remote_addr;
  1479. CAppService::Instance()->m_bHaveDeviceUpgrade = TRUE;
  1480. time(&CAppService::Instance()->m_tDeviceUpgrade);
  1481. CAppService::Instance()->m_tDeviceUpgrade -= 55;
  1482. //根据imei查找TCP链路
  1483. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1484. auto pContext = pAcceptor->FindContextByIMEI(imei);
  1485. if (pContext == nullptr)
  1486. {
  1487. CString strLog;
  1488. strLog.Format("%s %d 未找到设备 %s ", __FUNCTION__, __LINE__, imei);
  1489. CSimpleLog::Error(strLog);
  1490. return 1;
  1491. }
  1492. //下发升级指令
  1493. //response
  1494. StringBuffer strBuf;
  1495. Writer<StringBuffer> writer(strBuf);
  1496. writer.StartObject();
  1497. writer.Key("cmd");
  1498. writer.String("update");
  1499. writer.Key("IMEI");
  1500. writer.String(imei);
  1501. writer.Key("type");
  1502. writer.String(type.c_str());
  1503. writer.EndObject();
  1504. string data = strBuf.GetString();
  1505. CSimpleLog::Info(data.c_str());
  1506. auto ret = pContext->Send(data.c_str(), data.length()) != SOCKET_ERROR;
  1507. pContext->ReleaseSharedPointer();
  1508. if (ret)
  1509. return 0;
  1510. else
  1511. return 2;
  1512. }
  1513. int CLNHandle::SendMsgToDevice(const char* imei)
  1514. {
  1515. //根据imei查找TCP链路
  1516. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1517. auto pContext = pAcceptor->FindContextByIMEI(imei);
  1518. if (pContext == nullptr)
  1519. {
  1520. CString strLog;
  1521. strLog.Format("%s %d 未找到设备 %s ", __FUNCTION__, __LINE__, imei);
  1522. CSimpleLog::Error(strLog);
  1523. return 1;
  1524. }
  1525. char json[100];
  1526. int len = sprintf_s(json, 100, R"({"cmd":"query_msg","IMEI":"%s"})", imei);
  1527. auto ret = pContext->Send(json, len) != SOCKET_ERROR;
  1528. pContext->ReleaseSharedPointer();
  1529. CSimpleLog::Info(json);
  1530. if (ret)
  1531. return 0;
  1532. else
  1533. return 2;
  1534. }
  1535. std::string CLNHandle::m_strUpgradeRemoteAddr;
  1536. uint32_t CLNHandle::convertStrToArray(const string& str, std::vector<CString>& lst)
  1537. {
  1538. // string->char *
  1539. char *s_input = (char *)str.c_str();
  1540. const char * split = ",";
  1541. // 以逗号为分隔符拆分字符串
  1542. char *p = strtok(s_input, split);
  1543. int i = 0;
  1544. while (p != NULL)
  1545. {
  1546. if (i < lst.capacity())
  1547. lst[i++] = p;
  1548. p = strtok(NULL, split);
  1549. }
  1550. return i;
  1551. }
  1552. uint32_t CLNHandle::convertStrToArraytest(const string& str, std::vector<int>& lst)
  1553. {
  1554. // string->char *
  1555. char* s_input = (char*)str.c_str();
  1556. const char* split = ",";
  1557. // 以逗号为分隔符拆分字符串
  1558. char* p = strtok(s_input, split);
  1559. int i = 0;
  1560. while (p != NULL)
  1561. {
  1562. if (i < lst.capacity())
  1563. {
  1564. int l = strlen(p);
  1565. if (l > 4)
  1566. {
  1567. TRACE("%s,\r\n", p);
  1568. lst[i++] = strtol(p, NULL, 16) - 0x800000;
  1569. }
  1570. else if (l == 4)
  1571. {
  1572. ASSERT(strtol(p, NULL, 16) - 0x8000);
  1573. lst[i++] = strtol(p, NULL, 16) - 0x8000;
  1574. }
  1575. }
  1576. p = strtok(NULL, split);
  1577. }
  1578. return i;
  1579. }
  1580. std::map<CString, COleDateTime> CLNHandle::m_mapIMEI_time0;
  1581. std::map<CString, COleDateTime> CLNHandle::m_mapIMEI_time3;
  1582. std::map<CString, COleDateTime> CLNHandle::m_mapIMEI_time6;
  1583. std::map<CString, COleDateTime> CLNHandle::m_mapIMEI_temp;
  1584. void CLNHandle::ThreadForHandle(DWORD_PTR pThis)
  1585. {
  1586. Sleep(1000);
  1587. SPDLOG_INFO(" 51609 handle thread start");
  1588. auto pHanlde = (CLNHandle*)pThis;
  1589. while (pHanlde->m_bWork)
  1590. {
  1591. Sleep(1);
  1592. if (pHanlde->m_lst.size() == 0)
  1593. {
  1594. Sleep(10);
  1595. continue;
  1596. }
  1597. tagHandlePack* pack = nullptr;
  1598. {
  1599. lock_guard<mutex> lock(pHanlde->m_mtx);
  1600. pack = pHanlde->m_lst.front();
  1601. pHanlde->m_lst.pop_front();
  1602. }
  1603. pHanlde->ProcessPack(pack->pPack, pack->nPackLen, pack->psa.sa_family == 0x00 ? nullptr : &pack->psa, pack->pClientContext);
  1604. pack->join();//释放
  1605. }
  1606. SPDLOG_INFO(" 51609 handle thread exit");
  1607. }