Files
2026-05-29 10:07:05 +08:00

1448 lines
51 KiB
C#
Raw Permalink 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 BasicData;
using bizFacade;
using OpcData;
using System;
using System.Collections;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using SystemFramework;
using System.Drawing;
using MesServerWork;
using System.Configuration;
using MisDataFunction;
using System.Collections.Generic;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Receiving;
using System.Linq;
using OpcBasic;
using System.Collections.Concurrent;
using MesWork;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
/// <summary>
///
/// </summary>
namespace MisDataName
{
/// <summary>
///
/// </summary>
/// <param name="obj1"></param>
/// <param name="obj2"></param>
public delegate void RefreshForm(object obj1, EventArgs obj2);
/// <summary>
///
/// </summary>
public partial class MisData : MIS_BASE
{
/// <summary>
///
/// </summary>
public static string BasicDataTableFile = ConfigurationManager.AppSettings["BasicDataTableFile"];
/// <summary>
///
/// </summary>
public static int IsDemoMesServer = Convert.ToInt32(ConfigurationManager.AppSettings["IsDemoMesServer"]);
/// <summary>
///
/// </summary>
public static string MqttUrl = ConfigurationManager.AppSettings["MqttUrl"];
//public static string MqttUrlPLC = ConfigurationManager.AppSettings["MqttUrlPLC"];
/// <summary>
///
/// </summary>
public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"];
public static string MqttTargetTopicPLC = ConfigurationManager.AppSettings["MqttTargetTopicPLC"];
/// <summary>
///
/// </summary>
public static int IsWriteMonitorLog = Convert.ToInt32(ConfigurationManager.AppSettings["IsWriteMonitorLog"]);
/// <summary>
///
/// </summary>
public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"];
/// <summary>
///
/// </summary>
public static int WebApiPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WebApiPort"]);
/// <summary>
///
/// </summary>
public static RefreshForm MainFormRefresh, TestPlcStatusDel;
/// <summary>
/// 允许使用附加功能的变量只有在系统开始加载Tag时才允许读取PLC数据
/// </summary>
public static bool AllowLoad;
/// <summary>
///
/// </summary>
public MisData()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
this.Cursor = Cursors.WaitCursor;
TopMost = true;
Never_Know.Hello_You_All_Never_Know = Hello_You_All_Never_Know;
new ApplicationLog();
ThreadPool.SetMaxThreads(1000, 500);
MIS_BASE.MqttTargetTopic = MqttTargetTopic;
MIS_BASE.MqttTargetTopicPLC = MqttTargetTopicPLC;
new DataLinkMesWork.ApplicationConfig();
DataTable dt_Signal;
DataTable dt_Device;
DataTable dt_TagTypeDataType;
dt_Signal = bizFacade.BaseDataSystemMES.dt_Signal();
dt_Device = bizFacade.BaseDataSystemMES.dt_Device();
dt_TagTypeDataType = bizFacade.BaseDataSystemMES.dt_TagTypeDataType();
//if (LoadOPCData(BasicDataTableFile, IsDemoMesServer, IsWriteMonitorLog, true))
if (LoadOPCData(dt_Signal, dt_Device, IsDemoMesServer, IsWriteMonitorLog, true))
{
//MisData_SyncRawData();
MesDataFunction.LoadTagTypeCodeID.Load(dt_TagTypeDataType);
//MesDataFunction.LoadTagTypeCodeID.Load(BasicDataTableFile);
showMessagePLCInvoke = new ShowMessagePLCInvoke(ShowMessagePLC);
TestPlcConnectInit();
MainFormRefresh = new RefreshForm(button_ReadData_Click);
QueryMainFormPosition = new QueryFormData(QueryFormPosition);
MainActived = new MainAct(this.Activate);
TestPlcStatusDel = new RefreshForm(RefreshPlcConnectStatus);
AssemblyManagement.InitAssembly_Recycle();
new InitTagValueListData();
//设备保养通知计划:设备保养通知计划调度
InitMachinePlan(new MachinePlan_Invoke(MachinePlan));
if (IsDemoMesServer == 1)
{
toolStripStatusLabel_RunningStatus.Text = "变量模拟";
toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow;
}
else
{
toolStripStatusLabel_RunningStatus.Text = "PLC";
toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Green;
}
StartTime = Convert.ToDateTime(toolStripStatusLabel_StartTime.Text = DateTime.Now.ToString());
Runtime_Thread();
//查询出“全部原始基本数据列表”
var drs = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 变量类型代码=101 or 变量类型代码 = 102 or 变量类型代码 = 105 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'");
if(drs.Length>1)
{
BasicDataTagValue = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 变量类型代码=101 or 变量类型代码 = 102 or 变量类型代码 = 105 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'").CopyToDataTable<DataRow>();
if (BasicDataTagValue.Columns.Contains("上限值"))
{
BasicDataTagValue.Columns["上限值"].ColumnName = "值上限";
}
if (BasicDataTagValue.Columns.Contains("下限值"))
{
BasicDataTagValue.Columns["下限值"].ColumnName = "值下限";
}
}
// BasicDataTagValue = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'").CopyToDataTable<DataRow>();
//查询出“MES_基本数据_测量范围”
BasicDataTagValueUpDown = MesWork.PlcLinkForm.dt_BasicData;
if (BasicDataTagValueUpDown.Columns.Contains("上限值"))
{
BasicDataTagValueUpDown.Columns["上限值"].ColumnName = "值上限";
}
if (BasicDataTagValueUpDown.Columns.Contains("下限值"))
{
BasicDataTagValueUpDown.Columns["下限值"].ColumnName = "值下限";
}
// 模拟时,写入质量数据
InitBasicDataTagValue();
// 变量代码与其他字段的对应关系
InitHashtableTagID();
this.Cursor = Cursors.Default;
Cbx_StatusDisplay_CheckedChanged(null, null);
AllowLoad = true;
Cbx_StatusDisplay.Enabled = true;
button_ReadData_Click(null, null);
timer_TestPLC.Enabled = true;
EToolStripMenuItem_EquipAlarm_Click(null, null);
timer_LoadOver.Enabled = true;
TopMost = false;
// Thread.Sleep(200);
//First_TagMonitor(); //开启发送监控变量第一次的值
// Thread.Sleep(200);
// Init_TagMonitor(); //开启初始化监控变量
Thread.Sleep(200);
var deviceState = StartServer(WebApiPort); //开启监控服务
loadFinish = true;
InitcomboBox_OpName();
//初始化程序集列表
InitProgramFunctionAssembly();
WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString();
ListBox1_Item_Init();
}
}
/// <summary>
/// 模拟时,写入质量数据
/// </summary>
private void InitBasicDataTagValue()
{
if (IsDemoMesServer != 1) return;
string tagID;
double tagValue;
//写工位总合格标志 变量类型代码=21
for (int i = 0; i < MesWork.PlcLinkForm.dt_BasicData.Rows.Count; i++)
{
if(MesWork.PlcLinkForm.dt_BasicData.Rows[i]["变量类型代码"].ToString()=="21")
{
tagID = MesWork.PlcLinkForm.dt_BasicData.Rows[i]["TagID"].ToString();
WritePLC(tagID, 1);
}
}
if(BasicDataTagValue!=null)
{
for (int i = 0; i < BasicDataTagValue.Rows.Count; i++)
{
try
{
switch (Convert.ToInt32(BasicDataTagValue.Rows[i]["变量特点"]))
{
case 7:
tagID = BasicDataTagValue.Rows[i]["TagID"].ToString();
WritePLC(tagID, 1);
break;
case 6:
tagID = BasicDataTagValue.Rows[i]["TagID"].ToString();
tagValue = Convert.ToDouble(BasicDataTagValue.Rows[i]["列位置"]) * 100
+ Convert.ToDouble(BasicDataTagValue.Rows[i]["变量排序"]) / 100;
WritePLC(tagID, tagValue);
break;
}
}
catch { }
}
}
}
static bool loadFinish = false;
/// <summary>
/// 初始化Function对应的程序集
/// </summary>
void InitProgramFunctionAssembly()
{
int mesServerCode=0;
string mesServerdllName="";
System.Reflection.Assembly assembly = null;
foreach (var opName in opNameList)
{
try
{
mesServerCode = GetMesServerCodeByOpName(opName);
mesServerdllName = GetMesServeDllByOpName(opName);
assembly = System.Reflection.Assembly.Load(mesServerdllName);
if (assembly == null)
{
// return;
}
if (!MesDataFunction.OpcOperation.Hashtable_assembly.ContainsKey(mesServerdllName))
{
MesDataFunction.OpcOperation.Hashtable_assembly.Add(mesServerdllName, assembly);
}
}
catch (Exception err)
{
if (!MesDataFunction.OpcOperation.Hashtable_assembly.ContainsKey(mesServerdllName))
{
MesDataFunction.OpcOperation.Hashtable_assembly.Add(mesServerdllName, null);
}
ApplicationLog.WriteLog(err, err.Message);
}
}
}
List<String> opNameList;
/// <summary>
/// 初始化comboBox_OpName工位号
/// </summary>
private void InitcomboBox_OpName()
{
//全部工位号
comboBox_OpName.DataSource = opNameList = MesWork.PlcLinkForm.opNameList;
FunctionForm_HashiTable.OpName_Hash_Write("OpNameList", opNameList);
toolStripStatusLabel_WorkStationNum.Text = MesWork.PlcLinkForm.opNameList.Count.ToString();
toolStripStatusLabel_DownLine.Text = toolStripStatusLabel_WorkStationNum.Text;
}
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
try
{
string cmd;
string opName;
string tagValue;
string[] strList;
if (listBox1.Text != null)
{
strList = listBox1.Text.Split('|');
if (strList.Length >= 4)
{
cmd = strList[1];
opName = strList[2];
tagValue = strList[3];
textBox_Cmd.Text = cmd;
textBox_tagValue.Text = tagValue;
}
}
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
private void button_Write_Click(object sender, EventArgs e)
{
try
{
short tagValue_int;
string tagValue_str;
byte tagValue_byte;
bool tagValue_bool;
int tagType;
int tagDataType;
string cmd = textBox_Cmd.Text;
string opName = WorkStationNum_Now;
string tagValue = textBox_tagValue.Text;
tagType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagType[cmd]);
tagDataType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagTypeDataType[tagType.ToString()]);
switch (tagDataType)
{
case 2:
tagValue_int = Convert.ToInt16(tagValue);
WriteAnyData_Thread(tagType, opName, tagValue_int);
break;
case 8:
tagValue_str = tagValue.ToString();
WriteAnyData_Thread(tagType, opName, tagValue_str);
break;
case 17:
tagValue_byte = Convert.ToByte(tagValue);
WriteAnyData_Thread(tagType, opName, tagValue_byte);
break;
case 11:
tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue));
WriteAnyData_Thread(tagType, opName, tagValue_bool);
break;
}
}
catch (Exception err)
{
MessageBox.Show("输入命令异常,请重新输入!");
ApplicationLog.WriteLog(err, err.Message);
}
}
private void button_Read_Click(object sender, EventArgs e)
{
try
{
int tagType;
string cmd = textBox_Cmd.Text;
string opName = WorkStationNum_Now;
string tagValue = textBox_tagValue.Text;
tagType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagType[cmd]);
QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, textBox_tagValue_Read);
Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ByTagType_Thread));
t.Start(QualityStruct);
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
void ReadPLC_ByTagType_Thread(object obj)
{
try
{
QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj;
TextBox tbx = (TextBox)QualityStruct.Ctrl;
tbx.Text = ReadPLC(QualityStruct.tagType, QualityStruct.OpName).ToString();
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
bool isWorkStart;
private void timer_WorkStart_Tick(object sender, EventArgs e)
{
if (isWorkStart)
isWorkStart = false;
else
isWorkStart = true;
if (isWorkStart)
{
textBox_tagValue.Text = "1";
button_Write_Click(null, null);
}
else
{
textBox_tagValue.Text = "0";
button_Write_Click(null, null);
}
}
private void checkBox_WorkStart_CheckedChanged(object sender, EventArgs e)
{
if (textBox_Cmd.Text == "" && checkBox_WorkStart.Checked)
{
MessageBox.Show("请选择命令");
checkBox_WorkStart.Checked = false;
return;
}
if (checkBox_WorkStart.Checked)
{
timer_WorkStart.Enabled = true;
listBox1.Enabled = false;
textBox_Cmd.ReadOnly = true;
}
else
{
timer_WorkStart.Enabled = false;
listBox1.Enabled = true;
textBox_Cmd.ReadOnly = false;
}
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
timer_WorkStart.Interval = Convert.ToInt32(numericUpDown1.Value) * 1000;
}
static Thread ReadQuality_t = null;
private void ReadQualityData(string opName)
{
try
{
if (ReadQualityRunning) return;
ReadQualityRunning = true;
QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData);
ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread));
ReadQuality_t.Start(QltyQueryStr);
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
static bool ReadQualityRunning = false;
void ReadQualityData_Thread(object obj)
{
int fTime = 0;
try
{
QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj;
ListView listViewTemp = (ListView)QualityStruct.Ctrl;
ListViewItem listViewItem = null;
string[] listViewItemString = new string[4];
if (listViewTemp.InvokeRequired)
{
Action ActionDelegate = () => { listViewTemp.Items.Clear(); };
listViewTemp.Invoke(ActionDelegate);
}
else
{
listViewTemp.Items.Clear();
}
//System.Collections.Concurrent.ConcurrentDictionary<string, object> cd = null;
IEnumerable cd = null;
//IEnumerable<string,object> items;
string opName = QualityStruct.OpName;
var opTagList = GetDbAndMaxLengthByOpNameByBytes(opName);
//TagID 排序
//var cd_OpName = opTagList.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value);
//全部数据
var cd_OpName = from r in opTagList
orderby r.Key
select r;
//质量数据
var query_Qd = from r in opTagList
where ((OpcBasic.TagFormat)r.Value).TagTypeCodeID == 105
orderby r.Key
select r;
//监控变量
var query_Monitor = from r in opTagList
where ((OpcBasic.TagFormat)r.Value).TagTypeCodeID != 105
orderby r.Key
select r;
if (cb_MonitorData.Checked)
{
cd = query_Monitor;
//cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName);
}
if (cb_QdData.Checked)
{
cd = query_Qd;
//cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName);
}
if (cb_MonitorData.Checked == false & cb_QdData.Checked == false)
{
cd = cd_OpName;
//cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName);
}
if (cb_MonitorData.Checked == true & cb_QdData.Checked == true)
{
cd = cd_OpName;
//cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName);
}
//排序
var result2 = cd;// from pair in cd orderby pair.Key select pair;
ThisWorkStationData = new QualityDataType[1000];
foreach (KeyValuePair<string, object> _cd in result2)
{
var tagID = _cd.Key;
var TF = (OpcBasic.TagFormat)_cd.Value;
listViewItemString[0] = TF.OpName;
listViewItemString[3] = TF.TagID;
listViewItemString[1] = TF.ItemName;
listViewItemString[2] = TF.TagValue.ToString();
listViewItem = new ListViewItem(listViewItemString);
if (TF.IsMonitor == 1)
{
listViewItem.BackColor = Color.LimeGreen;
}
if (listViewTemp.InvokeRequired)
{
Action<ListViewItem> ActionDelegate = (x) => { listViewTemp.Items.Add(x); };
listViewTemp.BeginInvoke(ActionDelegate, listViewItem);
}
else
{
listViewTemp.Items.Add(listViewItem);
}
ThisWorkStationData[fTime].opName = TF.OpName;
ThisWorkStationData[fTime].tagID = TF.TagID;
ThisWorkStationData[fTime].tagTypeID = TF.TagTypeID;
ThisWorkStationData[fTime].tagValue = TF.TagValue;
fTime++;
}
ReadQualityRunning = false;
}
catch (Exception err)
{
ReadQualityRunning = false;
ApplicationLog.WriteLog(err, err.Message);
}
}
void ReadQualityData_ThreadBak(object obj)
{
//int fTime = 0;
//try
//{
// QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj;
// QualityDataType[] Array_value;
// Array_value = Sort(ReadPLC_ValueListForQualityDataTypeArray(QualityStruct.OpName));
// ThisWorkStationData = Array_value;
// ListView listViewTemp = (ListView)QualityStruct.Ctrl;
// ListViewItem listViewItem = null;
// string[] listViewItemString = new string[4];
// if (listViewTemp.InvokeRequired)
// {
// Action ActionDelegate = () => { listViewTemp.Items.Clear(); };
// listViewTemp.Invoke(ActionDelegate);
// }
// else
// {
// listViewTemp.Items.Clear();
// }
// for (int i = 0; i < Array_value.Length; i++)
// {
// if (Array_value[i].tagValueType == 79 || Array_value[i].tagValueType == 8 || Array_value[i].tagValueType == 51) continue;
// listViewItemString[0] = Array_value[i].opName;
// listViewItemString[3] = Array_value[i].tagID.ToString();
// listViewItemString[1] = InitTagValueListData.ItemValue_Hash[Array_value[i].tagID].ToString();
// if (Array_value[i].tagValue != null)
// {
// listViewItemString[2] = Array_value[i].tagValue.ToString();
// }
// listViewItem = new ListViewItem(listViewItemString);
// if (listViewTemp.InvokeRequired)
// {
// Action<ListViewItem> ActionDelegate = (x) => { listViewTemp.Items.Add(x); };
// listViewTemp.BeginInvoke(ActionDelegate, listViewItem);
// }
// else
// {
// listViewTemp.Items.Add(listViewItem);
// }
// ThisWorkStationData[fTime] = Array_value[i];
// fTime++;
// }
// ReadQualityRunning = false;
//}
//catch (Exception err)
//{
// ReadQualityRunning = false;
// ApplicationLog.WriteLog(err, err.Message);
//}
int fTime = 0;
try
{
QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj;
ListView listViewTemp = (ListView)QualityStruct.Ctrl;
ListViewItem listViewItem = null;
string[] listViewItemString = new string[4];
if (listViewTemp.InvokeRequired)
{
Action ActionDelegate = () => { listViewTemp.Items.Clear(); };
listViewTemp.Invoke(ActionDelegate);
}
else
{
listViewTemp.Items.Clear();
}
System.Collections.Concurrent.ConcurrentDictionary<string, object> cd = null;
if (cb_MonitorData.Checked)
{
cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName);
}
if (cb_QdData.Checked)
{
cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName);
}
if (cb_MonitorData.Checked == false & cb_QdData.Checked == false)
{
cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName);
}
if (cb_MonitorData.Checked == true & cb_QdData.Checked == true)
{
cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName);
}
//排序
var result2 = from pair in cd orderby pair.Key select pair;
ThisWorkStationData = new QualityDataType[cd.Count];
//var sortResult2 = from pair in cd orderby pair.Key descending select pair;
//cd.o.OrderBy(p => p.Value.Speed);
//foreach (KeyValuePair<string, object> _cd in cd)
foreach (KeyValuePair<string, object> _cd in result2)
{
var tagID = _cd.Key;
var TF = (OpcBasic.TagFormat)_cd.Value;
listViewItemString[0] = TF.OpName;
listViewItemString[3] = TF.TagID;
listViewItemString[1] = TF.ItemName;
listViewItemString[2] = TF.TagValue.ToString ();
listViewItem = new ListViewItem(listViewItemString);
if (TF.IsMonitor == 1)
{
listViewItem.BackColor = Color.LimeGreen;
}
if (listViewTemp.InvokeRequired)
{
Action<ListViewItem> ActionDelegate = (x) => { listViewTemp.Items.Add(x); };
listViewTemp.BeginInvoke(ActionDelegate, listViewItem);
}
else
{
listViewTemp.Items.Add(listViewItem);
}
ThisWorkStationData[fTime].opName = TF.OpName;
ThisWorkStationData[fTime].tagID = TF.TagID;
ThisWorkStationData[fTime].tagTypeID = TF.TagTypeID;
ThisWorkStationData[fTime].tagValue = TF.TagValue;
fTime++;
}
ReadQualityRunning = false;
}
catch (Exception err)
{
ReadQualityRunning = false;
ApplicationLog.WriteLog(err, err.Message);
}
}
private void button_ReadData_Click(object sender, EventArgs e)
{
if (loadFinish)
{
ReadQualityData(WorkStationNum_Now);
}
}
private void comboBox_OpName_SelectedIndexChanged(object sender, EventArgs e)
{
//此处需要异步查询当前工位在线状态
try
{
if (AllowLoad)
{
WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString();
InitFormBtnColor();//初始化按钮颜色
initStationStatus();//初始化工位状态栏
ListBox1_Item_Init();
if (Cbx_StatusDisplay.Checked)
{
ReadPLC_ProductInfo();//读取PLC状态
ReadMES_ProductInfo();//读取MES状态
button_ReadData_Click(null, null);
}
}
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
private void listView_ShowQualityData_MouseDoubleClick(object sender, MouseEventArgs e)
{
try
{
QualityDataType SelectData = new QualityDataType();
ListView.SelectedIndexCollection index = new ListView.SelectedIndexCollection(listView_ShowQualityData);
SelectData = ThisWorkStationData[index[0]];
WriteQualityValueForm WriteForm = new WriteQualityValueForm(SelectData, this);
WriteForm.ShowDialog();
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
private void groupBox_SignialSimulatorBtn_Click(object sender, EventArgs e)
{
WriteBoolSignalByFormBtn(sender);
}
private void Btn_Write_PLC_Click(object sender, EventArgs e)
{
WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender);
}
private void Btn_Write_MES_Click(object sender, EventArgs e)
{
WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender);
}
private void Btn_ClearRichBox_Click(object sender, EventArgs e)
{
richTextBox_MessagePLC.Clear();
}
private void Cbx_StatusDisplay_CheckedChanged(object sender, EventArgs e)
{
if (Cbx_StatusDisplay.Checked)
{
InitFormBtnColor();
initStationStatus();
button_ReadData_Click(null, null);
checkBox_PLCData_Display.Visible = true;
checkBox_MESData_Display.Visible = true;
checkBox_Quality_Display.Visible = true;
}
else
{
RefreshBtnColorWriteNull();
RefreshStationStatusWriteNull();
checkBox_PLCData_Display.Visible = false;
checkBox_MESData_Display.Visible = false;
checkBox_Quality_Display.Visible = false;
}
}
private void Btn_Read_PLC_Click(object sender, EventArgs e)
{
ReadPLC_ProductInfo();
}
private void Btn_Read_MES_Click(object sender, EventArgs e)
{
ReadMES_ProductInfo();
}
private void MisData_FormClosed(object sender, FormClosedEventArgs e)
{
notifyIcon_MIS.Visible = false;
this.Dispose();
Application.Exit();
System.Environment.Exit(0);
}
private void toolStripMenuItem_Show_Click(object sender, EventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
this.Activate();
}
private void toolStripMenuItem_Hide_Click(object sender, EventArgs e)
{
this.Hide();
if (PlcChange != null)
{
Sencondform.Invoke(SecondFormClose);
ToolStripMenuItem_VWSStatus.Checked = false;
}
}
private void toolStripMenuItem_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void MisData_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();
if (PlcChange != null)
{
Sencondform.Invoke(SecondFormClose);
ToolStripMenuItem_VWSStatus.Checked = false;
}
}
}
public static string WorkStationNum_Now;
private void MisData_FormClosing(object sender, FormClosingEventArgs e)
{
notifyIcon_MIS.Visible = false;
if (MessageBox.Show("你确定要退出程序吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
{
notifyIcon_MIS.Visible = false;
e.Cancel = false;
//判断SecondForm是否关闭
if (PlcChange != null)
{
Sencondform.BeginInvoke(SecondFormClose);
}
StopServer();
MesWork.Mqtt.StopAsync();
}
else
{
notifyIcon_MIS.Visible = true;
e.Cancel = true;
}
}
private void notifyIcon_MIS_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (!this.Visible)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
this.Activate();
}
private void ToolStripMenuItem_PrintScreen_Click(object sender, EventArgs e)
{
PrintMainForm_Thread();
}
private void ToolStripMenuItem_Quit_Click(object sender, EventArgs e)
{
this.Close();
}
private void ToolStripMenuItem_SaveLog_Click(object sender, EventArgs e)
{
SavePLCMessage SavePlcMSG = new SavePLCMessage();
SavePlcMSG.SavePlcMessage_Thread(richTextBox_MessagePLC.Text);
}
private string Hello_You_All_Never_Know(string[] args)
{
return Guid.NewGuid().ToString();
//return string.Empty;
}
private void ToolStripMenuItem_LockForm_Click(object sender, EventArgs e)
{
MainFormLock = new MainAct(LockMainForm);
MainFormUnlock = new MainAct(UnLockForm);
MainLockConfirm LockConfirm = new MainLockConfirm(this, Sencondform);
LockConfirm.ShowDialog();
}
private void ToolStripMenuItem_VWSStatus_Click(object sender, EventArgs e)
{
if (PlcChange == null)
{
OpenSecondForm_Thread();
}
else
{
Sencondform.BeginInvoke(SecondFormClose);
ToolStripMenuItem_VWSStatus.Checked = false;
}
}
private void MisData_LocationChanged(object sender, EventArgs e)
{
if (SyncSecondForm != null)
{
Sencondform.Invoke(SyncSecondForm, new Point(this.Left + this.Width, this.Top));
}
}
private void MisData_Activated(object sender, EventArgs e)
{
//Thread t = new Thread(new ParameterizedThreadStart(MainFormActive_Thread));
//t.Start(true);
}
void MainFormActive_Thread(object obj)
{
if (MainFormActive != null)
MainFormActive(obj);
}
private void WToolStripMenuItem_EWSStatus_Click(object sender, EventArgs e)
{
}
private void MToolStripMenuItem_AboutMacroinf_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://www.meswork.com");
}
private void toolStripMenuItem_HVersion_Click(object sender, EventArgs e)
{
VersionsInformation VersionForm = new VersionsInformation();
VersionForm.ShowDialog();
}
private void MisData_Load(object sender, EventArgs e)
{
new MesWork.WebApi().InitWebApi();
MesWork.Mqtt.StartAsync(MqttUrl);
MesWork.Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
MesWork.Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
MesWork.Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);
}
void Runtime_Thread()
{
DateTime Now = DateTime.Now;
TimeSpan x = Now.Subtract(StartTime);
toolStripStatusLabel_RunTime.Text = x.Days.ToString() + "天" + x.Hours.ToString("00") + "小时" + x.Minutes.ToString("00") + "分" + x.Seconds.ToString("00") + "秒";
//Thread t = new Thread(new ParameterizedThreadStart (Runtime));
//t.Start(toolStripStatusLabel_RunTime);
}
DateTime StartTime;
void Runtime(object obj)
{
try
{
ToolStripStatusLabel toolStripStatusLabel_RunningTime = (ToolStripStatusLabel)obj;
DateTime Now = DateTime.Now;
TimeSpan ts = Now.Subtract(StartTime);
Action<TimeSpan> ActionDelegate = (x) => { toolStripStatusLabel_RunningTime.Text = x.Days.ToString() + "天" + x.Hours.ToString("00") + "小时" + x.Minutes.ToString("00") + "分" + x.Seconds.ToString("00") + "秒"; };
ActionDelegate(ts);
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
private void timer_TestPLC_Tick(object sender, EventArgs e)
{
try
{
if (!AllowLoad) return;
timer_TestPLC.Enabled = false;
Runtime_Thread();
timer_TestPLC.Enabled = true;
SystemFramework.SystemClock.SystemClockTimerTick();
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
void RefreshPlcConnectStatus(object sender, EventArgs e)
{
try
{
toolStripStatusLabel_OnlineNum.Text = sender.ToString();
toolStripStatusLabel_DownLine.Text = (Convert.ToInt32(toolStripStatusLabel_WorkStationNum.Text) - Convert.ToInt32(sender.ToString())).ToString();
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
bool EToolStripMenuItem_EquipAlarm_Visiable = false;
private void timer_LoadOver_Tick(object sender, EventArgs e)
{
if (this.Opacity == 1)
{
timer_LoadOver.Enabled = false;
}
else
{
this.Opacity = this.Opacity + 0.01;
}
}
private void ToolStripMenuItem_HHelp_Click(object sender, EventArgs e)
{
string file = Environment.CurrentDirectory+ "\\MisData操作手册.pdf";
string str = file.Replace("\\bin\\Debug", "\\PDF\\MisData说明文档.pdf");
System.Diagnostics.Process.Start(file);
}
/// <summary>
/// 程序集界面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ToolStripMenuItem_Assembly_Click(object sender, EventArgs e)
{
AssemblyManagement AssemblyView = new AssemblyManagement();
AssemblyView.ShowDialog();
}
MesWork.OpcForm opcForm = null;
private void TSM_DebugPage_Click(object sender, EventArgs e)
{
if (opcForm != null)
{
opcForm.Close();
opcForm.Dispose();
opcForm = null;
}
opcForm = new MesWork.OpcForm(IsDemoMesServer);
opcForm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
WritePLC("71015001",1);
WritePLC("71015002",1.1);
WritePLC("71015003",2.2);
WritePLC("71015004", 0);
WritePLC("71015005", 3.3);
WritePLC("71015006", 4.4);
}
private void btn_Bytes_Test_Click(object sender, EventArgs e)
{
byte[] bts = new byte[] { 67, 68 };
var textByte = System.Text.Encoding.ASCII.GetString(new byte[] { 67, 68 });
WritePLC(104, "OP0010", textByte);
var readResult = ReadPLC(104, "OP0010").ToString();
var readResult1 = System.Text.Encoding.ASCII.GetBytes(ReadPLC(104,"OP0010").ToString ());
}
private void AppConfigSet_Click(object sender, EventArgs e)
{
new AppConfigSetting.AppConfigSetForm().ShowDialog();
}
private void button_TeadTagValussByBytes_Click(object sender, EventArgs e)
{
ConcurrentDictionary<string, object> cache_OpQualityDataList = DriverCache[CacheType.Cache_OpQualityDataList];
var opContent = (ConcurrentDictionary<string, object>)cache_OpQualityDataList["OP0030"];
var opTagList = (ConcurrentDictionary<string, object>)opContent["TagAdrListTagFormat"];
opTagList.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value);
var keyValues = opTagList.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value);
TagFormat tagFormat1=new TagFormat ();
TagFormat tagFormat2;
TagFormat tagFormatTemp;
int tagIndex=0;
ushort length=0;
string OpName="";
foreach (KeyValuePair<string, object> kv in keyValues)
{
if (kv.Key.ToString()[0].ToString()=="7")
{
if (tagIndex == 0)
{
tagFormat1 = (TagFormat)kv.Value;
tagFormatTemp = (TagFormat)kv.Value; ;
length = (ushort)tagFormat1.Length;
OpName = tagFormat1.OpName;
}
else
{
tagFormat2 = (TagFormat)kv.Value; ;
length = (ushort)((int)length + tagFormat2.Length);
}
tagIndex++;
}
else
{
break;
}
//Console.WriteLine($"key{kv.Key} value{kv.Value}");
}
string Adr = tagFormat1.TagDbAndStartAdr;
var tagValue = PlcLinkForm.ReadByteData_Op(OpName, Adr, length);
int a1 = BitConverter.ToInt16(tagValue, 0);
double f1 = BitConverter.ToDouble(tagValue, 2);
double f2 = BitConverter.ToDouble(tagValue, 6);
int a11 = BitConverter.ToInt16(tagValue, 10);
double f11 = BitConverter.ToDouble(tagValue, 12);
double f21 = BitConverter.ToDouble(tagValue, 16);
ConcurrentDictionary<string, TagFormat> tagFormatList = new ConcurrentDictionary<string, TagFormat> ();
//BitConverter.ToInt16 (tagValue, 0) ;
//起始地址,应该这样写:比如 DB411.20就是读这个PLC里的DB411从20地址开始
//public static byte[] ReadByteData_Ip(string ip, string startAdrr, ushort length);
//public static byte[] ReadByteData_Op(string opName, string startAdrr, ushort length);
foreach (KeyValuePair<string, object> item in opTagList)
{
var tagID = item.Key;
var tf = (TagFormat)item.Value;
}
}
public void ReadByteData_Op(string OpName, string Adr, string Length)
{
ushort LengthValue = Convert.ToUInt16(Length);
var tagValue = PlcLinkForm.ReadByteData_Op(OpName, Adr, LengthValue);
//ReturnValueString rv = new ReturnValueString();
//rv.CmdPlcReadWrite = "";
//rv.OpName = "";
//rv.TagValue = System.Text.Encoding.UTF8.GetString(tagValue);
//rv.TagID = "";
//rv.ValueType = tagValue.GetType().Name.ToLower();
//var pp = JsonConvert.SerializeObject(rv);
//HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(pp, Encoding.GetEncoding("UTF-8"), "application/json") };
//return result;
}
private void button_OnlyReadQtData_Click(object sender, EventArgs e)
{
string opName = WorkStationNum_Now;
Function.MesRead_ByOnlyDataGroup(opName);
//Hashtable ht = GetQualityDataTypeList(opName);
//GetEngineMainData_ByOnlyDataGroup(opName,
//out int qualityMask,
//out int engineTypeID,
//out string engineID,
//out string engineType, out string partPallet, out string engineTraceCode, out string engineCap, Hashtable hashtable_EngineTypeID=null,
//out int mes_MustTest, out int onLineState, out int partMoveDirection,
//out int pressIsOK, out int pressIsNoOK);
}
private void button_ReadTagID_Click(object sender, EventArgs e)
{
string tagID = textBox_TagIDRead.Text;
var tagValue = PlcLinkForm.ReadPLC(tagID);
textBox_ReadTagIdValue.Text = tagValue.ToString();
}
private void button_ReadDataByBytes_Click(object sender, EventArgs e)
{
string opName = WorkStationNum_Now;
GetDbAndMaxLengthByOpNameByBytes(opName);
}
private ConcurrentDictionary<string, object> GetDbAndMaxLengthByOpNameByBytes(string opName)
{
string tagStartAdr = "";
ushort tagAdrListMaxLength = 0;
GetDbAndMaxLengthByOpName(opName, out tagStartAdr, out tagAdrListMaxLength);
var tagAdrListTagFormat = ReadQualityDataList(opName, tagStartAdr, tagAdrListMaxLength);
return tagAdrListTagFormat;
}
private void button_WriteTestData_Click(object sender, EventArgs e)
{
string opName= WorkStationNum_Now;
InitBasicDataTagValue( opName);
}
private void InitBasicDataTagValue(string opName)
{
//if (IsDemoMesServer != 1) return;
string tagID;
double tagValue;
//写工位总合格标志 变量类型代码=21
for (int i = 0; i < MesWork.PlcLinkForm.dt_BasicData.Rows.Count; i++)
{
if (MesWork.PlcLinkForm.dt_BasicData.Rows[i]["变量类型代码"].ToString() == "21")
{
tagID = MesWork.PlcLinkForm.dt_BasicData.Rows[i]["TagID"].ToString();
WritePLC(tagID, 1);
}
}
if (BasicDataTagValue != null)
{
for (int i = 0; i < BasicDataTagValue.Rows.Count; i++)
{
try
{
switch (Convert.ToInt32(BasicDataTagValue.Rows[i]["变量特点"]))
{
case 7:
tagID = BasicDataTagValue.Rows[i]["TagID"].ToString();
WritePLC(tagID, 1);
break;
case 6:
tagID = BasicDataTagValue.Rows[i]["TagID"].ToString();
tagValue = Convert.ToDouble(BasicDataTagValue.Rows[i]["列位置"]) * 100
+ Convert.ToDouble(BasicDataTagValue.Rows[i]["变量排序"]) / 100;
WritePLC(tagID, tagValue);
break;
}
}
catch { }
}
}
}
/// <summary>
///
/// </summary>
/// <param name="opName"></param>
/// <returns></returns>
//public static object ReadPLC_Sync_DataList_MesRead_____(string opName)
//{
// lock (l)
// {
// Hashtable ht = new Hashtable();
// var cd = PlcLinkForm.ReadPLC_GroupData(opName);
// foreach (KeyValuePair<string, object> _cd in cd)
// {
// var tagID = Convert.ToInt32(_cd.Key);
// var TF = (TagFormat)_cd.Value;
// QualityDataType qualityDataType;
// qualityDataType = new QualityDataType();
// qualityDataType.tagID = TF.TagID;
// qualityDataType.tagTypeID = TF.TagTypeID;//变量类型
// qualityDataType.opName = opName;
// qualityDataType.isGoodBad = 192;
// int.TryParse(TF.TagQuality, out int TagQuality);
// qualityDataType.tagQuality = TagQuality;
// qualityDataType.tagValueType = TF.TagTypeCodeID;
// int.TryParse(TF.TagOrderBy, out int TagOrderBy);
// qualityDataType.tagOrderBy = TagOrderBy;
// int.TryParse(TF.TagItemOrderBy, out int TagItemOrderBy);
// qualityDataType.tagItemOrderBy = TagItemOrderBy;
// qualityDataType.tagProperty = TF.TagProperty;//变量特点
// qualityDataType.tagValue = TF.TagValue;//变量值
// ht.Add(tagID, qualityDataType);
// }
// return ht;
// }
//}
private void EToolStripMenuItem_EquipAlarm_Click(object sender, EventArgs e)
{
try
{
if (!EToolStripMenuItem_EquipAlarm.Checked)
{
groupBox_WorkStationQuality.Width = 307;
groupBox_WorkStationQuality.Height = 313;
listView_ShowQualityData.Width = 294;
listView_ShowQualityData.Height = 234;
button_ReadData_Click(null, null);
groupBox_Alarm.Visible = true;
EToolStripMenuItem_EquipAlarm.Checked = true;
EToolStripMenuItem_EquipAlarm_Visiable = true;
}
else
{
groupBox_Alarm.Visible = false;
groupBox_WorkStationQuality.Width = 307;
groupBox_WorkStationQuality.Height = 642;
listView_ShowQualityData.Width = 294;
listView_ShowQualityData.Height = 572;
button_ReadData_Click(null, null);
EToolStripMenuItem_EquipAlarm.Checked = false;
}
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Message);
}
}
}
}