Files
602_FD/LargeSquareOne/FrmDataMonitor.cs
T
2025-09-18 11:11:38 +08:00

795 lines
30 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using HML;
using JinYuan.CommunicationLib.Enum;
using JinYuan.ControlCenters;
using JinYuan.Helper;
using JinYuan.MES.Models;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using Newtonsoft.Json;
using PLCCommunication;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LargeSquareOne
{
public partial class FrmDataMonitor : Form
{
private System.Threading.Timer m_RefreshTimer;
/// <summary>
/// 上料条码电池数据显示
/// </summary>
private BindingList<AGearEntity> listTA = new BindingList<AGearEntity>();
/// <summary>
/// 下料电池数据绑定委托
/// </summary>
/// <param name="m"></param>
private BindingList<BGearEntity> listTB = new BindingList<BGearEntity>();
public FrmDataMonitor()
{
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);
this.dgvFeedingData.AutoGenerateColumns = false;
this.dgvFeedingData.DataSource = listTA;
this.dgvFeedingData.DataError += delegate (object sender, DataGridViewDataErrorEventArgs e) { };
this.dgvFeedingData.DoubleBufferedDataGirdView(true);
this.dgvBlankingData.AutoGenerateColumns = false;
this.dgvBlankingData.DataSource = listTB;
this.dgvBlankingData.DataError += delegate (object sender, DataGridViewDataErrorEventArgs e) { };
this.dgvBlankingData.DoubleBufferedDataGirdView(true);
this.lVConfigRange.DoubleBufferedListView(true);
//this.lst_Info.DoubleBufferedListView(true);
//this.lis_Info.DoubleBufferedListBox(true);
btStop.Enabled = false;
//m_RefreshTimer = new System.Threading.Timer(TimerWork_Elapsed, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
//StartTimer(m_RefreshTimer);//开启刷新
this.FormClosing += (sender, e) =>
{
//this.updateTimer.Stop();
};
}
private void FrmDataMonitor_Load(object sender, EventArgs e)
{
btSatrt.Enabled = false;
dgvFeedingData.ClearSelection();
//dgvBlankingData.ClearSelection();
SetCombOrg();
IsNoOrg = true;
}
private string CurrentTime
{
get { return DateTime.Now.ToString("HH:mm:ss"); }
}
/// <summary>
/// 从数据库获取产品型号并绑定到下拉框中
/// </summary>
///
bool IsModelInit = false;
public void SetCombOrg()
{
try
{
txtMaterialCode.Text = "";
CommonMethods.mesConfig.MaterialCode = "";
var productList = CommonMethods.db.QuerySqlList<ProductModel>(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}");
}
}
public bool IsNoOrg = false;
public bool IsSetParam = false;
private void cmbModelType_SelectedItemsChanged(object sender, EventArgs e)
{
if (IsNoOrg && CommonMethods.IsLoginOk)
{
btSatrt.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<ParamList>(CommonMethods.dBSQL.GetParamSql(CommonMethods.mesConfig.ModelName));
if (list != null && list.Count > 0)
{
CommonMethods.paramlists = list;
IsSetParam = false;
GetParam();
}
}
catch (Exception ex)
{
LoggerHelp.WriteEX(ex);
}
}
/// <summary>
/// 刷新参数
/// </summary>
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)
{
LoggerHelp.WriteEX("获取参数失败", ex);
}
}
/// <summary>
/// 加载MES参数
/// </summary>
public bool GetMesParaData(ref string strErr)
{
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("更改后参数值");
string resJson = "";
var result = CommonMethods.hbgMes.GetParamSetRequest(CommonMethods.mesConfig.ParamSetpointRequestMesUrl, CommonMethods.mesConfig.equipNum, CommonMethods.mesConfig.siteCode,
CommonMethods.mesConfig.lineCode, CommonMethods.mesConfig.MaterialCode, CommonMethods.mesConfig.mesUserName, ref resJson);
var resultData = JsonConvert.DeserializeObject<ParamReturnData>(resJson);
if (!resultData.success)
{
//获取参数未成功 81022652
strErr = "获取MES参数不成功!";
return false;
}
List<ParamList> NewParamlists = CommonMethods.paramlists;
for (int i = 0; i < resultData.total; i++)
{
List<RowsItem> 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<object>.WriterCSV(filePath, fileName, fileTitle, fileContent);
CommonMethods.paramlists = NewParamlists;
int res = CommonMethods.db.Delete<ParamList>(it => it.ModelName == CommonMethods.paramlists[0].ModelName);
if (res > 0)
{
CommonMethods.db.AddReturnBool<ParamList>(CommonMethods.paramlists);
}
strErr = "变更成功并保存";
IsSetParam = false;
}
else
{
strErr = "取消变更,采用本地参数配置";
}
LoggerHelp.WriteLog(strErr);
}
}
}
return true;
}
catch (Exception ex)
{
strErr = "获取参数失败" + ex.Message;
LoggerHelp.WriteEX("获取参数失败", ex);
}
return false;
}
#region 显示外观检测上料数据
/// <summary>
/// 显示上料
/// </summary>
/// <param name="m"></param>
///
public void ShowFeedingData(List<AGearEntity> list)
{
try
{
if (this.dgvFeedingData.InvokeRequired)
{
this.dgvFeedingData.Invoke(new Action<List<AGearEntity>>(ShowFeedingData), list);
}
else
{
if (list != null && list.Count > 0)
{
foreach (AGearEntity m in list)
{
listTA.Add(m);
}
if (listTA.Count >= 500)
{
listTA.Clear();
GC.Collect();
}
}
// 设置最新行为活动行 (当前行)
int index = this.dgvFeedingData.Rows.Count - 1;
this.dgvFeedingData.CurrentCell = this.dgvFeedingData.Rows[index].Cells[0];
for (int i = 0; i < list.Count; i++)
{
this.dgvFeedingData.Rows[index - i].Cells[0].Value = index + 1 - i;
}
}
}
catch (Exception ex)
{
//ShowLog("显示上料出现" + ex.Message, 1);
}
}
#endregion
#region 显示下料数据
/// <summary>
/// 显示下料数据
/// </summary>
/// <param name="list"></param>
public void ShowBankdingData(List<BGearEntity> list)
{
try
{
if (this.dgvBlankingData.InvokeRequired)
{
this.dgvBlankingData.Invoke(new Action<List<BGearEntity>>(ShowBankdingData), list);
}
else
{
if (list != null && list.Count > 0)
{
foreach (BGearEntity m in list)
{
listTB.Add(m);
}
if (listTB.Count >= 500)
{
listTB.Clear();
GC.Collect();
}
}
// 设置最新行为活动行 (当前行)
int index = this.dgvBlankingData.Rows.Count - 1;
this.dgvBlankingData.CurrentCell = this.dgvBlankingData.Rows[index].Cells[0];
for (int i = 0; i < list.Count; i++)
{
this.dgvBlankingData.Rows[index - i].Cells[0].Value = index + 1 - i;
}
//int index = this.dgvBlankingData.Rows.Count - 1;
////this.dgvBlankingData.FirstDisplayedScrollingRowIndex = index;
//// 设置最新行为活动行 (当前行)
//this.dgvBlankingData.CurrentCell = this.dgvBlankingData.Rows[index].Cells[1];
//this.dgvBlankingData.BeginEdit(true);
}
}
catch (Exception ex)
{
//ShowLog("显示上料出现" + ex.Message, 1);
}
}
#endregion
/// <summary>
/// 开始监控
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btSatrt_Click(object sender, EventArgs e)
{
if (!CommonMethods.IsLoginOk)
{
new FrmMsgBoxOutWithAck(2, "当前未登录,请登录!", "未登录").Show();
return;
}
if (CommonMethods.sysConfig.MesModeSwitching && !CommonMethods.mesConfig.IsLoginMesOK)
{
new FrmMsgBoxOutWithAck(2, "当前为MES模式,请登录!", "MES未登录").ShowDialog();
FrmLoginMes frmLoginMes = new FrmLoginMes();
if (frmLoginMes.ShowDialog() != DialogResult.OK) { return; }
}
if (CommonMethods.mesConfig.ModelName == "")
{
new FrmMsgBoxOutWithAck(2, "产品型号不能为空!", "型号选择").Show();
return;
}
if (txtMaterialCode.Text.Trim() == "")
{
new FrmMsgBoxOutWithAck(2, "物料编码不能为空!", "型号选择").Show();
return;
}
#region MES下发参数
CommonMethods.mesConfig.MaterialCode = txtMaterialCode.Text.Trim();
if (CommonMethods.sysConfig.MesModeSwitching && CommonMethods.mesConfig.IsMesParam)
{
string strErr = "";
bool nb = GetMesParaData(ref strErr);
if (!nb)
{
new FrmMsgBoxOutWithAck(2, strErr, "提示").Show();
return;
}
CommonMethods.AddDataMonitorLog(1, "MES参数设置成功");
LoggerHelp.WriteLog("MES参数设置成功");
}
#endregion
CommonMethods.AddDataMonitorLog(0, "启动开始监控");
btSatrt.Text = "连接PLC中…";
bool IsLink = CommonMethods.ConnectPLC();
bool IsGrading = CommonMethods.WriteGrading();
if (IsLink && IsGrading)
{
OmronStart(true);
CommonMethods.IsRun = true;
if (CommonMethods.plcDevice.IsConnected)
{
btSatrt.Text = "开始监控";
SetProductModelEnable(true);
Task.Run(() =>
{
SendRightToPLC();
});
}
}
else
{
btSatrt.Text = "开始监控";
CommonMethods.AddDataMonitorLog(2, "启动开始监控失败");
new FrmMsgBoxOutWithAck(2, "连接PLC失败,请检查PLC连接配置,网络", "连接PLC").Show();
}
}
/// <summary>
/// 停止监控
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btStop_Click(object sender, EventArgs e)
{
if (CommonMethods.IsRun)
{
SetProductModelEnable(false);
OmronStart(false);
CommonMethods.Statues = new List<bool> { false, false, false, false };
CommonMethods.PlcLink.Disconnect();
CommonMethods.plcDevice.IsConnected = false;
CommonMethods.IsRun = false;
CommonMethods.AddDataMonitorLog(2, "停止与PLC连接");
CommonMethods.AddOPLog(false, "停止与PLC连接!");
}
}
/// <summary>
/// 链接PLC状态
/// </summary>
/// <param name="status"></param>
public void OmronStart(bool status)
{
if (status)
{
CommonMethods.ResetEventRecv.Set();
}
else
{
CommonMethods.ResetEventRecv.Reset();
}
}
/// <summary>
/// 设置产品型号和工单是否只读
/// </summary>
/// <param name="b"></param>
public void SetProductModelEnable(bool b)
{
btSatrt.Enabled = !b;
btStop.Enabled = b;
cmbModelType.Enabled = true;
txtMaterialCode.Enabled = !b;
}
private void dgvFeedingData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
//显示序列号
DataGridViewHelper.DgvRowPostPaint(this.dgvFeedingData, e);
}
private void dgvFeedingData_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
//指定列字体颜色
DataGridViewHelper.DgvRowPrePaint(this.dgvFeedingData, "InResult", sender, e);
}
private void dgvBlankingData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
//显示序列号
DataGridViewHelper.DgvRowPostPaint(this.dgvBlankingData, e);
}
private void dgvBlankingData_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
//指定列字体颜色
DataGridViewHelper.DgvRowPrePaint(this.dgvBlankingData, "OutResult", sender, e);
}
#region 减少闪烁
protected override CreateParams CreateParams
{
get
{
CreateParams parss = base.CreateParams;
parss.ExStyle |= 0x02000000;
return parss;
}
}
#endregion
#region
StringFormat sf = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center };//字体水平位置居左,垂直居中
private void lVConfigRange_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
e.Graphics.FillRectangle(Brushes.RoyalBlue, e.Bounds); //设置背景颜色
Font font = new Font("微软雅黑", 12, FontStyle.Bold); //设置字体大小
e.Graphics.DrawString(e.Header.Text, font, Brushes.White, e.Bounds, sf); //设置字体颜色
}
private void lVConfigRange_DrawItem(object sender, DrawListViewItemEventArgs e)
{
e.DrawDefault = true; //采用系统默认方式绘制项
}
private void lVConfigRange_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
e.DrawDefault = true; //采用系统默认方式绘制项
}
#endregion
#region ListView日志记录
//public void AddDataMonitorLog(int level, string log)
//{
// if (level > 2)
// {
// level = 2;
// }
// if (level < 0)
// {
// level = 0;
// }
// if (this.lst_Info.InvokeRequired)
// {
// this.lst_Info.Invoke(new Action<int, string>(AddDataMonitorLog), level, log);
// }
// else
// {
// if (this.lst_Info.Items.Count > 1000)
// {
// this.lst_Info.Items.Clear();
// }
// System.Windows.Forms.ListViewItem item = new System.Windows.Forms.ListViewItem(" " + CurrentTime, level);
// item.SubItems.Add(log);
// this.lst_Info.Items.Add(item);
// //让最新的日志显示在最下面
// this.lst_Info.Items[this.lst_Info.Items.Count - 1].EnsureVisible();
// }
//}
#endregion
#region RichTextBox日志记录
public void AddDataMonitorLog(int level, string log)
{
if (level > 2)
{
level = 2;
}
if (level < 0)
{
level = 0;
}
if (this.rtb_Info.InvokeRequired)
{
this.rtb_Info.Invoke(new Action<int, string>(AddDataMonitorLog), level, log);
}
else
{
if (rtb_Info.Lines.Length > 200) //每当显示的通知数超过200行时,清除前面的150行
{
string[] strlines = new string[rtb_Info.Lines.Length - 150];
Array.ConstrainedCopy(rtb_Info.Lines, 50, strlines, 0, strlines.Length);
rtb_Info.Lines = strlines;
GC.Collect();
}
rtb_Info.SelectionStart = rtb_Info.Text.Length;
rtb_Info.SelectionLength = log.Length;
rtb_Info.SelectionColor = level == 0 ? Color.White : Color.Red;
rtb_Info.AppendText(string.Format("时间:{0}-{1}\r\n", DateTime.Now.ToString("HH:mm:ss.fff"), log));
rtb_Info.SelectionStart = rtb_Info.Text.Length;
rtb_Info.SelectionLength = log.Length;
rtb_Info.Focus();
}
}
#endregion
#region ListBox日志记录
//public void AddDataMonitorLog(int level, string log)
//{
// Color color = Color.White;
// if (level > 2)
// {
// color= Color.Red;
// level = 2;
// }
// if (level < 0)
// {
// color = Color.White;
// level = 0;
// }
// if (this.lis_Info.InvokeRequired)
// {
// this.lis_Info.Invoke(new Action<int, string>(AddDataMonitorLog), level, log);
// }
// else
// {
// this.lis_Info.AddLog(log, color);
// this.lis_Info.SelectedIndex = this.lis_Info.Items.Count - 1;
// this.lis_Info.SelectedIndex = -1;
// //System.Windows.Forms.ListViewItem item = new System.Windows.Forms.ListViewItem(" " + CurrentTime, level);
// //item.SubItems.Add(log);
// //this.rtb_Info.Items.Add(item);
// ////让最新的日志显示在最下面
// //this.rtb_Info.Items[this.lst_Info.Items.Count - 1].EnsureVisible();
// }
//}
#endregion
#region 下发权限给PLC
/// <summary>
/// 下发权限到PLC
/// </summary>
public void SendRightToPLC()
{
ushort quanxian = 1;
switch (CommonMethods.currentAdmin.LoginLevel)
{
case "操作员":
quanxian = 1;
break;
case "工程师":
quanxian = 2;
break;
case "管理员":
quanxian = 3;
break;
default:
break;
}
if (CommonMethods.plcDevice.IsConnected)
{
JYResult result = CommonMethods.PlcLink.WriteValue("D21", (short)quanxian, Data_Type.Short);
if (result.IsSuccess)
{
CommonMethods.AddOPLog(false, $"写入PLC权限(D21)-成功:{quanxian},{CommonMethods.currentAdmin.LoginLevel}");
}
else
{
CommonMethods.AddOPLog(true, $"写入PLC权限(D21)-失败");
}
}
}
#endregion
private void dgvFeedingData_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dgvBlankingData_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}