LNHandle.cpp 57 KB

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