using allInOneMachine; using BroadcastModule; using centralController.advert; using centralController.WebServer; using db; using Monitor; using MySql.Data.MySqlClient; using NumMachine; using parkMonitor.language; using parkMonitor.model; using PLCS7; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Management; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Monitor { public class Monitor : IMonitor { /// /// 监控模块单例 /// public static Monitor ins { get; set; } /// /// 中控系统总状态 /// public static bool globalStatus = false; /// /// 初始化步骤 /// public static int initializeState = 0; /// /// PLC对象句柄 /// public static AbstractPLCLinker PLC = null; public static string plcIPAddr { get; set; } public static int plcRack { get; set; } public static int plcSlot { get; set; } public static string[] plcDatablockConfig { get; set; } public static int plcTerminalCount { get; set; } public static int plcParkingSpaceCount { get; set; } public static int plcRefreshInterval { get; set; } public static MainBlockStru mainBlockInfo { get; set; } public static List parkingSpaceInfo { get; set; } /// /// 远程数据库操作句柄 /// public static DBOperation remoteDBOper; /// /// 本地数据库操作句柄 /// public static DBOperation localDBOper; /// /// 显示板操作对象句柄 /// public static BroadcastLinker allInOneMachine; public static string allInOneMachineIP { get; set; } public static int allInOneMachinePort { get; set; } /// /// 号牌机操作句柄 /// public static NumMachineLinker numMachineLinker; public static IntPtr flpHandle; /// /// 本地web操作句柄 /// public static IWebServer webServer; public static int webPort { get; set; } /// /// 广告路径 /// public static string advertPath { get; set; } public static AdvertManager advertMgr; public static centralController.centralController mainWin { get; set; } public static string defaultLic{get;set;} /// /// 系统初始化器句柄 /// internal static SystemInitializer sysInitializer; /// /// 系统关闭状态 /// public static bool isClosing; /// /// 车库ID /// public static int garageID; /// /// 将显示在界面的提示字符串 /// private static Queue notificationQueue = new Queue(); private const int MAXLINES = 80; private void PLCUpdate() { int linkCount = 0; bool disconnected = false; while (!isClosing) { if (PLC != null) { if (PLC.isConnected) { if (disconnected) {disconnected = false; SetNotification("PLC已重新连接",TextColor.Info); } linkCount = 0; List received = PLC.ReadFromPLC(PLCDataType.terminal, 0); //首先获取所有终端信息 try { //终端总数相同 if (Terminal.Terminal.terminalInfo.Count == plcTerminalCount) { for (int i = 0; i < plcTerminalCount; i++) { //一旦发现差异立刻更新 if (!Terminal.Terminal.terminalInfo[i].Equals(received[i])) { Terminal.Terminal.terminalInfo[i] = (TerminalStru)received[i]; } } } else { //初始化终端信息列表 Terminal.Terminal.terminalInfo.Clear(); for (int i = 0; i < plcTerminalCount; i++) { Terminal.Terminal.terminalInfo.Add((TerminalStru)received[i]); if (!Terminal.Terminal.termCalcMap.ContainsKey(((TerminalStru)received[i]).terminalID)) Terminal.Terminal.termCalcMap.Add(((TerminalStru)received[i]).terminalID, false); else Terminal.Terminal.termCalcMap[((TerminalStru)received[i]).terminalID] = false; } } } catch (Exception e) { Console.WriteLine("PLC监控终端数据," + e.Message); } //接下来获取中控监控信息 try { received = PLC.ReadFromPLC(PLCDataType.central, 0); if (received.Count > 0 && !mainBlockInfo.Equals(received[0])) { mainBlockInfo = (MainBlockStru)received[0]; } } catch (Exception e) { Console.WriteLine("PLC监控中控数据," + e.Message); } //最后获得所有车位信息 try { received = PLC.ReadFromPLC(PLCDataType.parkingSpace, 0); //Console.WriteLine(parkingSpaceInfo.Count+","+ plcParkingSpaceCount); //车位总数相同 if (parkingSpaceInfo.Count == plcParkingSpaceCount) { for (int i = 0; i < plcParkingSpaceCount; i++) { //一旦发现差异立刻更新 if (!parkingSpaceInfo[i].Equals(received[i])) { parkingSpaceInfo[i] = (ParkingSpaceStru)received[i]; } } } else { parkingSpaceInfo.Clear(); for (int i = 0; i < plcParkingSpaceCount; i++) { parkingSpaceInfo.Add((ParkingSpaceStru)received[i]); } } } catch (Exception e) { Console.WriteLine("PLC监控车位数据," + e.Message); } } else { linkCount += 1; if (linkCount == 1) { disconnected = true; SetNotification("PLC掉线,请检查连接",TextColor.Warning); }else if (linkCount == 5) { Terminal.Terminal.terminalInfo.Clear(); parkingSpaceInfo.Clear(); mainBlockInfo = new MainBlockStru(); } } } Thread.Sleep(500); } } /// /// CPU名 /// /// private static string getCPUName() { try { string str = string.Empty; ManagementClass mcCPU = new ManagementClass("Win32_Processor"); ManagementObjectCollection mocCPU = mcCPU.GetInstances(); foreach (ManagementObject m in mocCPU) { string name = m["Name"].ToString(); return name; } } catch { } return ""; } /// /// 操作系统版本 /// private static string getOsVersion() { string str = "Windows 10"; try { string hdId = string.Empty; ManagementClass hardDisk = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection hardDiskC = hardDisk.GetInstances(); foreach (ManagementObject m in hardDiskC) { str = m["Name"].ToString().Split('|')[0].Replace("Microsoft", "").Trim(); break; } } catch { } return str; } /// /// 显卡名 /// private static string getGPUName() { string result = ""; try { ManagementClass hardDisk = new ManagementClass("Win32_VideoController"); ManagementObjectCollection hardDiskC = hardDisk.GetInstances(); foreach (ManagementObject m in hardDiskC) { result = m["VideoProcessor"].ToString(); break; } } catch { } return result; } /// /// 获取系统内存大小 /// private static string getMenSize() { ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象 searcher.Query = new SelectQuery("Win32_PhysicalMemory", "", new string[] { "Capacity" });//设置查询条件 ManagementObjectCollection collection = searcher.Get(); //获取内存容量 ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator(); long capacity = 0; while (em.MoveNext()) { ManagementBaseObject baseObj = em.Current; if (baseObj.Properties["Capacity"].Value != null) { try { capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString()); } catch { return "-GB"; } } } int gb = 1024 * 1024 * 1024; return ((double)capacity / gb).ToString("0.0") + "GB"; } //************************************ 公有方法 ********************************** public Monitor(centralController.centralController mainWin, IntPtr flpHandle) { Monitor.mainWin = mainWin; Monitor.flpHandle = flpHandle; parkingSpaceInfo = new List(); mainBlockInfo = new MainBlockStru(); } ///// ///// 获取提示信息 ///// ///// //public string GetNotification() //{ // StringBuilder notificationStr = new StringBuilder(); // lock (notificationQueue) // { // string[] strs = notificationQueue.ToArray(); // Array.Reverse(strs); // for (int i = 0; i < strs.Length; i++) // { // notificationStr.Append(strs[i]); // } // //Queue.Enumerator notiEnumer = notificationQueue.GetEnumerator(); // //while (notiEnumer.MoveNext()) // //{ // // notificationStr.Append(notiEnumer.Current); // //} // } // return notificationStr.ToString(); //} /// /// 添加提示信息 /// /// public static void SetNotification(string notification, TextColor textColor=TextColor.Log) { if (notification == "clear") { //lock (notificationQueue) //{ // notificationQueue.Clear(); //} if (mainWin != null) { mainWin.Invoke(new Action(() => { mainWin.UpdateText(notification, textColor,MAXLINES); })); } return; } else { string time = DateTime.Now + "\r\n"; string notificationStr = time + notification + "\r\n"; //lock (notificationQueue) //{ // int count = notificationQueue.Count; // if (count >= MAXLINES) // { // notificationQueue.Dequeue(); // } // notificationQueue.Enqueue(notificationStr); //} if (mainWin != null) { mainWin.Invoke(new Action(() => { mainWin.UpdateText(notificationStr, textColor, MAXLINES); })); } } } /// /// 返回系统信息字符串 /// /// public static string GetSysInfo() { string info = ""; Language lng = Language.ins; try { string endl = "\r\n"; info += endl + lng.autoPackSys + " " + lng.centralPort + endl + endl; info += lng.version + ":" + SysConst.version() + endl + endl; info += lng.hostNmae + ":" + Dns.GetHostName() + endl + endl; info += lng.os + ":" + getOsVersion() + endl + endl; info += lng.cpu + ":" + getCPUName() + endl + endl; info += lng.mem + ":" + getMenSize() + endl + endl; info += lng.gpu + ":" + getGPUName() + endl + endl; } catch (Exception) { } return info; } /// /// 返回停车记录信息 /// /// public static List GetParkingRecords(string license = "", string startTime = "", string endTime = "") { DateTime now = DateTime.Now; List result = new List(); string getParkingRecordsSql = ""; if (startTime == "" || endTime == "") { DateTime yesterday = DateTime.Now - (new TimeSpan(1, 0, 0, 0)); DateTime twoDaysAgo = DateTime.Now - (new TimeSpan(2, 0, 0, 0)); getParkingRecordsSql = "select parkingRecordsID,userID,numberPlate,parkingSpaceID,realParkTime,realGetTime,receiptNum,parkingPrice,paymentStatus " + "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") + "%');"; } else { getParkingRecordsSql = "select parkingRecordsID,userID,numberPlate,parkingSpaceID,realParkTime,realGetTime,receiptNum,parkingPrice,paymentStatus " + "from parkingrecords where numberPlate " + (license == "" ? "like '%" : "= '" + license) + "' and realParkTime >= '" + startTime + "' and realParkTime <= '" + endTime + "';"; } if (localDBOper != null) { lock (localDBOper) { MySqlDataReader reader = localDBOper.Query(getParkingRecordsSql); try { while (reader != null && reader.Read()) { if (reader.HasRows) { object[] temp = new object[reader.FieldCount]; reader.GetValues(temp); result.Add(temp); } } } catch (Exception e) { Console.WriteLine(e.Message); } try { if (reader != null) { reader.Close(); reader.Dispose(); } } catch (Exception e) { Console.WriteLine(e.Message); } } } result.Reverse(); return result; } /// /// 返回预约记录信息 /// /// public static List GetOrderRecords(bool localDB, string license="", string startTime = "", string endTime = "") { DateTime now = DateTime.Now; List result = new List(); string getOrderRecordsSql = ""; if (startTime == "" || endTime == "") { DateTime yesterday = DateTime.Now - (new TimeSpan(1, 0, 0, 0)); DateTime twoDaysAgo = DateTime.Now - (new TimeSpan(2, 0, 0, 0)); getOrderRecordsSql = "select orderRecordsID,userID,numberPlate,bookParkTime,cancelBookTime,bookFetchTime,bookHour,bookPrice,bookState " + "from orderrecords where numberPlate " + (license == "" ? "like '%" : "= '" + license) + "' and (bookParkTime like '" + now.ToString("yyyy-MM-dd") + "%' or bookParkTime like '" + yesterday.ToString("yyyy-MM-dd") + "%' or bookFetchTime like '" + now.ToString("yyyy-MM-dd") + "%' or bookFetchTime like '" + yesterday.ToString("yyyy-MM-dd") + "%');"; } else { getOrderRecordsSql = "select orderRecordsID,userID,numberPlate,bookParkTime,cancelBookTime,bookFetchTime,bookHour,bookPrice,bookState " + "from orderrecords where numberPlate " + (license == "" ? "like '%" : "= '" + license) + "' and ((bookParkTime >= '" + startTime + "' and bookParkTime <= '" + endTime + "') or (bookFetchTime >= '" + startTime + "' and bookFetchTime <= '" + endTime + "'));"; } if (localDBOper != null) { lock (localDBOper) { MySqlDataReader reader; if (localDB) reader = localDBOper.Query(getOrderRecordsSql); else reader = remoteDBOper.Query(getOrderRecordsSql); try { while (reader != null && reader.Read()) { if (reader.HasRows) { object[] temp = new object[reader.FieldCount]; reader.GetValues(temp); result.Add(temp); } } } catch (Exception e) { Console.WriteLine(e.Message); } try { if (reader != null) { reader.Close(); reader.Dispose(); } } catch (Exception e) { Console.WriteLine(e.Message); } } } result.Reverse(); return result; } /// /// 返回空闲正常车位数 /// /// 状态:0.空闲与保留,1.空闲,2.保留,3.预约车位总数 /// public int GetFreeSpaceCount(int state) { int freeSpaceCount = 0; int bookableSpaceCount = 0; int bookedSpaceCount = 0; if(state == 3) { return mainBlockInfo.reserveTotalSpace; } try { if (parkingSpaceInfo != null) { foreach (ParkingSpaceStru psStru in parkingSpaceInfo) { if (psStru.spaceStatus == 3) bookedSpaceCount++; if (psStru.spaceStatus != 1 && psStru.spaceStatus != 3) { freeSpaceCount++; if (psStru.spaceStatus == 2) bookableSpaceCount++; } } } } catch { Console.WriteLine("空闲车位数,计数异常");return 0; } switch (state) { case 0: return freeSpaceCount;//0+2 case 1: return freeSpaceCount - bookableSpaceCount;//0 case 2: return bookableSpaceCount;//2 case 4: return bookedSpaceCount + bookableSpaceCount;//2+3 default: return freeSpaceCount; } } /// /// 暂未使用,查询本地数据库返回可预约车位数 /// /// //public int GetBookableSpaceCount() //{ // int bookableSpaceCount = 0; // string bookableSpaceSql = "select currentBookableSpace from garageproperties where garageID = " + garageID + ";"; // if (localDBOper != null) // { // MySqlDataReader reader = localDBOper.Query(bookableSpaceSql); // if (reader != null) // { // try // { // if (reader.Read() && reader.HasRows) // { // bookableSpaceCount = reader.GetInt32("currentBookableSpace"); // } // } // catch { } // try // { // reader.Close(); // reader.Dispose(); // } // catch { } // } // } // return bookableSpaceCount; //} /// /// 系统初始化,启动plc监控 /// public void Start() { if (flpHandle != IntPtr.Zero) { //初始化系统 if (sysInitializer == null) { sysInitializer = new SystemInitializer(); } Task.Factory.StartNew(() => { sysInitializer.Init(flpHandle); }); //更新PLC数据 Task.Factory.StartNew(() => { PLCUpdate(); }); } } /// /// 系统停止 /// public void Stop() { sysInitializer.Stop(); System.Environment.Exit(0); } } //public class ParkingRecord //{ // int parkingRecordsID; // int userID; // string numberPlate; // int parkingSpaceID; //} }