2025-03-31 13:39:28 +08:00

1441 lines
60 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 System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using HslCommunication.LogNet;
using WindowsFormsApp1.db;
using WindowsFormsApp1.form;
using WindowsFormsApp1.mod;
using WindowsFormsApp1.mod.database;
using WindowsFormsApp1.mod.server;
using WindowsFormsApp1.server;
using static SQLite.SQLite3;
using static WindowsFormsApp1.server.ApiClient;
using Label = System.Windows.Forms.Label;
namespace WindowsFormsApp1
{
public partial class MainForm : Form
{
// 添加一个标志变量,用于标记是否已经执行了清理操作
private bool _isCleanupDone = false;
private bool _isFormClosing = false; // 添加标志,表示窗体正在关闭
// 添加一个静态变量来跟踪下一个要使用的槽位
private static int _nextEventSlot = 1;
// 在MainForm类中添加一个字典,用于存储PLC状态控件
private Dictionary<int, System.Windows.Forms.Label> plcStatusLabels = new Dictionary<int, System.Windows.Forms.Label>();
private Dictionary<int, System.Windows.Forms.Panel> plcStatusIndicators = new Dictionary<int, System.Windows.Forms.Panel>();
// 在MainForm类的成员变量部分添加一个定时器
private System.Windows.Forms.Timer statusReportTimer = new System.Windows.Forms.Timer();
private ApiClient statusApiClient = new ApiClient(); // 专用于状态上报的API客户端
public MainForm()
{
InitializeComponent();
// 添加FormClosed事件处理程序
this.FormClosed += MainForm_FormClosed;
CheckForIllegalCrossThreadCalls = false;
// 初始化状态上报定时器
statusReportTimer.Interval = 15000; // 15秒
//statusReportTimer.Tick += StatusReportTimer_Tick;
}
private void Form1_Load(object sender, EventArgs e)
{
LogExecute.logNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
LogExecute.PlclogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
LogExecute.ApilogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
FormRecover();
linename.Text = Init.t_Line.linename;
linecode.Text = Init.t_Line.lineremark1;
linetype.Text = Init.t_Line.lineremark2;
linemode.Text = Init.t_Line.lineremark3;
//lineremark1.Text = "";
//lineremark2.Text = "";
//lineremark3.Text = "";
//lineremark4.Text = "";
//lineremark5.Text = "";
//lineremark6.Text = "";
//lineremark7.Text = "";
操作人员ID.Text = Init.t_User.username;
// 添加窗体关闭事件处理
this.FormClosing += MainForm_FormClosing;
// 自动开始处理
开始处理_Click(this, EventArgs.Empty);
}
public void build(t_plc Plc, CancellationToken token)
{
while (true)
{
try
{
if (token.IsCancellationRequested)
{
break;
}
ChangeBarcode();
if (Plc == null)
{
continue;
}
#region PLC链接及读取
SiemensHelp siemensHelp = Plc.plchelp;
var openresult = siemensHelp.OpenConn();
if (!openresult.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
// 更新对应PLC的状态指示器为红色
UpdatePlcStatus(Plc.id, false);
LogExecute.logNet.WriteError($"{Plc.plcip}建立S7连接失败");
continue;
}
List<t_plcaddress> plcaddress = Init.t_Plcaddresses.FindAll(a => a.plcid == Plc.id);
List<t_angleaddress> angleaddress = Init.t_Angleaddresses.FindAll(a => a.plcid == Plc.id);
List<t_torqueaddress> torqueaddress = Init.t_Torqueaddresses.FindAll(a => a.plcid == Plc.id);
List<t_pressurecurve> pressurecurveaddress = Init.t_Pressurecurves.FindAll(a => a.plcid == Plc.id);
plcdata PlcData = new plcdata();
var resdresult = siemensHelp.ReadAddress(plcaddress, PlcData);
if (!resdresult.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"{Plc.plcip}读取全部地址处理错误:处理停止");
continue;
}
//写入心跳
PlcData.Write_Heartbeat = PlcData.Write_Heartbeat == 0 ? (short)1 : (short)0;
var haertresult = siemensHelp.WriteAddress(plcaddress, PlcData);
if (!haertresult.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"{Plc.plcip}写入心跳错误:处理停止");
continue;
}
if(Plc.id == 1)
{
LOT号.Text = PlcData.Read_MaterialCode0;
Tray盘二维码.Text = PlcData.Read_MaterialCode1;
材料值.Text = PlcData.Read_MaterialCode2;
}
当前时间.Text = $"PLC状态:{plcstatus.GetName(typeof(plcstatus),PlcData.Read_Status)}";
DateTime Plc_Time = DateTime.Now;
//PLC链接状态.Text = "PLC链接状态:OK";
//PLC链接状态.BackColor = SystemColors.Control;
//PLC通讯时间.Text = "PLC通讯时间:" + Plc_Time.ToString("MM-dd HH:mm:ss");
// 更新对应PLC的状态指示器为绿色
//LogExecute.logNet.WriteError($"{Plc.plcname}");
UpdatePlcStatus(Plc.id, true);
#endregion
ApiClient apiClient = new ApiClient();
otherdata otherdata = new otherdata();
//Init.SN = PlcData.Read_MaterialCode0;
#region 机台状态及报警
//机台状态
//机台状态.Text = "机台状态:" + Enum.GetName(typeof(plcstatus), Init.Plcstatus);
int oldstatus = Init.Plcstatus;
if (PlcData.Read_Status != 0)
{
DateTime oldPlcstatus_LastTime = Init.Plcstatus_LastTime;
//状态+报警
if (oldstatus != PlcData.Read_Status)
{
//反馈状态
Init.Plcstatus = PlcData.Read_Status;
Init.Plcstatus_LastTime = DateTime.Now;
otherdata.Plc_Status = PlcData.Read_Status;
var statusresult = apiClient.CallFunctionByName("Status", PlcData, otherdata);
if (statusresult.Success)
{
//MES链接状态.Text = "MES链接状态:OK";
//MES链接状态.BackColor = SystemColors.Control;
//MES通讯时间.Text = "MES通讯时间:" + DateTime.Now.ToString("MM-dd HH:mm:ss");
MES_MsgfORM("Status", statusresult, statusresult.Requesttime);
if (statusresult.Mesresult != mesresult.PASS)
{
PlcData.Write_Status = 1001;
siemensHelp.WriteAddress(plcaddress, PlcData);
continue;
}
}
else
{
//MES链接状态.Text = "MES链接状态:NG";
//MES链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"MES通讯异常!");
PlcData.Write_Status = 1002;
var errresult = siemensHelp.WriteAddress(plcaddress, PlcData);
continue;
}
}
}
//机台报警
if (PlcData.Read_Status == (short)plcstatus.停机)
{
//机台状态.BackColor = Color.Red;
if (oldstatus != (short)plcstatus.停机)
{
//反馈报警
List<string> list = new List<string>();
///////////////////////////////测试用
list.Add("M03CVSO-01");
otherdata.Plc_ErrorMsgs = list;
Init.Plcstatus = PlcData.Read_Status;
Init.Plcstatus_LastTime = DateTime.Now;
var statusresult = apiClient.CallFunctionByName("Alarm", PlcData, otherdata);
if (statusresult.Success)
{
//MES链接状态.Text = "MES链接状态:OK";
//MES链接状态.BackColor = SystemColors.Control;
//MES通讯时间.Text = "MES通讯时间:" + DateTime.Now.ToString("MM-dd HH:mm:ss");
MES_MsgfORM("Alarm", statusresult, statusresult.Requesttime);
if (statusresult.Mesresult != mesresult.PASS)
{
PlcData.Write_Status = 1001;
siemensHelp.WriteAddress(plcaddress, PlcData);
continue;
}
}
else
{
//MES链接状态.Text = "MES链接状态:NG";
//MES链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"MES通讯异常!");
PlcData.Write_Status = 1002;
siemensHelp.WriteAddress(plcaddress, PlcData);
}
}
continue;
}
else
{
//机台状态.BackColor = SystemColors.Control;
}
#endregion
#region 判断及查找流程
if (PlcData.Read_Trigger == 0 && PlcData.Write_Status == 0)
{
continue;
}
else if (PlcData.Read_Trigger == PlcData.Write_Status)
{
continue;
}
else if (PlcData.Read_Trigger == 0 && PlcData.Write_Status != 0)
{
PlcData.Write_Status = 0;
var writeresult = siemensHelp.WriteAddress(plcaddress, PlcData);
if (!writeresult.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"{Plc.plcip}写入地址处理错误:处理停止");
}
continue;
}
LogExecute.logNet.WriteDebug($"读取状态字{PlcData.Read_Trigger}");
var nowflow = Init.t_Flows.FirstOrDefault(a => a.hopestatus == PlcData.Read_Trigger);
if (nowflow == null)
{
LogExecute.logNet.WriteError($"未找到当前触发字{PlcData.Read_Trigger},对应的流程!");
continue;
}
var nowinterface = Init.t_Interfaces.FirstOrDefault(a => a.id == nowflow.hopeinterfaceid);
if (nowinterface == null)
{
LogExecute.logNet.WriteError($"未找到当前期望接口ID {nowflow.hopeinterfaceid},对应的接口!");
continue;
}
#endregion
#region 根据流程,判断是否需要扫码、气密、扭力等
if (nowflow.scan)
{
//扫码
ScanForm scanForm = new ScanForm();
DialogResult scan_result = scanForm.ShowDialog();
if (scan_result == DialogResult.OK)
{
string returnValue = scanForm.ReturnValue;
otherdata.JS_SN = returnValue;
//Init.SN = returnValue;
LOT号.Text = returnValue;
Init.ScanString = returnValue;
}
else
{
continue;
}
}
if (nowflow.dzscan)
{
//扫码
var stationid = Init.t_Line.lineremark2;
// ccd扫码
if ("Assy1".Contains(stationid))
{
SQLiteHelper<t_keyvalue> sQLiteHelper_key = new db.SQLiteHelper<t_keyvalue>();
var key_sqlresult = sQLiteHelper_key.QueryAll();
var result1 = apiClient.CallFunctionByName("SN_FeedingCheck", PlcData, new otherdata() { JS_SN = PlcData.Read_MaterialCode2 });
if (result1.Success && result1.Mesresult == mesresult.PASS)
{
//继续调用接口
var result2 = apiClient.CallFunctionByName("Link_Comp", PlcData, new otherdata() { JS_SN = PlcData.Read_MaterialCode2 });
if (result2.Success && result2.Mesresult == mesresult.PASS)
{
// 写数据到 主页的barcode 数据库改,缓存改
var txt = Init.t_Keyvalues.FirstOrDefault(a => a.key == "Barcode1");
txt.value = PlcData.Read_MaterialCode2;
var code = key_sqlresult.Data.First(x => x.key == txt.key);
code.value = PlcData.Read_MaterialCode2;
sQLiteHelper_key.Update(code);
}
else
{
LogExecute.logNet.WriteError($"{PlcData.Read_MaterialCode2}绑定NG");
}
}
else
{
LogExecute.logNet.WriteError($"{PlcData.Read_MaterialCode2}核对NG");
}
}
else
{
ScanForm_DZ scanForm = new ScanForm_DZ();
DialogResult scan_result = scanForm.ShowDialog();
}
ChangeBarcode();
var writeresult = siemensHelp.WriteAddress(plcaddress, PlcData);
if (!writeresult.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"{Plc.plcip}写入地址处理错误:处理停止");
continue;
}
else
{
//MES链接状态.Text = "MES链接状态:OK";
//MES链接状态.BackColor = SystemColors.Control;
//MES通讯时间.Text = "MES通讯时间:" + DateTime.Now.ToString("MM-dd HH:mm:ss");
}
continue;
//if (scan_result == DialogResult.OK)
//{
// string returnValue = scanForm.ReturnValue;
// otherdata.JS_SN = returnValue;
// Init.ScanString = returnValue;
//}
//else
//{
// continue;
//}
}
if (nowflow.finalpressurecurve)
{
//压力曲线
var pressurecurveaddress_result = siemensHelp.ReadAddress(pressurecurveaddress);
if (!pressurecurveaddress_result.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"{Plc.plcip}压力曲线数据地址处理错误:处理停止");
continue;
}
otherdata.FinalPressureCurve = pressurecurveaddress_result.Data;
}
//if (nowflow.finaltorquecurve)
//{
// //扭力曲线(这里不处理,后端API获取)
//}
if (nowflow.finaltorquevalue)
{
//螺丝枪扭力数据
var finaltorquevalue_result = siemensHelp.ReadAddress(torqueaddress);
if (!finaltorquevalue_result.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"{Plc.plcip}螺丝枪扭力数据地址处理错误:处理停止");
continue;
}
otherdata.FinalTorqueValue = finaltorquevalue_result.Data;
}
if (nowflow.airtight)
{
//气密参数
otherdata.FinalAirtightValue = Init.airtight;
}
if (nowflow.finalanglevaluue)
{
//螺丝枪角度
var finalanglevaluue_result = siemensHelp.ReadAddress(angleaddress);
if (!finalanglevaluue_result.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"{Plc.plcip}螺丝枪角度数据地址处理错误:处理停止");
continue;
}
otherdata.FinalAngleValue = finalanglevaluue_result.Data;
}
if (nowflow.fileupload)
{
//文件上传
}
#endregion
// NG料进站不判断,进站MES返回FAIL,记录。该站其他事件不触发MES,直接跳过
//if()
#region 判断物料调用次数 固化站
if (Init.t_Line.lineremark2 == "Curing")
{
SQLiteHelper<t_materialcall> materialCallHelper = new SQLiteHelper<t_materialcall>();
string materialId = PlcData.Read_MaterialCode0;
bool shouldCallApi = false;
var materialCall = materialCallHelper.QuerySingle(m => m.materialid == materialId).Data;
if (materialCall == null)
{
// 首次进站,需要调用接口
materialCall = new t_materialcall { materialid = materialId };
materialCall.checkin1 = DateTime.Now;
materialCallHelper.Insert(materialCall);
shouldCallApi = true;
}
else
{
// 判断当前是第几次调用
if (!materialCall.checkin1.HasValue)
{
materialCall.checkin1 = DateTime.Now;
shouldCallApi = true;
}
else if (!materialCall.checkout3.HasValue
&& materialCall.checkout2.HasValue
&& materialCall.checkout1.HasValue
&& nowinterface.code.Contains("Checkout"))
{
// 第三次出站,需要调用接口
materialCall.checkout3 = DateTime.Now;
shouldCallApi = true;
}
else
{
// 更新对应的时间
if (nowinterface.code.Contains("SN_CheckIN"))
{
if (!materialCall.checkin2.HasValue)
materialCall.checkin2 = DateTime.Now;
else if (!materialCall.checkin3.HasValue)
materialCall.checkin3 = DateTime.Now;
PlcData.Write_Status = PLC_Status.SN_CheckIN;
}
else if (nowinterface.code.Contains("SN_Checkout"))
{
if (!materialCall.checkout1.HasValue)
materialCall.checkout1 = DateTime.Now;
else if (!materialCall.checkout2.HasValue)
materialCall.checkout2 = DateTime.Now;
PlcData.Write_Status = PLC_Status.SN_Checkout;
}
}
materialCallHelper.Update(materialCall);
}
if (!shouldCallApi)
{
// 不需要调用接口,直接返回成功
PlcData.Write_Status = nowinterface.code.Contains("SN_CheckIN")
? (short)PLC_Status.SN_CheckIN
: (short)PLC_Status.SN_Checkout;
var writeresult = siemensHelp.WriteAddress(plcaddress, PlcData);
if (!writeresult.Success)
{
LogExecute.logNet.WriteError($"{Plc.plcip}写入地址处理错误:处理停止");
continue;
}
continue;
}
}
#endregion
//文件路径 列表
otherdata.FileUploadAddress = Init.t_Keyvalues.First(x => x.key == "UploadPath").value;
otherdata.ImageAddress = Init.t_Keyvalues.First(x => x.key == "ImageFilePath").value;
otherdata.VedioAddress = Init.t_Keyvalues.First(x => x.key == "VedioFilePath").value;
#region 调用后端接口
var result = apiClient.CallFunctionByName(nowinterface.code, PlcData, otherdata);
if (result.IsShow)
{
MES_MsgfORM(nowinterface.code, result, result.Requesttime);
}
if (result.Success)
{
var writeresult = siemensHelp.WriteAddress(plcaddress, PlcData);
if (!writeresult.Success)
{
//PLC链接状态.Text = "PLC链接状态:NG";
//PLC链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"{Plc.plcip}写入地址处理错误:处理停止");
continue;
}
else
{
ChangeBarcode();
MES_MsgfORM(nowinterface.code, result, result.Requesttime);
//MES链接状态.Text = "MES链接状态:OK";
//MES链接状态.BackColor = SystemColors.Control;
//MES通讯时间.Text = "MES通讯时间:" + DateTime.Now.ToString("MM-dd HH:mm:ss");
if (result.Mesresult != mesresult.PASS)
{
PlcData.Write_Status = 1001;
siemensHelp.WriteAddress(plcaddress, PlcData);
continue;
}
}
}
else
{
//MES链接状态.Text = "MES链接状态:NG";
//MES链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"MES通讯异常!");
PlcData.Write_Status = 1002;
siemensHelp.WriteAddress(plcaddress, PlcData);
}
#endregion
}
catch (Exception e)
{
LogExecute.logNet.WriteError(e.Message);
}
finally
{
Thread.Sleep(1000);
}
}
}
#region 开始及结束处理按钮
private async void 开始处理_Click(object sender, EventArgs e)
{
if (开始处理.Text == "开始处理")
{
SQLiteHelper<t_plc> sQLiteHelper_plc = new db.SQLiteHelper<t_plc>();
var plc_sqlresult = sQLiteHelper_plc.QueryAll();
if (!plc_sqlresult.Success)
{
MessageBox.Show("无法初始化PLC信息,无法开始处理!");
return;
}
var plc_result = plc_sqlresult.Data.FindAll(a => Init.t_Lineplcs.Select(p => p.plcid).Contains(a.id));
SQLiteHelper<t_keyvalue> sQLiteHelper_key = new db.SQLiteHelper<t_keyvalue>();
var key_sqlresult = sQLiteHelper_key.QueryAll();
if (!key_sqlresult.Success)
{
MessageBox.Show("无法初始化信息信息,无法开始处理!");
return;
}
SQLiteHelper<t_flow> sQLiteHelper_flow = new db.SQLiteHelper<t_flow>();
var flow_result = sQLiteHelper_flow.Query(a => a.flowid == Init.t_Line.flowid);
if (!flow_result.Success)
{
MessageBox.Show("无法初始化流程信息,无法开始处理!");
return;
}
SQLiteHelper<t_plcaddress> sQLiteHelper_address = new db.SQLiteHelper<t_plcaddress>();
var address_result = sQLiteHelper_address.QueryAll();
if (!address_result.Success)
{
MessageBox.Show("无法初始化PLC地址信息,无法开始处理!");
return;
}
SQLiteHelper<t_torqueaddress> sQLiteHelper_torqueaddress = new db.SQLiteHelper<t_torqueaddress>();
var torqueaddress_result = sQLiteHelper_torqueaddress.QueryAll();
if (!torqueaddress_result.Success)
{
MessageBox.Show("无法初始化螺丝枪扭力信息,无法开始处理!");
return;
}
SQLiteHelper<t_angleaddress> sQLiteHelper_angleaddress = new db.SQLiteHelper<t_angleaddress>();
var angleaddress_result = sQLiteHelper_angleaddress.QueryAll();
if (!angleaddress_result.Success)
{
MessageBox.Show("无法初始化螺丝枪角度信息,无法开始处理!");
return;
}
SQLiteHelper<t_pressurecurve> sQLiteHelper_pressurecurve = new db.SQLiteHelper<t_pressurecurve>();
var pressurecurve_result = sQLiteHelper_pressurecurve.QueryAll();
if (!pressurecurve_result.Success)
{
MessageBox.Show("无法初始化压力曲线信息,无法开始处理!");
return;
}
SQLiteHelper<t_interface> sQLiteHelper_interface = new db.SQLiteHelper<t_interface>();
var interface_result = sQLiteHelper_interface.QueryAll();
if (!interface_result.Success)
{
MessageBox.Show("无法初始化接口地址信息,无法开始处理!");
return;
}
SQLiteHelper<t_serialport> sQLiteHelper_serialport = new db.SQLiteHelper<t_serialport>();
var serialport_result = sQLiteHelper_serialport.QueryAll();
if (!serialport_result.Success)
{
MessageBox.Show("无法初始化COM口信息,无法开始处理!");
return;
}
#region 初始化全局变量
Init.t_Flows = flow_result.Data;
Init.t_Plcaddresses = address_result.Data;
Init.t_Angleaddresses = angleaddress_result.Data;
Init.t_Torqueaddresses = torqueaddress_result.Data;
Init.t_Pressurecurves = pressurecurve_result.Data;
Init.t_Interfaces = interface_result.Data;
Init.t_Keyvalues = key_sqlresult.Data;
// 初始化PLC状态面板
InitializePlcStatusPanel();
#endregion
#region 初始化COM口服务
try
{
var scanport = serialport_result.Data.FirstOrDefault(a => a.name == "Scan");
if (scanport != null)
{
if (scanport.enable)
{
Enum.TryParse(scanport.parity, out Parity parity);
Init.ScanPort = new SerialPort(scanport.portName, scanport.baudRate, parity, scanport.dataBits);
if (!Init.ScanPort.IsOpen)
{
Init.ScanPort?.Open();
底部注释1.Text = "扫码枪COM-Ready";
底部注释1.Visible = true;
// 订阅 DataReceived 事件
胶水上下线.Enabled = true;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("无法开启扫码枪COM,无法开始处理!" + ex.Message);
return;
}
try
{
var scanport = serialport_result.Data.FirstOrDefault(a => a.name == "Airtight");
if (scanport != null)
{
if (scanport.enable)
{
Enum.TryParse(scanport.parity, out Parity parity);
Init.AirtightPort = new SerialPort(scanport.portName, scanport.baudRate, parity, scanport.dataBits);
if (!Init.AirtightPort.IsOpen)
{
Init.AirtightPort?.Open();
Init.AirtightPort.DataReceived += AirtightPort_DataReceived;
底部注释2.Text = "气密仪COM-Ready";
底部注释2.Visible = true;
}
胶水上下线.Enabled = true;
}
}
}
catch (Exception ex)
{
MessageBox.Show("无法开启气密仪COM,无法开始处理!" + ex.Message);
return;
}
#endregion
Init.threadHelps = new List<ThreadHelp>();
foreach (var plc in plc_result)
{
plc.plchelp = new SiemensHelp(plc.plcip, plc.timeout);
ThreadHelp threadHelp = new ThreadHelp();
if (!threadHelp.isrunning1)
{
threadHelp.cancellationTokenSource1 = new CancellationTokenSource();
threadHelp.Thread = new Thread(() => build(plc, threadHelp.cancellationTokenSource1.Token));
threadHelp.Thread.Start();
threadHelp.isrunning1 = true;
}
Init.threadHelps.Add(threadHelp);
}
开始处理.Text = "停止处理";
开始处理.BackColor = Color.Red;
LogExecute.logNet.WriteInfo($"用户{Init.t_User.username},开始处理!");
}
else
{
// 禁用按钮,防止重复点击
开始处理.Enabled = false;
// 显示 Loading 窗体
LoadingForm loadingForm = new LoadingForm("正在停止处理...");
loadingForm.Show();
try
{
// 异步清理资源
await Task.Run(() => CleanupResources());
// 恢复界面
FormRecover();
}
finally
{
loadingForm.Close();
开始处理.Enabled = true;
}
}
}
// 添加FormClosed事件处理程序
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
// 如果已经执行过清理,则直接返回
//if (_isCleanupDone)
// return;
//try
//{
// _isCleanupDone = true; // 标记清理操作已执行
// // 给日志系统一点时间完成写入
// System.Threading.Thread.Sleep(100);
// // 停止所有线程
// if (Init.threadHelps != null)
// {
// foreach (var thread in Init.threadHelps)
// {
// try
// {
// if (thread.Thread != null && thread.Thread.IsAlive)
// {
// thread.cancellationTokenSource1?.Cancel();
// }
// }
// catch { /* 忽略异常 */ }
// }
// }
// // 安全关闭串口
// try
// {
// if (Init.ScanPort != null && Init.ScanPort.IsOpen)
// {
// Init.ScanPort.Close();
// Init.ScanPort = null;
// }
// }
// catch { /* 忽略异常 */ }
// try
// {
// if (Init.AirtightPort != null && Init.AirtightPort.IsOpen)
// {
// Init.AirtightPort.Close();
// Init.AirtightPort = null;
// }
// }
// catch { /* 忽略异常 */ }
//}
//catch { /* 忽略所有异常 */ }
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// 设置窗体正在关闭标志
_isFormClosing = true;
// 如果当前正在处理中,则进行清理
if (开始处理.Text == "停止处理" && !_isCleanupDone)
{
e.Cancel = true; // 取消关闭
// 显示 Loading 窗体
LoadingForm loadingForm = new LoadingForm("正在关闭程序...");
loadingForm.Show();
Task.Run(() =>
{
try
{
_isCleanupDone = true;
CleanupResources();
}
finally
{
this.Invoke((Action)(() =>
{
loadingForm.Close();
this.Close(); // 重新触发关闭
}));
}
});
}
}
// 添加一个清理资源的私有方法
private void CleanupResources()
{
try
{
// 停止状态上报定时器
statusReportTimer.Stop();
// 停止所有线程
if (Init.threadHelps != null)
{
foreach (var thread in Init.threadHelps)
{
try
{
if (thread.Thread != null && thread.Thread.IsAlive)
{
thread.cancellationTokenSource1?.Cancel();
thread.Thread.Join(); // 等待线程完成
}
thread.isrunning1 = false;
}
catch { /* 忽略异常 */ }
}
}
// 安全关闭串口
try
{
if (Init.ScanPort != null && Init.ScanPort.IsOpen)
{
Init.ScanPort.Close();
Init.ScanPort = null;
}
}
catch { /* 忽略异常 */ }
try
{
if (Init.AirtightPort != null && Init.AirtightPort.IsOpen)
{
Init.AirtightPort.Close();
Init.AirtightPort = null;
}
}
catch { /* 忽略异常 */ }
// 记录日志
LogExecute.logNet.WriteInfo($"用户{Init.t_User.username},停止处理!");
// 给日志系统一点时间完成写入
System.Threading.Thread.Sleep(100);
}
catch { /* 忽略所有异常 */ }
}
#endregion
#region 页面按钮-跳转
private void 扭力角度扭矩设置ToolStripMenuItem_Click(object sender, EventArgs e)
{
Angleaddress_Manage angleaddress_Manage = new Angleaddress_Manage();
angleaddress_Manage.ShowDialog();
}
private void 螺丝枪扭力设置ToolStripMenuItem_Click(object sender, EventArgs e)
{
Torqueaddress_Manage torqueaddress_Manage = new Torqueaddress_Manage();
torqueaddress_Manage.ShowDialog();
}
private void 流程管理ToolStripMenuItem_Click(object sender, EventArgs e)
{
Flow_Manage fLOW_Mange = new Flow_Manage();
fLOW_Mange.ShowDialog();
}
private void 产线基础信息管理ToolStripMenuItem_Click(object sender, EventArgs e)
{
Line_Manage lINE_Manage = new Line_Manage();
lINE_Manage.ShowDialog();
}
private void 系统参数配置ToolStripMenuItem_Click(object sender, EventArgs e)
{
KeyValue keyValue = new KeyValue();
keyValue.ShowDialog();
}
private void 材料扫码ToolStripMenuItem_Click(object sender, EventArgs e)
{
MaterialScanForm materialScanForm = new MaterialScanForm();
materialScanForm.Show();
}
private void 图片展示ToolStripMenuItem_Click(object sender, EventArgs e)
{
ImageDisplayForm displayForm = new ImageDisplayForm();
displayForm.Show();
}
private void pLC通讯设置ToolStripMenuItem_Click(object sender, EventArgs e)
{
Plc_Manage pLC_Manage = new Plc_Manage();
pLC_Manage.ShowDialog();
}
private void pLC地址设置ToolStripMenuItem_Click(object sender, EventArgs e)
{
PlcAddress_Manage pLCADDRESS_Manage = new PlcAddress_Manage();
pLCADDRESS_Manage.ShowDialog();
}
private void 切换用户ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void mES接口配置ToolStripMenuItem_Click(object sender, EventArgs e)
{
MESUrl mES_URL = new MESUrl();
mES_URL.ShowDialog();
}
private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
{
UserChangeP uSER_ChangeP = new UserChangeP();
uSER_ChangeP.ShowDialog();
}
private void 用户管理ToolStripMenuItem1_Click(object sender, EventArgs e)
{
User_Manage uSER_Manage = new User_Manage();
uSER_Manage.ShowDialog();
}
private void 扫码枪配置ToolStripMenuItem1_Click(object sender, EventArgs e)
{
SerialPort_Manage serialPort_Manage = new SerialPort_Manage();
serialPort_Manage.ShowDialog();
}
#endregion
#region 页面-布局、日志等
private void LogNet_BeforeSaveToFile(object sender, HslEventArgs e)
{
// 如果窗体正在关闭,则不再尝试更新UI
if (_isFormClosing)
{
// 仅写入文件日志,不更新UI
return;
}
try
{
// 使用 BeginInvoke 而不是直接在锁内操作 UI 控件,减少 UI 线程阻塞
this.BeginInvoke(new Action(() =>
{
DateTime time = e.HslMessage.Time;
string text = e.HslMessage.Text;
// 使用 StringBuilder 构建日志文本,提高性能
StringBuilder logBuilder = new StringBuilder();
string logPrefix;
Color logColor;
// 根据日志级别设置前缀和颜色
switch (e.HslMessage.Degree)
{
case HslMessageDegree.ERROR:
logPrefix = "[错误] ";
logColor = Color.Red;
break;
case HslMessageDegree.DEBUG:
logPrefix = "[日志] ";
logColor = Color.Green;
break;
case HslMessageDegree.WARN:
case HslMessageDegree.INFO:
logPrefix = e.HslMessage.Degree == HslMessageDegree.WARN ? "[警告] " : "[提示] ";
logColor = Color.Orange;
break;
default:
logPrefix = "[未知] ";
logColor = Color.Red;
break;
}
logBuilder.Append(logPrefix).Append(time.ToString()).Append(" | ").Append(text).Append("\n");
// 检查日志行数,如果超过阈值则清理
int lineCount = richTextBox1.GetLineFromCharIndex(richTextBox1.TextLength);
if (lineCount >= 200)
{
// 优化:只保留后 100 行,而不是全部清空再重新添加
int startIndex = richTextBox1.GetFirstCharIndexFromLine(lineCount - 100);
if (startIndex > 0)
{
richTextBox1.Select(0, startIndex);
richTextBox1.SelectedText = "";
}
}
// 添加新日志
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = logColor;
richTextBox1.AppendText(logBuilder.ToString());
// 重置颜色并滚动到底部
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = richTextBox1.ForeColor;
richTextBox1.ScrollToCaret();
}));
}
catch { /* 忽略异常 */ }
}
private void timer1_Tick(object sender, EventArgs e)
{
当前时间.Text = "当前时间:" + DateTime.Now.ToString("MM-dd HH:mm:ss");
}
public void FormRecover()
{
开始处理.Text = "开始处理";
开始处理.BackColor = Color.Green;
//MES链接状态.Text = "MES链接状态:None";
//MES链接状态.BackColor = SystemColors.Control;
//MES通讯时间.Text = "MES通讯时间:None";
//MES通讯时间.BackColor = SystemColors.Control;
//胶水上下线.Enabled = false;
//MES提示信息.Visible = false;
//LOT号.Visible = false;
//Tray盘二维码.Visible = false;
底部注释1.Visible = false;
底部注释2.Visible = false;
底部注释3.Visible = false;
底部注释4.Visible = false;
底部注释5.Visible = false;
剩余寿命.Visible = false;
// 初始化所有PLC状态指示器为灰色(未连接状态)
foreach (var indicator in plcStatusIndicators.Values)
{
indicator.BackColor = Color.Gray;
}
}
public void ChangeBarcode()
{
剩余寿命.Visible = true;
var power = Init.t_Keyvalues.FirstOrDefault(a => a.key == "Power");
剩余寿命.Text = power == null ? "" : power.value;
}
// 添加初始化PLC状态面板的方法
private void InitializePlcStatusPanel()
{
// 假设我们已经有一个名为plcStatusGroupBox的GroupBox控件
// 和一个名为plcStatusTableLayout的TableLayoutPanel控件
// 清空现有控件
plcStatusTableLayout.Controls.Clear();
plcStatusLabels.Clear();
plcStatusIndicators.Clear();
// 设置TableLayoutPanel的行列数
int plcCount = Init.t_Lineplcs?.Count ?? 0;
// 修改为横向布局:每列显示一个PLC,每个PLC占用一行两列
plcStatusTableLayout.ColumnCount = plcCount * 2; // 每个PLC需要2列
plcStatusTableLayout.RowCount = 1; // 只需要1行
// 设置列样式
plcStatusTableLayout.ColumnStyles.Clear();
for (int i = 0; i < plcCount; i++)
{
// 为每个PLC添加两列:一列放指示灯,一列放标签
plcStatusTableLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 30F)); // 状态指示灯列
plcStatusTableLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 150F)); // PLC信息列
}
// 设置行样式
plcStatusTableLayout.RowStyles.Clear();
plcStatusTableLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 25F));
// 如果没有PLC,显示提示信息
if (plcCount == 0)
{
var noPlcLabel = new System.Windows.Forms.Label();
noPlcLabel.Text = "未配置PLC";
noPlcLabel.Dock = DockStyle.Fill;
noPlcLabel.TextAlign = ContentAlignment.MiddleCenter;
plcStatusTableLayout.Controls.Add(noPlcLabel, 0, 0);
plcStatusTableLayout.SetColumnSpan(noPlcLabel, 2);
return;
}
// 为每个PLC创建状态指示器
int colIndex = 0;
foreach (var linePlc in Init.t_Lineplcs)
{
// 获取PLC信息
var plc = Init.t_Plcaddresses.FirstOrDefault(p => p.plcid == linePlc.plcid);
if (plc == null) continue;
// 创建状态指示灯(一个小Panel)
Panel statusIndicator = new Panel();
statusIndicator.Size = new Size(16, 16);
statusIndicator.BackColor = Color.Gray; // 初始为灰色
statusIndicator.Margin = new Padding(5);
// 创建PLC名称标签
Label plcLabel = new Label();
plcLabel.Text = $"PLC-{plc.plcid}:{plc.dbaddress}";
plcLabel.Dock = DockStyle.Fill;
plcLabel.TextAlign = ContentAlignment.MiddleLeft;
// 添加到TableLayoutPanel(使用列索引)
plcStatusTableLayout.Controls.Add(statusIndicator, colIndex, 0); // 状态指示灯放在第一列
plcStatusTableLayout.Controls.Add(plcLabel, colIndex + 1, 0); // 标签放在第二列
// 保存引用以便后续更新
plcStatusIndicators[linePlc.plcid] = statusIndicator;
plcStatusLabels[linePlc.plcid] = plcLabel;
colIndex += 2; // 每个PLC占用两列,所以索引加2
}
}
// 添加更新PLC状态的方法
private void UpdatePlcStatus(int plcId, bool isConnected)
{
try
{
if (plcStatusIndicators.ContainsKey(plcId))
{
// 使用Invoke确保在UI线程上更新控件
this.Invoke((MethodInvoker)delegate
{
plcStatusIndicators[plcId].BackColor = isConnected ? Color.Green : Color.Red;
});
}
}
catch { /* 忽略异常 */ }
}
/// <summary>
/// 更新事件显示区域
/// </summary>
private void UpdateEventDisplay(string name, mesresult result, DateTime dateTime, string message)
{
UpdateEventSlot(事件1, 事件1结果, 事件1时间, name, result, dateTime, message);
// 根据接口名称显示特定信息
//UpdateSpecificEventInfo(name, message);
}
/// <summary>
/// 查找可用的事件显示槽位
/// </summary>
private int FindAvailableEventSlot()
{
// 首先查找不可见的事件槽位
if (!事件1.Visible) return 1;
return 1;
}
/// <summary>
/// 更新指定事件槽位的显示内容
/// </summary>
private void UpdateEventSlot(Label eventLabel, Label resultLabel, Label timeLabel,
string name, mesresult result, DateTime dateTime, string message)
{
// 设置事件名称
eventLabel.Text = $"{name}";
eventLabel.Visible = true;
// 设置事件结果
resultLabel.Text = $"{(result == mesresult.PASS ? "PASS" : "FAIL")}";
resultLabel.BackColor = result == mesresult.PASS ? Color.Green : Color.Red;
resultLabel.Visible = true;
// 设置事件时间
timeLabel.Text = $"{dateTime:MM-dd HH:mm:ss}";
timeLabel.Visible = true;
}
/// <summary>
/// 根据接口名称更新特定信息显示
/// </summary>
private void UpdateSpecificEventInfo(string name, string message)
{
// 根据不同的接口名称,显示特定的信息
switch (name)
{
case "SN_Release":
// 显示SN号
if (!string.IsNullOrEmpty(Init.ScanString))
{
LOT号.Text = $"SN号:{Init.ScanString}";
LOT号.Visible = true;
}
break;
case "Tray_Release":
// 显示Tray盘信息
if (!string.IsNullOrEmpty(message))
{
Tray盘二维码.Text = $"Tray盘:{message}";
Tray盘二维码.Visible = true;
}
break;
case "Status":
// 机台状态信息已在其他地方更新
break;
case "Alarm":
// 报警信息可以在底部注释中显示
if (!string.IsNullOrEmpty(message))
{
底部注释3.Text = $"报警信息:{message}";
底部注释3.Visible = true;
}
break;
// 可以根据需要添加更多的接口类型处理
default:
// 对于其他类型的接口,可以在底部注释中显示额外信息
if (!string.IsNullOrEmpty(message))
{
if (!底部注释4.Visible)
{
底部注释4.Text = $"{name}:{message}";
底部注释4.Visible = true;
}
else if (!底部注释5.Visible)
{
底部注释5.Text = $"{name}:{message}";
底部注释5.Visible = true;
}
}
break;
}
}
public void MES_MsgfORM(string name, ApiFormResult result, DateTime dateTime)
{
// 显示MES提示信息
MES提示信息.Visible = true;
MES提示信息.Text = $"{result.Msg}";
MES提示信息.ForeColor = result.Mesresult == mesresult.PASS ? Color.Green : Color.Red;
// 更新事件显示区域
UpdateEventDisplay(name, result.Mesresult, dateTime, result.Msg);
}
#endregion
#region 其他业务处理
private void 胶水上下线_Click(object sender, EventArgs e)
{
ScanForm_SSQ scanForm = new ScanForm_SSQ();
DialogResult result = scanForm.ShowDialog();
// 写plc
}
public void AirtightPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (!Init.AirtightPort.IsOpen)
{
Init.AirtightPort?.Open();
}
// 读取串口接收到的数据
// 读取串口接收到的数据
var dataBuilder = new StringBuilder();
while (Init.AirtightPort.BytesToRead > 0)
{
System.Threading.Thread.Sleep(100);
dataBuilder.Append(Init.AirtightPort.ReadExisting());
}
var ReturnValue = dataBuilder.ToString();
LogExecute.logNet.WriteDebug($"通过气密仪获取到 {ReturnValue}");
int index1 = 1;
int index2 = 1;
string press = string.Empty;
string leakage = string.Empty;
//pressure选择为yes// export选择为yes(非常重要)
var dataArray = ReturnValue.Trim('\r', '\n').Split('\t');
float[] sealFloat = new float[2];
//充气压力
if (dataArray[3] == "")
{
sealFloat[0] = 0;
}
else
{
if (dataArray[3].Contains("-"))
{
press = dataArray[3].Remove(0, 1);
index1 = -1;
}
else
{
press = dataArray[3];
index1 = 1;
}
sealFloat[0] = float.Parse(press);
}
//测试泄露结果
if (dataArray[5] == "")
sealFloat[1] = 0;
else
{
if (dataArray[5].Contains("-"))
{
leakage = dataArray[5].Remove(0, 1);
index2 = -1;
}
else
{
leakage = dataArray[5];
index2 = 1;
}
sealFloat[1] = float.Parse(leakage);
}
int[] sealInt = new int[2];
sealInt[0] = Convert.ToInt32(sealFloat[1] * 1000) * (index2);
sealInt[1] = Convert.ToInt32(sealFloat[0] * 1000) * (index1);
Init.airtight.Airtight_Value = sealInt[0].ToString();
Init.airtight.Leak_Value = sealInt[1].ToString();
Init.airtight.LastTime = DateTime.Now;
LogExecute.logNet.WriteDebug($"通过气密仪获取到 压力值:{Init.airtight.Airtight_Value},泄露值:{Init.airtight.Leak_Value}");
}
catch (Exception ex)
{
LogExecute.logNet.WriteError($"通过气密仪获取到压力参数失败,错误原因{ex.Message}");
}
}
#endregion
// 添加状态上报定时器的事件处理方法
private void StatusReportTimer_Tick(object sender, EventArgs e)
{
try
{
// 如果没有PLC数据或者状态为0,则不上报
if (Init.Plcstatus == 0)
return;
otherdata statusOtherData = new otherdata();
statusOtherData.Plc_Status = Init.Plcstatus;
var statusResult = statusApiClient.CallFunctionByName("Status", null, statusOtherData);
if (statusResult.Success)
{
MES_MsgfORM("Status", statusResult, statusResult.Requesttime);
// 更新最后上报时间
Init.Plcstatus_LastTime = DateTime.Now;
LogExecute.logNet.WriteDebug($"定时上报机台状态成功: {Init.Plcstatus}");
}
else
{
//MES链接状态.Text = "MES链接状态:NG";
//MES链接状态.BackColor = Color.Red;
LogExecute.logNet.WriteError($"定时上报机台状态失败: MES通讯异常!");
}
}
catch (Exception ex)
{
LogExecute.logNet.WriteError($"定时上报机台状态异常: {ex.Message}");
}
}
}
}