FormMain.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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.lbl_Temperature.TagString].ToString() + "℃";
  88. this.lbl_Humidness.Text = Globals.DataDic[this.lbl_Humidness.TagString].ToString() + "%";
  89. this.lbl_ProducteCount.Text = Globals.DataDic[this.lbl_ProducteCount.TagString].ToString();
  90. this.lbl_BadCount.Text = Globals.DataDic[this.lbl_BadCount.TagString].ToString();
  91. this.lbl_Beat.Text = Globals.DataDic[this.lbl_Beat.TagString].ToString();
  92. this.lbl_TotalAlarm.Text = Globals.DataDic[this.lbl_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.Color = Color.Red;
  116. this.led_ProducteState.BlinkInterval = 500;
  117. this.led_ProducteState.Blink = true;
  118. }
  119. //存储数据
  120. //用反射的方式将Globals.DataDic中对应Globals.SaveList名称的变量值保存到AddDataDto中,然后保存到数据库中
  121. AddDataDto addDataDto = new AddDataDto();
  122. addDataDto.InsertTime = DateTime.Now;
  123. //根据反射获取Globals.DataDic中对应Globals.SaveList名称的变量值,并赋值到addDataDto中
  124. foreach (var item in Globals.SaveList)
  125. {
  126. var type = typeof(AddDataDto).GetProperty(item).PropertyType.Name;
  127. if (type == "String")
  128. {
  129. addDataDto.GetType().GetProperty(item).SetValue(addDataDto, Globals.DataDic[item].ToString());
  130. }
  131. }
  132. //保存到数据库中
  133. await _dataManager.AddDataAsync(addDataDto);
  134. });
  135. }
  136. }
  137. }
  138. private List<string> CheckAlarms(List<string> alarmList)
  139. {
  140. List<string> alarmInfos = new List<string>();
  141. foreach (var alarm in alarmList)
  142. {
  143. if (Globals.DataDic[alarm].ToString() == "1")
  144. {
  145. //如果PLC变量值为1,则表示报警
  146. alarmInfos.Add(alarm);
  147. }
  148. }
  149. return alarmInfos;
  150. }
  151. private void InitConfig()
  152. {
  153. //读取PLC配置 192.168.1.180 127.0.0.1
  154. Globals.IpAddress = Globals.IniFile.ReadString("PLC参数", "IP", "127.0.0.1");
  155. Globals.Port = Globals.IniFile.ReadInt("PLC参数", "Port", 102);
  156. Globals.CpuType = Enum.Parse<SiemensVersion>(Globals.IniFile.ReadString("PLC参数", "CpuType", SiemensVersion.S7_1200.ToString()));
  157. Globals.Slot = Globals.IniFile.ReadByte("PLC参数", "Slot", 0);
  158. Globals.Rack = Globals.IniFile.ReadByte("PLC参数", "Rack", 0);
  159. Globals.ConnectTimeOut = Globals.IniFile.ReadInt("PLC参数", "ConnectTimeOut", 3000);
  160. Globals.ReadTimeInterval = Globals.IniFile.ReadInt("PLC参数", "ReadTimeInterval", 300);
  161. Globals.ReConnectTimeInterval = Globals.IniFile.ReadInt("PLC参数", "ReConnectTimeInterval", 3000);
  162. //PLC变量表路径
  163. Globals.PlcVarConfigPath = Globals.IniFile.ReadString("PLC参数", "变量表地址", Path.Combine(Application.StartupPath, "PLC_Var_Config.xlsx"));
  164. //删除文件夹路径
  165. Globals.DelFilePath = Globals.IniFile.ReadString("系统参数", "删除文件夹路径", Path.Combine(Application.StartupPath, "Logs"));
  166. //保存天数
  167. Globals.SaveDay = Globals.IniFile.ReadString("系统参数", "保存天数", "30");
  168. //试用时长
  169. Globals.SYTime = Globals.IniFile.ReadInt("软件参数", "试用时间", 100);
  170. //软件版本
  171. Globals.SoftwareVersion = Globals.IniFile.ReadString("软件参数", "软件版本", "V1.0");
  172. _logger.LogInformation("读取配置文件成功");
  173. }
  174. private void InitPlcClient()
  175. {
  176. var plcVarList = MiniExcel.Query<PLCVarConfigModel>(Globals.PlcVarConfigPath).ToList();
  177. Globals.SiemensClient = new SiemensClient(Globals.CpuType, Globals.IpAddress, Globals.Port, Globals.Slot, Globals.Rack, Globals.ConnectTimeOut);
  178. var connectResult = Globals.SiemensClient.Open();
  179. if (connectResult.IsSucceed)
  180. {
  181. plcIsConnected = true;
  182. this.led_PlcState.On = true;
  183. }
  184. else
  185. {
  186. plcIsConnected = false;
  187. this.led_PlcState.On = false;
  188. }
  189. for (int i = 0; i < plcVarList.Count; i++)
  190. {
  191. //初始化PLC变量地址字典 地址-类型
  192. Globals.ReadDic.Add(plcVarList[i].PLC地址, Enum.Parse<DataTypeEnum>(plcVarList[i].变量类型, true));//忽略大小写
  193. //初始化PLC变量写入 名称-地址 //初始化PLC变量值字典 名称-值
  194. Globals.WriteDic.Add(plcVarList[i].名称, plcVarList[i].PLC地址);
  195. //初始化PLC变量值字典 名称-值
  196. Globals.DataDic.Add(plcVarList[i].名称, "NA");
  197. if (plcVarList[i].是否保存.ToLower() == "true")
  198. {
  199. Globals.SaveList.Add(plcVarList[i].名称);
  200. }
  201. if (plcVarList[i].名称.EndsWith("报警") && !plcVarList[i].名称.Contains("累计"))
  202. {
  203. //如果是报警变量,则添加到报警列表中
  204. AlarmList.Add(plcVarList[i].名称);
  205. }
  206. }
  207. _logger.LogInformation("初始化PLC客户端成功");
  208. try
  209. {
  210. Task.Run(async () =>
  211. {
  212. while (!cts.IsCancellationRequested)
  213. {
  214. if (plcIsConnected)
  215. {
  216. //这个方法的目的是将大量的数据读取请求分批处理,以提高性能和可管理性。
  217. var readResult = Globals.SiemensClient.BatchRead(Globals.ReadDic);
  218. if (readResult.IsSucceed)
  219. {
  220. for (int i = 0; i < plcVarList.Count; i++)
  221. {
  222. Globals.DataDic[plcVarList[i].名称] = readResult.Value[plcVarList[i].PLC地址];
  223. }
  224. }
  225. else
  226. {
  227. Globals.SiemensClient.Close();
  228. plcIsConnected = false;
  229. this.Invoke(() =>
  230. {
  231. this.led_PlcState.On = false;
  232. });
  233. }
  234. await Task.Delay(Globals.ReadTimeInterval);
  235. }
  236. else
  237. {
  238. //重连PLC
  239. var reConnectResult = Globals.SiemensClient.Open();
  240. if (reConnectResult.IsSucceed)
  241. {
  242. plcIsConnected = true;
  243. this.Invoke(() =>
  244. {
  245. this.led_PlcState.On = true;
  246. });
  247. }
  248. else
  249. {
  250. plcIsConnected = false;
  251. this.Invoke(() =>
  252. {
  253. this.led_PlcState.On = false;
  254. });
  255. await Task.Delay(Globals.ReConnectTimeInterval);
  256. }
  257. }
  258. }
  259. await Task.Delay(1000);
  260. }, cts.Token);
  261. }
  262. catch (Exception)
  263. {
  264. throw;
  265. }
  266. }
  267. private void InitAsideUI()
  268. {
  269. int pageIndex = 1000;
  270. TreeNode parent0 = Aside.CreateNode("控制模块", 361461, 34, pageIndex);
  271. Aside.CreateChildNode(parent0, AddPage(Globals.ServiceProvider.GetRequiredService<PageTotalEquipmentControl>(), ++pageIndex));
  272. TreeNode parent1 = Aside.CreateNode("用户模块", 61447, 34, pageIndex);
  273. Aside.CreateChildNode(parent1, AddPage(Globals.ServiceProvider.GetRequiredService<PageUserManage>(), ++pageIndex));
  274. Aside.CreateChildNode(parent1, AddPage(Globals.ServiceProvider.GetRequiredService<PageAuthManage>(), ++pageIndex));
  275. TreeNode parent2 = Aside.CreateNode("监控模块", 560066, 34, pageIndex);
  276. Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor1>(), ++pageIndex));
  277. Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor2>(), ++pageIndex));
  278. Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor3>(), ++pageIndex));
  279. TreeNode parent3 = Aside.CreateNode("配方模块", 162677, 34, pageIndex);
  280. Aside.CreateChildNode(parent3, AddPage(Globals.ServiceProvider.GetRequiredService<PageRecipeManage>(), ++pageIndex));
  281. TreeNode parent4 = Aside.CreateNode("日志模块", 57557, 34, pageIndex);
  282. Aside.CreateChildNode(parent4, AddPage(Globals.ServiceProvider.GetRequiredService<PageLogManage>(), ++pageIndex));
  283. TreeNode parent5 = Aside.CreateNode("报表模块", 57586, 34, pageIndex);
  284. Aside.CreateChildNode(parent5, AddPage(Globals.ServiceProvider.GetRequiredService<PageReportManage>(), ++pageIndex));
  285. TreeNode parent6 = Aside.CreateNode("图表模块", 61950, 34, pageIndex);
  286. Aside.CreateChildNode(parent6, AddPage(Globals.ServiceProvider.GetRequiredService<PageChartManage>(), ++pageIndex));
  287. TreeNode parent7 = Aside.CreateNode("参数模块", 559576, 34, pageIndex);
  288. Aside.CreateChildNode(parent7, AddPage(Globals.ServiceProvider.GetRequiredService<PageSystemParameterSet>(), ++pageIndex));
  289. }
  290. private void InitHeaderUI()
  291. {
  292. //设置关联
  293. Header.TabControl = MainTabControl;
  294. Header.Nodes.Add("");
  295. Header.Nodes.Add("");
  296. Header.Nodes.Add("");
  297. Header.SetNodeSymbol(Header.Nodes[0], 558295, 34);
  298. Header.SetNodeSymbol(Header.Nodes[1], 61489, 34);
  299. Header.SetNodeSymbol(Header.Nodes[2], 557925, 34);
  300. var styles = UIStyles.PopularStyles();
  301. foreach (UIStyle style in styles)
  302. {
  303. Header.CreateChildNode(Header.Nodes[0], style.DisplayText(), style.Value());
  304. }
  305. //获取枚举FontsType的所有字体名称
  306. for (int i = 0; i < Enum.GetValues(typeof(SystemEnums.FontsType)).Length; i++)
  307. {
  308. Header.CreateChildNode(Header.Nodes[1], Enum.GetName(typeof(SystemEnums.FontsType), i), i + 1);
  309. }
  310. //获取枚举FontSize的所有字体大小 75-125的范围 75 80 85 90 95 100 105 110 115 120 125
  311. for (int i = 75; i <= 125; i += 5)
  312. {
  313. Header.CreateChildNode(Header.Nodes[2], i.ToString(), i);
  314. }
  315. }
  316. private void uiSymbolLabel2_Click(object sender, EventArgs e)
  317. {
  318. this.Close(); //关闭当前窗体
  319. }
  320. private void uiSymbolLabel1_Click(object sender, EventArgs e)
  321. {
  322. this.WindowState = FormWindowState.Minimized;
  323. }
  324. private void Header_MenuItemClick(string itemText, int menuIndex, int pageIndex)
  325. {
  326. switch (menuIndex)
  327. {
  328. case 0:
  329. UIStyle style = (UIStyle)pageIndex;
  330. if (pageIndex < UIStyle.Colorful.Value())
  331. {
  332. StyleManager.Style = style;
  333. if (UIExtension.SetStyleManager != null)
  334. {
  335. UIExtension.SetStyleManager(StyleManager);
  336. }
  337. }
  338. break;
  339. case 1:
  340. UIStyles.DPIScale = true;
  341. UIStyles.GlobalFont = true;
  342. UIStyles.GlobalFontName = itemText;
  343. UIStyles.GlobalFontScale = SystemConsts.DefaultFontScale;
  344. UIStyles.SetDPIScale();
  345. break;
  346. case 2:
  347. UIStyles.GlobalFontScale = int.Parse(itemText);
  348. UIStyles.SetDPIScale();
  349. break;
  350. default:
  351. break;
  352. }
  353. }
  354. private void Panel_MouseDown(object sender, MouseEventArgs e)
  355. {
  356. mPoint = new Point(e.X, e.Y);
  357. }
  358. private void Panel_MouseMove(object sender, MouseEventArgs e)
  359. {
  360. if (e.Button == MouseButtons.Left)
  361. {
  362. this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
  363. }
  364. }
  365. private void pictureBox2_Click(object sender, EventArgs e)
  366. {
  367. //把Aside折叠起来
  368. Aside.CollapseAll();
  369. Aside.SelectFirst();
  370. var frmLogin = Globals.ServiceProvider.GetRequiredService<FormLogin>();
  371. frmLogin.ShowDialog();
  372. if (frmLogin.IsLogin)
  373. {
  374. //更新登录用户
  375. this.lbl_User.Text = frmLogin.UserName;
  376. foreach (var control in pageControls.Values)
  377. {
  378. control.Enabled = true;
  379. }
  380. }
  381. }
  382. #region 控制权限
  383. /// <summary>
  384. /// 侧边栏菜单折叠事件(折叠之前)
  385. /// </summary>
  386. /// <param name="sender"></param>
  387. /// <param name="e"></param>
  388. private async void Aside_BeforeExpand(object sender, TreeViewCancelEventArgs e)
  389. {
  390. UINavMenu uINavMenu = sender as UINavMenu;
  391. string moduleName = e.Node.Text;
  392. string user = this.lbl_User.Text;
  393. var roleRes = await _userManager.GetUserAuthAsync(new QueryUserAuthDto() { UserName = user });
  394. if (roleRes.Result == SystemEnums.Result.Success)
  395. {
  396. if (roleRes.Data[0].Role != "管理员")
  397. {
  398. var authRes = await _authManager.GetAuthAsync(new QueryAuthDto { Role = roleRes.Data[0].Role });
  399. if (authRes.Result == SystemEnums.Result.Success)
  400. {
  401. UpdateControlAccess(moduleName, authRes.Data[0], pageControls);
  402. }
  403. }
  404. }
  405. }
  406. private void UpdateControlAccess(string moduleName, QueryAuthResultDto authDto, Dictionary<string, Control> pageControls)
  407. {
  408. switch (moduleName)
  409. {
  410. case "控制模块":
  411. pageControls["控制模块"].Enabled = authDto.ControlModule;
  412. break;
  413. case "用户模块":
  414. pageControls["用户模块"].Enabled = false;
  415. pageControls["权限模块"].Enabled = false;
  416. break;
  417. case "监控模块":
  418. pageControls["监控模块1"].Enabled = authDto.MonitorModule;
  419. pageControls["监控模块2"].Enabled = authDto.MonitorModule;
  420. pageControls["监控模块3"].Enabled = authDto.MonitorModule;
  421. break;
  422. case "配方模块":
  423. pageControls["配方模块"].Enabled = authDto.RecipeModule;
  424. break;
  425. case "日志模块":
  426. pageControls["日志模块"].Enabled = authDto.LogModule;
  427. break;
  428. case "报表模块":
  429. pageControls["报表模块"].Enabled = authDto.ReportModule;
  430. break;
  431. case "图表模块":
  432. pageControls["图表模块"].Enabled = authDto.ChartModule;
  433. break;
  434. case "参数模块":
  435. pageControls["参数模块"].Enabled = authDto.ParamModule;
  436. break;
  437. default:
  438. break;
  439. }
  440. }
  441. #endregion 控制权限
  442. }
  443. }