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 PLCCommunication;
using PLCCommunication.Common;
using PLCCommunication.Modbus;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.IO.Ports;
using System.Linq;
using System.Net;
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();
Font myFont = null;
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;
// 加载字体文件
//font.AddFontFile(Environment.CurrentDirectory + "\\Assts\\Fonts\\FZY4JW.ttf");
////定义成新的字体对象
//System.Drawing.FontFamily myFontFamily = new System.Drawing.FontFamily(font.Families[0].Name, font);
//myFont = new Font(myFontFamily, 16, System.Drawing.FontStyle.Regular);
//lblSubtitle.Font = myFont;
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();
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);
//2.打开图表窗体
CommonNaviButton_Click(this.nav_Monitor, null);
//打开集中监控窗体
CommonNaviButton_Click(this.nav_DataMonitor, null);
//登录日志
CommonMethods.AddOPLog(false, "登录成功".Translated() + "," + "登录用户".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();
}
}
#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.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"));
}
//CommonMethods.ProdDRFIDNgQty = Convert.ToInt32(IniConfigHelper.ReadIniData("统计计数", "ProdDRFIDNgQty", "0"));
//CommonMethods.ProdDXNgQty = Convert.ToInt32(IniConfigHelper.ReadIniData("统计计数", "ProdDXNgQty", "0"));
//CommonMethods.ProdGRFIDNgQty = Convert.ToInt32(IniConfigHelper.ReadIniData("统计计数", "ProdGRFIDNgQty", "0"));
//CommonMethods.ProdYLZNgQty = Convert.ToInt32(IniConfigHelper.ReadIniData("统计计数", "ProdYLZNgQty", "0"));
//读取电表配置
CommonMethods.IsStartZNDB = Convert.ToBoolean(CommonMethods.GetConfigValue(CommonMethods.Configxml, "ElectricityMeter", "IsEnableEM", "false"));
int EMCount = Convert.ToInt32(CommonMethods.GetConfigValue(CommonMethods.Configxml, "ElectricityMeter", "EMCount", "0"));
if (CommonMethods.IsStartZNDB && EMCount > 0)
{
string stopBits = CommonMethods.GetConfigValue(CommonMethods.Configxml, "ElectricityMeter", $"EMStopBits", "");
string parity = CommonMethods.GetConfigValue(CommonMethods.Configxml, "ElectricityMeter", $"EMParity", "");
string baudRate = CommonMethods.GetConfigValue(CommonMethods.Configxml, "ElectricityMeter", $"EMBaudRate", "");
string dataBits = CommonMethods.GetConfigValue(CommonMethods.Configxml, "ElectricityMeter", $"EMDataBits", "");
for (int i = 0; i < EMCount; i++)
{
string portName = CommonMethods.GetConfigValue(CommonMethods.Configxml, "ElectricityMeter", $"EMPortName{i}", "");
if (portName != "")
{
ModbusRtu busRtuClient = new ModbusRtu();
busRtuClient.SerialPortInni(sp =>
{
sp.PortName = portName;
sp.BaudRate = Convert.ToInt32(baudRate);
sp.DataBits = Convert.ToInt32(dataBits);
sp.StopBits = ParseStopBits(stopBits);
sp.Parity = ParseParity(parity);
});
CommonMethods.EM_modbusRtus.Add(busRtuClient);
CommonMethods.EM_ComResult.Add(false);
}
}
}
}
#endregion
private StopBits ParseStopBits(string stopBits)
{
return stopBits switch
{
"1" => StopBits.One,
"1.5" => StopBits.OnePointFive,
"2" => StopBits.Two,
_ => StopBits.One
};
}
private Parity ParseParity(string parity)
{
return parity.ToUpper() switch
{
"0" => Parity.None,
"2" => Parity.Even,
"1" => Parity.Odd,
_ => Parity.None
};
}
#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)
{
this.BeginInvoke(() => LockWorkStation());
}
}
if (CommonMethods.sysConfig.AutoQieHuanM)
{
CommonMethods.tickHomeCount++;
if (CommonMethods.tickHomeCount >= CommonMethods.sysConfig.QieHuanMPeriod * 60 * 1000 / this.updateTimer.Interval)
{
this.BeginInvoke((Action)(() => CommonNaviButton_Click(this.nav_Monitor, null)));
}
}
});
}
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;
}
else
{
this.DialogResult = DialogResult.OK;
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 + " " + $"{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;
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)
{
CommonMethods.listener.Stop();
//关闭线程
CommonMethods.IsExit = true;
ControlCenter.Instance._cts?.Cancel();
Thread.Sleep(500);
this.Dispose();//清理正在使用的资源 `在这里插入代码片`
System.Environment.Exit(0);//退出全部线程
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
else
{
e.Cancel = true;
}
}
}
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;
//if (!CommonMethods.currentAdmin.CpkData)
//{
// new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足!", "权限不足").ShowDialog();
// return;
//}
//break;
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);
//设置Title
//SetTitle(this.lbl_Title, 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).ShowBankdingData;//下料显示
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.devPath);
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;
//置前
frm.BringToFront();
frm.Show();
}
}
}
///
/// 设置标题内容
///
/// 标题控件
/// 窗体枚举名称
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;
}
#region MES下发参数
CommonMethods.mesConfig.MaterialCode = txtMaterialCode.Text.Trim();
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());
CommonMethods.AddOPLog(false, "连接PLC".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);
if (CommonMethods.IsStartZNDB)//连接电表
{
if (CommonMethods.EM_modbusRtus != null && CommonMethods.EM_modbusRtus.Count > 0)
{
for (int i = 0; i < CommonMethods.EM_modbusRtus.Count; i++)
{
if (!CommonMethods.EM_ComResult[i])
{
CommonMethods.EM_modbusRtus[i].Open();
CommonMethods.EM_ComResult[i] = CommonMethods.EM_modbusRtus[i].IsOpen();
if (CommonMethods.EM_ComResult[i])
CommonMethods.AddDataMonitorLog(0, $"电表{i + 1}连接成功");
else
CommonMethods.AddDataMonitorLog(0, $"电表{i + 1}连接失败");
}
}
}
}
}
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;
if (CommonMethods.IsStartZNDB)//连接电表
{
for (int i = 0; i < CommonMethods.EM_modbusRtus.Count; i++)
{
if (CommonMethods.EM_ComResult[i])
{
CommonMethods.EM_modbusRtus[i].Close();
if (!CommonMethods.EM_modbusRtus[i].IsOpen())
{
CommonMethods.EM_ComResult[i] = false;
CommonMethods.AddDataMonitorLog(0, $"电表{i + 1}连接已关闭");
}
else
CommonMethods.AddDataMonitorLog(0, $"电表{i + 1}连接失败。");
}
}
}
}
}
}
///
/// 设置产品型号和工单是否只读
///
///
public void SetProductModelEnable(bool b)
{
cmbModelType.Enabled = true;
}
#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();
for (int i = 0; i < productList.Count; i++)
{
list.Add(new DropDownListPlusItem() { Text = productList[i].ModelName, Tag = productList[i].MaterialCode });
}
this.cmbModelType.BindItemsSource(list);
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