LNHandle.cpp 57 KB

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