LNHandle.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  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
  1001. sensor_status[i][j] = SENSOR_STATUS::NORMAL;
  1002. }
  1003. }
  1004. for (int i = 0; i < 9; i++)
  1005. {
  1006. for (int j = 0; j < 2; j++)
  1007. {
  1008. const auto& tt = sensor_status[i][j];
  1009. auto& src_tt = pDevice->m_sensor_status[i][j];
  1010. bool bNew = false, bConver = false;
  1011. if (src_tt != SENSOR_STATUS::UNKONW && tt == src_tt)
  1012. continue;
  1013. if (tt == SENSOR_STATUS::NORMAL && src_tt == SENSOR_STATUS::ABNORMAL) //恢复
  1014. bConver = true;
  1015. else if (tt == SENSOR_STATUS::ABNORMAL && src_tt == SENSOR_STATUS::NORMAL) //产生
  1016. bNew = true;
  1017. else if (src_tt == SENSOR_STATUS::UNKONW && tt == SENSOR_STATUS::ABNORMAL)
  1018. bNew = true;
  1019. else if (src_tt == SENSOR_STATUS::UNKONW)
  1020. src_tt = tt;
  1021. else if (tt == SENSOR_STATUS::UNKONW) //丢失
  1022. bNew = true;
  1023. else
  1024. ASSERT(FALSE);
  1025. src_tt = tt; //赋值
  1026. if (bConver == false && bNew == false) continue;
  1027. string mo, mp;
  1028. uint8_t idx = i % 3;
  1029. if (false == CMonitorObjectMng::Instance()->IMEI2MOMP(imei, idx, mo, mp)) continue;
  1030. auto pInfo = CMonitorObjectMng::Instance()->GetMoMpInfo(mo + '.' + mp);
  1031. if (pInfo == nullptr)
  1032. {
  1033. ASSERT(FALSE);
  1034. continue;
  1035. }
  1036. //判断是否安装
  1037. switch (idx)
  1038. {
  1039. case 0:
  1040. if (pInfo->binstall_1 == false)
  1041. continue;
  1042. break;
  1043. case 1:
  1044. if (pInfo->binstall_2 == false)
  1045. continue;
  1046. break;
  1047. case 2:
  1048. if (pInfo->binstall_3 == false)
  1049. continue;
  1050. break;
  1051. default:
  1052. ASSERT(FALSE);
  1053. break;
  1054. }
  1055. SYSTEMTIME stNow;
  1056. GetLocalTime(&stNow);
  1057. //报警发送
  1058. if (bNew)
  1059. {
  1060. //存入数据库
  1061. CResistAlarmMng::Instance()->GeneralAlarm(mo, mp, idx, eZL_ALARMTYPE::SENSOR_ABNORMAL, 1, stNow);
  1062. //上送报警 传感器异常暂时屏蔽 等待放开
  1063. //g_p315ClientManager->GetTcpClient()->SendAlarmData(CMonitorObjectMng::Instance()->GetZZJNO(mo + '.' + mp), 1, CTime(stNow).GetTime(), 0xFFFFFFFF,
  1064. // eZL_ALARMTYPE::SENSOR_ABNORMAL, eDaoChaPosi::DCP_UNKNOWN, 0, 0, TIEDA_ACQ_VALUE(INT_MIN), TIEDA_ACQ_VALUE(INT_MIN), 0);
  1065. }
  1066. else if (bConver)
  1067. {
  1068. CResistAlarmMng::Instance()->RecoverAlarm(mo, mp, idx, eZL_ALARMTYPE::SENSOR_ABNORMAL, 1, stNow);
  1069. //g_p315ClientManager->GetTcpClient()->SendAlarmData(CMonitorObjectMng::Instance()->GetZZJNO(mo + '.' + mp), 2, CTime(stNow).GetTime(), CTime(stNow).GetTime(),
  1070. // eZL_ALARMTYPE::SENSOR_ABNORMAL, eDaoChaPosi::DCP_UNKNOWN, 0, 0, TIEDA_ACQ_VALUE(INT_MIN), TIEDA_ACQ_VALUE(INT_MIN), 0);
  1071. }
  1072. }
  1073. }
  1074. return TRUE;
  1075. }
  1076. //client
  1077. BOOL CLNHandle::HandleUpdate(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext /*= NULL*/)
  1078. {
  1079. if (pClientContext == FALSE) return FALSE;
  1080. auto pContext = (CLNContext*)pClientContext;
  1081. pContext->ivuname = imei;
  1082. BOOL bDataRight = TRUE;
  1083. //接收文件数据
  1084. string data;
  1085. if (doc.HasMember("data") && doc["data"].IsString())
  1086. data = doc["data"].GetString();
  1087. else
  1088. bDataRight = FALSE;
  1089. string type;
  1090. if (doc.HasMember("type") && doc["type"].IsString())
  1091. type = doc["type"].GetString();
  1092. else
  1093. bDataRight = FALSE;
  1094. uint32_t filecrc;
  1095. if (doc.HasMember("filecrc") && doc["filecrc"].IsUint())
  1096. filecrc = doc["filecrc"].GetUint();
  1097. else
  1098. bDataRight = FALSE;
  1099. uint32_t filesize;
  1100. if (doc.HasMember("filesize") && doc["filesize"].IsUint())
  1101. filesize = doc["filesize"].GetUint();
  1102. else
  1103. bDataRight = FALSE;
  1104. if (bDataRight)
  1105. {
  1106. auto& mapTypeData = CAppService::Instance()->m_mapTypeData;
  1107. auto it = mapTypeData.find(type.c_str());
  1108. int datalen = data.length();
  1109. if (it != mapTypeData.end())
  1110. {
  1111. it->second->Join();
  1112. it->second = nullptr;
  1113. }
  1114. char* pData = new char[datalen + 2];
  1115. auto pInfo = new UPGRADE_FILE_DATA;
  1116. mapTypeData[type.c_str()] = pInfo;
  1117. pInfo->data = pData;
  1118. pInfo->len = filesize * 2;
  1119. pInfo->crc = filecrc;
  1120. memcpy_s(pData, datalen + 2, data.c_str(), datalen);
  1121. pData[datalen] = 0x00;
  1122. pData[datalen + 1] = 0x00;
  1123. }
  1124. else
  1125. {
  1126. CSimpleLog::Error("HandleUpdate 数据解析错误!");
  1127. }
  1128. //校验文件数据OK
  1129. //response
  1130. StringBuffer strBuf;
  1131. Writer<StringBuffer> writer(strBuf);
  1132. writer.StartObject();
  1133. BOOL bUpdateToDevice = FALSE;
  1134. char ip[30];
  1135. uint16_t port = 0;
  1136. pContext->GetIPAdressNew(ip, 30, port);
  1137. if (bDataRight && SendUpdateToDevice(imei, ip, type))
  1138. {
  1139. //writer.Key("cmd");
  1140. //writer.String("update_ack");
  1141. //writer.Key("result");
  1142. //writer.String("true");
  1143. bUpdateToDevice = TRUE;
  1144. }
  1145. else
  1146. {
  1147. writer.Key("cmd");
  1148. writer.String("update_ack");
  1149. writer.Key("IMEI");
  1150. writer.String(imei);
  1151. writer.Key("result");
  1152. writer.String("false");
  1153. writer.EndObject();
  1154. string senddata = strBuf.GetString();
  1155. #ifdef SEND_LOG
  1156. CSimpleLog::Info(senddata.c_str());
  1157. #endif // SEND_LOG
  1158. bUpdateToDevice &= pContext->Send(senddata.c_str(), senddata.length()) != SOCKET_ERROR;
  1159. }
  1160. return bUpdateToDevice;
  1161. }
  1162. //device
  1163. BOOL CLNHandle::HandleUpdateAck(const rapidjson::Document& doc, LPBYTE pPack, int nPackLen, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext /*= NULL*/)
  1164. {
  1165. CString strLog;
  1166. string result;
  1167. if (doc.HasMember("result") && doc["result"].IsString())
  1168. result = doc["result"].GetString();
  1169. strLog.Format("收到设备升级数据ok包:" + CString(imei) + "result:" + result.c_str());
  1170. TRACE("%s\r\n", strLog);
  1171. CSimpleLog::Info(strLog);
  1172. //根据imei查找TCP链路
  1173. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1174. auto pContext = pAcceptor->FindContextByIVU(imei);
  1175. if (pContext == nullptr) return FALSE;
  1176. auto ret = pContext->Send(pPack, nPackLen) != SOCKET_ERROR;
  1177. pContext->ReleaseSharedPointer();
  1178. return ret;
  1179. }
  1180. //client
  1181. BOOL CLNHandle::HandleOnlineDevice(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext /*= NULL*/)
  1182. {
  1183. if (pClientContext == FALSE) return FALSE;
  1184. auto pContext = (CLNContext*)pClientContext;
  1185. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1186. if (pAcceptor == nullptr) return FALSE;
  1187. std::list<CString> lst;
  1188. pAcceptor->GetAllContextImei(lst);
  1189. //response
  1190. StringBuffer strBuf;
  1191. Writer<StringBuffer> writer(strBuf);
  1192. writer.StartObject();
  1193. writer.Key("cmd");
  1194. writer.String("get_online_ack");
  1195. writer.Key("list");
  1196. writer.StartArray();
  1197. for (const auto& it : lst)
  1198. writer.String(it);
  1199. writer.EndArray();
  1200. writer.EndObject();
  1201. string data = strBuf.GetString();
  1202. return pContext->Send(data.c_str(), data.length()) != SOCKET_ERROR;
  1203. }
  1204. BOOL CLNHandle::HandleOnlineDeviceNew(const SOCKADDR* psa, CLNContext* pContext /*= NULL*/)
  1205. {
  1206. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1207. if (pAcceptor == nullptr) return FALSE;
  1208. std::list<CString> lst;
  1209. pAcceptor->GetAllContextImei(lst);
  1210. auto doc = yyjson_mut_doc_new(nullptr);
  1211. auto root = yyjson_mut_obj(doc);
  1212. yyjson_mut_doc_set_root(doc, root);
  1213. yyjson_mut_obj_add_str(doc, root, "cmd", "get_online_ack");
  1214. auto list = yyjson_mut_arr(doc);
  1215. yyjson_mut_obj_add_val(doc, root, "list", list);
  1216. auto desc_arr = yyjson_mut_arr(doc);
  1217. yyjson_mut_obj_add_val(doc, root, "desc", desc_arr);
  1218. for (auto& it : lst)
  1219. {
  1220. yyjson_mut_arr_add_str(doc, list, it);
  1221. string imei_idx = it + ".0";
  1222. string mo_mp;
  1223. string desc = " ";
  1224. if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei_idx, mo_mp))
  1225. desc += "[" + mo_mp + "]";
  1226. imei_idx = it + ".1";
  1227. if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei_idx, mo_mp))
  1228. desc += "[" + mo_mp + "]";
  1229. imei_idx = it + ".2";
  1230. if (CMonitorObjectMng::Instance()->IMEI2MOMP(imei_idx, mo_mp))
  1231. desc += "[" + mo_mp + "]";
  1232. yyjson_mut_arr_add_strcpy(doc, desc_arr, desc.c_str());
  1233. }
  1234. size_t len;
  1235. auto json = yyjson_mut_write(doc, 0, &len);
  1236. BOOL bRet = FALSE;
  1237. if (pContext)
  1238. bRet = pContext->Send(json, len) != SOCKET_ERROR;
  1239. else if (psa)
  1240. bRet = CAppService::Instance()->GetUdpSocket()->SendTo(json, len, psa, sizeof(SOCKADDR));
  1241. return bRet;
  1242. }
  1243. BOOL CLNHandle::HandleQueryMsgAck(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext /*= NULL*/)
  1244. {
  1245. if (doc.HasMember("result") == FALSE || doc["result"].IsString() == FALSE) return FALSE;
  1246. string result = doc["result"].GetString();
  1247. CString strLog;
  1248. if (result.compare("true") == 0)
  1249. strLog.Format("设备[%s]响应实时数据成功.",imei);
  1250. else if (result.compare("false") == 0)
  1251. strLog.Format("设备[%s]响应实时数据失败.", imei);
  1252. else
  1253. strLog.Format("设备[%s]响应实时数据%s.", result.c_str());
  1254. CSimpleLog::Info(strLog);
  1255. return TRUE;
  1256. }
  1257. BOOL CLNHandle::HandleUpdateInit(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext)
  1258. {
  1259. CAppService::Instance()->m_bHaveDeviceUpgrade = TRUE;
  1260. time(&CAppService::Instance()->m_tDeviceUpgrade);
  1261. //根据type 来发送 filelen 和 filecrc updateinit_ack
  1262. if (psa == nullptr && pClientContext == nullptr)
  1263. return FALSE;
  1264. CString sql;
  1265. sql.Format("UPDATE rm_deviceinfo SET model = 1 WHERE IMEI = '%s';", imei);
  1266. if (CDBConnectPool::Instance()->DBExecuteSQL(sql) == FALSE)
  1267. CSimpleLog::Error(sql);
  1268. uint32_t filesize = 0;
  1269. uint32_t filecrc = 0;
  1270. do
  1271. {
  1272. string type;
  1273. if (doc.HasMember("type") && doc["type"].IsString())
  1274. type = doc["type"].GetString();
  1275. else
  1276. break;
  1277. auto& mapTypeData = CAppService::Instance()->m_mapTypeData;
  1278. const auto it = mapTypeData.find(type.c_str());
  1279. if (it == mapTypeData.end())
  1280. {
  1281. CString strLog;
  1282. strLog.Format("%s %d 未找到文件 IMEI:%s type:%s ", __FUNCTION__, __LINE__, imei, type.c_str());
  1283. CSimpleLog::Error(strLog);
  1284. break;
  1285. }
  1286. if (it->second == nullptr)
  1287. break;
  1288. auto pInfo = it->second;
  1289. filesize = it->second->len / 2;
  1290. filecrc = it->second->crc;
  1291. } while (false);
  1292. //response
  1293. StringBuffer strBuf;
  1294. Writer<StringBuffer> writer(strBuf);
  1295. writer.StartObject();
  1296. writer.Key("cmd");
  1297. writer.String("updateinit_ack");
  1298. writer.Key("IMEI");
  1299. writer.String(imei);
  1300. writer.Key("filesize");
  1301. writer.Uint(filesize);
  1302. writer.Key("filecrc");
  1303. writer.Uint(filecrc);
  1304. writer.EndObject();
  1305. string data = strBuf.GetString();
  1306. #ifdef SEND_LOG
  1307. CSimpleLog::Info(data.c_str());
  1308. #endif // SEND_LOG
  1309. if (psa)
  1310. {
  1311. return CAppService::Instance()->GetUdpSocket()->SendTo(data.c_str(), data.length(), psa, sizeof(SOCKADDR)) != SOCKET_ERROR;
  1312. }
  1313. else if (pClientContext)
  1314. {
  1315. const auto pContext = (CLNContext*)pClientContext;
  1316. return pContext->Send(data.c_str(), data.length()) > 0;
  1317. }
  1318. return false;
  1319. }
  1320. BOOL CLNHandle::HandleUpdateSeq(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext)
  1321. {
  1322. CAppService::Instance()->m_bHaveDeviceUpgrade = TRUE;
  1323. time(&CAppService::Instance()->m_tDeviceUpgrade);
  1324. //根据type 和 seq 来发送 seq datalen data updateseq_ack
  1325. if (psa == nullptr && pClientContext == nullptr)
  1326. return FALSE;
  1327. int datalen = 0;
  1328. char szData[1025] = { 0 };
  1329. int seq = -1;
  1330. do
  1331. {
  1332. string type;
  1333. if (doc.HasMember("type") && doc["type"].IsString())
  1334. type = doc["type"].GetString();
  1335. else
  1336. break;
  1337. if (doc.HasMember("seq") && doc["seq"].IsInt())
  1338. seq = doc["seq"].GetInt();
  1339. else
  1340. break;
  1341. auto& mapTypeData = CAppService::Instance()->m_mapTypeData;
  1342. const auto it = mapTypeData.find(type.c_str());
  1343. if (it == mapTypeData.end())
  1344. {
  1345. CString strLog;
  1346. strLog.Format("%s %d 未找到文件 %s ", __FUNCTION__, __LINE__, imei);
  1347. CSimpleLog::Error(strLog);
  1348. break;
  1349. }
  1350. if (it->second == nullptr)
  1351. break;
  1352. auto pInfo = it->second;
  1353. int start = seq * 512 * 2;
  1354. int end = start + 512;
  1355. if (start > pInfo->len)
  1356. datalen = 0;
  1357. else if (end > pInfo->len)
  1358. datalen = (pInfo->len - start) / 2;
  1359. else
  1360. datalen = 512;
  1361. memcpy_s(szData, 1024, pInfo->data + start, datalen * 2);
  1362. } while (false);
  1363. //response
  1364. StringBuffer strBuf;
  1365. Writer<StringBuffer> writer(strBuf);
  1366. writer.StartObject();
  1367. writer.Key("cmd");
  1368. writer.String("updateseq_ack");
  1369. writer.Key("IMEI");
  1370. writer.String(imei);
  1371. writer.Key("seq");
  1372. writer.Int(seq);
  1373. writer.Key("datalen");
  1374. writer.Int(datalen);
  1375. writer.Key("data");
  1376. writer.String(szData);
  1377. writer.EndObject();
  1378. string data = strBuf.GetString();
  1379. #ifdef SEND_LOG
  1380. CSimpleLog::Info(data.c_str());
  1381. #endif // _DEBUG
  1382. if (psa)
  1383. {
  1384. return CAppService::Instance()->GetUdpSocket()->SendTo(data.c_str(), data.length(), psa, sizeof(SOCKADDR)) != SOCKET_ERROR;
  1385. }
  1386. else if (pClientContext)
  1387. {
  1388. const auto pContext = (CLNContext*)pClientContext;
  1389. return pContext->Send(data.c_str(), data.length()) > 0;
  1390. }
  1391. return false;
  1392. }
  1393. BOOL CLNHandle::HandleUpdateOk(const rapidjson::Document& doc, const char* imei, const SOCKADDR* psa, CLNContext* pClientContext)
  1394. {
  1395. CAppService::Instance()->m_bHaveDeviceUpgrade = FALSE;
  1396. time(&CAppService::Instance()->m_tDeviceUpgrade);
  1397. //返回升级成功命令, 删除升级临时数据 type updateok_ack
  1398. string type;
  1399. if (doc.HasMember("type") && doc["type"].IsString())
  1400. type = doc["type"].GetString();
  1401. else
  1402. return FALSE;
  1403. CString strLog;
  1404. strLog.Format("%s %s 升级完成", imei, type.c_str());
  1405. CSimpleLog::Info(strLog);
  1406. if (psa == nullptr && pClientContext == nullptr)
  1407. return FALSE;
  1408. //response
  1409. StringBuffer strBuf;
  1410. Writer<StringBuffer> writer(strBuf);
  1411. writer.StartObject();
  1412. writer.Key("cmd");
  1413. writer.String("updateok_ack");
  1414. writer.Key("IMEI");
  1415. writer.String(imei);
  1416. writer.EndObject();
  1417. string data = strBuf.GetString();
  1418. #ifdef SEND_LOG
  1419. CSimpleLog::Info(data.c_str());
  1420. #endif // _DEBUG
  1421. BOOL ret = FALSE;
  1422. if (psa)
  1423. {
  1424. ret = CAppService::Instance()->GetUdpSocket()->SendTo(data.c_str(), data.length(), psa, sizeof(SOCKADDR)) != SOCKET_ERROR;
  1425. }
  1426. else if (pClientContext)
  1427. {
  1428. const auto pContext = (CLNContext*)pClientContext;
  1429. ret = pContext->Send(data.c_str(), data.length()) > 0;
  1430. }
  1431. //通知websocket
  1432. //auto lwsService = CAppService::Instance()->GetLwsServer();
  1433. //std::map<lws*, per_session_data> m_mapLwsSession;
  1434. //{
  1435. // uint8_t s_data[200];
  1436. // memcpy_s(s_data + LWS_PRE, 200 - LWS_PRE, data.c_str(), data.length());
  1437. // std::lock_guard<std::mutex> lcok(lwsService->m_mtxSession);
  1438. // for (auto& it : lwsService->m_mapLwsSession)
  1439. // {
  1440. // if (m_strUpgradeRemoteAddr.compare(it.second.ip) == 0)
  1441. // {
  1442. // lws_write(it.first, s_data + LWS_PRE, data.length(), lws_write_protocol::LWS_WRITE_TEXT);
  1443. // }
  1444. // }
  1445. //}
  1446. auto mgService = CAppService::Instance()->GetMgServer();
  1447. if (mgService)
  1448. mgService->SendToClient(data.c_str(), data.length(), m_strUpgradeRemoteAddr.c_str());
  1449. return ret;
  1450. }
  1451. //device
  1452. int CLNHandle::SendUpdateToDevice(const char* imei, string remote_addr, string type)
  1453. {
  1454. m_strUpgradeRemoteAddr = remote_addr;
  1455. CAppService::Instance()->m_bHaveDeviceUpgrade = TRUE;
  1456. time(&CAppService::Instance()->m_tDeviceUpgrade);
  1457. CAppService::Instance()->m_tDeviceUpgrade -= 55;
  1458. //根据imei查找TCP链路
  1459. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1460. auto pContext = pAcceptor->FindContextByIMEI(imei);
  1461. if (pContext == nullptr)
  1462. {
  1463. CString strLog;
  1464. strLog.Format("%s %d 未找到设备 %s ", __FUNCTION__, __LINE__, imei);
  1465. CSimpleLog::Error(strLog);
  1466. return 1;
  1467. }
  1468. //下发升级指令
  1469. //response
  1470. StringBuffer strBuf;
  1471. Writer<StringBuffer> writer(strBuf);
  1472. writer.StartObject();
  1473. writer.Key("cmd");
  1474. writer.String("update");
  1475. writer.Key("IMEI");
  1476. writer.String(imei);
  1477. writer.Key("type");
  1478. writer.String(type.c_str());
  1479. writer.EndObject();
  1480. string data = strBuf.GetString();
  1481. CSimpleLog::Info(data.c_str());
  1482. auto ret = pContext->Send(data.c_str(), data.length()) != SOCKET_ERROR;
  1483. pContext->ReleaseSharedPointer();
  1484. if (ret)
  1485. return 0;
  1486. else
  1487. return 2;
  1488. }
  1489. int CLNHandle::SendMsgToDevice(const char* imei)
  1490. {
  1491. //根据imei查找TCP链路
  1492. auto pAcceptor = CAppService::Instance()->GetAcceptor();
  1493. auto pContext = pAcceptor->FindContextByIMEI(imei);
  1494. if (pContext == nullptr)
  1495. {
  1496. CString strLog;
  1497. strLog.Format("%s %d 未找到设备 %s ", __FUNCTION__, __LINE__, imei);
  1498. CSimpleLog::Error(strLog);
  1499. return 1;
  1500. }
  1501. char json[100];
  1502. int len = sprintf_s(json, 100, R"({"cmd":"query_msg","IMEI":"%s"})", imei);
  1503. auto ret = pContext->Send(json, len) != SOCKET_ERROR;
  1504. pContext->ReleaseSharedPointer();
  1505. CSimpleLog::Info(json);
  1506. if (ret)
  1507. return 0;
  1508. else
  1509. return 2;
  1510. }
  1511. std::string CLNHandle::m_strUpgradeRemoteAddr;
  1512. uint32_t CLNHandle::convertStrToArray(const string& str, std::vector<CString>& lst)
  1513. {
  1514. // string->char *
  1515. char *s_input = (char *)str.c_str();
  1516. const char * split = ",";
  1517. // 以逗号为分隔符拆分字符串
  1518. char *p = strtok(s_input, split);
  1519. int i = 0;
  1520. while (p != NULL)
  1521. {
  1522. if (i < lst.capacity())
  1523. lst[i++] = p;
  1524. p = strtok(NULL, split);
  1525. }
  1526. return i;
  1527. }
  1528. uint32_t CLNHandle::convertStrToArraytest(const string& str, std::vector<int>& lst)
  1529. {
  1530. // string->char *
  1531. char* s_input = (char*)str.c_str();
  1532. const char* split = ",";
  1533. // 以逗号为分隔符拆分字符串
  1534. char* p = strtok(s_input, split);
  1535. int i = 0;
  1536. while (p != NULL)
  1537. {
  1538. if (i < lst.capacity())
  1539. {
  1540. int l = strlen(p);
  1541. if (l > 4)
  1542. {
  1543. TRACE("%s,\r\n", p);
  1544. lst[i++] = strtol(p, NULL, 16) - 0x800000;
  1545. }
  1546. else if (l == 4)
  1547. {
  1548. ASSERT(strtol(p, NULL, 16) - 0x8000);
  1549. lst[i++] = strtol(p, NULL, 16) - 0x8000;
  1550. }
  1551. }
  1552. p = strtok(NULL, split);
  1553. }
  1554. return i;
  1555. }
  1556. std::map<CString, COleDateTime> CLNHandle::m_mapIMEI_time0;
  1557. std::map<CString, COleDateTime> CLNHandle::m_mapIMEI_time3;
  1558. std::map<CString, COleDateTime> CLNHandle::m_mapIMEI_time6;
  1559. std::map<CString, COleDateTime> CLNHandle::m_mapIMEI_temp;
  1560. void CLNHandle::ThreadForHandle(DWORD_PTR pThis)
  1561. {
  1562. Sleep(1000);
  1563. SPDLOG_INFO(" 51609 handle thread start");
  1564. auto pHanlde = (CLNHandle*)pThis;
  1565. while (pHanlde->m_bWork)
  1566. {
  1567. Sleep(1);
  1568. if (pHanlde->m_lst.size() == 0)
  1569. {
  1570. Sleep(10);
  1571. continue;
  1572. }
  1573. tagHandlePack* pack = nullptr;
  1574. {
  1575. lock_guard<mutex> lock(pHanlde->m_mtx);
  1576. pack = pHanlde->m_lst.front();
  1577. pHanlde->m_lst.pop_front();
  1578. }
  1579. pHanlde->ProcessPack(pack->pPack, pack->nPackLen, pack->psa.sa_family == 0x00 ? nullptr : &pack->psa, pack->pClientContext);
  1580. pack->join();//释放
  1581. }
  1582. SPDLOG_INFO(" 51609 handle thread exit");
  1583. }