FormMain.cs 21 KB

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