using AntdUI; using HML; using JinYuan.ControlCenters; using JinYuan.ControlLib; using JinYuan.Helper; using JinYuan.MES.Models; using JinYuan.Models; using JinYuan.VirtualDataLibrary; using Language; using LargeSquareOne.ViewModel; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Drawing.Text; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace LargeSquareOne { public partial class FrmMain : MultiLanguageForm { private ControlCenter _controlCenter; //实时更新的定时器 private System.Windows.Forms.Timer updateTimer; //加载字体 private PrivateFontCollection font = new PrivateFontCollection(); //private Image _backgroundImage; //定时存储定时器 private System.Timers.Timer storeTimer; /// /// 时间更新委托 /// /// public delegate void ShowTimeHandler(DateTime time); //当前页面索引 private int CurrentIndex = 0; private List naviButton2s = new List(); public bool IsNoOrg = false; public bool IsSetParam = false; public FrmMain() { InitializeComponent(); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.Selectable, true); this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.SetStyle(ControlStyles.UserPaint, true); InitializeLanguageSwitch(); SetCombOrg(); IsNoOrg = true; this.Resize += FrmNewMain_Resize; // 关联 Resize 事件 #region 添加工具栏 naviButton2s.Add(this.nav_Monitor); naviButton2s.Add(this.nav_DataMonitor); naviButton2s.Add(this.nav_CPK); naviButton2s.Add(this.nav_AlarmLog); naviButton2s.Add(this.nav_HistotryData); naviButton2s.Add(this.nav_SetSystem); naviButton2s.Add(this.nav_System); naviButton2s.Add(this.nav_UserInfo); #endregion storeTimer = new System.Timers.Timer(); storeTimer.Interval = 1000; storeTimer.AutoReset = true; storeTimer.Elapsed += StoreTimer_Elapsed; //开启定时器 storeTimer.Start(); updateTimer = new System.Windows.Forms.Timer(); updateTimer.Interval = 200; updateTimer.Tick += UpdateTimer_Tick; updateTimer.Start(); //刷卡模式 if (CommonMethods.sysConfig.SwipeCardMode) { CommonMethods.listener.ScanerEvent += Listener_ScanerEvent; } CommonMethods.listener.Start(); } private async void FrmNewMain_Load(object sender, EventArgs e) { InitReadInI(); UserTimeOut(30); _controlCenter = ControlCenter.Instance; await ControlCenter.Instance.StartAsync(); //1.设置登录用户 this.lbl_LoginLevel.Text = CommonMethods.currentAdmin?.LoginLevel; this.lbl_LoginName.Text = CommonMethods.currentAdmin?.LoginName; //2.打开日志报警窗体 CommonNaviButton_Click(this.nav_AlarmLog, null); //3.打开图表窗体 CommonNaviButton_Click(this.nav_Monitor, null); //打开集中监控窗体 CommonNaviButton_Click(this.nav_DataMonitor, null); //登录日志 CommonMethods.AddOPLog(false, "登录成功,登录用户".Translated() + $":{CommonMethods.currentAdmin?.LoginName}," + "权限".Translated() + $":{CommonMethods.currentAdmin?.LoginLevel}"); //自动锁屏 if (CommonMethods.sysConfig.AutoLock) { //开启监听键盘和鼠标操作 Application.AddMessageFilter(new MessageFilter()); } // if (CommonMethods.sysConfig != null) { CommonMethods.AddLog(false, "加载系统配置成功".Translated()); } else { CommonMethods.AddLog(true, "加载系统配置失败".Translated()); } if (CommonMethods.sysConfig.MesModeSwitching && !CommonMethods.mesConfig.IsLoginMesOK) { new FrmMsgBoxOutWithAck(2, "当前为MES模式,请登录!".Translated(), "MES未登录".Translated()).ShowDialog(); FrmLoginMes frmLoginMes = new FrmLoginMes(); frmLoginMes.ShowDialog(); } if (CommonMethods.btwConfig.IsConnectPrinter && CommonMethods.tcpClient == null) { CommonMethods.tcpClient = new PrintSocket.TCPClient(); CommonMethods.tcpClient.InitClient("127.0.0.1", 8000); } } #region 读取配置文件 /// /// 读取配置文件 /// public void InitReadInI() { #region 系统配置 CommonMethods.sysConfig = CommonMethods.GetSysConfig(); //CommonMethods.sysConfig.MesModeSwitching = Convert.ToBoolean(CommonMethods.GetConfigValue(CommonMethods.Configxml, "CONFIG_INFO", "MESModeSwitch", "false")); //CommonMethods.sysConfig.GetMesParam = Convert.ToBoolean(CommonMethods.GetConfigValue(CommonMethods.Configxml, "CONFIG_INFO", "FetchMESParams", "false")); //CommonMethods.mesConfig.IsGet_Server = Convert.ToBoolean(CommonMethods.GetConfigValue(CommonMethods.Configxml, "CONFIG_INFO", "FetchServerData", "false")); //CommonMethods.sysConfig.IsDebugMode = Convert.ToBoolean(CommonMethods.GetConfigValue(CommonMethods.Configxml, "CONFIG_INFO", "IsDebugMode", "false")); //CommonMethods.mesConfig.CoreCount = Convert.ToInt32(CommonMethods.GetConfigValue(CommonMethods.Configxml, "CONFIG_INFO", "CoreCount", "1")); //CommonMethods.mesConfig.SteelshellCount = Convert.ToInt32(CommonMethods.GetConfigValue(CommonMethods.Configxml, "CONFIG_INFO", "SteelshellCount", "1")); #endregion #region MES配置 CommonMethods.mesConfig.RotueServerIP = CommonMethods.GetConfigValue(CommonMethods.Configxml, "MES_CONFIG", "StorageServerIP", "192.168.2.108"); ///获取MES参数 CommonMethods.mesConfig = CommonMethods.GetMesConfig(); CommonMethods.btwConfig = CommonMethods.GetBtwConfig(); CommonMethods.mesConfig.electricMeterNum.Clear(); string str = CommonMethods.GetConfigValue(CommonMethods.Configxml, "MES_CONFIG", "SmartMeterCode", "1"); if (str.Contains(',')) { string[] strArray = str.Split(','); for (int i = 0; i < strArray.Length; i++) { CommonMethods.mesConfig.electricMeterNum.Add(strArray[i]); } } CommonMethods.ChangeClassTime = CommonMethods.GetConfigValue(CommonMethods.Configxml, "MES_CONFIG", "ShiftChangeTime", "20:30:00"); CommonMethods.strDeletepath = CommonMethods.GetConfigValue(CommonMethods.Configxml, "MES_CONFIG", "MESLogPath", "D:\\APILog") + "\\"; CommonMethods.strAlarmLogspath = CommonMethods.strDeletepath + "Logs\\AlarmLogs\\"; CommonMethods.strMesLogspath = CommonMethods.strDeletepath + "Logs\\MesLogs"; CommonMethods.strSystemLogspath = CommonMethods.strDeletepath + "Logs\\SystemLogs"; CommonMethods.strErrorLogspath = CommonMethods.strDeletepath + "Logs\\ErrorLogs"; CommonMethods.strsqlLogspath = CommonMethods.strDeletepath + "Logs\\SqlLogs\\"; CommonMethods.strWattrMeterpath = CommonMethods.strDeletepath + "Logs\\智能电表数据\\"; #endregion CommonMethods.mesConfig.listAntiDustAirSpeedNum.Clear(); CommonMethods.mesConfig.AntiDustAirSpeedCount = Convert.ToInt32(CommonMethods.GetConfigValue(CommonMethods.Configxml, "ANEMOMETER", "AntiDustAirSpeedCount", "1")); for (int i = 0; i < CommonMethods.mesConfig.AntiDustAirSpeedCount; i++) { CommonMethods.mesConfig.listAntiDustAirSpeedNum.Add(CommonMethods.GetConfigValue(CommonMethods.Configxml, "ANEMOMETER", $"AntiDustAirSpeed{i + 1}", "0")); } } #endregion #region 无操作 系统锁屏+切换到主监控界面 private async void UpdateTimer_Tick(object sender, EventArgs e) { try { await Task.Run(() => { if (CommonMethods.sysConfig.AutoLock) { CommonMethods.tickCount++; if (CommonMethods.tickCount >= CommonMethods.sysConfig.LockPeriod * 60 * 1000 / this.updateTimer.Interval) { CommonMethods.tickCount=0; this.BeginInvoke(() => LockWorkStation()); } } if (CommonMethods.sysConfig.AutoQieHuanM) { CommonMethods.tickHomeCount++; if (CommonMethods.tickHomeCount >= CommonMethods.sysConfig.QieHuanMPeriod * 60 * 1000 / this.updateTimer.Interval) { CommonMethods.tickHomeCount=0; this.BeginInvoke((Action)(() => CommonNaviButton_Click(this.nav_Monitor, null))); } } }).ConfigureAwait(false); } catch (Exception ex) { LogHelper.Instance.WriteEX(ex); } } private async void StoreTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { DateTime time = DateTime.Now; await Task.Run(() => ShowButtonEven_Run(time)); } catch (Exception ex) { LogHelper.Instance.WriteEX(ex); } } [DllImport("user32")] public static extern bool LockWorkStation(); #endregion /// /// 刷卡事件 /// /// private void Listener_ScanerEvent(ScanerHook.ScanerCodes codes) { //封装对象 SysAdmin sysAdmin = new SysAdmin() { LoginUid = codes.Result, }; //调用查询方法 sysAdmin = CommonMethods.db.Query(it => it.LoginUid == sysAdmin.LoginUid); if (sysAdmin == null) { new FrmMsgBoxOutWithAck(3, "登录用户或密码错误".Translated(), "登录提示".Translated()).ShowDialog(); return; } CommonMethods.IsLoginOk = true; //存储用户对象 CommonMethods.currentAdmin = sysAdmin; //1.设置登录用户 this.lbl_LoginLevel.Text = CommonMethods.currentAdmin?.LoginLevel; this.lbl_LoginName.Text = CommonMethods.currentAdmin?.LoginName; //登录日志 CommonMethods.AddOPLog(false, "登录成功,登录用户".Translated() + $":{CommonMethods.currentAdmin?.LoginName}," + "权限".Translated() + $":{CommonMethods.currentAdmin?.LoginLevel}"); } #region 获取日期/星期,班次信息,更新 private void ShowButtonEven_Run(DateTime time) { try { this.Invoke(new Action(() => { //this.led_StopState.Value = CommonMethods.EMCStatues; this.lbl_DateTime.Text = CurrentTime + " " + week.Translated() + " " + $"{CommonMethods.strClass}"; if (CommonMethods.plcDevices != null && CommonMethods.plcDevices.Count > 0) { this.led_PLCState.Value = CommonMethods.plcDevices[0].IsConnected; } if (CommonMethods.sysConfig.MesModeSwitching && CommonMethods.mesConfig.IsLoginMesOK && CommonMethods.mesConfig.isConnected)//MES { CommonMethods.mesConfig.isUpMes = true; this.led_MESState.Value = true; avMesicon.Visible = true; lblMES.Visible = true; lblMES.Text = CommonMethods.mesConfig.mesUserName; } else { CommonMethods.mesConfig.isUpMes = false; avMesicon.Visible = false; lblMES.Visible = false; this.led_MESState.Value = false; } if (CommonMethods.sysConfig.SwipeCardMode && !CommonMethods.IsLoginOk)//刷卡模式 { lbl_LoginName.Visible = false; lbl_LoginLevel.Text = "未登录"; } else { lbl_LoginName.Visible = true; } if (CommonMethods.sysConfig.ScreenCutting) { CommonNaviButton_Click(this.nav_DataMonitor, null); CommonMethods.sysConfig.ScreenCutting = false; } if (CommonMethods.Statues != null && CommonMethods.Statues.Count > 0) { // 第一种状态:直接设置颜色 this.led_State.BlinkColor = Color.Lime; this.led_State.OnColor = Color.Lime; this.led_State.Value = CommonMethods.Statues[0]; // 闪烁状态 if (CommonMethods.Statues[1] || CommonMethods.Statues[2] || CommonMethods.Statues[3]) { this.led_State.BlinkOn = true; // 启用闪烁 // 根据不同的状态设置闪烁模式 if (CommonMethods.Statues[1]) { // 闪烁模式 1 停止状态 this.led_State.BlinkColor = Color.Yellow; this.led_State.OnColor = Color.Yellow; } else if (CommonMethods.Statues[2]) { // 闪烁模式 2 报警状态 this.led_State.BlinkColor = Color.Red; this.led_State.OnColor = Color.Red; } else if (CommonMethods.Statues[3]) { // 闪烁模式 3 闲置状态 this.led_State.BlinkColor = Color.Yellow; this.led_State.OnColor = Color.Yellow; } } else { this.led_State.BlinkOn = false; // 关闭闪烁 } if (!CommonMethods.Statues[2]) { string SlideAlarm = "当前无报警".Translated(); this.ucRollText1.Text = SlideAlarm; this.ucRollText1.ForeColor = System.Drawing.Color.White; CommonMethods.SlideAlarmText = ""; } else { this.ucRollText1.Text = CommonMethods.SlideAlarmText; if(CommonMethods.SlideAlarmText == "当前无报警".Translated() || string.IsNullOrEmpty(CommonMethods.SlideAlarmText.Trim())) this.ucRollText1.ForeColor = System.Drawing.Color.White; else this.ucRollText1.ForeColor = System.Drawing.Color.Red; } } })); } catch (Exception ex) { LogHelper.Instance.WriteEX(ex); } } private string CurrentTime { get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } } private string[] weeks = new string[] { "星期日".Translated(), "星期一".Translated(), "星期二".Translated(), "星期三".Translated(), "星期四".Translated(), "星期五".Translated(), "星期六".Translated() }; private string week { get { return weeks[Convert.ToInt32(DateTime.Now.DayOfWeek)]; } } #endregion #region 窗体操作 #region 无边框拖动 private System.Drawing.Point mPoint; private void Panel_MouseDown(object sender, MouseEventArgs e) { mPoint = new System.Drawing.Point(e.X, e.Y); } private void Panel_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Location = new System.Drawing.Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y); } } #endregion /// /// 关闭程序 /// /// /// private void btExit_Click(object sender, EventArgs e) { // 关闭窗体 this.Close(); } private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; // 先取消关闭 DialogResult dialogResult = new FrmMsgBoxWithAck("是否确定要退出系统".Translated(), "退出系统".Translated()).ShowDialog(); if (dialogResult == DialogResult.OK) { try { CommonMethods.IsRun = false; CommonMethods.IsExit = true; CommonMethods.listener?.Stop(); ControlCenter.Instance.Dispose(); foreach (var plc in CommonMethods.plcDevices) { try { plc.Disconnect(); } catch { } } if (CommonMethods.tcpClient != null) { CommonMethods.tcpClient.CloseSocket(); CommonMethods.tcpClient = null; } this.Dispose(true); Application.Exit(); } catch (Exception ex) { // 记录退出异常,避免程序崩溃 LogHelper.Instance.WriteLog($"程序退出时异常:{ex.Message}", "ExitError"); // 异常时兜底退出(仅作为最后手段) Environment.Exit(1); } } else { e.Cancel = true; } } else { ControlCenter.Instance.Dispose(); Environment.Exit(0); } } private void btnScale_Click(object sender, EventArgs e) { // 手动触发窗体最小化的逻辑 this.WindowState = FormWindowState.Minimized; // 将窗体最小化 FrmNewMain_Resize(this, EventArgs.Empty); // 调用 Resize 事件处理程序 } private void FrmNewMain_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { // 在这里编写窗体最小化时的逻辑 //MessageBox.Show("窗体已最小化"); // 例如:隐藏窗体、显示通知等 } } #endregion #region 左右切换 private void btn_Left_Click(object sender, EventArgs e) { CurrentIndex--; if (CurrentIndex >= 0) { CommonNaviButton_Click(naviButton2s[CurrentIndex], null); } else { CurrentIndex++; } } private void btn_right_Click(object sender, EventArgs e) { CurrentIndex++; if (CurrentIndex < naviButton2s.Count) { CommonNaviButton_Click(naviButton2s[CurrentIndex], null); } else { CurrentIndex--; } } #endregion #region 通用窗体切换 /// /// 通用窗体切换 /// /// /// private void CommonNaviButton_Click(object sender, EventArgs e) { if (sender is NaviButton2 navi) { if (Enum.IsDefined(typeof(FormNames), navi.Tag.ToString())) { //拿到导航按钮对应的窗体枚举值 FormNames formNames = (FormNames)Enum.Parse(typeof(FormNames), navi.Tag.ToString(), true); //用户权限处理 switch (formNames) { case FormNames.日志报警: if (CommonMethods.IsLoginOk) { if (!CommonMethods.currentAdmin.SystemLog) { new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足!".Translated(), "权限不足".Translated()).ShowDialog(); return; } } else { new FrmMsgBoxOutWithAck(2, "请先刷卡登录!".Translated(), "登录系统".Translated()).ShowDialog(); return; } break; case FormNames.数据分析: new FrmMsgBoxOutWithAck(2, "功能待开发中!".Translated(), "数据分析".Translated()).ShowDialog(); return; case FormNames.数据追溯: if (CommonMethods.IsLoginOk) { if (!CommonMethods.currentAdmin.HistoryData) { new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足!".Translated(), "权限不足".Translated()).ShowDialog(); return; } } else { new FrmMsgBoxOutWithAck(2, "请先刷卡登录!".Translated(), "登录系统".Translated()).ShowDialog(); return; } break; case FormNames.参数设置: if (CommonMethods.IsLoginOk) { if (!CommonMethods.currentAdmin.ParamSet) { new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足!".Translated(), "权限不足".Translated()).ShowDialog(); return; } } else { new FrmMsgBoxOutWithAck(2, "请先刷卡登录!".Translated(), "登录系统".Translated()).ShowDialog(); return; } break; case FormNames.系统设置: if (CommonMethods.IsLoginOk) { if (!CommonMethods.currentAdmin.UserManage) { new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足!".Translated(), "权限不足".Translated()).ShowDialog(); return; } } else { new FrmMsgBoxOutWithAck(2, "请先刷卡登录!".Translated(), "登录系统".Translated()).ShowDialog(); return; } break; case FormNames.用户管理: if (CommonMethods.IsLoginOk) { if (!CommonMethods.currentAdmin.SystemLog) { new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足!".Translated(), "权限不足".Translated()).ShowDialog(); return; } } else { new FrmMsgBoxOutWithAck(2, "请先刷卡登录!".Translated(), "登录系统".Translated()).ShowDialog(); return; } break; default: break; } //窗体切换 OpenForm(this.MainPanel, formNames); //设置选中 SetNaviButtonSelected(this.TopPanel, navi); } } } /// /// 通用打开窗体 /// /// 容器控件 /// 窗体枚举名称 private void OpenForm(System.Windows.Forms.Panel mainPanel, FormNames formNames) { int total = mainPanel.Controls.Count; int closeCount = 0; bool isFind = false; for (int i = 0; i < total; i++) { Control ct = mainPanel.Controls[i - closeCount]; if (ct is Form frm) { //如果当前Form是我们需要操作的窗体 if (frm.Text == formNames.ToString()) { frm.BringToFront(); isFind = true; break; } //如果当前Form不是我们需要操作的窗体,然后判断是否为固定窗体,如果不是,则关闭,如果是,则不做处理 else if ((FormNames)Enum.Parse(typeof(FormNames), frm.Text, true) >= FormNames.临界窗体) { frm.Close(); closeCount++; } } } if (!isFind) { Form frm = null; switch (formNames) { case FormNames.集中监控: frm = new FrmMonitor(); break; case FormNames.数据监控: frm = new FrmDataMonitor(); CommonMethods.AddDataMonitorDelegate += ((FrmDataMonitor)frm).AddDataMonitorLog;//日志记录显示 CommonMethods.ShowFeedingDelegate += ((FrmDataMonitor)frm).ShowFeedingData;//上料显示 CommonMethods.ShowBlankingDelegate += ((FrmDataMonitor)frm).ShowBlankingData;//出站显示 CommonMethods.ShowPrintContainergDelegate += ((FrmDataMonitor)frm).ShowPrintContainerData;//箱唛打印显示 CommonMethods.ShowPrintPalletDelegate += ((FrmDataMonitor)frm).ShowPrintPalletData;//栈板打印显示 CommonMethods.ChangeParamDelegate += ((FrmDataMonitor)frm).GetLocalParaData;//参数更新 break; case FormNames.日志报警: frm = new FrmAlarmLog(); //绑定委托 CommonMethods.AddLogDelegate += ((FrmAlarmLog)frm).AddLog;//系统日志 CommonMethods.AddOPLogDelegate += ((FrmAlarmLog)frm).AddOPLog;//操作日志 CommonMethods.AddAlarmDelegate += ((FrmAlarmLog)frm).AddAlarm;//报警日志 break; case FormNames.临界窗体: break; case FormNames.数据分析: frm = new FrmCpkCount(); break; case FormNames.数据追溯: frm = new FrmHistory(); break; case FormNames.参数设置: frm = new FrmRecipe(); break; case FormNames.系统设置: frm = new FrmSystemSet(CommonMethods.deviceConfigPath); break; case FormNames.用户管理: frm = new FrmUserManage(); break; default: break; } if (frm != null) { //设置非顶层窗体 frm.TopLevel = false; //去除边框 frm.FormBorderStyle = FormBorderStyle.None; //填充 frm.Dock = DockStyle.Fill; //设置父容器为容器控件 frm.Parent = mainPanel; System.Diagnostics.Debug.WriteLine($"frm.Text:{frm.Text}, frm.Size: {frm.Size}, mainPanel.ClientSize:{mainPanel.ClientSize}"); // 强制同步尺寸 frm.Size = mainPanel.ClientSize; frm.Location = new Point(0, 0); //置前 frm.BringToFront(); frm.Show(); //// 强制刷新布局 mainPanel.PerformLayout(); frm.PerformLayout(); } } } /// /// 设置标题内容 /// /// 标题控件 /// 窗体枚举名称 private void SetTitle(System.Windows.Forms.Label label, FormNames formNames) { label.Text = formNames.ToString(); } /// /// 设置导航按钮选中 /// /// 导航按钮的容器 /// 导航按钮 private void SetNaviButtonSelected(System.Windows.Forms.Panel topPanel, NaviButton2 naviButton) { foreach (var item in topPanel.Controls.OfType()) { item.IsSelected = false; } naviButton.IsSelected = true; } #endregion /// /// 获取鼠标光标的当前位置 /// /// /// [DllImport("user32.dll")] public static extern bool GetCursorPos(out Point pt); /// /// 刷卡用户登录超时检查 /// /// private void UserTimeOut(int secTime) { Task task = Task.Run(() => { for (int i = 0; i < secTime; i++) { GetCursorPos(out Point sourcePoint); System.Threading.Thread.Sleep(1000); GetCursorPos(out Point currentPoint); if (sourcePoint.X != currentPoint.X | sourcePoint.Y == currentPoint.Y) { i = 0; } if (CommonMethods.LoginOut) { break; } } LoginLocalOut(); }); } private void LoginLocalOut() { CommonMethods.AddOPLog(false, "退出成功".Translated() + "," + "退出用户".Translated() + $":{CommonMethods.currentAdmin?.LoginName}," + "权限".Translated() + $":{CommonMethods.currentAdmin?.LoginLevel}"); LogHelper.Instance.WriteLog("用户".Translated() + $":{CommonMethods.currentAdmin?.LoginName} - " + "退出".Translated()); CommonMethods.LoginOut = true; } /// /// 切换监控状态 /// /// /// private async void btToggleMonitor_Click(object sender, EventArgs e) { AntdUI.Button btn = sender as AntdUI.Button; if (btn.Text == "START") { // 执行开始监控的逻辑 if (!CommonMethods.IsLoginOk) { new FrmMsgBoxOutWithAck(2, "当前未登录,请登录".Translated(), "未登录".Translated()).Show(); return; } //if (CommonMethods.sysConfig.MesModeSwitching && !CommonMethods.mesConfig.IsLoginMesOK) //{ // new FrmMsgBoxOutWithAck(2, "当前为MES模式,请登录!".Translated(), "MES未登录".Translated()).ShowDialog(); // FrmLoginMes frmLoginMes = new FrmLoginMes(); // if (frmLoginMes.ShowDialog() != DialogResult.OK) { return; } //} if (CommonMethods.mesConfig.ModelName == "") { new FrmMsgBoxOutWithAck(2, "产品型号不能为空".Translated(), "型号选择".Translated()).Show(); return; } if (txtMaterialCode.Text.Trim() == "") { new FrmMsgBoxOutWithAck(2, "物料编码不能为空".Translated(), "型号选择".Translated()).Show(); return; } CommonMethods.mesConfig.MaterialCode = txtMaterialCode.Text.Trim(); #region MES下发参数 //if (CommonMethods.sysConfig.MesModeSwitching && CommonMethods.mesConfig.IsMesParam) //{ // var (res, mesg) = await GetMesParaDataAsync(); // if (!res) // { // new FrmMsgBoxOutWithAck(2, mesg, "提示").Show(); // return; // } // CommonMethods.AddDataMonitorLog(1, "MES参数设置成功".Translated()); // LogHelper.Instance.WriteLog("MES参数设置成功"); //} #endregion CommonMethods.AddDataMonitorLog(0, "启动开始监控".Translated()); btn.Text = "连接PLC".Translated(); bool IsLink = await ControlCenter.Instance.ConnectAllPlcsAsync(); if (IsLink) { CommonMethods.IsRun = true; btn.Text = "STOP"; btn.DefaultBack = Color.Red; // 按钮背景变为红色 btn.IconSvg = Properties.Resources.StopPLC; SetProductModelEnable(true); } else { btn.Text = "START"; btn.DefaultBack = Color.FromArgb(18, 184, 61); // 按钮背景恢复绿色 btn.IconSvg = Properties.Resources.StartPLC; CommonMethods.AddDataMonitorLog(2, "启动开始监控失败".Translated()); new FrmMsgBoxOutWithAck(2, "连接PLC失败,请检查PLC连接配置,网络".Translated(), "连接PLC".Translated()).Show(); } } else if (btn.Text == "STOP") { // 执行停止监控的逻辑 if (CommonMethods.IsRun) { SetProductModelEnable(false); CommonMethods.IsRun = false; CommonMethods.Statues = new List { false, false, false, false }; ControlCenter.Instance.DisconnectAllPlcs(); CommonMethods.AddDataMonitorLog(0, "停止与PLC连接".Translated()); CommonMethods.AddOPLog(false, "停止与PLC连接".Translated()); btn.Text = "START"; btn.DefaultBack = Color.FromArgb(18, 184, 61); // 按钮背景恢复绿色 btn.IconSvg = Properties.Resources.StartPLC; } } } /// /// 设置产品型号和工单是否只读 /// /// public void SetProductModelEnable(bool b) { cmbModelType.Enabled = !b; } #region 获取参数 /// /// 从数据库获取产品型号并绑定到下拉框中 /// /// bool IsModelInit = false; public void SetCombOrg() { try { txtMaterialCode.Text = ""; CommonMethods.mesConfig.MaterialCode = ""; var productList = CommonMethods.db.QuerySqlList(CommonMethods.dBSQL.GetProdTypeSql()); if (!IsModelInit) { //DropDownListPlusItemCollection list = new DropDownListPlusItemCollection(); CommonMethods.DropDownItemList.Clear(); for (int i = 0; i < productList.Count; i++) { CommonMethods.DropDownItemList.Add(new DropDownListPlusItem() { Text = productList[i].ModelName, Tag = productList[i].MaterialCode }); } this.cmbModelType.BindItemsSource(CommonMethods.DropDownItemList); IsModelInit = true; } if (productList != null && productList.Count > 0) { CommonMethods.mesConfig.ModelName = ""; CommonMethods.mesConfig.MaterialCode = ""; DropDownListPlusItem gg = cmbModelType.SelectedItem; if (gg != null) { CommonMethods.mesConfig.ModelName = gg.Text.ToString(); CommonMethods.mesConfig.MaterialCode = gg.Tag.ToString(); txtMaterialCode.Text = CommonMethods.mesConfig.MaterialCode; } } } catch (Exception ex) { //LogHelper.Instance.WriteEx("获取数据库型号异常", ex); MessageBox.Show($"获取数据库型号异常:{ex}"); } } private void cmbModelType_SelectedItemsChanged(object sender, EventArgs e) { if (IsNoOrg && CommonMethods.IsLoginOk) { btToggleMonitor.Enabled = true; IsSetParam = false; SetCombOrg(); GetLocalParaData(); } else { this.cmbModelType.BindItemsSource(null); IsModelInit = false; SetCombOrg(); new FrmMsgBoxOutWithAck(2, "当前未登录,请先登录再操作!", "提示").ShowDialog(); } } public void GetLocalParaData() { if (string.IsNullOrEmpty(CommonMethods.mesConfig.ModelName)) { new FrmMsgBoxOutWithAck(2, "产品型号不能为空!", "型号选择").Show(); return; } try { var list = CommonMethods.db.QuerySqlList(CommonMethods.dBSQL.GetParamSql(CommonMethods.mesConfig.ModelName)); if (list != null && list.Count > 0) { CommonMethods.paramlists = list; IsSetParam = false; CommonMethods.ChangeParamData(); //GetParam(); } } catch (Exception ex) { LogHelper.Instance.WriteEX(ex); } } /// /// 刷新参数 /// //public void GetParam() //{ // try // { // if (!IsSetParam && CommonMethods.paramlists != null) // { // System.Windows.Forms.ListViewItem listItem = null; // lVConfigRange.Items.Clear(); // int j = 0; // foreach (var ProductPara in CommonMethods.paramlists) //遍历list集合 // { // string strRemark = ProductPara.Remark; // string strName = ProductPara.ParaName; // listItem = new System.Windows.Forms.ListViewItem(CommonMethods.paramlists[j].Remark); // listItem.SubItems.Add("0"); // listItem.SubItems.Add("0"); // listItem.SubItems.Add("0"); // lVConfigRange.Items.Add(listItem); // lVConfigRange.Items[j].SubItems[1].Text = ProductPara.ParaValueMin; // lVConfigRange.Items[j].SubItems[2].Text = ProductPara.ParaValueMax; // lVConfigRange.Items[j].SubItems[3].Text = ProductPara.Uint; // switch (strName) // { // //case "intoShellPressure1SettingA07": //入壳压力1 // // CommonMethods.parRange.PrePressure1Max = Convert.ToDecimal(ProductPara.ParaValueMax == "" ? "0" : ProductPara.ParaValueMax); // // break; // //case "intoShellPressure2SettingA07": //入壳压力2 // // CommonMethods.parRange.PrePressure2Max = Convert.ToDecimal(ProductPara.ParaValueMax == "" ? "0" : ProductPara.ParaValueMax); // // break; // //case "intoShellPressure3SettingA07": //入壳压力3 // // CommonMethods.parRange.PrePressure3Max = Convert.ToDecimal(ProductPara.ParaValueMax == "" ? "0" : ProductPara.ParaValueMax); // // break; // //default: // // break; // } // j++; // } // IsSetParam = true; // } // } // catch (Exception ex) // { // LogHelper.Instance.WriteEX("获取参数失败", ex); // } //} /// /// 加载MES参数 /// public async Task<(bool Success, string msg)> GetMesParaDataAsync() { bool Success = false; // 操作结果 string Message = ""; // 消息 try { bool isChangeParam = false; var nowDate = DateTime.Now; string filePath = $@"{CommonMethods.strMesLogspath}\参数设定值请求\变更记录\{nowDate.Year}\{nowDate.Month}"; string fileName = $@"{nowDate.Day}.csv"; string fileTitle = "时间,机台,MES账户,更改参数名称,更改前参数值,更改后参数值"; string fileContent = string.Empty; DataTable dt = new DataTable(); dt.Columns.Add("MES账户"); dt.Columns.Add("更改参数名称"); dt.Columns.Add("更改前参数值"); dt.Columns.Add("更改后参数值"); var (resultData, Mesage) = await CommonMethods.hbgMes.GetParamSetRequestAsync( CommonMethods.mesConfig.DeviceParamChange, CommonMethods.mesConfig.equipNum, CommonMethods.mesConfig.siteCode, CommonMethods.mesConfig.lineCode, CommonMethods.mesConfig.MaterialCode, CommonMethods.mesConfig.mesUserName); //var resultData = JsonConvert.DeserializeObject(Data); if (!resultData.success) { // 获取参数未成功 Message = "获取MES参数不成功!"; return (Success, Message); } List NewParamlists = CommonMethods.paramlists; for (int i = 0; i < resultData.total; i++) { List rows = resultData.rows; for (int j = 0; j < rows.Count; j++) { var tagList = rows[j].tagList; for (int k = 0; k < NewParamlists.Count; k++) { for (int n = 0; n < rows[j].tagList.Count; n++) { if (NewParamlists[k].ParaName == tagList[n].tagCode) { string strMin = "0"; if (String.IsNullOrEmpty(tagList[n].minValue.Trim()) || tagList[n].minValue.Trim() == "null") strMin = "0"; else strMin = tagList[n].minValue.Trim(); if (NewParamlists[k].ParaValueMin != strMin) { fileContent += $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss")},{CommonMethods.mesConfig.equipNum}," + $"{CommonMethods.mesConfig.mesUserName},{tagList[n].tagDescription}最小值,{NewParamlists[k].ParaValueMin},{strMin}\n"; dt.Rows.Add(CommonMethods.mesConfig.mesUserName, $"{tagList[n].tagDescription}最小值", NewParamlists[k].ParaValueMin, strMin); NewParamlists[k].ParaValueMin = strMin; isChangeParam = true; } string strMax = "0"; if (String.IsNullOrEmpty(tagList[n].maxValue.Trim()) || tagList[n].maxValue.Trim() == "null") strMax = "0"; else strMax = tagList[n].maxValue.Trim(); if (NewParamlists[k].ParaValueMax != tagList[n].maxValue) { fileContent += $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss")},{CommonMethods.mesConfig.equipNum}," + $"{CommonMethods.mesConfig.mesUserName},{tagList[n].tagDescription}最大值,{NewParamlists[k].ParaValueMax},{strMax}\n"; dt.Rows.Add(CommonMethods.mesConfig.mesUserName, $"{tagList[n].tagDescription}最大值", NewParamlists[k].ParaValueMax, strMax); NewParamlists[k].ParaValueMax = strMax; isChangeParam = true; } } } } if (isChangeParam) { CustomMessageBox customMessageBox = new CustomMessageBox(dt, $"当前MES下发参数与设备本地参数不一致,请确认是否使用MES下发参数"); if (customMessageBox.ShowDialog() == DialogResult.OK) { // 写csv文件 fileContent = fileContent.Substring(0, fileContent.Length - 1); CSVHelper.WriterCSV(filePath, fileName, fileTitle, fileContent); CommonMethods.paramlists = NewParamlists; int res = CommonMethods.db.Delete(it => it.ModelName == CommonMethods.paramlists[0].ModelName); if (res > 0) { CommonMethods.db.AddReturnBool(CommonMethods.paramlists); } Message = "变更成功并保存"; Success = true; } else { Message = "取消变更,采用本地参数配置"; } LogHelper.Instance.WriteLog(Message); } } } Success = true; // 操作成功 Message = "参数获取成功"; } catch (Exception ex) { Message = "获取参数失败:" + ex.Message; LogHelper.Instance.WriteEX("获取参数失败", ex); } return (Success, Message); } #endregion private void InitializeLanguageSwitch() { SwitchLanguage.Items.Clear(); SwitchLanguage.Items.Add(new SelectItem(Properties.Resources.中国国旗, "中文")); SwitchLanguage.Items.Add(new SelectItem(Properties.Resources.美国国旗, "English")); SwitchLanguage.Items.Add(new SelectItem(Properties.Resources.匈牙利国旗, "Hungary")); SwitchLanguage.Items.Add(new SelectItem(Properties.Resources.马来西亚国旗, "Malaysia")); } /// /// 切换语言 /// /// /// private void SwitchLanguage_SelectedValueChanged(object sender, ObjectNEventArgs e) { if (e.Value is SelectItem selectedItem) { string selectedLanguage = selectedItem.Text; string languageCode = selectedLanguage switch { "中文" => "zh", "English" => "en", "Hungary" => "hu", "Malaysia" => "ms", _ => "zh" }; LanguageManager.ChangeLanguage(languageCode); DgvColumnsClear(); //DgvShiftItemsChange(); } } /// /// 清除dgv内容 /// public void DgvColumnsClear() { //清除 if (FrmHistory._Form != null) { // 进出站 if (FrmHistory._Form.dgv_Main.Columns != null) { if (FrmHistory._Form.dgv_Main.Columns.Count > 0) { FrmHistory._Form.dgv_Main.Columns.Clear(); } } if (FrmHistory._Form.dgv_Main.Rows != null) { if (FrmHistory._Form.dgv_Main.Rows.Count > 0) { FrmHistory._Form.dgv_Main.Rows.Clear(); } } // 班次 if (FrmHistory._Form.dgvClass.Columns != null) { if (FrmHistory._Form.dgvClass.Columns.Count > 0) { FrmHistory._Form.dgvClass.Columns.Clear(); } } if (FrmHistory._Form.dgvClass.Rows != null) { if (FrmHistory._Form.dgvClass.Rows.Count > 0) { FrmHistory._Form.dgvClass.Rows.Clear(); } } // 日 if (FrmHistory._Form.dgvDays.Columns != null) { if (FrmHistory._Form.dgvDays.Columns.Count > 0) { FrmHistory._Form.dgvDays.Columns.Clear(); } } if (FrmHistory._Form.dgvDays.Rows != null) { if (FrmHistory._Form.dgvDays.Rows.Count > 0) { FrmHistory._Form.dgvDays.Rows.Clear(); } } // 月 if (FrmHistory._Form.dgvMonth.Columns != null) { if (FrmHistory._Form.dgvMonth.Columns.Count > 0) { FrmHistory._Form.dgvMonth.Columns.Clear(); } } if (FrmHistory._Form.dgvMonth.Rows != null) { if (FrmHistory._Form.dgvMonth.Rows.Count > 0) { FrmHistory._Form.dgvMonth.Rows.Clear(); } } // 周 if (FrmHistory._Form.dgvWeek.Columns != null) { if (FrmHistory._Form.dgvWeek.Columns.Count > 0) { FrmHistory._Form.dgvWeek.Columns.Clear(); } } if (FrmHistory._Form.dgvWeek.Rows != null) { if (FrmHistory._Form.dgvWeek.Rows.Count > 0) { FrmHistory._Form.dgvWeek.Rows.Clear(); } } // 报警信息 if (FrmHistory._Form.dgv_AlarmData.Columns != null) { if (FrmHistory._Form.dgv_AlarmData.Columns.Count > 0) { FrmHistory._Form.dgv_AlarmData.Columns.Clear(); } } if (FrmHistory._Form.dgv_AlarmData.Rows != null) { if (FrmHistory._Form.dgv_AlarmData.Rows.Count > 0) { FrmHistory._Form.dgv_AlarmData.Rows.Clear(); } } } } /// /// 下拉框语言切换 /// public void DgvShiftItemsChange() { if (FrmHistory._Form != null) { FrmHistory._Form.cmb_SelectType.Items.Clear(); FrmHistory._Form.cmb_SelectType.Items.AddRange(new string[] { "包装箱进站".Translated(), /*"箱唛标签打印".Translated(),*/ "包装箱出站".Translated(), /*"栈板标签打印".Translated(),*/ "箱唛信息".Translated(), "栈板信息".Translated(), "箱唛码与栈板码绑定关系".Translated() }); FrmHistory._Form.cmb_SelectType.SelectedIndex = 0; FrmHistory._Form.cmbClass.Items.Clear(); FrmHistory._Form.cmbClass.Items.AddRange(new string[] { "白班".Translated(), "夜班".Translated() }); FrmHistory._Form.cmbClass.SelectedIndex = 0; //FrmHistory._Form.cmbYears.Items.Clear(); //FrmHistory._Form.cmbYears.Items.AddRange(new string[] { "白班".Translated(), "夜班".Translated() }); //FrmHistory._Form.cmbYears.SelectedIndex = 0; FrmHistory._Form.cmb_AlarmType.Items.Clear(); FrmHistory._Form.cmb_AlarmType.Items.AddRange(new string[] { "全天".Translated(), "白班".Translated(), "夜班".Translated() }); FrmHistory._Form.cmb_AlarmType.SelectedIndex = 0; } } private void ToolStripMenuItem_Click(object sender, EventArgs e) { FrmLogin frmLogin = new FrmLogin(); if (frmLogin.ShowDialog() == DialogResult.OK) { CommonMethods.sysConfig.SwipeCardMode = false; IniConfigHelper.WriteIniData("配置信息", "开启刷卡模式", CommonMethods.sysConfig.SwipeCardMode.ToString()); lbl_LoginLevel.Text = CommonMethods.currentAdmin?.LoginLevel; lbl_LoginName.Text = CommonMethods.currentAdmin?.LoginName; lbl_LoginName.Visible = true; //登录日志 CommonMethods.AddOPLog(false, $"登录成功,登录用户:{CommonMethods.currentAdmin?.LoginName},权限:{CommonMethods.currentAdmin?.LoginLevel}"); } } private void cmbModelType_Enter(object sender, EventArgs e) { if (cmbModelType.SelectedItem != null) { int index = CommonMethods.DropDownItemList.IndexOf(cmbModelType.SelectedItem); if (index == -1) cmbModelType.SelectedItem = null; } } } #region 枚举定义 public enum FormNames { 集中监控, 数据监控, 数据分析, 日志报警, 临界窗体, 数据追溯, 参数设置, 系统设置, 用户管理 } #endregion #region 消息筛选器 internal class MessageFilter : IMessageFilter { //0x0200:鼠标移动 //0x0202:鼠标左键UP //0x201:鼠标左键Down //0x0203:鼠标左键双击 //0x0205:鼠标右键UP //0x0204:鼠标右键Down //0x020a:鼠标滚轮 //0x100:键盘按下 public bool PreFilterMessage(ref System.Windows.Forms.Message m) { //throw new NotImplementedException(); if (m.Msg == 0x0200 || m.Msg == 0x0202 || m.Msg == 0x201 || m.Msg == 0x0203 || m.Msg == 0x0205 || m.Msg == 0x204 || m.Msg == 0x20a || m.Msg == 0x100) { CommonMethods.tickCount = 0; CommonMethods.tickHomeCount = 0; } return false; } } #endregion }