AppService.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. #include "stdafx.h"
  2. #include "AppService.h"
  3. #include <ace/Init_ACE.h>
  4. #include <Simplelog.h>
  5. #include <ODBC/DBConnectPool.h>
  6. #include "MonitorObject.h"
  7. #include "ResistAlarm.h"
  8. #include "httplib.h"
  9. #include <Simplelog.h>
  10. #include <gbk2utf8.h>
  11. #include <HjFunc.h>
  12. #include "TimeSyncServerDlg.h"
  13. #include "315ClientManager.h"
  14. #ifdef _DEBUG
  15. #pragma comment(lib, "HJ_ACE650d.lib")
  16. #pragma message("Automatically linking with aced.dll")
  17. #else
  18. #pragma comment(lib, "HJ_ACE650.lib")
  19. #pragma message("Automatically linking with ace.dll")
  20. #endif
  21. #ifdef _DEBUG
  22. bool g_bLog = true;
  23. #else
  24. bool g_bLog;
  25. #endif // _DEBUG
  26. time_t g_stStart; //程序启动的时间
  27. string g_strExepath; //程序目录
  28. string g_strVersion; //程序版本
  29. uint32_t g_tReminderInterval = 21600;
  30. string g_strMoMp; //监控日志
  31. CMyRWLock g_lockSync; //同步读写锁
  32. bool g_bDataCompression; //历史数据是否压缩
  33. C315ClientManager *g_p315ClientManager;
  34. void tagFileData::Join()
  35. {
  36. delete this;
  37. }
  38. CAppService::CAppService()
  39. {
  40. CreateDirectory("E:\\DB", NULL);
  41. CSimpleLog::CreateLogDir("E:\\DB\\Log\\");
  42. CSimpleLog::SetFileName("DataServices");
  43. #ifdef DEBUG_202
  44. CSimpleLog::SetDaysNum(7);
  45. #else
  46. CSimpleLog::SetDaysNum(15);
  47. #endif // DEBUG
  48. #ifdef _DEBUG
  49. CSimpleLog::SetLevel(CSimpleLog::debug);
  50. #else
  51. CSimpleLog::SetLevel(CSimpleLog::info);
  52. #endif // _DEBUG
  53. AfxSocketInit();
  54. CSimpleLog::Info("AfxSocketInit");
  55. ACE::init();
  56. CSimpleLog::Info(" ACE::init();");
  57. CString strLog;
  58. strLog.Format(_T("进程ID:%d"), getpid());
  59. CSimpleLog::Info(strLog);
  60. }
  61. CAppService::~CAppService()
  62. {
  63. for (auto& it :m_mapTempTypeData)
  64. {
  65. it.second->Join();
  66. it.second = nullptr;
  67. }
  68. for (auto& it : m_mapTypeData)
  69. {
  70. it.second->Join();
  71. it.second = nullptr;
  72. }
  73. m_mapTempTypeData.clear();
  74. m_mapTypeData.clear();
  75. ACE::fini();
  76. AfxSocketTerm();
  77. }
  78. bool CAppService::Start()
  79. {
  80. SYSTEM_INFO sysinfo;
  81. GetSystemInfo(&sysinfo);
  82. g_strExepath = hjfunc_GetAppDir();
  83. g_strVersion = hjfunc_GetVersion();
  84. auto strPath = CSimpleLog::GetAppDir() + "svg";
  85. if (CSimpleLog::PathFileExistsA(strPath) == FALSE)
  86. CreateDirectory(strPath, nullptr);
  87. strPath = CSimpleLog::GetAppDir() + "refer";
  88. if (CSimpleLog::PathFileExistsA(strPath) == FALSE)
  89. CreateDirectory(strPath, nullptr);
  90. m_strIniPath = CSimpleLog::GetAppDir() + "DataServices.ini";
  91. char szTemp[100] = { 0 };
  92. CString m_strDriver = "ODBC Driver 11 for SQL Server";
  93. CString m_strDataSource = "127.0.0.1,21009";
  94. CString m_strCataLog = "RMDB";
  95. CString m_strUserID = "zljc";
  96. CString m_strPassWD = "Zljc123!@#";
  97. int port = 10086;
  98. ::GetPrivateProfileStringA("ODBC", "DRIVER", CStringA(m_strDriver), szTemp, sizeof(szTemp), m_strIniPath);
  99. m_strDriver = CString(szTemp);
  100. ::GetPrivateProfileStringA("ODBC", "SERVER", CStringA(m_strDataSource), szTemp, sizeof(szTemp), m_strIniPath);
  101. m_strDataSource = CString(szTemp);
  102. ::GetPrivateProfileStringA("ODBC", "UID", CStringA(m_strUserID), szTemp, sizeof(szTemp), m_strIniPath);
  103. m_strUserID = CString(szTemp);
  104. ::GetPrivateProfileStringA("ODBC", "PWD", CStringA(m_strPassWD), szTemp, sizeof(szTemp), m_strIniPath);
  105. m_strPassWD = CString(szTemp);
  106. ::GetPrivateProfileStringA("ODBC", "DATABASE", CStringA(m_strCataLog), szTemp, sizeof(szTemp), m_strIniPath);
  107. m_strCataLog = CString(szTemp);
  108. port = ::GetPrivateProfileInt("SET", "port", port, m_strIniPath);
  109. g_tReminderInterval = ::GetPrivateProfileInt("SET", "reminder_interval", g_tReminderInterval, m_strIniPath);
  110. ::GetPrivateProfileString("SET", "momp", "", szTemp, sizeof(szTemp), m_strIniPath);
  111. g_strMoMp = szTemp;
  112. g_bDataCompression = ::GetPrivateProfileInt("SET", "DataCompression", g_bDataCompression, m_strIniPath);
  113. ::WritePrivateProfileStringA("ODBC", "DRIVER", CStringA(m_strDriver), m_strIniPath);
  114. ::WritePrivateProfileStringA("ODBC", "SERVER", CStringA(m_strDataSource), m_strIniPath);
  115. ::WritePrivateProfileStringA("ODBC", "DATABASE", CStringA(m_strCataLog), m_strIniPath);
  116. ::WritePrivateProfileString("ODBC", "UID", m_strUserID, m_strIniPath);
  117. ::WritePrivateProfileString("ODBC", "PWD", m_strPassWD, m_strIniPath);
  118. ::WritePrivateProfileStringA("SET", "port", (to_string(port) + " #Websocket 端口").c_str(), m_strIniPath);
  119. ::WritePrivateProfileString("SET", "reminder_interval", (to_string(g_tReminderInterval) + " #报警提醒间隔").c_str(), m_strIniPath);
  120. ::WritePrivateProfileString("SET", "momp", g_strMoMp.c_str(), m_strIniPath);
  121. ::WritePrivateProfileString("SET", "DataCompression", to_string(g_bDataCompression).c_str(), m_strIniPath);
  122. //ODBC
  123. if (CDBConnectPool::Instance()->Init(m_strDriver, m_strDataSource, m_strUserID, m_strPassWD, m_strCataLog, 5) == FALSE)
  124. {
  125. ASSERT(0);
  126. CString strLog;
  127. strLog.Format("数据库连接池初始化失败");
  128. TRACE("%s\r\n", strLog);
  129. CSimpleLog::Save(strLog, true, CSimpleLog::error);
  130. return false;
  131. }
  132. //升级
  133. {
  134. CString sql;
  135. BOOL ret;
  136. sql = "SELECT top 1 name1 FROM rm_map";
  137. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  138. if (TRUE != ret)
  139. {
  140. sql = "alter table rm_map add name1 nvarchar(50) default '';";
  141. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  142. sql = "update rm_map set name1 = '' where name1 is null;";
  143. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  144. sql = "alter table rm_map add name2 nvarchar(50) default '';";
  145. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  146. sql = "update rm_map set name2 = '' where name2 is null;";
  147. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  148. sql = "alter table rm_map add name3 nvarchar(50) default '';";
  149. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  150. sql = "update rm_map set name3 = '' where name3 is null;";
  151. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  152. }
  153. sql = "DELETE FROM rm_map WHERE zl_1_loca is null;";
  154. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  155. sql = "if not exists (select 1 from [rm_mo] where [id] = '100000' )\
  156. BEGIN\
  157. INSERT INTO [rm_mo] ([id],[type],[up],[name],[updatetime]) VALUES ('100000' ,'group' ,'100000', '国铁集团',GETDATE());\
  158. END";
  159. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  160. sql = "if not exists (select 1 from [rm_user] where [username] = 'system' )\
  161. BEGIN\
  162. INSERT INTO [dbo].[rm_user]([username] ,[password] ,[name] ,[admin] ,[token] ,[node] ,[enable] ,[mobile] ,[email] ,[mark]) VALUES ('system' ,'Zljc123!@#' ,'系统管理员' ,1 ,'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA','100000',1,'15305712458','','');\
  163. END";
  164. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  165. sql = "UPDATE rm_alarm SET ack_result = 1,ack_name='system',ack_time=GETDATE() WHERE DATEDIFF(d,occur_time,GETDATE()) > 7 AND ack_result = 0;";
  166. CDBConnectPool::Instance()->DBExecuteSQL(sql);
  167. sql = "UPDATE rm_alarm SET handle_result = 1,handle_name='system',handle_time=GETDATE() WHERE DATEDIFF(d,occur_time,GETDATE()) > 30 AND handle_result = 0";
  168. CDBConnectPool::Instance()->DBExecuteSQL(sql);
  169. sql = "SELECT top 1 module FROM rm_record";
  170. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  171. if (TRUE != ret)
  172. {
  173. sql = "create table rm_record (\
  174. module tinyint not null,\
  175. dura int not null,\
  176. analyze_type tinyint null,\
  177. station nvarchar(50) not null,\
  178. station_name nvarchar(50) not null,\
  179. mo varchar(20) null,\
  180. mo_name varchar(20) null,\
  181. mp varchar(20) null,\
  182. mp_name varchar(20) null,\
  183. start_time bigint not null,\
  184. end_time bigint null,\
  185. time bigint not null,\
  186. name nvarchar(50) not null,\
  187. username varchar(50) null default '',\
  188. opt smallint not null,\
  189. mark nvarchar(200) null default ''\
  190. );\
  191. create clustered index IDX_STATION on rm_record(\
  192. station_name ASC,\
  193. time DESC\
  194. );\
  195. create index IDX_TIME on rm_record(\
  196. time DESC\
  197. );";
  198. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  199. if (ret != TRUE)
  200. CSimpleLog::Error(sql);
  201. }
  202. sql = "select top 1 event_id from rm_alarm";
  203. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  204. if (true != ret)
  205. {
  206. sql = "alter table rm_alarm add event_id char(36) null default newid();\
  207. alter table rm_alarm add rel_id char(36) null default ''; ";
  208. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  209. sql = "UPDATE [rm_alarm] SET [event_id]=NEWID() WHERE [event_id] is null;\
  210. UPDATE [rm_alarm] SET [rel_id]='' WHERE [rel_id] is null;";
  211. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  212. }
  213. sql = " IF NOT EXISTS ( SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('rm_alarm') AND name = 'IDX_GUID' )\
  214. BEGIN CREATE INDEX IDX_GUID ON rm_alarm(event_id ASC) END";
  215. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  216. sql = " IF NOT EXISTS ( SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('rm_alarm') AND name = 'IDX_REL_GUID' )\
  217. BEGIN CREATE INDEX IDX_REL_GUID ON rm_alarm(rel_id ASC) END";
  218. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  219. sql = "select top 1 posi from rm_alarm";
  220. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  221. if (true != ret)
  222. {
  223. sql = "alter table rm_alarm add posi tinyint null default 0;";
  224. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  225. sql = "alter table rm_alarm add loworhigh tinyint null default 0;";
  226. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  227. sql = "alter table rm_alarm add referval int null default 0;";
  228. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  229. sql = "alter table rm_alarm add recovery_time datetime null default 0;";
  230. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  231. sql = "update rm_alarm set posi = 0, loworhigh = 0, referval = 0, recovery_time=0 where posi is null;";
  232. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  233. }
  234. sql = "select top 1 sunroof from rm_alarm";
  235. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  236. if (true != ret)
  237. {
  238. sql = "alter table rm_alarm add sunroof tinyint null default 0;";
  239. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  240. sql = "update rm_alarm set sunroof= CASE WHEN (DATEPART(HOUR, occur_time) > 4) THEN 0 ELSE 1 END where sunroof is null;";
  241. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  242. }
  243. sql = " select top 1 zzjno from rm_map";
  244. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  245. if (true != ret)
  246. {
  247. sql = "ALTER TABLE [rm_map] ADD [zzjno] int default 0 ;";
  248. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  249. sql = "WITH CTE AS ( SELECT [zzjno], ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum FROM [rm_map] ) UPDATE CTE SET [zzjno] = RowNum;\
  250. CREATE UNIQUE INDEX idx_unique_zzjno ON rm_map(zzjno);";
  251. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  252. sql = "ALTER TABLE rm_map add epos INT default 0;";
  253. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  254. sql = "UPDATE rm_map SET epos=0 WHERE epos is null;";
  255. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  256. }
  257. sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'rm_map' AND COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1;";
  258. COdbcStatement stmt;
  259. ret = CDBConnectPool::Instance()->DBQuery(stmt, sql);
  260. if (true == ret)
  261. {
  262. if (stmt.FetchNext() == 0)
  263. {
  264. sql = "ALTER TABLE [rm_map] DROP COLUMN [zzjno];";
  265. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  266. sql = "ALTER TABLE [rm_map] ADD [zzjno] int;";
  267. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  268. sql = "WITH CTE AS ( SELECT [zzjno], ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum FROM [rm_map] ) UPDATE CTE SET [zzjno] = RowNum;\
  269. CREATE UNIQUE INDEX idx_unique_zzjno ON rm_map(zzjno);";
  270. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  271. }
  272. }
  273. sql = " select top 1 install_1 from rm_map";
  274. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  275. if (true != ret)
  276. {
  277. sql = "ALTER TABLE rm_map add install_1 tinyint default 1;ALTER TABLE rm_map add install_2 tinyint default 1;ALTER TABLE rm_map add install_3 tinyint default 1; ";
  278. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  279. sql = "UPDATE rm_map SET install_1=1 WHERE install_1 is null;UPDATE rm_map SET install_2=1 WHERE install_2 is null;UPDATE rm_map SET install_3=1 WHERE install_3 is null;";
  280. ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  281. }
  282. }
  283. //end 升级
  284. m_bWork = true;
  285. m_pCreateTableThread = new std::thread(CAppService::ThreadProcCreateTable, (DWORD_PTR)this);
  286. Sleep(10);
  287. if (!CMonitorObjectMng::Instance()->LoadMonitorTree())
  288. {
  289. ASSERT(0);
  290. CSimpleLog::Error("LoadMonitorTree Fail. ");
  291. }
  292. else
  293. {
  294. CMonitorObjectMng::Instance()->LoadHistoryData();
  295. //开启新的websocket
  296. m_mgServer = new CMGWSServer;
  297. if (!m_mgServer->Start(port))
  298. {
  299. ASSERT(0);
  300. CSimpleLog::Error("start mg websocket server fail.");
  301. return false;
  302. }
  303. //m_lwsServer = new CLWSServer;
  304. //if (!m_lwsServer->Start(port + 1))
  305. //{
  306. // assert(0);
  307. // CSimpleLog::Error("start lws server fail.");
  308. // return false;
  309. //}
  310. }
  311. if (!CResistAlarmMng::Instance()->Start())
  312. {
  313. CSimpleLog::Error("Alarm Start Fail.");
  314. }
  315. //启动315协议
  316. if (g_p315ClientManager == nullptr) g_p315ClientManager = new C315ClientManager;
  317. if (g_p315ClientManager->Run(m_strIniPath)) CSimpleLog::Info("[315]启动成功!");
  318. else CSimpleLog::Error("[315]启动失败!");
  319. if (!CSuperManager::Instance()->Start(m_strIniPath))
  320. {
  321. ASSERT(0);
  322. CSimpleLog::Error("start Super Manager fail.");
  323. return false;
  324. }
  325. m_pHandle = new CLNHandle;
  326. m_pProactorTask = new CProactorTask;
  327. m_pProactorTask->start(2);
  328. m_pAcceptor = new CLNAcceptor(m_pHandle);
  329. if (m_pAcceptor == nullptr)
  330. {
  331. ASSERT(0);
  332. CSimpleLog::Error("CZHGSAcceptor 创建失败!");
  333. return false;
  334. }
  335. if (m_pAcceptor->listen(51609) == -1)
  336. {
  337. ASSERT(0);
  338. CSimpleLog::Error("CZHGSAcceptor 51609 监听失败!");
  339. return false;
  340. }
  341. m_pUdpSocket = new CUDPSocket;
  342. m_pUdpSocket->SetProtocolHandler(m_pHandle);
  343. if (!m_pUdpSocket->Open(51609, NULL, 0, NULL))
  344. {
  345. ASSERT(0);
  346. CSimpleLog::Error("CUDPSocket 监听失败!");
  347. return false;
  348. }
  349. m_bRun = true;
  350. m_pThreadClearConn = new std::thread(CAppService::ThreadProc, (DWORD_PTR)this);
  351. m_pHttpThread = new std::thread(CAppService::ThreadProcForHTTP10088, (DWORD_PTR)this);
  352. m_pHttpThread2 = new std::thread(CAppService::ThreadProcForHTTP10087, (DWORD_PTR)this);
  353. m_pThreadSpace = new std::thread(CAppService::ThreadProcForSpace, (DWORD_PTR)this);
  354. m_pThreadTime = new std::thread(CAppService::ThreadProcForTime, (DWORD_PTR)this);
  355. m_pThreadSync = new std::thread(CAppService::ThreadProcSync, (DWORD_PTR)this);
  356. time(&g_stStart);
  357. PostMessage(AfxGetApp()->m_pMainWnd->GetSafeHwnd(), WM_START, 0, 0);
  358. CSimpleLog::Info(("start succ.Version:" + g_strVersion).c_str());
  359. SPDLOG_INFO("start succ.Version:{}", g_strVersion);
  360. TRACE("start succ.\r\n");
  361. return true;
  362. }
  363. void CAppService::Stop()
  364. {
  365. CSimpleLog::Info("停止服务");
  366. m_bRun = false;
  367. m_bWork = false;
  368. g_p315ClientManager->Stop();
  369. Sleep(100);
  370. TerminateProcess((HANDLE)-1, 0);
  371. if (m_pThreadSpace)
  372. {
  373. m_pThreadSpace->join();
  374. delete m_pThreadSpace;
  375. m_pThreadSpace = nullptr;
  376. }
  377. if (m_pThreadTime)
  378. {
  379. m_pThreadTime->join();
  380. delete m_pThreadTime;
  381. m_pThreadTime = nullptr;
  382. }
  383. if (m_pThreadClearConn)
  384. {
  385. m_pThreadClearConn->join();
  386. delete m_pThreadClearConn;
  387. m_pThreadClearConn = nullptr;
  388. }
  389. if (m_pCreateTableThread)
  390. {
  391. m_pCreateTableThread->join();
  392. delete m_pCreateTableThread;
  393. m_pCreateTableThread = nullptr;
  394. }
  395. if (m_pHttpThread)
  396. {
  397. m_svr10088.stop();
  398. m_pHttpThread->join();
  399. delete m_pHttpThread;
  400. m_pHttpThread = nullptr;
  401. }
  402. if (m_pHttpThread2)
  403. {
  404. m_svr10087.stop();
  405. m_pHttpThread2->join();
  406. delete m_pHttpThread2;
  407. m_pHttpThread2 = nullptr;
  408. }
  409. if (m_pAcceptor)
  410. {
  411. m_pAcceptor->ClearAllContexts();
  412. delete m_pAcceptor;
  413. m_pAcceptor = nullptr;
  414. }
  415. if (m_pUdpSocket)
  416. {
  417. m_pUdpSocket->Close();
  418. delete m_pUdpSocket;
  419. m_pUdpSocket = nullptr;
  420. }
  421. CResistAlarmMng::Instance()->Stop();
  422. //if (m_lwsServer)
  423. //{
  424. // m_lwsServer->Stop();
  425. // delete m_lwsServer;
  426. // m_lwsServer = nullptr;
  427. //}
  428. if (m_mgServer)
  429. {
  430. m_mgServer->Stop();
  431. delete m_mgServer;
  432. m_mgServer = nullptr;
  433. }
  434. if (m_pHandle)
  435. {
  436. m_pHandle->Close();
  437. delete m_pHandle;
  438. m_pHandle = nullptr;
  439. }
  440. CSuperManager::Instance()->Stop();
  441. CDBConnectPool::Instance()->Clear();
  442. }
  443. BOOL CAppService::FileDataConvertCharData(const uint8_t* filedata, const int filelen, char* strData)
  444. {
  445. if (strData == nullptr) return FALSE;
  446. for (auto i = 0; i < filelen; i++)
  447. sprintf_s(strData + i * 2, 3, "%02X", filedata[i]);
  448. return TRUE;
  449. }
  450. void CAppService::ThreadProc(DWORD_PTR wparam)
  451. {
  452. CAppService* pThis = (CAppService*)wparam;
  453. std::this_thread::sleep_for(std::chrono::seconds(10));
  454. while (pThis->m_bWork)
  455. {
  456. for (size_t i = 0; i < 10; i++)
  457. {
  458. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  459. if (pThis->m_bWork == false) break;
  460. }
  461. pThis->m_pAcceptor->OnClearContext();
  462. for (size_t i = 0; i < 10; i++)
  463. {
  464. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  465. if (pThis->m_bWork == false) break;
  466. }
  467. }
  468. }
  469. #include "HttpPrcess.h"
  470. void CAppService::ThreadProcForHTTP10088(DWORD_PTR pThis)
  471. {
  472. using namespace httplib;
  473. m_svr10088.Post("/data/.*", DealHttpPost);
  474. m_svr10088.Get("/data/.*", DealHttpGet);
  475. m_svr10088.Put("/data/.*", DealHttpPut);
  476. //string strPath = CSimpleLog::GetAppDir();
  477. //auto ret = m_svr.set_mount_point("/", strPath);
  478. //if (!ret) {
  479. // // The specified base directory doesn't exist...
  480. //}
  481. m_svr10088.set_keep_alive_max_count(20);// Default is 5
  482. m_svr10088.set_keep_alive_timeout(300);// Default is 5
  483. auto ret = m_svr10088.listen("0.0.0.0", 10088);
  484. return ;
  485. }
  486. void CAppService::ThreadProcForHTTP10087(DWORD_PTR)
  487. {
  488. using namespace httplib;
  489. m_svr10087.Post("/hist/.*", DealHttpPost);
  490. m_svr10087.Get("/hist/.*", DealHttpGet);
  491. m_svr10087.Put("/hist/.*", DealHttpPut);
  492. //string strPath = CSimpleLog::GetAppDir();
  493. //auto ret = m_svr.set_mount_point("/", strPath);
  494. //if (!ret) {
  495. // // The specified base directory doesn't exist...
  496. //}
  497. m_svr10087.set_keep_alive_max_count(20);// Default is 5
  498. m_svr10087.set_keep_alive_timeout(300);// Default is 5
  499. auto ret = m_svr10087.listen("0.0.0.0", 10087);
  500. return;
  501. }
  502. void CAppService::ThreadProcCreateTable(DWORD_PTR pThis)
  503. {
  504. auto pService = (CAppService*)pThis;
  505. CSimpleLog::Info("ThreadProcCreateTable 线程开始!");
  506. do
  507. {
  508. SYSTEMTIME stNow, stTom, stYest;
  509. GetLocalTime(&stNow);
  510. COleDateTime odt_now(stNow);
  511. COleDateTime odt_tom = odt_now + COleDateTimeSpan(1, 0, 0, 0);
  512. COleDateTime odt_yest = odt_now - COleDateTimeSpan(1, 0, 0, 0);
  513. odt_tom.GetAsSystemTime(stTom);
  514. odt_yest.GetAsSystemTime(stYest);
  515. CString tableName;
  516. CString tableNameTom;
  517. CString tableNameYest;
  518. tableName.Format("rm_resistance_%04d%02d%02d", stNow.wYear, stNow.wMonth, stNow.wDay, stNow.wHour, stNow.wMinute, stNow.wSecond);
  519. tableNameTom.Format("rm_resistance_%04d%02d%02d", stTom.wYear, stTom.wMonth, stTom.wDay, stTom.wHour, stTom.wMinute, stTom.wSecond);
  520. tableNameYest.Format("rm_resistance_%04d%02d%02d", stYest.wYear, stYest.wMonth, stYest.wDay, stYest.wHour, stYest.wMinute, stYest.wSecond);
  521. CString existsql = CString("select top 1 id from sysobjects where name = '") + tableName + "' and type = 'U';";
  522. CString existsqlTom = CString("select top 1 id from sysobjects where name = '") + tableNameTom + "' and type = 'U';";
  523. CString existsqlYest = CString("select top 1 id from sysobjects where name = '") + tableNameYest + "' and type = 'U';";
  524. CString tablesqltoday = CString("create table ") + tableName + " (\n" +
  525. " IMEI varchar(50) not null,\n" +
  526. " acquisitiontime datetime not null,\n" +
  527. " idx tinyint not null,\n" +
  528. " data0 int null,\n" +
  529. " data1 int null,\n" +
  530. " data2 int null\n" +
  531. ");" +
  532. "create unique clustered index IDX_TIME on " + tableName + " (\n" +
  533. "IMEI ASC,\n" +
  534. "acquisitiontime ASC,\n" +
  535. "idx ASC\n" +
  536. ")";
  537. CString tablesqlTom = "create table " + tableNameTom + " (\n" +
  538. " IMEI varchar(50) not null,\n" +
  539. " acquisitiontime datetime not null,\n" +
  540. " idx tinyint not null,\n" +
  541. " data0 int null,\n" +
  542. " data1 int null,\n" +
  543. " data2 int null\n" +
  544. ");" +
  545. "create unique clustered index IDX_TIME on " + tableNameTom + " (\n" +
  546. "IMEI ASC,\n" +
  547. "acquisitiontime ASC,\n" +
  548. "idx ASC\n" +
  549. ")";
  550. CString tableYest = "create table " + tableNameYest + " (\n" +
  551. " IMEI varchar(50) not null,\n" +
  552. " acquisitiontime datetime not null,\n" +
  553. " idx tinyint not null,\n" +
  554. " data0 int null,\n" +
  555. " data1 int null,\n" +
  556. " data2 int null\n" +
  557. ");" +
  558. "create unique clustered index IDX_TIME on " + tableNameYest + " (\n" +
  559. "IMEI ASC,\n" +
  560. "acquisitiontime ASC,\n" +
  561. "idx ASC\n" +
  562. ")";
  563. COdbcStatement stmt;
  564. CDBConnectPool::Instance()->DBQuery(stmt, existsql);
  565. int id = 0;
  566. stmt.BindIntCol(1, &id);
  567. if (stmt.FetchNext() != 0)
  568. {
  569. //不存在
  570. if (!CDBConnectPool::Instance()->DBExecuteSQL(tablesqltoday))
  571. {
  572. CSimpleLog::Error("数据库执行错误:" + tablesqltoday);
  573. }
  574. }
  575. stmt.Close();
  576. COdbcStatement stmtTom;
  577. CDBConnectPool::Instance()->DBQuery(stmtTom, existsqlTom);
  578. stmtTom.BindIntCol(1, &id);
  579. if (stmtTom.FetchNext() != 0)
  580. {
  581. //不存在
  582. if (!CDBConnectPool::Instance()->DBExecuteSQL(tablesqlTom))
  583. {
  584. CSimpleLog::Error("数据库执行错误:" + tablesqlTom);
  585. }
  586. }
  587. stmtTom.Close();
  588. COdbcStatement stmtYest;
  589. CDBConnectPool::Instance()->DBQuery(stmtYest, existsqlYest);
  590. stmtYest.BindIntCol(1, &id);
  591. if (stmtYest.FetchNext() != 0)
  592. {
  593. //不存在
  594. if (!CDBConnectPool::Instance()->DBExecuteSQL(tableYest))
  595. {
  596. CSimpleLog::Error("数据库执行错误:" + tableYest);
  597. }
  598. }
  599. stmtYest.Close();
  600. //temperature
  601. tableName.Format("rm_temphumidity_%04d%02d", stNow.wYear, stNow.wMonth, stNow.wDay, stNow.wHour, stNow.wMinute);
  602. tableNameTom.Format("rm_temphumidity_%04d%02d", stTom.wYear, stTom.wMonth, stTom.wDay, stTom.wHour, stTom.wMinute);
  603. existsql = CString("select top 1 id from sysobjects where name = '") + tableName + "' and type = 'U';";
  604. existsqlTom = CString("select top 1 id from sysobjects where name = '") + tableNameTom + "' and type = 'U';";
  605. tablesqltoday = CString("create table ") + tableName + " (\n" +
  606. " IMEI varchar(50) not null,\n" +
  607. " acquisitiontime datetime not null,\n" +
  608. " temperature int not null,\n" +
  609. " humidity int not null\n" +
  610. ");" +
  611. "create unique clustered index IDX_IMEI on " + tableName + " (\n" +
  612. "IMEI ASC,\n" +
  613. "acquisitiontime ASC\n" +
  614. ")";
  615. CDBConnectPool::Instance()->DBQuery(stmt, existsql);
  616. stmt.BindIntCol(1, &id);
  617. if (stmt.FetchNext() != 0)
  618. {
  619. //不存在
  620. if (!CDBConnectPool::Instance()->DBExecuteSQL(tablesqltoday))
  621. {
  622. CSimpleLog::Error("数据库执行错误:" + tablesqltoday);
  623. }
  624. }
  625. stmt.Close();
  626. if (stNow.wMonth != stTom.wMonth || stNow.wYear != stTom.wYear)
  627. {
  628. CDBConnectPool::Instance()->DBQuery(stmt, existsqlTom);
  629. stmt.BindIntCol(1, &id);
  630. if (stmt.FetchNext() != 0)
  631. {
  632. //不存在
  633. tablesqlTom = CString("create table ") + tableNameTom + " (\n" +
  634. " IMEI varchar(50) not null,\n" +
  635. " acquisitiontime datetime not null,\n" +
  636. " temperature int not null,\n" +
  637. " humidity int not null\n" +
  638. ");" +
  639. "create unique clustered index IDX_IMEI on " + tableNameTom + " (\n" +
  640. "IMEI ASC,\n" +
  641. "acquisitiontime ASC\n" +
  642. ")";
  643. if (!CDBConnectPool::Instance()->DBExecuteSQL(tablesqlTom))
  644. {
  645. CSimpleLog::Error("数据库执行错误:" + tablesqlTom);
  646. }
  647. }
  648. stmt.Close();
  649. }
  650. //扳动记录表
  651. {
  652. SYSTEMTIME lastSt;
  653. memcpy(&lastSt, &stNow, sizeof(SYSTEMTIME));
  654. move_today:
  655. string table_today = fmt::format("rm_move_{:0>4}{:0>2}", lastSt.wYear, lastSt.wMonth);
  656. COdbcStatement stmt;
  657. CDBConnectPool::Instance()->DBQuery(stmt, CString(fmt::format("select top 1 id from sysobjects where name = '{}' and type = 'U'; ", table_today).c_str()));
  658. int id = 0;
  659. stmt.BindIntCol(1, &id);
  660. if (stmt.FetchNext() != 0)
  661. {
  662. CString strSql = fmt::format("create table {0} (\
  663. mo varchar(20) not null,\
  664. mp varchar(20) not null,\
  665. show_time datetime not null,\
  666. start_time datetime null,\
  667. end_time datetime null,\
  668. curr_val int null,\
  669. show_val int not null,\
  670. idx tinyint null,\
  671. posi tinyint not null,\
  672. mark nvarchar(255) null,\
  673. type tinyint not null default(0),\
  674. sunroof tinyint not null default(0),\
  675. );create unique clustered index IDX_MO_MP on {0}(mo ASC,mp ASC,show_time ASC);", table_today).c_str();
  676. //不存在
  677. if (!CDBConnectPool::Instance()->DBExecuteSQL(strSql))
  678. {
  679. CSimpleLog::Error("数据库执行错误:" + strSql);
  680. }
  681. }
  682. stmt.Close();
  683. if (lastSt.wYear != stTom.wYear || lastSt.wMonth != stTom.wMonth)
  684. {
  685. memcpy(&lastSt, &stTom, sizeof(SYSTEMTIME));
  686. goto move_today;
  687. }
  688. auto move_reserve = ::GetPrivateProfileInt("SET", "move_reserve", 730, pService->m_strIniPath);
  689. if (move_reserve < 90) move_reserve = 90;
  690. ::WritePrivateProfileStringA("SET", "move_reserve", fmt::format("{} 天 #转换过程记录保留天数, 默认730天, 20230701起", move_reserve).c_str(), pService->m_strIniPath);
  691. static bool bExec_rm_move = true;
  692. COleDateTimeSpan dts_delete(move_reserve, 0, 0, 0);
  693. CString sql = "select name from sys.tables where name like 'rm_move_%' ORDER BY name;";
  694. if (CDBConnectPool::Instance()->DBQuery(stmt, sql)) {
  695. char tablename[50];
  696. stmt.BindCharCol(1, tablename, sizeof(tablename));
  697. while (true)
  698. {
  699. memset(tablename, 0, sizeof(tablename));
  700. if (stmt.FetchNext() != 0) {
  701. break;
  702. }
  703. if (strlen(tablename) < 14)
  704. {
  705. assert(0);
  706. continue;
  707. }
  708. COleDateTime dd;
  709. try
  710. {
  711. int year, month;
  712. sscanf_s(tablename, "rm_move_%04d%02d", &year, &month);
  713. dd = COleDateTime(year, month, 1, 0, 0, 0);
  714. }
  715. catch (const std::exception&)
  716. {
  717. assert(0);
  718. continue;
  719. }
  720. if (odt_now - dd > dts_delete)
  721. {
  722. sql.Format(" DROP TABLE %s ", tablename);
  723. CDBConnectPool::Instance()->DBExecuteSQL(sql);
  724. }
  725. else
  726. {
  727. int ret = 0;
  728. if (bExec_rm_move == false) break;
  729. CString qq = CString("SELECT top 1 end_time FROM ") + tablename;
  730. if (CDBConnectPool::Instance()->DBExecuteSQL(qq) == FALSE)
  731. {
  732. qq.Format("ALTER TABLE %s ADD end_time datetime null;", tablename);
  733. CDBConnectPool::Instance()->DBExecuteSQL(qq);
  734. qq.Format("UPDATE %s SET end_time = 0 where end_time is null;", tablename);
  735. CDBConnectPool::Instance()->DBExecuteSQL(qq);
  736. }
  737. qq = CString("SELECT top 1 type FROM ") + tablename;
  738. if (CDBConnectPool::Instance()->DBExecuteSQL(qq) == FALSE)
  739. {
  740. qq.Format("ALTER TABLE %s ADD type tinyint null default(0);", tablename);
  741. ret = CDBConnectPool::Instance()->DBExecuteSQL(qq);
  742. qq.Format("UPDATE %s SET type = 0 where type is null;", tablename);
  743. ret = CDBConnectPool::Instance()->DBExecuteSQL(qq);
  744. }
  745. qq = CString("SELECT top 1 sunroof FROM ") + tablename;
  746. if (CDBConnectPool::Instance()->DBExecuteSQL(qq) == FALSE)
  747. {
  748. qq.Format("ALTER TABLE %s ADD sunroof tinyint null default(0);", tablename);
  749. ret = CDBConnectPool::Instance()->DBExecuteSQL(qq);
  750. }
  751. qq.Format("UPDATE %s SET sunroof = CASE WHEN (DATEPART(HOUR, show_time) > 4) THEN 0 ELSE 1 END where sunroof is null;", tablename);
  752. ret = CDBConnectPool::Instance()->DBExecuteSQL(qq);
  753. qq.Format("UPDATE %s set show_val = curr_val where show_val = 0 and type = 2 and curr_val !=0;", tablename); //临时
  754. ret = CDBConnectPool::Instance()->DBExecuteSQL(qq);
  755. }
  756. }
  757. stmt.Close();
  758. bExec_rm_move = false;
  759. }
  760. }
  761. //过车记录表
  762. {
  763. SYSTEMTIME lastSt;
  764. memcpy(&lastSt, &stNow, sizeof(SYSTEMTIME));
  765. pass_today:
  766. string table_today = fmt::format("rm_pass_{:0>4}{:0>2}", lastSt.wYear, lastSt.wMonth);
  767. COdbcStatement stmt;
  768. CDBConnectPool::Instance()->DBQuery(stmt, CString(fmt::format("select top 1 id from sysobjects where name = '{}' and type = 'U'; ", table_today).c_str()));
  769. int id = 0;
  770. stmt.BindIntCol(1, &id);
  771. if (stmt.FetchNext() != 0)
  772. {
  773. CString strSql = fmt::format("create table {0} (\
  774. mo varchar(20) not null,\
  775. mp varchar(20) not null,\
  776. show_time datetime null,\
  777. show_val int not null default(0),\
  778. curr_val int not null,\
  779. start_time datetime not null,\
  780. end_time datetime not null,\
  781. idx tinyint not null,\
  782. shaking int null default 0\
  783. );create unique clustered index IDX_MO_MP on {0}(mo ASC,mp ASC,start_time ASC);", table_today).c_str();
  784. //不存在
  785. if (!CDBConnectPool::Instance()->DBExecuteSQL(strSql))
  786. {
  787. CSimpleLog::Error("数据库执行错误:" + strSql);
  788. }
  789. }
  790. stmt.Close();
  791. if (lastSt.wYear != stTom.wYear || lastSt.wMonth != stTom.wMonth)
  792. {
  793. memcpy(&lastSt, &stTom, sizeof(SYSTEMTIME));
  794. goto pass_today;
  795. }
  796. auto move_reserve = ::GetPrivateProfileInt("SET", "pass_reserve", 730, pService->m_strIniPath);
  797. if (move_reserve < 90) move_reserve = 90;
  798. ::WritePrivateProfileStringA("SET", "pass_reserve", fmt::format("{} 天 #过车过程记录保留天数, 默认730天, 20240601起", move_reserve).c_str(), pService->m_strIniPath);
  799. static bool bExec_rm_pass = true;
  800. COleDateTimeSpan dts_delete(move_reserve, 0, 0, 0);
  801. CString sql = "select name from sys.tables where name like 'rm_pass_%' ORDER BY name;";
  802. if (CDBConnectPool::Instance()->DBQuery(stmt, sql)) {
  803. char tablename[50];
  804. stmt.BindCharCol(1, tablename, sizeof(tablename));
  805. while (true)
  806. {
  807. memset(tablename, 0, sizeof(tablename));
  808. if (stmt.FetchNext() != 0) {
  809. break;
  810. }
  811. if (strlen(tablename) < 14)
  812. {
  813. assert(0);
  814. continue;
  815. }
  816. COleDateTime dd;
  817. try
  818. {
  819. int year, month;
  820. sscanf_s(tablename, "rm_pass_%04d%02d", &year, &month);
  821. dd = COleDateTime(year, month, 1, 0, 0, 0);
  822. }
  823. catch (const std::exception&)
  824. {
  825. assert(0);
  826. continue;
  827. }
  828. if (odt_now - dd > dts_delete)
  829. {
  830. sql.Format(" DROP TABLE %s ", tablename);
  831. CDBConnectPool::Instance()->DBExecuteSQL(sql);
  832. }
  833. else
  834. {
  835. if (bExec_rm_pass == false) break;
  836. //CString qq = CString("SELECT end_time FROM ") + tablename;
  837. //if (CDBConnectPool::Instance()->DBExecuteSQL(qq) == FALSE)
  838. //{
  839. // qq.Format("ALTER TABLE %s ADD end_time datetime null;", tablename);
  840. // CDBConnectPool::Instance()->DBExecuteSQL(qq);
  841. // qq.Format("UPDATE %s SET end_time = 0 where end_time is null;", tablename);
  842. // CDBConnectPool::Instance()->DBExecuteSQL(qq);
  843. //}
  844. //qq = CString("SELECT type FROM ") + tablename;
  845. //if (CDBConnectPool::Instance()->DBExecuteSQL(qq) == FALSE)
  846. //{
  847. // qq.Format("ALTER TABLE %s ADD type tinyint not null default(0);", tablename);
  848. // CDBConnectPool::Instance()->DBExecuteSQL(qq);
  849. // qq.Format("UPDATE %s SET type = 0 where type is null;", tablename);
  850. // CDBConnectPool::Instance()->DBExecuteSQL(qq);
  851. //}
  852. }
  853. }
  854. stmt.Close();
  855. bExec_rm_pass = false;
  856. }
  857. }
  858. ULARGE_INTEGER FreeBytesAvailableToCaller, TotalNumberOfBytes, TotalNumberOfFreeBytes;
  859. if (!GetDiskFreeSpaceEx("E:", &FreeBytesAvailableToCaller,
  860. &TotalNumberOfBytes, &TotalNumberOfFreeBytes))
  861. continue;
  862. auto dwCurLeftDisk = DWORD(FreeBytesAvailableToCaller.QuadPart >> 20);
  863. auto idle_reserve = ::GetPrivateProfileInt("SET", "idle_reserve", 20, pService->m_strIniPath);
  864. if (idle_reserve < 5) idle_reserve = 5;
  865. ::WritePrivateProfileStringA("SET", "idle_reserve", fmt::format("{} GB #E盘闲置空间, 默认20GB, 20230701起", idle_reserve).c_str(), pService->m_strIniPath);
  866. BOOL bClear = (dwCurLeftDisk < idle_reserve * 1024); BOOL bForceClear = (dwCurLeftDisk < 3 * 1024);
  867. auto resist_reserve = ::GetPrivateProfileInt("SET", "resist_reserve", 365, pService->m_strIniPath);
  868. if (resist_reserve < 30) resist_reserve = 30;
  869. ::WritePrivateProfileStringA("SET", "resist_reserve", fmt::format("{} 天 #阻力数据保留天数, 默认365天, 20230701起", resist_reserve).c_str(), pService->m_strIniPath);
  870. auto temp_reserve = ::GetPrivateProfileInt("SET", "temp_reserve", 365, pService->m_strIniPath);
  871. if (temp_reserve < 30) temp_reserve = 30;
  872. ::WritePrivateProfileStringA("SET", "temp_reserve", fmt::format("{} 天 #温湿度数据保留天数, 默认365天, 20230701起", temp_reserve).c_str(), pService->m_strIniPath);
  873. //删除365天前的数据
  874. if (bClear)
  875. {
  876. if (bForceClear) resist_reserve = resist_reserve / 2;
  877. COleDateTimeSpan dts_delete(resist_reserve, 0, 0, 0);
  878. COdbcStatement stmt;
  879. CString sql = "select name from sys.tables where name like 'rm_resistance_%' ORDER BY name;";
  880. if (CDBConnectPool::Instance()->DBQuery(stmt, sql)) {
  881. char tablename[50];
  882. stmt.BindCharCol(1, tablename, sizeof(tablename));
  883. while (true)
  884. {
  885. memset(tablename, 0, sizeof(tablename));
  886. if (stmt.FetchNext() != 0) {
  887. break;
  888. }
  889. if (strlen(tablename) < 22)
  890. {
  891. assert(0);
  892. continue;
  893. }
  894. COleDateTime dd;
  895. try
  896. {
  897. dd = COleDateTime(atoi(CString(tablename + 14, 4)), atoi(CString(tablename + 18, 2)), atoi(CString(tablename + 20, 2)), 0, 0, 0);
  898. }
  899. catch (const std::exception&)
  900. {
  901. assert(0);
  902. continue;
  903. }
  904. if (odt_now - dd > dts_delete)
  905. {
  906. sql.Format(" DROP TABLE [%s] ", tablename);
  907. CDBConnectPool::Instance()->DBExecuteSQL(sql);
  908. }
  909. else
  910. {
  911. break;
  912. }
  913. }
  914. }
  915. }
  916. //删除200天的数据
  917. if (bClear)
  918. {
  919. if (bForceClear) temp_reserve = temp_reserve / 2;
  920. COleDateTimeSpan dts_delete(temp_reserve, 0, 0, 0);
  921. COdbcStatement stmt;
  922. CString sql = "select name from sys.tables where name like 'rm_temphumidity_%';";
  923. if (CDBConnectPool::Instance()->DBQuery(stmt, sql)) {
  924. char tablename[50];
  925. stmt.BindCharCol(1, tablename, sizeof(tablename));
  926. while (true)
  927. {
  928. memset(tablename, 0, sizeof(tablename));
  929. if (stmt.FetchNext() != 0) {
  930. break;
  931. }
  932. if (strlen(tablename) < 22)
  933. {
  934. assert(0);
  935. continue;
  936. }
  937. COleDateTime dd;
  938. try
  939. {
  940. auto a = atoi(CString(tablename + 16, 4));
  941. auto b = atoi(CString(tablename + 20, 2));
  942. dd = COleDateTime(atoi(CString(tablename + 16, 4)), atoi(CString(tablename + 20, 2)), 28, 0, 0, 0);
  943. }
  944. catch (const std::exception&)
  945. {
  946. assert(0);
  947. continue;
  948. }
  949. if (odt_now - dd > dts_delete)
  950. {
  951. sql.Format(" DROP TABLE %s ", tablename);
  952. CDBConnectPool::Instance()->DBExecuteSQL(sql);
  953. }
  954. else
  955. {
  956. break;
  957. }
  958. }
  959. }
  960. }
  961. {
  962. CTime ctTime(stNow);
  963. CString sql;
  964. sql.Format("DELETE rm_record WHERE time < %I64d", (ctTime - CTimeSpan(366, 0, 0, 0)).GetTime());
  965. auto ret = CDBConnectPool::Instance()->DBExecuteSQL(sql);
  966. }
  967. //5小时检测一次
  968. #ifdef _DEBUG
  969. for (auto i = 0; i < 60; i++)
  970. #else
  971. for (auto i = 0; i < 18000; i++)
  972. #endif // _DEBUG
  973. if (pService->m_bWork)
  974. Sleep(1);
  975. else
  976. goto l;
  977. } while (pService->m_bWork);
  978. l:
  979. CSimpleLog::Info("ThreadProcCreateTable 线程结束!");
  980. }
  981. //获取E盘剩余容量,返回值以GB为单位
  982. double Get_E_DiskRemainingSpace()
  983. {
  984. DWORD64 qwFreeBytes, qwFreeBytesTocaller, qwTotalBytes;
  985. GetDiskFreeSpaceEx(TEXT("e:"), (PULARGE_INTEGER)&qwFreeBytesTocaller, (PULARGE_INTEGER)&qwTotalBytes, (PULARGE_INTEGER)&qwFreeBytes);
  986. double RemainingSpace = qwFreeBytes / 1024 / 1024 / 1024;
  987. return RemainingSpace;
  988. }
  989. void CAppService::ThreadProcForSpace(DWORD_PTR param)
  990. {
  991. CAppService* pThis = (CAppService*)param;
  992. //刚开始运行,停止一分钟
  993. std::this_thread::sleep_for(std::chrono::seconds(20));
  994. do
  995. {
  996. std::this_thread::sleep_for(std::chrono::milliseconds(950));
  997. auto ttNow = chrono::system_clock::to_time_t(chrono::system_clock::now());
  998. if (ttNow % pThis->m_nInterval) continue;
  999. if (ttNow == pThis->m_tmLastSpaceTime) continue;
  1000. pThis->m_tmLastSpaceTime = ttNow;
  1001. auto e_disk_space = Get_E_DiskRemainingSpace();
  1002. if (e_disk_space < 100 && pThis->m_bWork)
  1003. {
  1004. auto json = R"({"cmd":"disk_alarm","code":200,"msg":"磁盘余量告警,还剩 )" + fmt::format("{:.1f}", e_disk_space) + " GB.\"}";
  1005. auto utf = ANSItoUTF8(json);
  1006. pThis->GetMgServer()->SendToAllClient(utf.c_str(), utf.length());
  1007. }
  1008. } while (pThis->m_bWork);
  1009. }
  1010. void CAppService::ThreadProcForTime(DWORD_PTR param)
  1011. {
  1012. CAppService* pThis = (CAppService*)param;
  1013. //刚开始运行,停止一分钟
  1014. std::this_thread::sleep_for(std::chrono::seconds(20));
  1015. do
  1016. {
  1017. std::this_thread::sleep_for(std::chrono::milliseconds(950));
  1018. auto ttNow = chrono::system_clock::to_time_t(chrono::system_clock::now());
  1019. if (ttNow == pThis->m_tmLastSyncTime) continue;
  1020. pThis->m_tmLastSyncTime = ttNow;
  1021. SYSTEMTIME st;
  1022. GetLocalTime(&st);
  1023. if (st.wHour == 0 && st.wMinute == 5 && st.wSecond == 0 && pThis->m_bWork) //每天0点5分, 下发时钟同步
  1024. pThis->GetHandle()->SendTimeAckToAllDevice();
  1025. } while (pThis->m_bWork);
  1026. }
  1027. //半小时同步一次
  1028. void CAppService::ThreadProcSync(DWORD_PTR param)
  1029. {
  1030. CAppService* pThis = (CAppService*)param;
  1031. //刚开始运行,停止一分钟
  1032. Sleep(3000);
  1033. do
  1034. {
  1035. Sleep(950);
  1036. auto ttNow = chrono::system_clock::to_time_t(chrono::system_clock::now());
  1037. if (ttNow - pThis->m_tmLastSyncSuper < pThis->m_nIntervalSync) continue;
  1038. pThis->m_tmLastSyncSuper = ttNow;
  1039. if (CSuperManager::Instance()->GetSuperNum() == 0)
  1040. break;
  1041. uint8_t* pack = nullptr; int len = 0;
  1042. //同步机构数据
  1043. auto packno = CMonitorObjectMng::Instance()->GeneralMoPack(&pack, &len);
  1044. if (packno) CSuperManager::Instance()->SendPack(pack, len, packno, E_ZL_PROTOCAL::ZL_MO, false);
  1045. delete[] pack;
  1046. if (pThis->m_bWork == false)break;
  1047. Sleep(1000);
  1048. //同步设备数据
  1049. packno = CMonitorObjectMng::Instance()->GeneralMpPack(&pack, &len);
  1050. if (packno) CSuperManager::Instance()->SendPack(pack, len, packno, E_ZL_PROTOCAL::ZL_MP, false);
  1051. delete[] pack;
  1052. if (pThis->m_bWork == false)break;
  1053. Sleep(1000);
  1054. //同步svg数据
  1055. if (pThis->m_index % 10 == 0)
  1056. {
  1057. CFileFind filefind;
  1058. string filePath = g_strExepath + "svg\\*.svg";
  1059. bool bFind = filefind.FindFile(filePath.c_str());
  1060. while (bFind) {
  1061. bFind = filefind.FindNextFile();
  1062. CString strFilenName = filefind.GetFileName();//含后缀
  1063. auto strTitle = filefind.GetFileTitle(); //不含后缀
  1064. auto filelen = filefind.GetLength(); //文件长度
  1065. auto strFilePath = filefind.GetFilePath();//全部路径
  1066. auto new_len = sizeof(HJDATAHEAD2) + 2 + 64 + filelen;
  1067. pack = new uint8_t[new_len];
  1068. memset(pack, 0, new_len);
  1069. auto pData = pack + sizeof(HJDATAHEAD2);
  1070. strcpy_s((char*)pData, 50, (char*)(LPCSTR)strTitle);
  1071. CFile file;
  1072. if (file.Open(strFilePath, CFile::modeRead | CFile::typeBinary) == FALSE)
  1073. {
  1074. SPDLOG_ERROR("打开文件{}失败", strFilePath);
  1075. }
  1076. else
  1077. {
  1078. file.Read(pData + 64, filelen);
  1079. file.Close();
  1080. packno = pThis->GetPackNo();
  1081. auto send_len = CHjDataConver::conver_sendpack(pack, pData, 64 + filelen, 0, packno, E_ZL_PROTOCAL::ZL_SVG,
  1082. OR_DATA_INFO(0, 0, 1, 2, OPT_TYPE::OPT_SYNC));
  1083. if (packno) CSuperManager::Instance()->SendPack(pack, send_len, packno, E_ZL_PROTOCAL::ZL_SVG, FALSE);
  1084. SPDLOG_INFO("发送SVG:{} packno:{}) len:{}", strFilePath, packno, send_len);
  1085. }
  1086. delete[] pack;
  1087. pack = nullptr;
  1088. Sleep(5000);
  1089. if (pThis->m_bWork == false)break;
  1090. }
  1091. filefind.Close();
  1092. Sleep(100);
  1093. }
  1094. //同步refer数据
  1095. if (pThis->m_index % 10 == 0)
  1096. {
  1097. CFileFind filefind;
  1098. string filePath = g_strExepath + "refer\\*.json";
  1099. bool bFind = filefind.FindFile(filePath.c_str());
  1100. while (bFind) {
  1101. bFind = filefind.FindNextFile();
  1102. CString strFilenName = filefind.GetFileName();//含后缀
  1103. auto strTitle = filefind.GetFileTitle(); //不含后缀
  1104. auto filelen = filefind.GetLength(); //文件长度
  1105. auto strFilePath = filefind.GetFilePath();//全部路径
  1106. auto new_len = sizeof(HJDATAHEAD2) + 2 + 64 + filelen;
  1107. pack = new uint8_t[new_len];
  1108. memset(pack, 0, new_len);
  1109. auto pData = pack + sizeof(HJDATAHEAD2);
  1110. //CTime lastWriteTime;
  1111. //filefind.GetLastWriteTime(lastWriteTime);
  1112. //*(uint64_t*)(pData) = lastWriteTime.GetTime();
  1113. strcpy_s((char*)pData, 50, (char*)(LPCSTR)strTitle);
  1114. CFile file;
  1115. if (file.Open(strFilePath, CFile::modeRead | CFile::typeBinary) == FALSE)
  1116. {
  1117. SPDLOG_ERROR("打开文件{}失败", strFilePath);
  1118. }
  1119. else
  1120. {
  1121. file.Read(pData + 64, filelen);
  1122. file.Close();
  1123. packno = pThis->GetPackNo();
  1124. auto send_len = CHjDataConver::conver_sendpack(pack, pData, 64 + filelen, 0, packno, E_ZL_PROTOCAL::ZL_REFER,
  1125. OR_DATA_INFO(0, 0, 1, 2, OPT_TYPE::OPT_SYNC));
  1126. if (packno) CSuperManager::Instance()->SendPack(pack, send_len, packno, E_ZL_PROTOCAL::ZL_REFER, false);
  1127. }
  1128. delete[] pack;
  1129. pack = nullptr;
  1130. Sleep(1000);
  1131. if (pThis->m_bWork == false)break;
  1132. }
  1133. filefind.Close();
  1134. Sleep(100);
  1135. }
  1136. //同步扳动数据
  1137. packno = CAppService::GeneralMovePack(&pack, &len);
  1138. if (packno) CSuperManager::Instance()->SendPack(pack, len, packno, E_ZL_PROTOCAL::ZL_MOVE, false);
  1139. delete[] pack;
  1140. pack = nullptr;
  1141. if (pThis->m_bWork == false)break;
  1142. Sleep(1000);
  1143. //同步报警设置
  1144. packno = CResistAlarmMng::Instance()->GeneralAlarmSet(&pack, &len);
  1145. if (packno) CSuperManager::Instance()->SendPack(pack, len, packno, E_ZL_PROTOCAL::ZL_ALARM_SET, false);
  1146. delete[] pack;
  1147. if (pThis->m_bWork == false)break;
  1148. Sleep(1000);
  1149. //同步未受理报警数据
  1150. packno = CResistAlarmMng::Instance()->GeneralUnAck(&pack, &len);
  1151. if (packno) CSuperManager::Instance()->SendPack(pack, len, packno, E_ZL_PROTOCAL::ZL_ALARM_UNACK, false);
  1152. delete[] pack;
  1153. if (pThis->m_bWork == false)break;
  1154. Sleep(1000);
  1155. pThis->m_index++;
  1156. } while (pThis->m_bWork);
  1157. }
  1158. CAppService CAppService::obj;
  1159. httplib::Server CAppService::m_svr10088;
  1160. httplib::Server CAppService::m_svr10087;
  1161. uint32_t CAppService::GeneralMovePack(uint8_t** pack, int* len)
  1162. {
  1163. #ifdef _DEBUG
  1164. string table_name = "rm_move_202405";
  1165. string strWhere = "";
  1166. #else
  1167. SYSTEMTIME st;
  1168. GetLocalTime(&st);
  1169. string table_name = fmt::format("rm_move_{:0>4}{:0>2}", st.wYear, st.wMonth);
  1170. string strWhere = " WHERE [show_time] > DATEADD(mi, -35, GETDATE())";
  1171. #endif // _DEBUG
  1172. CString sql = fmt::format("SELECT [mo],[mp],[show_time],[start_time],[end_time],[curr_val],[show_val],[idx],[posi],[mark],[type] FROM {} {}",
  1173. table_name, strWhere).c_str();
  1174. COdbcStatement stmt;
  1175. if (CDBConnectPool::Instance()->DBQuery(stmt, sql))
  1176. {
  1177. int nCol = 1;
  1178. int show_val, curr_val;
  1179. BYTE posi, idx, type;
  1180. char mo[20], mp[10], show_time[25], start_time[25], end_time[25], mark[50];
  1181. stmt.BindCharCol(nCol++, mo, sizeof(mo));
  1182. stmt.BindCharCol(nCol++, mp, sizeof(mp));
  1183. stmt.BindCharCol(nCol++, show_time, sizeof(show_time));
  1184. stmt.BindCharCol(nCol++, start_time, sizeof(start_time));
  1185. stmt.BindCharCol(nCol++, end_time, sizeof(end_time));
  1186. stmt.BindIntCol(nCol++, &curr_val);
  1187. stmt.BindIntCol(nCol++, &show_val);
  1188. stmt.BindTinyIntCol(nCol++, &idx);
  1189. stmt.BindTinyIntCol(nCol++, &posi);
  1190. stmt.BindCharCol(nCol++, mark, sizeof(mark));
  1191. stmt.BindTinyIntCol(nCol++, &type);
  1192. //组装数据
  1193. auto doc = yyjson_mut_doc_new(nullptr);
  1194. auto root = yyjson_mut_arr(doc);
  1195. yyjson_mut_doc_set_root(doc, root);
  1196. int num = 0;
  1197. while (true)
  1198. {
  1199. memset(mo, 0, sizeof(mo));
  1200. memset(mp, 0, sizeof(mp));
  1201. memset(show_time, 0, sizeof(show_time));
  1202. memset(start_time, 0, sizeof(start_time));
  1203. memset(end_time, 0, sizeof(end_time));
  1204. memset(mark, 0, sizeof(mark));
  1205. if (stmt.FetchNext() != 0)
  1206. break;
  1207. //添加数据
  1208. auto obj = yyjson_mut_obj(doc);
  1209. yyjson_mut_arr_add_val(root, obj);
  1210. yyjson_mut_obj_add_strcpy(doc, obj, "mo", mo);
  1211. yyjson_mut_obj_add_strcpy(doc, obj, "mp", mp);
  1212. yyjson_mut_obj_add_strcpy(doc, obj, "show_time", show_time);
  1213. yyjson_mut_obj_add_strcpy(doc, obj, "start_time", start_time);
  1214. yyjson_mut_obj_add_strcpy(doc, obj, "end_time", end_time);
  1215. yyjson_mut_obj_add_strcpy(doc, obj, "mark", mark);
  1216. yyjson_mut_obj_add_int(doc, obj, "curr_val", curr_val);
  1217. yyjson_mut_obj_add_int(doc, obj, "show_val", show_val);
  1218. yyjson_mut_obj_add_int(doc, obj, "idx", idx);
  1219. yyjson_mut_obj_add_int(doc, obj, "posi", posi);
  1220. yyjson_mut_obj_add_int(doc, obj, "type", type);
  1221. num++;
  1222. }
  1223. stmt.Close();
  1224. uint32_t no = 0;
  1225. if (num > 0)
  1226. {
  1227. size_t json_len;
  1228. auto json = yyjson_mut_write(doc, 0, &json_len);
  1229. *len = json_len + sizeof(HJDATAHEAD2) + 2;
  1230. *pack = new uint8_t[*len];
  1231. no = CAppService::Instance()->GetPackNo();
  1232. CHjDataConver::conver_sendpack(*pack, (LPBYTE)json, json_len, 0, no, E_ZL_PROTOCAL::ZL_MOVE,
  1233. OR_DATA_INFO(0, 0, 1, 2, OPT_TYPE::OPT_SYNC));
  1234. free(json);
  1235. }
  1236. yyjson_mut_doc_free(doc);
  1237. return no;
  1238. }
  1239. else
  1240. {
  1241. SPDLOG_ERROR("语句查询错误:{}", sql);
  1242. return 0;
  1243. }
  1244. }