Monitor.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. using allInOneMachine;
  2. using BroadcastModule;
  3. using centralController.advert;
  4. using centralController.WebServer;
  5. using db;
  6. using Monitor;
  7. using MySql.Data.MySqlClient;
  8. using NumMachine;
  9. using parkMonitor.language;
  10. using parkMonitor.model;
  11. using PLCS7;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Data;
  15. using System.Diagnostics;
  16. using System.Management;
  17. using System.Net;
  18. using System.Text;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using System.Windows.Forms;
  22. namespace Monitor
  23. {
  24. public class Monitor : IMonitor
  25. {
  26. /// <summary>
  27. /// 监控模块单例
  28. /// </summary>
  29. public static Monitor ins { get; set; }
  30. /// <summary>
  31. /// 中控系统总状态
  32. /// </summary>
  33. public static bool globalStatus = false;
  34. /// <summary>
  35. /// 初始化步骤
  36. /// </summary>
  37. public static int initializeState = 0;
  38. /// <summary>
  39. /// PLC对象句柄
  40. /// </summary>
  41. public static AbstractPLCLinker PLC = null;
  42. public static string plcIPAddr { get; set; }
  43. public static int plcRack { get; set; }
  44. public static int plcSlot { get; set; }
  45. public static string[] plcDatablockConfig { get; set; }
  46. public static int plcTerminalCount { get; set; }
  47. public static int plcParkingSpaceCount { get; set; }
  48. public static int plcRefreshInterval { get; set; }
  49. public static MainBlockStru mainBlockInfo { get; set; }
  50. public static List<ParkingSpaceStru> parkingSpaceInfo { get; set; }
  51. /// <summary>
  52. /// 远程数据库操作句柄
  53. /// </summary>
  54. public static DBOperation remoteDBOper;
  55. /// <summary>
  56. /// 本地数据库操作句柄
  57. /// </summary>
  58. public static DBOperation localDBOper;
  59. /// <summary>
  60. /// 显示板操作对象句柄
  61. /// </summary>
  62. public static BroadcastLinker allInOneMachine;
  63. public static string allInOneMachineIP { get; set; }
  64. public static int allInOneMachinePort { get; set; }
  65. /// <summary>
  66. /// 号牌机操作句柄
  67. /// </summary>
  68. public static NumMachineLinker numMachineLinker;
  69. public static IntPtr flpHandle;
  70. /// <summary>
  71. /// 本地web操作句柄
  72. /// </summary>
  73. public static IWebServer webServer;
  74. public static int webPort { get; set; }
  75. /// <summary>
  76. /// 广告路径
  77. /// </summary>
  78. public static string advertPath { get; set; }
  79. public static AdvertManager advertMgr;
  80. public static centralController.centralController mainWin { get; set; }
  81. /// <summary>
  82. /// 系统初始化器句柄
  83. /// </summary>
  84. internal static SystemInitializer sysInitializer;
  85. /// <summary>
  86. /// 系统关闭状态
  87. /// </summary>
  88. public static bool isClosing;
  89. /// <summary>
  90. /// 车库ID
  91. /// </summary>
  92. public static int garageID;
  93. /// <summary>
  94. /// 将显示在界面的提示字符串
  95. /// </summary>
  96. private static Queue<string> notificationQueue = new Queue<string>();
  97. private const int MAXLINES = 80;
  98. private void PLCUpdate()
  99. {
  100. int linkCount = 0;
  101. bool disconnected = false;
  102. while (!isClosing)
  103. {
  104. if (PLC != null)
  105. {
  106. if (PLC.isConnected)
  107. {
  108. if (disconnected) {disconnected = false; SetNotification("PLC已重新连接",TextColor.Info); }
  109. linkCount = 0;
  110. List<object> received = PLC.ReadFromPLC(PLCDataType.terminal, 0);
  111. //首先获取所有终端信息
  112. try
  113. {
  114. //终端总数相同
  115. if (Terminal.Terminal.terminalInfo.Count == plcTerminalCount)
  116. {
  117. for (int i = 0; i < plcTerminalCount; i++)
  118. {
  119. //一旦发现差异立刻更新
  120. if (!Terminal.Terminal.terminalInfo[i].Equals(received[i]))
  121. {
  122. Terminal.Terminal.terminalInfo[i] = (TerminalStru)received[i];
  123. }
  124. }
  125. }
  126. else
  127. {
  128. //初始化终端信息列表
  129. Terminal.Terminal.terminalInfo.Clear();
  130. for (int i = 0; i < plcTerminalCount; i++)
  131. {
  132. Terminal.Terminal.terminalInfo.Add((TerminalStru)received[i]);
  133. if (!Terminal.Terminal.termCalcMap.ContainsKey(((TerminalStru)received[i]).terminalID))
  134. Terminal.Terminal.termCalcMap.Add(((TerminalStru)received[i]).terminalID, false);
  135. else
  136. Terminal.Terminal.termCalcMap[((TerminalStru)received[i]).terminalID] = false;
  137. }
  138. }
  139. }
  140. catch (Exception e) { Console.WriteLine("PLC监控终端数据," + e.Message); }
  141. //接下来获取中控监控信息
  142. try
  143. {
  144. received = PLC.ReadFromPLC(PLCDataType.central, 0);
  145. if (received.Count > 0 && !mainBlockInfo.Equals(received[0]))
  146. {
  147. mainBlockInfo = (MainBlockStru)received[0];
  148. }
  149. }
  150. catch (Exception e) { Console.WriteLine("PLC监控中控数据," + e.Message); }
  151. //最后获得所有车位信息
  152. try
  153. {
  154. received = PLC.ReadFromPLC(PLCDataType.parkingSpace, 0);
  155. //Console.WriteLine(parkingSpaceInfo.Count+","+ plcParkingSpaceCount);
  156. //车位总数相同
  157. if (parkingSpaceInfo.Count == plcParkingSpaceCount)
  158. {
  159. for (int i = 0; i < plcParkingSpaceCount; i++)
  160. {
  161. //一旦发现差异立刻更新
  162. if (!parkingSpaceInfo[i].Equals(received[i]))
  163. {
  164. parkingSpaceInfo[i] = (ParkingSpaceStru)received[i];
  165. }
  166. }
  167. }
  168. else
  169. {
  170. parkingSpaceInfo.Clear();
  171. for (int i = 0; i < plcParkingSpaceCount; i++)
  172. {
  173. parkingSpaceInfo.Add((ParkingSpaceStru)received[i]);
  174. }
  175. }
  176. }
  177. catch (Exception e) { Console.WriteLine("PLC监控车位数据," + e.Message); }
  178. }
  179. else
  180. {
  181. linkCount += 1;
  182. if (linkCount == 1)
  183. {
  184. disconnected = true;
  185. SetNotification("PLC掉线,请检查连接",TextColor.Warning);
  186. }else if (linkCount == 5)
  187. {
  188. Terminal.Terminal.terminalInfo.Clear();
  189. parkingSpaceInfo.Clear();
  190. mainBlockInfo = new MainBlockStru();
  191. }
  192. }
  193. }
  194. Thread.Sleep(500);
  195. }
  196. }
  197. /// <summary>
  198. /// CPU名
  199. /// </summary>
  200. /// <returns></returns>
  201. private static string getCPUName()
  202. {
  203. try
  204. {
  205. string str = string.Empty;
  206. ManagementClass mcCPU = new ManagementClass("Win32_Processor");
  207. ManagementObjectCollection mocCPU = mcCPU.GetInstances();
  208. foreach (ManagementObject m in mocCPU)
  209. {
  210. string name = m["Name"].ToString();
  211. return name;
  212. }
  213. }
  214. catch { }
  215. return "";
  216. }
  217. /// <summary>
  218. /// 操作系统版本
  219. /// </summary>
  220. private static string getOsVersion()
  221. {
  222. string str = "Windows 10";
  223. try
  224. {
  225. string hdId = string.Empty;
  226. ManagementClass hardDisk = new ManagementClass("Win32_OperatingSystem");
  227. ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
  228. foreach (ManagementObject m in hardDiskC)
  229. {
  230. str = m["Name"].ToString().Split('|')[0].Replace("Microsoft", "").Trim();
  231. break;
  232. }
  233. }
  234. catch
  235. {
  236. }
  237. return str;
  238. }
  239. /// <summary>
  240. /// 显卡名
  241. /// </summary>
  242. private static string getGPUName()
  243. {
  244. string result = "";
  245. try
  246. {
  247. ManagementClass hardDisk = new ManagementClass("Win32_VideoController");
  248. ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
  249. foreach (ManagementObject m in hardDiskC)
  250. {
  251. result = m["VideoProcessor"].ToString();
  252. break;
  253. }
  254. }
  255. catch
  256. {
  257. }
  258. return result;
  259. }
  260. /// <summary>
  261. /// 获取系统内存大小
  262. /// </summary>
  263. private static string getMenSize()
  264. {
  265. ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象
  266. searcher.Query = new SelectQuery("Win32_PhysicalMemory", "", new string[] { "Capacity" });//设置查询条件
  267. ManagementObjectCollection collection = searcher.Get(); //获取内存容量
  268. ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();
  269. long capacity = 0;
  270. while (em.MoveNext())
  271. {
  272. ManagementBaseObject baseObj = em.Current;
  273. if (baseObj.Properties["Capacity"].Value != null)
  274. {
  275. try
  276. {
  277. capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString());
  278. }
  279. catch
  280. {
  281. return "-GB";
  282. }
  283. }
  284. }
  285. int gb = 1024 * 1024 * 1024;
  286. return ((double)capacity / gb).ToString("0.0") + "GB";
  287. }
  288. //************************************ 公有方法 **********************************
  289. public Monitor(centralController.centralController mainWin, IntPtr flpHandle)
  290. {
  291. Monitor.mainWin = mainWin;
  292. Monitor.flpHandle = flpHandle;
  293. parkingSpaceInfo = new List<ParkingSpaceStru>();
  294. mainBlockInfo = new MainBlockStru();
  295. }
  296. ///// <summary>
  297. ///// 获取提示信息
  298. ///// </summary>
  299. ///// <returns></returns>
  300. //public string GetNotification()
  301. //{
  302. // StringBuilder notificationStr = new StringBuilder();
  303. // lock (notificationQueue)
  304. // {
  305. // string[] strs = notificationQueue.ToArray();
  306. // Array.Reverse(strs);
  307. // for (int i = 0; i < strs.Length; i++)
  308. // {
  309. // notificationStr.Append(strs[i]);
  310. // }
  311. // //Queue<string>.Enumerator notiEnumer = notificationQueue.GetEnumerator();
  312. // //while (notiEnumer.MoveNext())
  313. // //{
  314. // // notificationStr.Append(notiEnumer.Current);
  315. // //}
  316. // }
  317. // return notificationStr.ToString();
  318. //}
  319. /// <summary>
  320. /// 添加提示信息
  321. /// </summary>
  322. /// <param name="notification"></param>
  323. public static void SetNotification(string notification, TextColor textColor=TextColor.Log)
  324. {
  325. if (notification == "clear")
  326. {
  327. //lock (notificationQueue)
  328. //{
  329. // notificationQueue.Clear();
  330. //}
  331. if (mainWin != null)
  332. {
  333. mainWin.Invoke(new Action(() => {
  334. mainWin.UpdateText(notification, textColor,MAXLINES);
  335. }));
  336. }
  337. return;
  338. }
  339. else
  340. {
  341. string time = DateTime.Now + "\r\n";
  342. string notificationStr = time + notification + "\r\n";
  343. //lock (notificationQueue)
  344. //{
  345. // int count = notificationQueue.Count;
  346. // if (count >= MAXLINES)
  347. // {
  348. // notificationQueue.Dequeue();
  349. // }
  350. // notificationQueue.Enqueue(notificationStr);
  351. //}
  352. if (mainWin != null)
  353. {
  354. mainWin.Invoke(new Action(() => {
  355. mainWin.UpdateText(notificationStr, textColor, MAXLINES);
  356. }));
  357. }
  358. }
  359. }
  360. /// <summary>
  361. /// 返回系统信息字符串
  362. /// </summary>
  363. /// <returns></returns>
  364. public static string GetSysInfo()
  365. {
  366. string info = "";
  367. Language lng = Language.ins;
  368. try
  369. {
  370. string endl = "\r\n";
  371. info += endl + lng.autoPackSys + " " + lng.centralPort + endl + endl;
  372. info += lng.version + ":" + SysConst.version() + endl + endl;
  373. info += lng.hostNmae + ":" + Dns.GetHostName() + endl + endl;
  374. info += lng.os + ":" + getOsVersion() + endl + endl;
  375. info += lng.cpu + ":" + getCPUName() + endl + endl;
  376. info += lng.mem + ":" + getMenSize() + endl + endl;
  377. info += lng.gpu + ":" + getGPUName() + endl + endl;
  378. }
  379. catch (Exception) { }
  380. return info;
  381. }
  382. /// <summary>
  383. /// 返回停车记录信息
  384. /// </summary>
  385. /// <returns></returns>
  386. public static List<object[]> GetParkingRecords(string license = "", string startTime = "", string endTime = "")
  387. {
  388. DateTime now = DateTime.Now;
  389. List<object[]> result = new List<object[]>();
  390. string getParkingRecordsSql = "";
  391. if (startTime == "" || endTime == "")
  392. {
  393. DateTime yesterday = DateTime.Now - (new TimeSpan(1, 0, 0, 0));
  394. DateTime twoDaysAgo = DateTime.Now - (new TimeSpan(2, 0, 0, 0));
  395. getParkingRecordsSql = "select parkingRecordsID,userID,numberPlate,parkingSpaceID,realParkTime,realGetTime,receiptNum,parkingPrice,paymentStatus " +
  396. "from parkingrecords where numberPlate " + (license == "" ? "like '%" : "= '" + license) + "' and (realParkTime like '" + now.ToString("yyyy-MM-dd") + "%' or realParkTime like '" + yesterday.ToString("yyyy-MM-dd") + "%' or realParkTime like '" + twoDaysAgo.ToString("yyyy-MM-dd") + "%');";
  397. }
  398. else
  399. {
  400. getParkingRecordsSql = "select parkingRecordsID,userID,numberPlate,parkingSpaceID,realParkTime,realGetTime,receiptNum,parkingPrice,paymentStatus " +
  401. "from parkingrecords where numberPlate " + (license == "" ? "like '%" : "= '" + license) + "' and realParkTime >= '" + startTime + "' and realParkTime <= '" + endTime + "';";
  402. }
  403. if (localDBOper != null)
  404. {
  405. lock (localDBOper)
  406. {
  407. MySqlDataReader reader = localDBOper.Query(getParkingRecordsSql);
  408. try
  409. {
  410. while (reader != null && reader.Read())
  411. {
  412. if (reader.HasRows)
  413. {
  414. object[] temp = new object[reader.FieldCount];
  415. reader.GetValues(temp);
  416. result.Add(temp);
  417. }
  418. }
  419. }
  420. catch (Exception e) { Console.WriteLine(e.Message); }
  421. try
  422. {
  423. if (reader != null)
  424. {
  425. reader.Close();
  426. reader.Dispose();
  427. }
  428. }
  429. catch (Exception e) { Console.WriteLine(e.Message); }
  430. }
  431. }
  432. result.Reverse();
  433. return result;
  434. }
  435. /// <summary>
  436. /// 返回预约记录信息
  437. /// </summary>
  438. /// <returns></returns>
  439. public static List<object[]> GetOrderRecords(bool localDB, string license="", string startTime = "", string endTime = "")
  440. {
  441. DateTime now = DateTime.Now;
  442. List<object[]> result = new List<object[]>();
  443. string getOrderRecordsSql = "";
  444. if (startTime == "" || endTime == "")
  445. {
  446. DateTime yesterday = DateTime.Now - (new TimeSpan(1, 0, 0, 0));
  447. DateTime twoDaysAgo = DateTime.Now - (new TimeSpan(2, 0, 0, 0));
  448. getOrderRecordsSql = "select orderRecordsID,userID,numberPlate,bookParkTime,cancelBookTime,bookFetchTime,bookHour,bookPrice,bookState " +
  449. "from orderrecords where numberPlate " + (license == "" ? "like '%" : "= '" + license) + "' and (bookParkTime like '" + now.ToString("yyyy-MM-dd") +
  450. "%' or bookParkTime like '" + yesterday.ToString("yyyy-MM-dd") + "%' or bookFetchTime like '" + now.ToString("yyyy-MM-dd") + "%' or bookFetchTime like '" + yesterday.ToString("yyyy-MM-dd") + "%');";
  451. }
  452. else
  453. {
  454. getOrderRecordsSql = "select orderRecordsID,userID,numberPlate,bookParkTime,cancelBookTime,bookFetchTime,bookHour,bookPrice,bookState " +
  455. "from orderrecords where numberPlate " + (license == "" ? "like '%" : "= '" + license) + "' and ((bookParkTime >= '" + startTime + "' and bookParkTime <= '" + endTime + "') or (bookFetchTime >= '" + startTime + "' and bookFetchTime <= '" + endTime + "'));";
  456. }
  457. if (localDBOper != null)
  458. {
  459. lock (localDBOper)
  460. {
  461. MySqlDataReader reader;
  462. if (localDB)
  463. reader = localDBOper.Query(getOrderRecordsSql);
  464. else
  465. reader = remoteDBOper.Query(getOrderRecordsSql);
  466. try
  467. {
  468. while (reader != null && reader.Read())
  469. {
  470. if (reader.HasRows)
  471. {
  472. object[] temp = new object[reader.FieldCount];
  473. reader.GetValues(temp);
  474. result.Add(temp);
  475. }
  476. }
  477. }
  478. catch (Exception e) { Console.WriteLine(e.Message); }
  479. try
  480. {
  481. if (reader != null)
  482. {
  483. reader.Close();
  484. reader.Dispose();
  485. }
  486. }
  487. catch (Exception e) { Console.WriteLine(e.Message); }
  488. }
  489. }
  490. result.Reverse();
  491. return result;
  492. }
  493. /// <summary>
  494. /// 返回空闲正常车位数
  495. /// </summary>
  496. /// <param name="state">状态:0.空闲与保留,1.空闲,2.保留,3.预约车位总数</param>
  497. /// <returns></returns>
  498. public int GetFreeSpaceCount(int state)
  499. {
  500. int freeSpaceCount = 0;
  501. int bookableSpaceCount = 0;
  502. int bookedSpaceCount = 0;
  503. if(state == 3)
  504. {
  505. return mainBlockInfo.reserveTotalSpace;
  506. }
  507. try
  508. {
  509. if (parkingSpaceInfo != null)
  510. {
  511. foreach (ParkingSpaceStru psStru in parkingSpaceInfo)
  512. {
  513. if (psStru.spaceStatus == 3)
  514. bookedSpaceCount++;
  515. if (psStru.spaceStatus != 1 && psStru.spaceStatus != 3)
  516. {
  517. freeSpaceCount++;
  518. if (psStru.spaceStatus == 2)
  519. bookableSpaceCount++;
  520. }
  521. }
  522. }
  523. }
  524. catch { Console.WriteLine("空闲车位数,计数异常");return 0; }
  525. switch (state)
  526. {
  527. case 0:
  528. return freeSpaceCount;//0+2
  529. case 1:
  530. return freeSpaceCount - bookableSpaceCount;//0
  531. case 2:
  532. return bookableSpaceCount;//2
  533. case 4:
  534. return bookedSpaceCount + bookableSpaceCount;//2+3
  535. default:
  536. return freeSpaceCount;
  537. }
  538. }
  539. /// <summary>
  540. /// 暂未使用,查询本地数据库返回可预约车位数
  541. /// </summary>
  542. /// <returns></returns>
  543. //public int GetBookableSpaceCount()
  544. //{
  545. // int bookableSpaceCount = 0;
  546. // string bookableSpaceSql = "select currentBookableSpace from garageproperties where garageID = " + garageID + ";";
  547. // if (localDBOper != null)
  548. // {
  549. // MySqlDataReader reader = localDBOper.Query(bookableSpaceSql);
  550. // if (reader != null)
  551. // {
  552. // try
  553. // {
  554. // if (reader.Read() && reader.HasRows)
  555. // {
  556. // bookableSpaceCount = reader.GetInt32("currentBookableSpace");
  557. // }
  558. // }
  559. // catch { }
  560. // try
  561. // {
  562. // reader.Close();
  563. // reader.Dispose();
  564. // }
  565. // catch { }
  566. // }
  567. // }
  568. // return bookableSpaceCount;
  569. //}
  570. /// <summary>
  571. /// 系统初始化,启动plc监控
  572. /// </summary>
  573. public void Start()
  574. {
  575. if (flpHandle != IntPtr.Zero)
  576. {
  577. //初始化系统
  578. if (sysInitializer == null)
  579. {
  580. sysInitializer = new SystemInitializer();
  581. }
  582. Task.Factory.StartNew(() =>
  583. {
  584. sysInitializer.Init(flpHandle);
  585. });
  586. //更新PLC数据
  587. Task.Factory.StartNew(() =>
  588. {
  589. PLCUpdate();
  590. });
  591. }
  592. }
  593. /// <summary>
  594. /// 系统停止
  595. /// </summary>
  596. public void Stop()
  597. {
  598. sysInitializer.Stop();
  599. System.Environment.Exit(0);
  600. }
  601. }
  602. //public class ParkingRecord
  603. //{
  604. // int parkingRecordsID;
  605. // int userID;
  606. // string numberPlate;
  607. // int parkingSpaceID;
  608. //}
  609. }