2062 lines
89 KiB
C#
2062 lines
89 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.ComponentModel;
|
||
using System.Data;
|
||
using System.Drawing;
|
||
using System.IO;
|
||
using System.IO.Ports;
|
||
using System.Linq;
|
||
using System.Media;
|
||
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 Newtonsoft.Json.Linq;
|
||
using WindowsFormsApp1.db;
|
||
using WindowsFormsApp1.form;
|
||
using WindowsFormsApp1.mod;
|
||
using WindowsFormsApp1.mod.database;
|
||
using WindowsFormsApp1.mod.server;
|
||
using WindowsFormsApp1.server;
|
||
using static System.Collections.Specialized.BitVector32;
|
||
using static SQLite.SQLite3;
|
||
using static WindowsFormsApp1.server.ApiClient;
|
||
using Label = System.Windows.Forms.Label;
|
||
|
||
|
||
namespace WindowsFormsApp1
|
||
{
|
||
public partial class MainForm : Form
|
||
{
|
||
#region 内部变量
|
||
// 添加一个静态互斥体对象,用于防止程序多开
|
||
private static Mutex _singleInstanceMutex;
|
||
|
||
// 添加一个标志变量,用于标记是否已经执行了清理操作
|
||
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 System.Windows.Forms.Timer screwReportTimer = new System.Windows.Forms.Timer();
|
||
|
||
private System.Windows.Forms.Timer fileUploadTimer = new System.Windows.Forms.Timer();
|
||
|
||
private ApiClient statusApiClient = new ApiClient(); // 专用于状态上报的API客户端
|
||
private object curingLock = new object();
|
||
private Dictionary<int, int> OldPlcTrigger = new Dictionary<int, int>();
|
||
|
||
// 在MainForm类的成员变量部分添加
|
||
private List<Label> eventNameLabels = new List<Label>();
|
||
private List<Panel> eventPanels = new List<Panel>();
|
||
private Queue<EventInfo> eventHistory = new Queue<EventInfo>();
|
||
private const int MAX_EVENT_DISPLAY = 5;
|
||
|
||
private int beginScrewReportTimer = -100;
|
||
#endregion 内部变量
|
||
|
||
public MainForm()
|
||
{
|
||
if (!EnsureSingleInstance())
|
||
{
|
||
MessageBox.Show("程序已经在运行中,不能重复启动!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||
Environment.Exit(0);
|
||
return;
|
||
}
|
||
InitializeComponent();
|
||
InitializeEventDisplay();
|
||
CheckForIllegalCrossThreadCalls = false;
|
||
}
|
||
|
||
// 单实例运行的方法
|
||
private bool EnsureSingleInstance()
|
||
{
|
||
bool createdNew;
|
||
// 创建一个全局命名的互斥体
|
||
_singleInstanceMutex = new Mutex(true, "WindowsFormsApp1_MES_PLC_Control_SingleInstance" + Init.t_Line.linename, out createdNew);
|
||
return createdNew;
|
||
}
|
||
|
||
private void Form1_Load(object sender, EventArgs e)
|
||
{
|
||
LogExecute.logNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
|
||
LogExecute.PlclogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
|
||
LogExecute.ApilogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
|
||
LogExecute.OEElogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
|
||
|
||
FormRecover();
|
||
|
||
linename.Text = $"{Init.t_Line.linename}";
|
||
linecode.Text = $"Line: {Init.t_Line.lineremark1}";
|
||
linetype.Text = $"Station: {Init.t_Line.lineremark2}";
|
||
linemode.Text = $"MachineID: {Init.t_Line.lineremark3}";
|
||
|
||
操作人员ID.Text = Init.t_User.username;
|
||
|
||
if (Init.t_User.username == "admin")
|
||
{
|
||
修改密码ToolStripMenuItem.Enabled = true;
|
||
用户管理ToolStripMenuItem.Enabled = true;
|
||
产线管理ToolStripMenuItem.Enabled = true;
|
||
pLC管理ToolStripMenuItem.Enabled = true;
|
||
流程管理ToolStripMenuItem.Enabled = true;
|
||
mES接口配置ToolStripMenuItem.Enabled = true;
|
||
扫码枪配置ToolStripMenuItem.Enabled = true;
|
||
系统参数配置ToolStripMenuItem.Enabled = true;
|
||
}
|
||
|
||
// 初始化测试模式切换按钮
|
||
InitializeTestModeButton();
|
||
|
||
// 添加窗体关闭事件处理
|
||
this.FormClosing += MainForm_FormClosing;
|
||
|
||
// 自动开始处理
|
||
开始处理_Click(this, EventArgs.Empty);
|
||
|
||
// 初始化状态上报定时器
|
||
//statusReportTimer.Interval = int.Parse(Init.t_Keyvalues.First(x => x.key == "StatusTime").value) * 1000; // 15秒
|
||
statusReportTimer.Interval = 1000 * 15;
|
||
statusReportTimer.Tick += StatusReportTimer_Tick;
|
||
|
||
screwReportTimer.Interval = 1000 * 60 * 5;
|
||
screwReportTimer.Tick += ScrewReportTimer_Tick;
|
||
|
||
fileUploadTimer.Interval = 1000 * 60 * 2;
|
||
fileUploadTimer.Tick += FileUploadTimer_Tick;
|
||
}
|
||
|
||
public void build(t_plc Plc, CancellationToken token)
|
||
{
|
||
// 获取当前线程名称
|
||
string threadName = Thread.CurrentThread.Name ?? $"PLC_{Plc?.id}_Thread";
|
||
|
||
// 确保线程只操作自己的PLC
|
||
if (!threadName.Contains($"PLC_{Plc.id}"))
|
||
{
|
||
LogExecute.logNet.WriteError($"线程 {threadName} 尝试操作非指定PLC {Plc.id},已跳过");
|
||
return;
|
||
}
|
||
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.plcname}:{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);
|
||
List<t_oeeaddress> oeeaddresses = Init.t_Oeeaddresses.ToList();
|
||
|
||
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.plcname}:{Plc.plcip}读取全部地址处理错误:处理停止");
|
||
continue;
|
||
}
|
||
|
||
/*
|
||
* //写入心跳 在主线程取消,单独开线程 写plc心跳
|
||
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.plcname}:{Plc.plcip}写入心跳错误:处理停止");
|
||
continue;
|
||
}*/
|
||
|
||
if (Init.t_Lineplcs.Count >= 2 && Plc.id == Init.t_Lineplcs.First().plcid)
|
||
{
|
||
LOT号.Text = PlcData.Write_stSN;
|
||
Tray盘二维码.Text = PlcData.Read_MaterialCode1;
|
||
/*
|
||
//额外功能,将sn写入数据库中
|
||
var snHelper = new db.SQLiteHelper<t_sn>();
|
||
var snList = snHelper.QueryAll();
|
||
if(snList.Success && snList.Data.Count > 0)
|
||
{
|
||
var t_sn = new t_sn
|
||
{
|
||
id = 1,
|
||
sn = PlcData.Read_MaterialCode0
|
||
};
|
||
snHelper.Update(t_sn);
|
||
}
|
||
else
|
||
{
|
||
var t_sn = new t_sn
|
||
{
|
||
id = 1,
|
||
sn = PlcData.Read_MaterialCode0
|
||
};
|
||
snHelper.Insert(t_sn);
|
||
}
|
||
*/
|
||
|
||
}
|
||
if (Init.t_Lineplcs.Count == 1)
|
||
{
|
||
LOT号.Text = PlcData.Write_stSN;
|
||
Tray盘二维码.Text = PlcData.Read_MaterialCode1;
|
||
}
|
||
材料值.Text = PlcData.Read_MaterialCode2;
|
||
Init.ImageLocation = PlcData.Read_Other4;
|
||
Init.ImageName = PlcData.Read_Other3.ToString();
|
||
Init.ScrewBegin = PlcData.Read_Other2;
|
||
|
||
#region 螺丝引导相关
|
||
// 螺丝 OK/NG
|
||
string vedioFolder = Path.Combine(Application.StartupPath, "WAV");
|
||
if (PlcData.Read_Other1 == 1 && PlcData.Write_Other0 != 1)
|
||
{
|
||
var player = new SoundPlayer(Path.Combine(vedioFolder, "OK.wav"));
|
||
player.Play();
|
||
PlcData.Write_Other0 = 1;
|
||
}
|
||
else if (PlcData.Read_Other1 == 2 && PlcData.Write_Other0 != 1)
|
||
{
|
||
var player = new SoundPlayer(Path.Combine(vedioFolder, "NOK.wav"));
|
||
player.Play();
|
||
PlcData.Write_Other0 = 1;
|
||
}
|
||
|
||
var okNgresult = siemensHelp.WriteAddress(plcaddress, PlcData);
|
||
if (!okNgresult.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{Plc.plcip}写入OK/NG:处理停止");
|
||
continue;
|
||
}
|
||
|
||
var imageFormIsOpened = false;
|
||
foreach (Form form in Application.OpenForms)
|
||
{
|
||
if (form.Name == "ImageDisplayForm")
|
||
{
|
||
imageFormIsOpened = true;
|
||
}
|
||
}
|
||
// 开始打螺丝 1
|
||
if (PlcData.Read_Other2 == 1)
|
||
{
|
||
if (!imageFormIsOpened)
|
||
{
|
||
this.Invoke(new Action(() =>
|
||
{
|
||
ImageDisplayForm imageDisplayForm = new ImageDisplayForm();
|
||
imageDisplayForm.Show();
|
||
}));
|
||
}
|
||
}
|
||
#endregion 螺丝引导相关
|
||
|
||
当前时间.Text = $"PLC状态:{plcstatus.GetName(typeof(plcstatus), PlcData.Read_Status)}";
|
||
|
||
DateTime Plc_Time = DateTime.Now;
|
||
|
||
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);
|
||
//Init.Plcstatus = PlcData.Read_Status;
|
||
// 多个plc 只有一个报警
|
||
if (Plc.id == Init.t_Lineplcs.First().plcid)
|
||
{
|
||
int oldstatus = Init.Plcstatus;
|
||
if (PlcData.Read_Status != 0)
|
||
{
|
||
//状态+报警
|
||
if (oldstatus != PlcData.Read_Status)
|
||
{
|
||
//反馈状态
|
||
Init.Plcstatus = PlcData.Read_Status;
|
||
|
||
Init.Plcstatus_LastTime = DateTime.Now;
|
||
otherdata.Plc_Status = PlcData.Read_Status.ToString();
|
||
if (PlcData.Read_Status == 2)
|
||
{
|
||
// 报警的时候 赋值报警代码
|
||
var oeeresult1 = siemensHelp.ReadAddress(oeeaddresses);
|
||
|
||
Init.ErrorCode = oeeresult1.Data.FirstOrDefault(x => x.value.ToLower() == "true")?.code;
|
||
|
||
otherdata.Plc_Status = $"{PlcData.Read_Status}_{Init.ErrorCode}";
|
||
}
|
||
var statusresult = apiClient.CallFunctionByName("Status", PlcData, otherdata);
|
||
if (statusresult.Success)
|
||
{
|
||
LogExecute.OEElogNet.WriteDebug($"上报机台状态成功: {plcstatus.GetName(typeof(plcstatus), Init.Plcstatus)} {otherdata.Plc_Status}");
|
||
//beginScrewReportTimer = 0;
|
||
if (!statusReportTimer.Enabled)
|
||
{
|
||
this.Invoke(new Action(() =>
|
||
{
|
||
statusReportTimer.Start();
|
||
}));
|
||
}
|
||
else
|
||
{
|
||
this.Invoke(new Action(() =>
|
||
{
|
||
statusReportTimer.Stop();
|
||
statusReportTimer.Start();
|
||
}));
|
||
}
|
||
//MES_MsgfORM("Status", statusresult, statusresult.Requesttime);
|
||
if (statusresult.Mesresult != mesresult.PASS)
|
||
{
|
||
PlcData.Write_Status = 1001;
|
||
siemensHelp.WriteAddress(plcaddress, PlcData);
|
||
continue;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
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.停机)
|
||
{
|
||
//反馈报警
|
||
Init.Plcstatus = PlcData.Read_Status;
|
||
Init.Plcstatus_LastTime = DateTime.Now;
|
||
var statusresult = apiClient.CallFunctionByName("Alarm", PlcData, otherdata);
|
||
if (statusresult.Success)
|
||
{
|
||
LogExecute.OEElogNet.WriteDebug($"上报机台报警成功: {Init.ErrorCode}");
|
||
|
||
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 判断及查找流程
|
||
|
||
var oldtrigger = OldPlcTrigger[Plc.id];
|
||
if (PlcData.Read_Trigger == oldtrigger)
|
||
{
|
||
continue;
|
||
}
|
||
else
|
||
{
|
||
OldPlcTrigger[Plc.id] = PlcData.Read_Trigger;
|
||
}
|
||
|
||
LogExecute.logNet.WriteDebug($"读取状态字{Plc.plcname}:{Plc.id}-{PlcData.Read_Trigger}");
|
||
|
||
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}写入地址处理错误:处理停止");
|
||
}
|
||
LogExecute.logNet.WriteDebug($"写入状态字0");
|
||
continue;
|
||
}
|
||
|
||
|
||
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;
|
||
PlcData.Write_stSN = returnValue;
|
||
//Init.SN = returnValue;
|
||
LOT号.Text = returnValue;
|
||
Init.ScanString = returnValue;
|
||
}
|
||
else
|
||
{
|
||
continue;
|
||
}
|
||
}
|
||
// ccd 扫码,dzcan不用了
|
||
if (nowflow.dzscan)
|
||
{
|
||
//扫码
|
||
|
||
ScanForm scanForm = new ScanForm();
|
||
DialogResult scan_result = scanForm.ShowDialog();
|
||
if (scan_result == DialogResult.OK)
|
||
{
|
||
string returnValue = scanForm.ReturnValue;
|
||
材料值.Text = returnValue;
|
||
Init.DZString = returnValue;
|
||
}
|
||
else
|
||
{
|
||
continue;
|
||
}
|
||
/*
|
||
//扫码
|
||
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.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)
|
||
{
|
||
LogExecute.logNet.WriteError($"{Plc.plcip}螺丝枪角度数据地址处理错误:处理停止");
|
||
continue;
|
||
}
|
||
|
||
otherdata.FinalAngleValue = Enumerable
|
||
.Range(0, (finalanglevaluue_result.Data.Count + 3) / 4) // 计算组数
|
||
.Select(i => finalanglevaluue_result.Data.Skip(i * 4).Take(4).ToList())
|
||
.ToList();
|
||
}
|
||
if (nowflow.fileupload)
|
||
{
|
||
//文件上传
|
||
}
|
||
// oeedatacollection
|
||
try
|
||
{
|
||
var oeeresult = siemensHelp.ReadAddress(oeeaddresses);
|
||
otherdata.Oeeaddresses = oeeaddresses;
|
||
}
|
||
catch
|
||
{
|
||
LogExecute.logNet.WriteError("读取PLC OEE失败!");
|
||
}
|
||
#endregion
|
||
|
||
#region 判断物料调用次数 固化站,抽真空
|
||
|
||
lock (curingLock)
|
||
{
|
||
bool shouldCallApi = false;
|
||
if (Init.t_Line.lineremark2.ToLower() == "curing")
|
||
{
|
||
SQLiteHelper<t_materialcall> materialCallHelper = new SQLiteHelper<t_materialcall>();
|
||
string materialId = PlcData.Read_MaterialCode1;
|
||
|
||
var materialCall = materialCallHelper.QuerySingle(m => m.materialid == materialId
|
||
&& !m.isout).Data;
|
||
// plc1 进 plc2,3 加热,冷却,plc3 出
|
||
if (Plc.id == 1)
|
||
{
|
||
// checkin callapi
|
||
if (nowinterface.code.Contains("SN_CheckIN"))
|
||
{
|
||
materialCall = new t_materialcall { materialid = materialId };
|
||
materialCall.sn = "testsn";
|
||
materialCall.checkin1 = DateTime.Now;
|
||
materialCallHelper.Insert(materialCall);
|
||
shouldCallApi = true;
|
||
}
|
||
else if (nowinterface.code.Contains("Checkout"))
|
||
{
|
||
materialCall.checkout1 = DateTime.Now;
|
||
materialCall.sn = PlcData.Write_stSN;
|
||
materialCallHelper.Update(materialCall);
|
||
}
|
||
}
|
||
else if (Plc.id == 2 || Plc.id == 3)
|
||
{
|
||
if (nowinterface.code.Contains("SN_CheckIN"))
|
||
{
|
||
materialCall.checkin2 = DateTime.Now;
|
||
materialCallHelper.Update(materialCall);
|
||
|
||
PlcData.Write_stSN = materialCall.sn;
|
||
}
|
||
else if (nowinterface.code.Contains("Checkout"))
|
||
{
|
||
materialCall.checkout2 = DateTime.Now;
|
||
materialCallHelper.Update(materialCall);
|
||
}
|
||
}
|
||
else if (Plc.id == 4)
|
||
{
|
||
//checkout callapi
|
||
if (nowinterface.code.Contains("SN_CheckIN"))
|
||
{
|
||
materialCall.checkin3 = DateTime.Now;
|
||
materialCallHelper.Update(materialCall);
|
||
|
||
PlcData.Write_stSN = materialCall.sn;
|
||
}
|
||
else if (nowinterface.code.Contains("Checkout"))
|
||
{
|
||
materialCall.checkout3 = DateTime.Now;
|
||
materialCall.isout = true;
|
||
materialCallHelper.Update(materialCall);
|
||
shouldCallApi = true;
|
||
}
|
||
}
|
||
|
||
if (!shouldCallApi)
|
||
{
|
||
// 不需要调用接口,直接返回成功
|
||
PlcData.Write_Status = PlcData.Read_Trigger;
|
||
var writeresult = siemensHelp.WriteAddress(plcaddress, PlcData);
|
||
if (!writeresult.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{Plc.plcip}写入地址处理错误:处理停止");
|
||
continue;
|
||
}
|
||
continue;
|
||
}
|
||
}
|
||
|
||
/* else if (Init.t_Line.lineremark2.ToLower() == "vacuum")
|
||
{
|
||
//抽真空,两个穴位,判断是否重复进站
|
||
SQLiteHelper<t_materialcall> materialCallHelper = new SQLiteHelper<t_materialcall>();
|
||
string materialId = PlcData.Read_MaterialCode1;
|
||
|
||
var materialCall = materialCallHelper.QuerySingle(m => m.materialid == materialId
|
||
&& !m.isout).Data;
|
||
if (materialCall == null)
|
||
{
|
||
//首次进站 in
|
||
materialCall.materialid = materialId;
|
||
materialCallHelper.Insert(materialCall);
|
||
shouldCallApi = true;
|
||
}
|
||
else if (materialCall.isout)
|
||
{
|
||
//不交互MES,直接返回状态字
|
||
PlcData.Write_Status = PlcData.Read_Trigger;
|
||
var writeresult = siemensHelp.WriteAddress(plcaddress, PlcData);
|
||
if (!writeresult.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{Plc.plcip}写入地址处理错误:处理停止");
|
||
continue;
|
||
}
|
||
continue;
|
||
}
|
||
else
|
||
{
|
||
// out
|
||
materialCall.isout = true;
|
||
materialCallHelper.Update(materialCall);
|
||
shouldCallApi = true;
|
||
}
|
||
}*/
|
||
}
|
||
#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;
|
||
otherdata.plcid = Plc.id;
|
||
|
||
#region 调用后端接口
|
||
var result = apiClient.CallFunctionByName(nowinterface.code, PlcData, otherdata);
|
||
//if (result.IsShow)
|
||
//{
|
||
// MES_MsgfORM(nowinterface.code, result, result.Requesttime);
|
||
//}
|
||
|
||
if (result.Success)
|
||
{
|
||
ChangeBarcode();
|
||
MES_MsgfORM(nowinterface.code, result, result.Requesttime);
|
||
|
||
var writeresult = siemensHelp.WriteAddress(plcaddress, PlcData);
|
||
if (!writeresult.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{Plc.plcname}:{Plc.plcip}写入地址处理错误:处理停止");
|
||
continue;
|
||
}
|
||
else
|
||
{
|
||
if (result.Mesresult != mesresult.PASS)
|
||
{
|
||
if (result.Msg.Contains("机台上料数量不够扣料")
|
||
|| result.Msg.Contains("没有上料"))
|
||
{
|
||
PlcData.Write_Status = 1003;
|
||
}
|
||
else if (result.Msg.Contains("此载具为空"))
|
||
{
|
||
PlcData.Write_Status = 1004;
|
||
}
|
||
else
|
||
{
|
||
PlcData.Write_Status = 1001;
|
||
}
|
||
siemensHelp.WriteAddress(plcaddress, PlcData);
|
||
LogExecute.logNet.WriteDebug($"{Plc.plcname}:{Plc.plcip}上位机写入触发字:{PlcData.Write_Status}");
|
||
continue;
|
||
}
|
||
else
|
||
{
|
||
//出站清空sn
|
||
if (nowinterface.code == "SN_Checkout")
|
||
{
|
||
PlcData.Write_stSN = "";
|
||
}
|
||
}
|
||
LogExecute.logNet.WriteDebug($"{Plc.plcname}:{Plc.plcip}上位机写入触发字:{PlcData.Write_Status}");
|
||
|
||
}
|
||
}
|
||
else
|
||
{
|
||
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_oeeaddress> sQLiteHelper_oee = new db.SQLiteHelper<t_oeeaddress>();
|
||
var oee_result = sQLiteHelper_oee.QueryAll();
|
||
if (!oee_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;
|
||
}
|
||
|
||
foreach (var item in Init.t_Lineplcs)
|
||
{
|
||
if (!OldPlcTrigger.ContainsKey(item.plcid))
|
||
OldPlcTrigger.Add(item.plcid, 0);
|
||
}
|
||
|
||
#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_Oeeaddresses = oee_result.Data;
|
||
Init.t_Interfaces = interface_result.Data;
|
||
Init.t_Keyvalues = key_sqlresult.Data;
|
||
Init.t_plcs = plc_result;
|
||
|
||
// 初始化PLC状态面板
|
||
InitializePlcStatusPanel();
|
||
|
||
// 启动状态上报定时器
|
||
statusReportTimer.Start();
|
||
|
||
//测试环境不上传数据
|
||
if (Init.t_Keyvalues.FirstOrDefault(x => x.key == "TestMode").value == "0")
|
||
{
|
||
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".ToLower().Contains(Init.t_Line.lineremark2.ToLower()))
|
||
{
|
||
screwReportTimer.Start();
|
||
}
|
||
fileUploadTimer.Start();
|
||
}
|
||
#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 事件
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
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;
|
||
}
|
||
|
||
}
|
||
}
|
||
}
|
||
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.Name = $"PLC_{plc.id}_Thread"; // 显式设置线程名称
|
||
threadHelp.Thread.Start();
|
||
threadHelp.isrunning1 = true;
|
||
}
|
||
Init.threadHelps.Add(threadHelp);
|
||
//心跳线程
|
||
ThreadHelp threadHelp1 = new ThreadHelp();
|
||
if (!threadHelp1.isrunning1)
|
||
{
|
||
threadHelp1.cancellationTokenSource1 = new CancellationTokenSource();
|
||
threadHelp1.Thread = new Thread(() => plcheart(plc, threadHelp1.cancellationTokenSource1.Token));
|
||
threadHelp1.Thread.Name = $"PLC_{plc.id}_heartThread"; // 显式设置线程名称
|
||
threadHelp1.Thread.Start();
|
||
threadHelp1.isrunning1 = true;
|
||
}
|
||
Init.threadHelps.Add(threadHelp1);
|
||
}
|
||
|
||
if (Init.t_User.username.ToLower() != "admin")
|
||
{
|
||
this.btnToggleTestMode.Enabled = false;
|
||
}
|
||
|
||
开始处理.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;
|
||
}
|
||
}
|
||
}
|
||
|
||
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
|
||
{
|
||
开始处理.Enabled = false;
|
||
// 设置窗体正在关闭标志
|
||
_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(); // 重新触发关闭
|
||
}));
|
||
}
|
||
});
|
||
}
|
||
|
||
// 释放互斥体
|
||
if (_singleInstanceMutex != null)
|
||
{
|
||
_singleInstanceMutex.ReleaseMutex();
|
||
_singleInstanceMutex.Close();
|
||
_singleInstanceMutex = null;
|
||
}
|
||
}
|
||
|
||
// 添加一个清理资源的私有方法
|
||
private void CleanupResources()
|
||
{
|
||
try
|
||
{
|
||
// 停止状态上报定时器
|
||
statusReportTimer.Stop();
|
||
screwReportTimer.Stop();
|
||
fileUploadTimer.Stop();
|
||
|
||
// 停止所有线程
|
||
if (Init.threadHelps != null)
|
||
{
|
||
foreach (var thread in Init.threadHelps)
|
||
{
|
||
try
|
||
{
|
||
if (thread.Thread != null && thread.Thread.IsAlive)
|
||
{
|
||
thread.cancellationTokenSource1?.Cancel();
|
||
var threadEnded = thread.Thread.Join(3000); // 等待线程完成
|
||
if (!threadEnded)
|
||
{
|
||
LogExecute.logNet.WriteWarn($"线程 {thread.Thread.Name} 未能在规定时间内结束,将强制继续");
|
||
}
|
||
}
|
||
thread.isrunning1 = false;
|
||
thread.Dispose();
|
||
}
|
||
catch { /* 忽略异常 */ }
|
||
}
|
||
Init.threadHelps.Clear();
|
||
}
|
||
|
||
// 安全关闭串口
|
||
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 oEE地址管理ToolStripMenuItem_Click(object sender, EventArgs e)
|
||
{
|
||
OEEaddress_Manage oeeManage = new OEEaddress_Manage();
|
||
oeeManage.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 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();
|
||
}
|
||
|
||
private void 图片标注ToolStripMenuItem_Click(object sender, EventArgs e)
|
||
{
|
||
SimpleImageDisplayForm simpleImageDisplayForm = new SimpleImageDisplayForm();
|
||
simpleImageDisplayForm.ShowDialog();
|
||
}
|
||
|
||
private void 螺丝引导ToolStripMenuItem_Click(object sender, EventArgs e)
|
||
{
|
||
try
|
||
{
|
||
ImageDisplayForm imageDisplayForm = new ImageDisplayForm();
|
||
imageDisplayForm.SetCurrentName(Init.ImageName);
|
||
imageDisplayForm.ShowDialog();
|
||
}
|
||
catch
|
||
{
|
||
}
|
||
}
|
||
#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;
|
||
}
|
||
|
||
// 确定应该显示在哪个日志框中
|
||
RichTextBox targetLogBox;
|
||
|
||
// 根据日志来源确定目标日志框
|
||
if (sender == LogExecute.OEElogNet)
|
||
{
|
||
targetLogBox = richTextBox2; // PLC相关日志显示在第二个日志框
|
||
}
|
||
else
|
||
{
|
||
targetLogBox = richTextBox1; // 其他日志显示在第一个日志框
|
||
}
|
||
|
||
logBuilder.Append(logPrefix).Append(time.ToString()).Append(" | ").Append(text).Append("\n");
|
||
|
||
// 检查日志行数,如果超过阈值则清理
|
||
int lineCount = targetLogBox.GetLineFromCharIndex(targetLogBox.TextLength);
|
||
if (lineCount >= 200)
|
||
{
|
||
// 优化:只保留后 100 行,而不是全部清空再重新添加
|
||
int startIndex = targetLogBox.GetFirstCharIndexFromLine(lineCount - 100);
|
||
if (startIndex > 0)
|
||
{
|
||
targetLogBox.Select(0, startIndex);
|
||
targetLogBox.SelectedText = "";
|
||
}
|
||
}
|
||
|
||
// 添加新日志
|
||
targetLogBox.SelectionStart = richTextBox1.TextLength;
|
||
targetLogBox.SelectionLength = 0;
|
||
targetLogBox.SelectionColor = logColor;
|
||
targetLogBox.AppendText(logBuilder.ToString());
|
||
|
||
// 重置颜色并滚动到底部
|
||
targetLogBox.SelectionStart = richTextBox1.TextLength;
|
||
targetLogBox.SelectionLength = 0;
|
||
targetLogBox.SelectionColor = richTextBox1.ForeColor;
|
||
targetLogBox.ScrollToCaret();
|
||
}));
|
||
}
|
||
catch { /* 忽略异常 */ }
|
||
}
|
||
|
||
// 添加一个事件信息类
|
||
private class EventInfo
|
||
{
|
||
public string Name { get; set; }
|
||
public mesresult Result { get; set; }
|
||
public DateTime Time { get; set; }
|
||
public string Message { get; set; }
|
||
}
|
||
|
||
private void timer1_Tick(object sender, EventArgs e)
|
||
{
|
||
当前时间.Text = "当前时间:" + DateTime.Now.ToString("MM-dd HH:mm:ss");
|
||
}
|
||
|
||
public void FormRecover()
|
||
{
|
||
开始处理.Text = "开始处理";
|
||
开始处理.BackColor = Color.Green;
|
||
|
||
底部注释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;
|
||
}
|
||
|
||
#region PLC状态面板
|
||
// 添加初始化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 = Color.Gray;
|
||
plcStatusIndicators[plcId].BackColor = isConnected ? Color.Green : Color.Red;
|
||
});
|
||
}
|
||
}
|
||
catch { /* 忽略异常 */ }
|
||
}
|
||
#endregion PLC状态面板
|
||
|
||
#region 事件显示区域
|
||
// 添加初始化事件显示区域的方法
|
||
private void InitializeEventDisplay()
|
||
{
|
||
// 清空现有列表
|
||
eventNameLabels.Clear();
|
||
eventPanels.Clear();
|
||
|
||
// 检查 eventTableLayout 是否已存在并且已配置
|
||
if (eventTableLayout != null && eventTableLayout.RowCount >= MAX_EVENT_DISPLAY)
|
||
{
|
||
// 从 TableLayoutPanel 中获取已有的控件
|
||
for (int i = 0; i < MAX_EVENT_DISPLAY; i++)
|
||
{
|
||
// 获取每行的标签和面板
|
||
var nameLabel = eventTableLayout.GetControlFromPosition(0, i) as Label;
|
||
var resultPanel = eventTableLayout.GetControlFromPosition(1, i) as Panel;
|
||
|
||
if (nameLabel != null && resultPanel != null)
|
||
{
|
||
// 将找到的控件添加到列表中
|
||
eventNameLabels.Add(nameLabel);
|
||
eventPanels.Add(resultPanel);
|
||
|
||
// 初始化标签和面板的状态
|
||
nameLabel.Text = "";
|
||
resultPanel.BackColor = SystemColors.Control;
|
||
}
|
||
}
|
||
|
||
// 如果没有找到足够的控件,则创建新的
|
||
if (eventNameLabels.Count < MAX_EVENT_DISPLAY)
|
||
{
|
||
LogExecute.logNet.WriteDebug($"事件显示区域控件不足,需要重新创建");
|
||
|
||
// 清空现有控件
|
||
eventTableLayout.Controls.Clear();
|
||
eventNameLabels.Clear();
|
||
eventPanels.Clear();
|
||
|
||
// 重新创建控件
|
||
for (int i = 0; i < MAX_EVENT_DISPLAY; i++)
|
||
{
|
||
// 创建事件名称标签
|
||
Label nameLabel = new Label();
|
||
nameLabel.Dock = DockStyle.Fill;
|
||
nameLabel.TextAlign = ContentAlignment.MiddleLeft;
|
||
nameLabel.Margin = new Padding(3);
|
||
nameLabel.Text = "";
|
||
|
||
// 创建事件结果面板
|
||
Panel resultPanel = new Panel();
|
||
resultPanel.Dock = DockStyle.Fill;
|
||
resultPanel.Margin = new Padding(3);
|
||
resultPanel.BackColor = SystemColors.Control;
|
||
|
||
// 添加到TableLayoutPanel
|
||
eventTableLayout.Controls.Add(nameLabel, 0, i);
|
||
eventTableLayout.Controls.Add(resultPanel, 1, i);
|
||
|
||
// 保存引用以便后续更新
|
||
eventNameLabels.Add(nameLabel);
|
||
eventPanels.Add(resultPanel);
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
// eventTableLayout 不存在或未正确配置,记录错误
|
||
LogExecute.logNet.WriteError("事件显示区域未正确配置,无法初始化");
|
||
}
|
||
|
||
// 初始化事件历史队列
|
||
eventHistory = new Queue<EventInfo>();
|
||
|
||
}
|
||
|
||
// 修改UpdateEventDisplay方法
|
||
private void UpdateEventDisplay(string name, mesresult result, DateTime dateTime, string message)
|
||
{
|
||
// 创建新的事件信息
|
||
EventInfo newEvent = new EventInfo
|
||
{
|
||
Name = name,
|
||
Result = result,
|
||
Time = dateTime,
|
||
Message = message
|
||
};
|
||
|
||
// 添加到历史记录
|
||
eventHistory.Enqueue(newEvent);
|
||
|
||
// 如果超过最大显示数量,移除最早的记录
|
||
while (eventHistory.Count > MAX_EVENT_DISPLAY)
|
||
{
|
||
eventHistory.Dequeue();
|
||
}
|
||
|
||
// 更新显示
|
||
UpdateEventDisplayFromHistory();
|
||
}
|
||
|
||
// 添加从历史记录更新显示的方法
|
||
private void UpdateEventDisplayFromHistory()
|
||
{
|
||
// 将历史记录转换为数组以便倒序访问
|
||
EventInfo[] events = eventHistory.ToArray();
|
||
|
||
// 清空所有标签和面板
|
||
for (int i = 0; i < MAX_EVENT_DISPLAY; i++)
|
||
{
|
||
eventNameLabels[i].Text = "";
|
||
eventPanels[i].BackColor = SystemColors.Control;
|
||
}
|
||
|
||
// 计算开始显示的索引,确保最新的事件显示在底部
|
||
int startIndex = 0;
|
||
int displayCount = Math.Min(events.Length, MAX_EVENT_DISPLAY);
|
||
|
||
// 填充显示区域,按照时间顺序从上到下排列
|
||
for (int i = 0; i < displayCount; i++)
|
||
{
|
||
// 获取当前事件(从最早的开始)
|
||
EventInfo currentEvent = events[i];
|
||
|
||
// 更新事件名称标签
|
||
eventNameLabels[i].Text = $"{currentEvent.Name} | {currentEvent.Time.ToString("HH:mm:ss")} ";
|
||
|
||
// 更新事件结果面板颜色
|
||
switch (currentEvent.Result)
|
||
{
|
||
case mesresult.PASS:
|
||
eventPanels[i].BackColor = Color.Green;
|
||
break;
|
||
case mesresult.FAIL:
|
||
eventPanels[i].BackColor = Color.Red;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 显示信息
|
||
public void MES_MsgfORM(string name, ApiFormResult result, DateTime dateTime)
|
||
{
|
||
if ("status,alarm".Contains(name.ToLower()))
|
||
return;
|
||
// 显示MES提示信息
|
||
MES提示信息.Visible = true;
|
||
MES提示信息.Text = $"{result.Msg}";
|
||
MES提示信息.ForeColor = result.Mesresult == mesresult.PASS ? Color.Green : Color.Red;
|
||
|
||
事件结果.Visible = true;
|
||
事件结果.Text = result.Mesresult == mesresult.PASS ? "PASS" : "FAIL";
|
||
事件结果.ForeColor = result.Mesresult == mesresult.PASS ? Color.Green : Color.Red;
|
||
|
||
// 更新事件显示区域
|
||
UpdateEventDisplay(name, result.Mesresult, dateTime, result.Msg);
|
||
}
|
||
|
||
#endregion 事件显示区域
|
||
|
||
#endregion
|
||
|
||
#region 其他业务处理
|
||
//气密接收
|
||
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}");
|
||
if (ReturnValue.Length < 30)
|
||
{
|
||
//后一台气密
|
||
//<01>:(OK): 0.032 ml/min
|
||
//LogExecute.logNet.WriteDebug(ReturnValue);
|
||
Init.airtight.Leak_Value = ReturnValue.Substring(11, 5);
|
||
Init.airtight.LastTime = DateTime.Now;
|
||
}
|
||
else
|
||
{
|
||
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;
|
||
}
|
||
CsvLogger.Log($"{Init.airtight.Airtight_Value},{Init.airtight.Leak_Value}");
|
||
LogExecute.SNlogNet.WriteDebug($"通过气密仪获取到 压力值:{Init.airtight.Airtight_Value},泄露值:{Init.airtight.Leak_Value}");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogExecute.logNet.WriteError($"通过气密仪获取到压力参数失败,错误原因{ex.Message}");
|
||
}
|
||
}
|
||
|
||
// 在初始化组件的方法中添加按钮
|
||
private void InitializeTestModeButton()
|
||
{
|
||
// 初始化按钮状态
|
||
UpdateTestModeButtonState();
|
||
}
|
||
|
||
// 切换测试模式的事件处理程序
|
||
private void BtnToggleTestMode_Click(object sender, EventArgs e)
|
||
{
|
||
// 获取当前模式并切换
|
||
SQLiteHelper<t_keyvalue> kvHelper = new db.SQLiteHelper<t_keyvalue>();
|
||
var testModeSetting = kvHelper.QuerySingle(x => x.key == "TestMode");
|
||
bool currentMode = testModeSetting.Success ? testModeSetting.Data.value == "1" : true;
|
||
|
||
// 切换模式
|
||
bool newMode = !currentMode;
|
||
|
||
// 更新数据库
|
||
if (testModeSetting.Success)
|
||
{
|
||
testModeSetting.Data.value = newMode ? "1" : "0";
|
||
kvHelper.Update(testModeSetting.Data);
|
||
}
|
||
else
|
||
{
|
||
// 如果设置不存在,创建新的设置
|
||
t_keyvalue newSetting = new t_keyvalue
|
||
{
|
||
key = "TestMode",
|
||
value = newMode ? "1" : "0",
|
||
remark = "接口测试模式:1=调试模式,0=MES模式"
|
||
};
|
||
kvHelper.Insert(newSetting);
|
||
}
|
||
|
||
// 更新按钮状态
|
||
UpdateTestModeButtonState();
|
||
|
||
// 显示提示
|
||
MessageBox.Show(newMode ? "已切换到调试模式,不调用实际接口" : "已切换到MES模式,将调用实际接口");
|
||
|
||
// 记录日志
|
||
LogExecute.logNet.WriteInfo($"用户{Init.t_User.username}切换接口模式为: {(newMode ? "调试模式" : "MES模式")}");
|
||
}
|
||
|
||
// 更新测试模式按钮状态
|
||
private void UpdateTestModeButtonState()
|
||
{
|
||
SQLiteHelper<t_keyvalue> kvHelper = new db.SQLiteHelper<t_keyvalue>();
|
||
var testModeSetting = kvHelper.QuerySingle(x => x.key == "TestMode");
|
||
bool isTestMode = testModeSetting.Success ? testModeSetting.Data.value == "1" : true;
|
||
|
||
btnToggleTestMode.Text = $"{(isTestMode ? "调试模式" : "MES模式")}";
|
||
btnToggleTestMode.BackColor = isTestMode ? Color.LightPink : Color.LightGreen;
|
||
}
|
||
#endregion
|
||
|
||
#region 定时器
|
||
// 添加状态上报定时器的事件处理方法
|
||
private void StatusReportTimer_Tick(object sender, EventArgs e)
|
||
{
|
||
try
|
||
{
|
||
//beginScrewReportTimer++;
|
||
// 如果没有PLC数据或者状态为0,则不上报
|
||
if (Init.Plcstatus == 0 || Init.Plcstatus == -1)
|
||
{
|
||
return;
|
||
}
|
||
|
||
otherdata statusOtherData = new otherdata();
|
||
statusOtherData.Plc_Status = Init.Plcstatus.ToString();
|
||
if (Init.Plcstatus == 2)
|
||
{
|
||
//报警
|
||
statusOtherData.Plc_Status = $"{Init.Plcstatus}_{Init.ErrorCode}";
|
||
}
|
||
var statusResult = statusApiClient.CallFunctionByName("Status", new plcdata(), statusOtherData);
|
||
if (statusResult.Success)
|
||
{
|
||
beginScrewReportTimer = 0;
|
||
//MES_MsgfORM("Status", statusResult, statusResult.Requesttime);
|
||
|
||
// 更新最后上报时间
|
||
Init.Plcstatus_LastTime = DateTime.Now;
|
||
|
||
LogExecute.OEElogNet.WriteDebug($"定时上报机台状态成功: {plcstatus.GetName(typeof(plcstatus), Init.Plcstatus)},{statusOtherData.Plc_Status}");
|
||
}
|
||
else
|
||
{
|
||
LogExecute.OEElogNet.WriteError($"定时上报机台状态失败: MES通讯异常!");
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogExecute.logNet.WriteError($"定时上报机台状态异常: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
//螺丝扭力上传定时器
|
||
private void ScrewReportTimer_Tick(object sender, EventArgs e)
|
||
{
|
||
// 螺丝站
|
||
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".ToLower().Contains(Init.t_Line.lineremark2.ToLower()))
|
||
{
|
||
SQLiteHelper<t_materialupload> sQLiteHelper_upload = new db.SQLiteHelper<t_materialupload>();
|
||
var material_sqlresult = sQLiteHelper_upload
|
||
.Query(x => x.datacollectionUploaded == 1 && x.sn != "");
|
||
if (material_sqlresult.Success)
|
||
{
|
||
ApiClient apiClient = new ApiClient();
|
||
var materialList = material_sqlresult.Data.Where(x => (DateTime.Now - x.outtime).TotalMinutes > 20).Take(5);
|
||
foreach (var material in materialList)
|
||
{
|
||
otherdata OtherData = new otherdata();
|
||
OtherData.material = material;
|
||
var result = apiClient.CallFunctionByName("Data_Collection", new plcdata(), OtherData);
|
||
if (result.Success)
|
||
{
|
||
//MES_MsgfORM("Data_Collection", result, result.Requesttime);
|
||
if (result.Mesresult == mesresult.PASS)
|
||
{
|
||
//标记该物料已上传
|
||
material.datacollectionUploaded = 2;
|
||
sQLiteHelper_upload.Update(material);
|
||
LogExecute.logNet.WriteDebug($"{material.sn} 扭力上报成功!");
|
||
}
|
||
else if (result.Mesresult == mesresult.NONE)
|
||
{
|
||
material.datacollectionUploaded = 3;
|
||
sQLiteHelper_upload.Update(material);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// 定时扫描 周期扫描未上传 图片,视频等 sn,然后调用上传文件接口 todo
|
||
|
||
private void FileUploadTimer_Tick(object sender, EventArgs e)
|
||
{
|
||
//LogExecute.logNet.WriteDebug($"定时器文件执行!");
|
||
SQLiteHelper<t_materialupload> sQLiteHelper_upload = new db.SQLiteHelper<t_materialupload>();
|
||
var material_sqlresult = sQLiteHelper_upload
|
||
.Query(x => (x.imageUploaded == 1 || x.vedioUploaded == 1)
|
||
&& x.sn != ""
|
||
&& x.sn != "TEST MODE testsn");
|
||
if (material_sqlresult.Success)
|
||
{
|
||
ApiClient apiClient = new ApiClient();
|
||
var materialList = material_sqlresult.Data.Take(5);
|
||
foreach (var material in materialList)
|
||
{
|
||
otherdata OtherData = new otherdata();
|
||
OtherData.material = material;
|
||
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;
|
||
|
||
var result = apiClient.CallFunctionByName("SN_FileUpload", new plcdata(), OtherData);
|
||
if (result.Success)
|
||
{
|
||
//MES_MsgfORM("Data_Collection", result, result.Requesttime);
|
||
if (result.Mesresult == mesresult.PASS)
|
||
{
|
||
//标记该物料已上传
|
||
if (material.imageUploaded == 1)
|
||
material.imageUploaded = 2;
|
||
if (material.vedioUploaded == 1)
|
||
material.vedioUploaded = 2;
|
||
sQLiteHelper_upload.Update(material);
|
||
LogExecute.logNet.WriteDebug($"{material.sn} 文件上传成功!");
|
||
}
|
||
else if (result.Mesresult == mesresult.NONE)
|
||
{
|
||
//标记该物料已上传
|
||
if (material.imageUploaded == 1)
|
||
material.imageUploaded = 3;
|
||
if (material.vedioUploaded == 1)
|
||
material.vedioUploaded = 3;
|
||
sQLiteHelper_upload.Update(material);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
#endregion 定时器
|
||
|
||
/// <summary>
|
||
/// 螺丝开盖
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void button1_Click(object sender, EventArgs e)
|
||
{
|
||
var plc = Init.t_plcs.FirstOrDefault();
|
||
plc.plchelp = new SiemensHelp(plc.plcip, plc.timeout);
|
||
SiemensHelp siemensHelp = plc.plchelp;
|
||
|
||
List<t_plcaddress> plcaddress = Init.t_Plcaddresses.FindAll(a => a.plcid == plc.id);
|
||
|
||
var openresult = siemensHelp.OpenConn();
|
||
|
||
plcdata PlcData = new plcdata();
|
||
|
||
var resdresult = siemensHelp.ReadAddress(plcaddress, PlcData);
|
||
if (!resdresult.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{plc.plcname}:{plc.plcip}读取全部地址处理错误:处理停止");
|
||
}
|
||
|
||
//扫码
|
||
ScanForm scanForm = new ScanForm();
|
||
DialogResult scan_result = scanForm.ShowDialog();
|
||
if (scan_result == DialogResult.OK)
|
||
{
|
||
string returnValue = scanForm.ReturnValue;
|
||
|
||
var writeVal = Init.t_Keyvalues.First(x => x.key == returnValue)?.value;
|
||
if (string.IsNullOrEmpty(writeVal))
|
||
{
|
||
PlcData.Write_Other4 = short.Parse(writeVal);
|
||
var result = siemensHelp.WriteAddress(plcaddress, PlcData);
|
||
if (!result.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{plc.plcname}:{plc.plcip}写入螺丝开盖失败:处理停止");
|
||
}
|
||
else
|
||
{
|
||
LogExecute.logNet.WriteInfo($"{plc.plcname}:{plc.plcip}写入螺丝开盖成功,值:{writeVal}");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
LogExecute.logNet.WriteError($"未找到螺丝开盖二维码!");
|
||
}
|
||
}
|
||
}
|
||
|
||
//plc心跳
|
||
private void plcheart(t_plc Plc, CancellationToken token)
|
||
{
|
||
Task.Factory.StartNew(() =>
|
||
{
|
||
while (!token.IsCancellationRequested)
|
||
{
|
||
try
|
||
{
|
||
SiemensHelp siemensHelp = Plc.plchelp;
|
||
List<t_plcaddress> plcaddress = Init.t_Plcaddresses.FindAll(a => a.plcid == Plc.id
|
||
&& a.code == "Write_Heartbeat");
|
||
|
||
List<t_plcaddress> timeplcaddress = Init.t_Plcaddresses.FindAll(a => a.plcid == Plc.id
|
||
&& a.code == "NowDateTime");
|
||
|
||
plcdata PlcData = new plcdata();
|
||
|
||
var resdresult = siemensHelp.ReadAddress(plcaddress, PlcData);
|
||
if (!resdresult.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{Plc.plcname}:{Plc.plcip}读取全部地址处理错误!");
|
||
}
|
||
|
||
//写入心跳
|
||
PlcData.Write_Heartbeat = PlcData.Write_Heartbeat == 0 ? (short)1 : (short)0;
|
||
|
||
var haertresult = siemensHelp.WriteAddress(plcaddress, PlcData);
|
||
if (!haertresult.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{Plc.plcname}:{Plc.plcip}写入心跳失败!");
|
||
}
|
||
|
||
//写入时间
|
||
var timeData = new plcdata
|
||
{
|
||
NowDateTime = DateTime.Now.AddSeconds(3)
|
||
};
|
||
var timeresult = siemensHelp.WriteAddress(timeplcaddress, timeData);
|
||
if (!timeresult.Success)
|
||
{
|
||
LogExecute.logNet.WriteError($"{Plc.plcname}:{Plc.plcip}写入时间失败!");
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
finally
|
||
{
|
||
Thread.Sleep(1000);
|
||
}
|
||
}
|
||
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default
|
||
);
|
||
}
|
||
}
|
||
}
|