FormMain.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. using BLL;
  2. using BLL.Dto.AuthDto;
  3. using BLL.Dto.DataDto;
  4. using BLL.Dto.UserDto;
  5. using BLL.Manager;
  6. using Dm.util;
  7. using Helper;
  8. using HZY.Framework.DependencyInjection;
  9. using IoTClient.Clients.PLC;
  10. using IoTClient.Common.Enums;
  11. using IoTClient.Enums;
  12. using Microsoft.Extensions.DependencyInjection;
  13. using Microsoft.Extensions.Logging;
  14. using MiniExcelLibs;
  15. using Model;
  16. using Scada.Page;
  17. using Sunny.UI;
  18. namespace Scada
  19. {
  20. public partial class FormMain : UIHeaderAsideMainFooterFrame, IScopedSelfDependency
  21. {
  22. private bool plcIsConnected;
  23. private readonly ILogger<FormMain> _logger;
  24. private Point mPoint;
  25. private CancellationTokenSource cts = new CancellationTokenSource();
  26. private readonly UserManager _userManager;
  27. private readonly AuthManager _authManager;
  28. private readonly DataManager _dataManager;
  29. private System.Timers.Timer Timer = new System.Timers.Timer(); // 定时器每秒触发一次
  30. private Dictionary<string, Control> pageControls = new Dictionary<string, Control>
  31. {
  32. { "控制模块", Globals.ServiceProvider.GetRequiredService<PageTotalEquipmentControl>() },
  33. { "用户模块", Globals.ServiceProvider.GetRequiredService<PageUserManage>() },
  34. { "权限模块", Globals.ServiceProvider.GetRequiredService<PageAuthManage>() },
  35. { "监控模块1", Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor1>() },
  36. { "监控模块2", Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor2>() },
  37. { "监控模块3", Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor3>() },
  38. { "配方模块", Globals.ServiceProvider.GetRequiredService<PageRecipeManage>() },
  39. { "日志模块", Globals.ServiceProvider.GetRequiredService<PageLogManage>() },
  40. { "报表模块", Globals.ServiceProvider.GetRequiredService<PageReportManage>() },
  41. { "图表模块", Globals.ServiceProvider.GetRequiredService<PageChartManage>() },
  42. { "参数模块", Globals.ServiceProvider.GetRequiredService<PageSystemParameterSet>() }
  43. };
  44. private List<string> AlarmList = new List<string>();
  45. public FormMain(ILogger<FormMain> logger, UserManager userManager, AuthManager authManager, DataManager
  46. dataManager)
  47. {
  48. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  49. _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
  50. _authManager = authManager ?? throw new ArgumentNullException(nameof(authManager));
  51. _dataManager = dataManager ?? throw new ArgumentNullException(nameof(dataManager));
  52. //初始化窗体
  53. InitializeComponent();
  54. InitAsideUI();
  55. InitHeaderUI();
  56. InitConfig();
  57. InitPlcClient();
  58. InitOther();
  59. this.Closed += (s, e) =>
  60. {
  61. //取消令牌源
  62. cts.Cancel();
  63. cts.Dispose();
  64. //关闭PLC客户端
  65. if (Globals.SiemensClient != null)
  66. {
  67. Globals.SiemensClient.Close();
  68. }
  69. };
  70. //显示默认界面
  71. Aside.SelectFirst();
  72. Aside.BeforeExpand += Aside_BeforeExpand;
  73. }
  74. private void InitOther()
  75. {
  76. if(Globals.SaveDay!="不清理")
  77. {
  78. DelFile.DeleteFolder(Globals.DelFilePath, Globals.SaveDay.replace("天","").ToInt());
  79. }
  80. Timer.Interval = 1000; // 设置定时器间隔为1秒
  81. Timer.Elapsed += Timer_Elapsed;
  82. Timer.Start();
  83. }
  84. private void Timer_Elapsed(object? sender, EventArgs e)
  85. {
  86. if (plcIsConnected)
  87. {
  88. if (this.InvokeRequired)
  89. {
  90. this.Invoke(async () =>
  91. {
  92. this.lbl_Temperature.Text = Globals.DataDic[this.lbl_Temperature.TagString].ToString() + "℃";
  93. this.lbl_Humidness.Text = Globals.DataDic[this.lbl_Humidness.TagString].ToString() + "%";
  94. this.lbl_ProducteCount.Text = Globals.DataDic[this.lbl_ProducteCount.TagString].ToString();
  95. this.lbl_BadCount.Text = Globals.DataDic[this.lbl_BadCount.TagString].ToString();
  96. this.lbl_Beat.Text = Globals.DataDic[this.lbl_Beat.TagString].ToString();
  97. this.lbl_TotalAlarm.Text = Globals.DataDic[this.lbl_TotalAlarm.TagString].ToString();
  98. //CPU和内存
  99. string CPUstr = RuntimeStatusHelper.DataManager.GetCpuUtilization();
  100. string MemoryStr = RuntimeStatusHelper.DataManager.GetMemoryUtilization().Replace("G", "");
  101. string NeiResult = (double.Parse(MemoryStr.Split('/')[0]) / double.Parse(MemoryStr.Split('/')[1]) * 100).ToString("f1") + "%";
  102. this.lbl_CPUInformation.Text = double.Parse(CPUstr).ToString("f1") + "%";
  103. this.lbl_MemoryInformation.Text = NeiResult;
  104. //时间
  105. this.lbl_Time.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  106. List<string> alarmInfos = CheckAlarms(AlarmList);
  107. string alarmInfo = string.Join(",", alarmInfos);
  108. if (string.IsNullOrEmpty(alarmInfo))
  109. {
  110. this.st_AlarmInfo.Text = "系统正常";
  111. this.st_AlarmInfo.ForeColor = Color.Green;
  112. this.led_ProducteState.On = true;
  113. this.led_ProducteState.Color = Color.Green;
  114. this.led_ProducteState.Blink = false;
  115. }
  116. else
  117. {
  118. this.st_AlarmInfo.Text = alarmInfo;
  119. this.st_AlarmInfo.ForeColor = Color.Red;
  120. this.led_ProducteState.Color = Color.Red;
  121. this.led_ProducteState.BlinkInterval = 500;
  122. this.led_ProducteState.Blink = true;
  123. }
  124. //存储数据
  125. //用反射的方式将Globals.DataDic中对应Globals.SaveList名称的变量值保存到AddDataDto中,然后保存到数据库中
  126. AddDataDto addDataDto = new AddDataDto();
  127. addDataDto.InsertTime = DateTime.Now;
  128. //根据反射获取Globals.DataDic中对应Globals.SaveList名称的变量值,并赋值到addDataDto中
  129. foreach (var item in Globals.SaveList)
  130. {
  131. var type = typeof(AddDataDto).GetProperty(item).PropertyType.Name;
  132. if (type == "String")
  133. {
  134. addDataDto.GetType().GetProperty(item).SetValue(addDataDto, Globals.DataDic[item].ToString());
  135. }
  136. }
  137. //保存到数据库中
  138. await _dataManager.AddDataAsync(addDataDto);
  139. });
  140. }
  141. }
  142. }
  143. private List<string> CheckAlarms(List<string> alarmList)
  144. {
  145. List<string> alarmInfos = new List<string>();
  146. foreach (var alarm in alarmList)
  147. {
  148. if (Globals.DataDic[alarm].ToString() == "1")
  149. {
  150. //如果PLC变量值为1,则表示报警
  151. alarmInfos.Add(alarm);
  152. }
  153. }
  154. return alarmInfos;
  155. }
  156. private void InitConfig()
  157. {
  158. //读取PLC配置 192.168.1.180 127.0.0.1
  159. Globals.IpAddress = Globals.IniFile.ReadString("PLC参数", "IP", "127.0.0.1");
  160. Globals.Port = Globals.IniFile.ReadInt("PLC参数", "Port", 102);
  161. Globals.CpuType = Enum.Parse<SiemensVersion>(Globals.IniFile.ReadString("PLC参数", "CpuType", SiemensVersion.S7_1200.ToString()));
  162. Globals.Slot = Globals.IniFile.ReadByte("PLC参数", "Slot", 0);
  163. Globals.Rack = Globals.IniFile.ReadByte("PLC参数", "Rack", 0);
  164. Globals.ConnectTimeOut = Globals.IniFile.ReadInt("PLC参数", "ConnectTimeOut", 3000);
  165. Globals.ReadTimeInterval = Globals.IniFile.ReadInt("PLC参数", "ReadTimeInterval", 300);
  166. Globals.ReConnectTimeInterval = Globals.IniFile.ReadInt("PLC参数", "ReConnectTimeInterval", 3000);
  167. //PLC变量表路径
  168. Globals.PlcVarConfigPath = Globals.IniFile.ReadString("PLC参数", "变量表地址", Path.Combine(Application.StartupPath, "PLC_Var_Config.xlsx"));
  169. //删除文件夹路径
  170. Globals.DelFilePath = Globals.IniFile.ReadString("系统参数", "删除文件夹路径", Path.Combine(Application.StartupPath, "Logs"));
  171. //保存天数
  172. Globals.SaveDay = Globals.IniFile.ReadString("系统参数", "保存天数", "30");
  173. //试用时长
  174. Globals.SYTime = Globals.IniFile.ReadInt("软件参数", "试用时间", 100);
  175. //软件版本
  176. Globals.SoftwareVersion = Globals.IniFile.ReadString("软件参数", "软件版本", "V1.0");
  177. Globals.DelFilePath = Globals.IniFile.ReadString("系统参数", "删除文件夹路径", Path.Combine(Application.StartupPath, "Logs"));
  178. Globals.SaveDay = Globals.IniFile.ReadString("系统参数", "保存文件夹天数", "30天");
  179. _logger.LogInformation("读取配置文件成功");
  180. }
  181. private void InitPlcClient()
  182. {
  183. var plcVarList = MiniExcel.Query<PLCVarConfigModel>(Globals.PlcVarConfigPath).ToList();
  184. Globals.SiemensClient = new SiemensClient(Globals.CpuType, Globals.IpAddress, Globals.Port, Globals.Slot, Globals.Rack, Globals.ConnectTimeOut);
  185. var connectResult = Globals.SiemensClient.Open();
  186. if (connectResult.IsSucceed)
  187. {
  188. plcIsConnected = true;
  189. this.led_PlcState.On = true;
  190. }
  191. else
  192. {
  193. plcIsConnected = false;
  194. this.led_PlcState.On = false;
  195. }
  196. for (int i = 0; i < plcVarList.Count; i++)
  197. {
  198. //初始化PLC变量地址字典 地址-类型
  199. Globals.ReadDic.Add(plcVarList[i].PLC地址, Enum.Parse<DataTypeEnum>(plcVarList[i].变量类型, true));//忽略大小写
  200. //初始化PLC变量写入 名称-地址 //初始化PLC变量值字典 名称-值
  201. Globals.WriteDic.Add(plcVarList[i].名称, plcVarList[i].PLC地址);
  202. //初始化PLC变量值字典 名称-值
  203. Globals.DataDic.Add(plcVarList[i].名称, "NA");
  204. if (plcVarList[i].是否保存.ToLower() == "true")
  205. {
  206. Globals.SaveList.Add(plcVarList[i].名称);
  207. }
  208. if (plcVarList[i].名称.EndsWith("报警") && !plcVarList[i].名称.Contains("累计"))
  209. {
  210. //如果是报警变量,则添加到报警列表中
  211. AlarmList.Add(plcVarList[i].名称);
  212. }
  213. }
  214. _logger.LogInformation("初始化PLC客户端成功");
  215. try
  216. {
  217. Task.Run(async () =>
  218. {
  219. while (!cts.IsCancellationRequested)
  220. {
  221. if (plcIsConnected)
  222. {
  223. //这个方法的目的是将大量的数据读取请求分批处理,以提高性能和可管理性。
  224. var readResult = Globals.SiemensClient.BatchRead(Globals.ReadDic);
  225. if (readResult.IsSucceed)
  226. {
  227. for (int i = 0; i < plcVarList.Count; i++)
  228. {
  229. Globals.DataDic[plcVarList[i].名称] = readResult.Value[plcVarList[i].PLC地址];
  230. }
  231. }
  232. else
  233. {
  234. Globals.SiemensClient.Close();
  235. plcIsConnected = false;
  236. this.Invoke(() =>
  237. {
  238. this.led_PlcState.On = false;
  239. });
  240. }
  241. await Task.Delay(Globals.ReadTimeInterval);
  242. }
  243. else
  244. {
  245. //重连PLC
  246. var reConnectResult = Globals.SiemensClient.Open();
  247. if (reConnectResult.IsSucceed)
  248. {
  249. plcIsConnected = true;
  250. this.Invoke(() =>
  251. {
  252. this.led_PlcState.On = true;
  253. });
  254. }
  255. else
  256. {
  257. plcIsConnected = false;
  258. this.Invoke(() =>
  259. {
  260. this.led_PlcState.On = false;
  261. });
  262. await Task.Delay(Globals.ReConnectTimeInterval);
  263. }
  264. }
  265. }
  266. await Task.Delay(1000);
  267. }, cts.Token);
  268. }
  269. catch (Exception)
  270. {
  271. throw;
  272. }
  273. }
  274. private void InitAsideUI()
  275. {
  276. int pageIndex = 1000;
  277. TreeNode parent0 = Aside.CreateNode("控制模块", 361461, 34, pageIndex);
  278. Aside.CreateChildNode(parent0, AddPage(Globals.ServiceProvider.GetRequiredService<PageTotalEquipmentControl>(), ++pageIndex));
  279. TreeNode parent1 = Aside.CreateNode("用户模块", 61447, 34, pageIndex);
  280. Aside.CreateChildNode(parent1, AddPage(Globals.ServiceProvider.GetRequiredService<PageUserManage>(), ++pageIndex));
  281. Aside.CreateChildNode(parent1, AddPage(Globals.ServiceProvider.GetRequiredService<PageAuthManage>(), ++pageIndex));
  282. TreeNode parent2 = Aside.CreateNode("监控模块", 560066, 34, pageIndex);
  283. Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor1>(), ++pageIndex));
  284. Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor2>(), ++pageIndex));
  285. Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor3>(), ++pageIndex));
  286. TreeNode parent3 = Aside.CreateNode("配方模块", 162677, 34, pageIndex);
  287. Aside.CreateChildNode(parent3, AddPage(Globals.ServiceProvider.GetRequiredService<PageRecipeManage>(), ++pageIndex));
  288. TreeNode parent4 = Aside.CreateNode("日志模块", 57557, 34, pageIndex);
  289. Aside.CreateChildNode(parent4, AddPage(Globals.ServiceProvider.GetRequiredService<PageLogManage>(), ++pageIndex));
  290. TreeNode parent5 = Aside.CreateNode("报表模块", 57586, 34, pageIndex);
  291. Aside.CreateChildNode(parent5, AddPage(Globals.ServiceProvider.GetRequiredService<PageReportManage>(), ++pageIndex));
  292. TreeNode parent6 = Aside.CreateNode("图表模块", 61950, 34, pageIndex);
  293. Aside.CreateChildNode(parent6, AddPage(Globals.ServiceProvider.GetRequiredService<PageChartManage>(), ++pageIndex));
  294. TreeNode parent7 = Aside.CreateNode("参数模块", 559576, 34, pageIndex);
  295. Aside.CreateChildNode(parent7, AddPage(Globals.ServiceProvider.GetRequiredService<PageSystemParameterSet>(), ++pageIndex));
  296. }
  297. private void InitHeaderUI()
  298. {
  299. //设置关联
  300. Header.TabControl = MainTabControl;
  301. Header.Nodes.Add("");
  302. Header.Nodes.Add("");
  303. Header.Nodes.Add("");
  304. Header.SetNodeSymbol(Header.Nodes[0], 558295, 34);
  305. Header.SetNodeSymbol(Header.Nodes[1], 61489, 34);
  306. Header.SetNodeSymbol(Header.Nodes[2], 557925, 34);
  307. var styles = UIStyles.PopularStyles();
  308. foreach (UIStyle style in styles)
  309. {
  310. Header.CreateChildNode(Header.Nodes[0], style.DisplayText(), style.Value());
  311. }
  312. //获取枚举FontsType的所有字体名称
  313. for (int i = 0; i < Enum.GetValues(typeof(SystemEnums.FontsType)).Length; i++)
  314. {
  315. Header.CreateChildNode(Header.Nodes[1], Enum.GetName(typeof(SystemEnums.FontsType), i), i + 1);
  316. }
  317. //获取枚举FontSize的所有字体大小 75-125的范围 75 80 85 90 95 100 105 110 115 120 125
  318. for (int i = 75; i <= 125; i += 5)
  319. {
  320. Header.CreateChildNode(Header.Nodes[2], i.ToString(), i);
  321. }
  322. }
  323. private void uiSymbolLabel2_Click(object sender, EventArgs e)
  324. {
  325. this.Close(); //关闭当前窗体
  326. }
  327. private void uiSymbolLabel1_Click(object sender, EventArgs e)
  328. {
  329. this.WindowState = FormWindowState.Minimized;
  330. }
  331. private void Header_MenuItemClick(string itemText, int menuIndex, int pageIndex)
  332. {
  333. switch (menuIndex)
  334. {
  335. case 0:
  336. UIStyle style = (UIStyle)pageIndex;
  337. if (pageIndex < UIStyle.Colorful.Value())
  338. {
  339. StyleManager.Style = style;
  340. if (UIExtension.SetStyleManager != null)
  341. {
  342. UIExtension.SetStyleManager(StyleManager);
  343. }
  344. }
  345. break;
  346. case 1:
  347. UIStyles.DPIScale = true;
  348. UIStyles.GlobalFont = true;
  349. UIStyles.GlobalFontName = itemText;
  350. UIStyles.GlobalFontScale = SystemConsts.DefaultFontScale;
  351. UIStyles.SetDPIScale();
  352. break;
  353. case 2:
  354. UIStyles.GlobalFontScale = int.Parse(itemText);
  355. UIStyles.SetDPIScale();
  356. break;
  357. default:
  358. break;
  359. }
  360. }
  361. private void Panel_MouseDown(object sender, MouseEventArgs e)
  362. {
  363. mPoint = new Point(e.X, e.Y);
  364. }
  365. private void Panel_MouseMove(object sender, MouseEventArgs e)
  366. {
  367. if (e.Button == MouseButtons.Left)
  368. {
  369. this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
  370. }
  371. }
  372. private void pictureBox2_Click(object sender, EventArgs e)
  373. {
  374. //把Aside折叠起来
  375. Aside.CollapseAll();
  376. Aside.SelectFirst();
  377. var frmLogin = Globals.ServiceProvider.GetRequiredService<FormLogin>();
  378. frmLogin.ShowDialog();
  379. if (frmLogin.IsLogin)
  380. {
  381. //更新登录用户
  382. this.lbl_User.Text = frmLogin.UserName;
  383. foreach (var control in pageControls.Values)
  384. {
  385. control.Enabled = true;
  386. }
  387. }
  388. }
  389. #region 控制权限
  390. /// <summary>
  391. /// 侧边栏菜单折叠事件(折叠之前)
  392. /// </summary>
  393. /// <param name="sender"></param>
  394. /// <param name="e"></param>
  395. private async void Aside_BeforeExpand(object sender, TreeViewCancelEventArgs e)
  396. {
  397. UINavMenu uINavMenu = sender as UINavMenu;
  398. string moduleName = e.Node.Text;
  399. string user = this.lbl_User.Text;
  400. var roleRes = await _userManager.GetUserAuthAsync(new QueryUserAuthDto() { UserName = user });
  401. if (roleRes.Result == SystemEnums.Result.Success)
  402. {
  403. if (roleRes.Data[0].Role != "管理员")
  404. {
  405. var authRes = await _authManager.GetAuthAsync(new QueryAuthDto { Role = roleRes.Data[0].Role });
  406. if (authRes.Result == SystemEnums.Result.Success)
  407. {
  408. UpdateControlAccess(moduleName, authRes.Data[0], pageControls);
  409. }
  410. }
  411. }
  412. }
  413. private void UpdateControlAccess(string moduleName, QueryAuthResultDto authDto, Dictionary<string, Control> pageControls)
  414. {
  415. switch (moduleName)
  416. {
  417. case "控制模块":
  418. pageControls["控制模块"].Enabled = authDto.ControlModule;
  419. break;
  420. case "用户模块":
  421. pageControls["用户模块"].Enabled = false;
  422. pageControls["权限模块"].Enabled = false;
  423. break;
  424. case "监控模块":
  425. pageControls["监控模块1"].Enabled = authDto.MonitorModule;
  426. pageControls["监控模块2"].Enabled = authDto.MonitorModule;
  427. pageControls["监控模块3"].Enabled = authDto.MonitorModule;
  428. break;
  429. case "配方模块":
  430. pageControls["配方模块"].Enabled = authDto.RecipeModule;
  431. break;
  432. case "日志模块":
  433. pageControls["日志模块"].Enabled = authDto.LogModule;
  434. break;
  435. case "报表模块":
  436. pageControls["报表模块"].Enabled = authDto.ReportModule;
  437. break;
  438. case "图表模块":
  439. pageControls["图表模块"].Enabled = authDto.ChartModule;
  440. break;
  441. case "参数模块":
  442. pageControls["参数模块"].Enabled = authDto.ParamModule;
  443. break;
  444. default:
  445. break;
  446. }
  447. }
  448. #endregion 控制权限
  449. }
  450. }