123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510 |
- using BLL;
- using BLL.Dto.AuthDto;
- using BLL.Dto.DataDto;
- using BLL.Dto.UserDto;
- using BLL.Manager;
- using Helper;
- using HZY.Framework.DependencyInjection;
- using IoTClient.Clients.PLC;
- using IoTClient.Common.Enums;
- using IoTClient.Enums;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using MiniExcelLibs;
- using Model;
- using Scada.Page;
- using Sunny.UI;
- namespace Scada
- {
- public partial class FormMain : UIHeaderAsideMainFooterFrame, IScopedSelfDependency
- {
- private bool plcIsConnected;
- private readonly ILogger<FormMain> _logger;
- private Point mPoint;
- private CancellationTokenSource cts = new CancellationTokenSource();
- private readonly UserManager _userManager;
- private readonly AuthManager _authManager;
- private readonly DataManager _dataManager;
- private System.Timers.Timer Timer = new System.Timers.Timer(); // 定时器每秒触发一次
- private Dictionary<string, Control> pageControls = new Dictionary<string, Control>
- {
- { "控制模块", Globals.ServiceProvider.GetRequiredService<PageTotalEquipmentControl>() },
- { "用户模块", Globals.ServiceProvider.GetRequiredService<PageUserManage>() },
- { "权限模块", Globals.ServiceProvider.GetRequiredService<PageAuthManage>() },
- { "监控模块1", Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor1>() },
- { "监控模块2", Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor2>() },
- { "监控模块3", Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor3>() },
- { "配方模块", Globals.ServiceProvider.GetRequiredService<PageRecipeManage>() },
- { "日志模块", Globals.ServiceProvider.GetRequiredService<PageLogManage>() },
- { "报表模块", Globals.ServiceProvider.GetRequiredService<PageReportManage>() },
- { "图表模块", Globals.ServiceProvider.GetRequiredService<PageChartManage>() },
- { "参数模块", Globals.ServiceProvider.GetRequiredService<PageSystemParameterSet>() }
- };
- private List<string> AlarmList = new List<string>();
- public FormMain(ILogger<FormMain> logger, UserManager userManager, AuthManager authManager, DataManager
- dataManager)
- {
- _logger = logger ?? throw new ArgumentNullException(nameof(logger));
- _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
- _authManager = authManager ?? throw new ArgumentNullException(nameof(authManager));
- _dataManager = dataManager ?? throw new ArgumentNullException(nameof(dataManager));
- //初始化窗体
- InitializeComponent();
- InitAsideUI();
- InitHeaderUI();
- InitConfig();
- InitPlcClient();
- InitOther();
- this.Closed += (s, e) =>
- {
- //取消令牌源
- cts.Cancel();
- cts.Dispose();
- //关闭PLC客户端
- if (Globals.SiemensClient != null)
- {
- Globals.SiemensClient.Close();
- }
- };
- //显示默认界面
- Aside.SelectFirst();
- Aside.BeforeExpand += Aside_BeforeExpand;
- }
- private void InitOther()
- {
- Timer.Interval = 1000; // 设置定时器间隔为1秒
- Timer.Elapsed += Timer_Elapsed;
- Timer.Start();
- }
- private void Timer_Elapsed(object? sender, EventArgs e)
- {
- if (plcIsConnected)
- {
- if (this.InvokeRequired)
- {
- this.Invoke(async () =>
- {
- this.lbl_Temperature.Text = Globals.DataDic[this.lbl_Temperature.TagString].ToString() + "℃";
- this.lbl_Humidness.Text = Globals.DataDic[this.lbl_Humidness.TagString].ToString() + "%";
- this.lbl_ProducteCount.Text = Globals.DataDic[this.lbl_ProducteCount.TagString].ToString();
- this.lbl_BadCount.Text = Globals.DataDic[this.lbl_BadCount.TagString].ToString();
- this.lbl_Beat.Text = Globals.DataDic[this.lbl_Beat.TagString].ToString();
- this.lbl_TotalAlarm.Text = Globals.DataDic[this.lbl_TotalAlarm.TagString].ToString();
- //CPU和内存
- string CPUstr = RuntimeStatusHelper.DataManager.GetCpuUtilization();
- string MemoryStr = RuntimeStatusHelper.DataManager.GetMemoryUtilization().Replace("G", "");
- string NeiResult = (double.Parse(MemoryStr.Split('/')[0]) / double.Parse(MemoryStr.Split('/')[1]) * 100).ToString("f1") + "%";
- this.lbl_CPUInformation.Text = double.Parse(CPUstr).ToString("f1") + "%";
- this.lbl_MemoryInformation.Text = NeiResult;
- //时间
- this.lbl_Time.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- List<string> alarmInfos = CheckAlarms(AlarmList);
- string alarmInfo = string.Join(",", alarmInfos);
- if (string.IsNullOrEmpty(alarmInfo))
- {
- this.st_AlarmInfo.Text = "系统正常";
- this.st_AlarmInfo.ForeColor = Color.Green;
- this.led_ProducteState.On = true;
- this.led_ProducteState.Color = Color.Green;
- this.led_ProducteState.Blink = false;
- }
- else
- {
- this.st_AlarmInfo.Text = alarmInfo;
- this.st_AlarmInfo.ForeColor = Color.Red;
- this.led_ProducteState.Color = Color.Red;
- this.led_ProducteState.BlinkInterval = 500;
- this.led_ProducteState.Blink = true;
- }
- //存储数据
- //用反射的方式将Globals.DataDic中对应Globals.SaveList名称的变量值保存到AddDataDto中,然后保存到数据库中
- AddDataDto addDataDto = new AddDataDto();
- addDataDto.InsertTime = DateTime.Now;
- //根据反射获取Globals.DataDic中对应Globals.SaveList名称的变量值,并赋值到addDataDto中
- foreach (var item in Globals.SaveList)
- {
- var type = typeof(AddDataDto).GetProperty(item).PropertyType.Name;
- if (type == "String")
- {
- addDataDto.GetType().GetProperty(item).SetValue(addDataDto, Globals.DataDic[item].ToString());
- }
- }
- //保存到数据库中
- await _dataManager.AddDataAsync(addDataDto);
- });
- }
- }
- }
- private List<string> CheckAlarms(List<string> alarmList)
- {
- List<string> alarmInfos = new List<string>();
- foreach (var alarm in alarmList)
- {
- if (Globals.DataDic[alarm].ToString() == "1")
- {
- //如果PLC变量值为1,则表示报警
- alarmInfos.Add(alarm);
- }
- }
- return alarmInfos;
- }
- private void InitConfig()
- {
- //读取PLC配置 192.168.1.180 127.0.0.1
- Globals.IpAddress = Globals.IniFile.ReadString("PLC参数", "IP", "127.0.0.1");
- Globals.Port = Globals.IniFile.ReadInt("PLC参数", "Port", 102);
- Globals.CpuType = Enum.Parse<SiemensVersion>(Globals.IniFile.ReadString("PLC参数", "CpuType", SiemensVersion.S7_1200.ToString()));
- Globals.Slot = Globals.IniFile.ReadByte("PLC参数", "Slot", 0);
- Globals.Rack = Globals.IniFile.ReadByte("PLC参数", "Rack", 0);
- Globals.ConnectTimeOut = Globals.IniFile.ReadInt("PLC参数", "ConnectTimeOut", 3000);
- Globals.ReadTimeInterval = Globals.IniFile.ReadInt("PLC参数", "ReadTimeInterval", 300);
- Globals.ReConnectTimeInterval = Globals.IniFile.ReadInt("PLC参数", "ReConnectTimeInterval", 3000);
- //PLC变量表路径
- Globals.PlcVarConfigPath = Globals.IniFile.ReadString("PLC参数", "变量表地址", Path.Combine(Application.StartupPath, "PLC_Var_Config.xlsx"));
- //删除文件夹路径
- Globals.DelFilePath = Globals.IniFile.ReadString("系统参数", "删除文件夹路径", Path.Combine(Application.StartupPath, "Logs"));
- //保存天数
- Globals.SaveDay = Globals.IniFile.ReadString("系统参数", "保存天数", "30");
- //试用时长
- Globals.SYTime = Globals.IniFile.ReadInt("软件参数", "试用时间", 100);
- //软件版本
- Globals.SoftwareVersion = Globals.IniFile.ReadString("软件参数", "软件版本", "V1.0");
- _logger.LogInformation("读取配置文件成功");
- }
- private void InitPlcClient()
- {
- var plcVarList = MiniExcel.Query<PLCVarConfigModel>(Globals.PlcVarConfigPath).ToList();
- Globals.SiemensClient = new SiemensClient(Globals.CpuType, Globals.IpAddress, Globals.Port, Globals.Slot, Globals.Rack, Globals.ConnectTimeOut);
- var connectResult = Globals.SiemensClient.Open();
- if (connectResult.IsSucceed)
- {
- plcIsConnected = true;
- this.led_PlcState.On = true;
- }
- else
- {
- plcIsConnected = false;
- this.led_PlcState.On = false;
- }
- for (int i = 0; i < plcVarList.Count; i++)
- {
- //初始化PLC变量地址字典 地址-类型
- Globals.ReadDic.Add(plcVarList[i].PLC地址, Enum.Parse<DataTypeEnum>(plcVarList[i].变量类型, true));//忽略大小写
- //初始化PLC变量写入 名称-地址 //初始化PLC变量值字典 名称-值
- Globals.WriteDic.Add(plcVarList[i].名称, plcVarList[i].PLC地址);
- //初始化PLC变量值字典 名称-值
- Globals.DataDic.Add(plcVarList[i].名称, "NA");
- if (plcVarList[i].是否保存.ToLower() == "true")
- {
- Globals.SaveList.Add(plcVarList[i].名称);
- }
- if (plcVarList[i].名称.EndsWith("报警") && !plcVarList[i].名称.Contains("累计"))
- {
- //如果是报警变量,则添加到报警列表中
- AlarmList.Add(plcVarList[i].名称);
- }
- }
- _logger.LogInformation("初始化PLC客户端成功");
- try
- {
- Task.Run(async () =>
- {
- while (!cts.IsCancellationRequested)
- {
- if (plcIsConnected)
- {
- //这个方法的目的是将大量的数据读取请求分批处理,以提高性能和可管理性。
- var readResult = Globals.SiemensClient.BatchRead(Globals.ReadDic);
- if (readResult.IsSucceed)
- {
- for (int i = 0; i < plcVarList.Count; i++)
- {
- Globals.DataDic[plcVarList[i].名称] = readResult.Value[plcVarList[i].PLC地址];
- }
- }
- else
- {
- Globals.SiemensClient.Close();
- plcIsConnected = false;
- this.Invoke(() =>
- {
- this.led_PlcState.On = false;
- });
- }
- await Task.Delay(Globals.ReadTimeInterval);
- }
- else
- {
- //重连PLC
- var reConnectResult = Globals.SiemensClient.Open();
- if (reConnectResult.IsSucceed)
- {
- plcIsConnected = true;
- this.Invoke(() =>
- {
- this.led_PlcState.On = true;
- });
- }
- else
- {
- plcIsConnected = false;
- this.Invoke(() =>
- {
- this.led_PlcState.On = false;
- });
- await Task.Delay(Globals.ReConnectTimeInterval);
- }
- }
- }
- await Task.Delay(1000);
- }, cts.Token);
- }
- catch (Exception)
- {
- throw;
- }
- }
- private void InitAsideUI()
- {
- int pageIndex = 1000;
- TreeNode parent0 = Aside.CreateNode("控制模块", 361461, 34, pageIndex);
- Aside.CreateChildNode(parent0, AddPage(Globals.ServiceProvider.GetRequiredService<PageTotalEquipmentControl>(), ++pageIndex));
- TreeNode parent1 = Aside.CreateNode("用户模块", 61447, 34, pageIndex);
- Aside.CreateChildNode(parent1, AddPage(Globals.ServiceProvider.GetRequiredService<PageUserManage>(), ++pageIndex));
- Aside.CreateChildNode(parent1, AddPage(Globals.ServiceProvider.GetRequiredService<PageAuthManage>(), ++pageIndex));
- TreeNode parent2 = Aside.CreateNode("监控模块", 560066, 34, pageIndex);
- Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor1>(), ++pageIndex));
- Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor2>(), ++pageIndex));
- Aside.CreateChildNode(parent2, AddPage(Globals.ServiceProvider.GetRequiredService<PageEquipmentMonitor3>(), ++pageIndex));
- TreeNode parent3 = Aside.CreateNode("配方模块", 162677, 34, pageIndex);
- Aside.CreateChildNode(parent3, AddPage(Globals.ServiceProvider.GetRequiredService<PageRecipeManage>(), ++pageIndex));
- TreeNode parent4 = Aside.CreateNode("日志模块", 57557, 34, pageIndex);
- Aside.CreateChildNode(parent4, AddPage(Globals.ServiceProvider.GetRequiredService<PageLogManage>(), ++pageIndex));
- TreeNode parent5 = Aside.CreateNode("报表模块", 57586, 34, pageIndex);
- Aside.CreateChildNode(parent5, AddPage(Globals.ServiceProvider.GetRequiredService<PageReportManage>(), ++pageIndex));
- TreeNode parent6 = Aside.CreateNode("图表模块", 61950, 34, pageIndex);
- Aside.CreateChildNode(parent6, AddPage(Globals.ServiceProvider.GetRequiredService<PageChartManage>(), ++pageIndex));
- TreeNode parent7 = Aside.CreateNode("参数模块", 559576, 34, pageIndex);
- Aside.CreateChildNode(parent7, AddPage(Globals.ServiceProvider.GetRequiredService<PageSystemParameterSet>(), ++pageIndex));
- }
- private void InitHeaderUI()
- {
- //设置关联
- Header.TabControl = MainTabControl;
- Header.Nodes.Add("");
- Header.Nodes.Add("");
- Header.Nodes.Add("");
- Header.SetNodeSymbol(Header.Nodes[0], 558295, 34);
- Header.SetNodeSymbol(Header.Nodes[1], 61489, 34);
- Header.SetNodeSymbol(Header.Nodes[2], 557925, 34);
- var styles = UIStyles.PopularStyles();
- foreach (UIStyle style in styles)
- {
- Header.CreateChildNode(Header.Nodes[0], style.DisplayText(), style.Value());
- }
- //获取枚举FontsType的所有字体名称
- for (int i = 0; i < Enum.GetValues(typeof(SystemEnums.FontsType)).Length; i++)
- {
- Header.CreateChildNode(Header.Nodes[1], Enum.GetName(typeof(SystemEnums.FontsType), i), i + 1);
- }
- //获取枚举FontSize的所有字体大小 75-125的范围 75 80 85 90 95 100 105 110 115 120 125
- for (int i = 75; i <= 125; i += 5)
- {
- Header.CreateChildNode(Header.Nodes[2], i.ToString(), i);
- }
- }
- private void uiSymbolLabel2_Click(object sender, EventArgs e)
- {
- this.Close(); //关闭当前窗体
- }
- private void uiSymbolLabel1_Click(object sender, EventArgs e)
- {
- this.WindowState = FormWindowState.Minimized;
- }
- private void Header_MenuItemClick(string itemText, int menuIndex, int pageIndex)
- {
- switch (menuIndex)
- {
- case 0:
- UIStyle style = (UIStyle)pageIndex;
- if (pageIndex < UIStyle.Colorful.Value())
- {
- StyleManager.Style = style;
- if (UIExtension.SetStyleManager != null)
- {
- UIExtension.SetStyleManager(StyleManager);
- }
- }
- break;
- case 1:
- UIStyles.DPIScale = true;
- UIStyles.GlobalFont = true;
- UIStyles.GlobalFontName = itemText;
- UIStyles.GlobalFontScale = SystemConsts.DefaultFontScale;
- UIStyles.SetDPIScale();
- break;
- case 2:
- UIStyles.GlobalFontScale = int.Parse(itemText);
- UIStyles.SetDPIScale();
- break;
- default:
- break;
- }
- }
- private void Panel_MouseDown(object sender, MouseEventArgs e)
- {
- mPoint = new Point(e.X, e.Y);
- }
- private void Panel_MouseMove(object sender, MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Left)
- {
- this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
- }
- }
- private void pictureBox2_Click(object sender, EventArgs e)
- {
- //把Aside折叠起来
- Aside.CollapseAll();
- Aside.SelectFirst();
- var frmLogin = Globals.ServiceProvider.GetRequiredService<FormLogin>();
- frmLogin.ShowDialog();
- if (frmLogin.IsLogin)
- {
- //更新登录用户
- this.lbl_User.Text = frmLogin.UserName;
- foreach (var control in pageControls.Values)
- {
- control.Enabled = true;
- }
- }
- }
- #region 控制权限
- /// <summary>
- /// 侧边栏菜单折叠事件(折叠之前)
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private async void Aside_BeforeExpand(object sender, TreeViewCancelEventArgs e)
- {
- UINavMenu uINavMenu = sender as UINavMenu;
- string moduleName = e.Node.Text;
- string user = this.lbl_User.Text;
- var roleRes = await _userManager.GetUserAuthAsync(new QueryUserAuthDto() { UserName = user });
- if (roleRes.Result == SystemEnums.Result.Success)
- {
- if (roleRes.Data[0].Role != "管理员")
- {
- var authRes = await _authManager.GetAuthAsync(new QueryAuthDto { Role = roleRes.Data[0].Role });
- if (authRes.Result == SystemEnums.Result.Success)
- {
- UpdateControlAccess(moduleName, authRes.Data[0], pageControls);
- }
- }
- }
- }
- private void UpdateControlAccess(string moduleName, QueryAuthResultDto authDto, Dictionary<string, Control> pageControls)
- {
- switch (moduleName)
- {
- case "控制模块":
- pageControls["控制模块"].Enabled = authDto.ControlModule;
- break;
- case "用户模块":
- pageControls["用户模块"].Enabled = false;
- pageControls["权限模块"].Enabled = false;
- break;
- case "监控模块":
- pageControls["监控模块1"].Enabled = authDto.MonitorModule;
- pageControls["监控模块2"].Enabled = authDto.MonitorModule;
- pageControls["监控模块3"].Enabled = authDto.MonitorModule;
- break;
- case "配方模块":
- pageControls["配方模块"].Enabled = authDto.RecipeModule;
- break;
- case "日志模块":
- pageControls["日志模块"].Enabled = authDto.LogModule;
- break;
- case "报表模块":
- pageControls["报表模块"].Enabled = authDto.ReportModule;
- break;
- case "图表模块":
- pageControls["图表模块"].Enabled = authDto.ChartModule;
- break;
- case "参数模块":
- pageControls["参数模块"].Enabled = authDto.ParamModule;
- break;
- default:
- break;
- }
- }
- #endregion 控制权限
-
- }
- }
|