4.18 checkin不管成功失败都写sn

加上needwork的判定
datacollection 判断dcinfo为空,不传mes,事件不显示在事件列表,只记录日志
状态上传定时器重新修改上传逻辑
文件上传定时器
This commit is contained in:
gf zhou 2025-04-20 18:13:53 +08:00
parent 4419a4de3c
commit 76cd069435
7 changed files with 461 additions and 239 deletions

View File

@ -182,7 +182,9 @@
<Compile Include="form\OEEaddress_Manage.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="form\OEEaddress_Manage.Designer.cs" />
<Compile Include="form\OEEaddress_Manage.Designer.cs">
<DependentUpon>OEEaddress_Manage.cs</DependentUpon>
</Compile>
<Compile Include="form\ScanForm_DZ.cs">
<SubType>Form</SubType>
</Compile>
@ -342,6 +344,11 @@
<EmbeddedResource Include="form\Angleaddress_Manage.resx">
<DependentUpon>Angleaddress_Manage.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="form\OEEaddress_Manage.resx">
<DependentUpon>OEEaddress_Manage.cs</DependentUpon>
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>OEEaddress_Manage1.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Include="form\ScanForm_DZ.resx">
<DependentUpon>ScanForm_DZ.cs</DependentUpon>
</EmbeddedResource>

View File

@ -23,6 +23,7 @@ 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;
@ -50,6 +51,9 @@ namespace WindowsFormsApp1
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>();
@ -59,6 +63,8 @@ namespace WindowsFormsApp1
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()
@ -121,11 +127,15 @@ namespace WindowsFormsApp1
开始处理_Click(this, EventArgs.Empty);
// 初始化状态上报定时器
statusReportTimer.Interval = int.Parse(Init.t_Keyvalues.First(x => x.key == "StatusTime").value) * 1000; // 15秒
//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 = 8000;
screwReportTimer.Interval = 1000 * 60 * 15;
screwReportTimer.Tick += ScrewReportTimer_Tick;
fileUploadTimer.Interval = 1000 * 60 * 5;
fileUploadTimer.Tick += FileUploadTimer_Tick;
}
public void build(t_plc Plc, CancellationToken token)
@ -188,17 +198,17 @@ namespace WindowsFormsApp1
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;
}*/
/*
* //写入心跳 在主线程取消,单独开线程 写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)
@ -228,9 +238,9 @@ namespace WindowsFormsApp1
snHelper.Insert(t_sn);
}
*/
}
if(Init.t_Lineplcs.Count == 1)
if (Init.t_Lineplcs.Count == 1)
{
LOT号.Text = PlcData.Write_stSN;
Tray盘二维码.Text = PlcData.Read_MaterialCode1;
@ -276,7 +286,8 @@ namespace WindowsFormsApp1
{
if (!imageFormIsOpened)
{
this.Invoke(new Action(() => {
this.Invoke(new Action(() =>
{
ImageDisplayForm imageDisplayForm = new ImageDisplayForm();
imageDisplayForm.Show();
}));
@ -312,7 +323,7 @@ namespace WindowsFormsApp1
{
//反馈状态
Init.Plcstatus = PlcData.Read_Status;
Init.Plcstatus_LastTime = DateTime.Now;
otherdata.Plc_Status = PlcData.Read_Status.ToString();
if (PlcData.Read_Status == 2)
@ -328,8 +339,23 @@ namespace WindowsFormsApp1
if (statusresult.Success)
{
LogExecute.OEElogNet.WriteDebug($"上报机台状态成功: {plcstatus.GetName(typeof(plcstatus), Init.Plcstatus)} {Init.ErrorCode}");
MES_MsgfORM("Status", statusresult, statusresult.Requesttime);
//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;
@ -434,7 +460,7 @@ namespace WindowsFormsApp1
}
#endregion
#region 根据流程,判断是否需要扫码、气密、扭力等
if (nowflow.scan)
{
@ -472,62 +498,62 @@ namespace WindowsFormsApp1
{
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 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 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;
*/
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;
@ -735,7 +761,7 @@ namespace WindowsFormsApp1
{
ChangeBarcode();
MES_MsgfORM(nowinterface.code, result, result.Requesttime);
var writeresult = siemensHelp.WriteAddress(plcaddress, PlcData);
if (!writeresult.Success)
{
@ -771,7 +797,7 @@ namespace WindowsFormsApp1
PlcData.Write_stSN = "";
}
}
LogExecute.logNet.WriteDebug($"上位机写入触发字:{PlcData.Write_Status}");
}
}
else
@ -884,7 +910,7 @@ namespace WindowsFormsApp1
foreach (var item in Init.t_Lineplcs)
{
if(!OldPlcTrigger.ContainsKey(item.plcid))
if (!OldPlcTrigger.ContainsKey(item.plcid))
OldPlcTrigger.Add(item.plcid, 0);
}
@ -905,7 +931,12 @@ namespace WindowsFormsApp1
// 启动状态上报定时器
statusReportTimer.Start();
screwReportTimer.Start();
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".ToLower().Contains(Init.t_Line.lineremark2.ToLower()))
{
screwReportTimer.Start();
}
//fileUploadTimer.Start();
#endregion
@ -989,7 +1020,7 @@ namespace WindowsFormsApp1
Init.threadHelps.Add(threadHelp1);
}
if(Init.t_User.username.ToLower() != "admin")
if (Init.t_User.username.ToLower() != "admin")
{
this.btnToggleTestMode.Enabled = false;
}
@ -1073,6 +1104,7 @@ namespace WindowsFormsApp1
// 停止状态上报定时器
statusReportTimer.Stop();
screwReportTimer.Stop();
fileUploadTimer.Stop();
// 停止所有线程
if (Init.threadHelps != null)
@ -1091,9 +1123,11 @@ namespace WindowsFormsApp1
}
}
thread.isrunning1 = false;
thread.Dispose();
}
catch { /* 忽略异常 */ }
}
Init.threadHelps.Clear();
}
// 安全关闭串口
@ -1624,91 +1658,95 @@ namespace WindowsFormsApp1
//气密接收
public void AirtightPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
// 使用异步方法处理串口数据
Task.Run(() =>
{
if (!Init.AirtightPort.IsOpen)
try
{
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
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] == "")
if (!Init.AirtightPort.IsOpen)
{
sealFloat[0] = 0;
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
Init.airtight.Leak_Value = ReturnValue.Substring(11, 5);
Init.airtight.LastTime = DateTime.Now;
}
else
{
if (dataArray[3].Contains("-"))
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] == "")
{
press = dataArray[3].Remove(0, 1);
index1 = -1;
sealFloat[0] = 0;
}
else
{
press = dataArray[3];
index1 = 1;
if (dataArray[3].Contains("-"))
{
press = dataArray[3].Remove(0, 1);
index1 = -1;
}
else
{
press = dataArray[3];
index1 = 1;
}
sealFloat[0] = float.Parse(press);
}
sealFloat[0] = float.Parse(press);
}
//测试泄露结果
if (dataArray[5] == "")
sealFloat[1] = 0;
else
{
if (dataArray[5].Contains("-"))
{
leakage = dataArray[5].Remove(0, 1);
index2 = -1;
}
//测试泄露结果
if (dataArray[5] == "")
sealFloat[1] = 0;
else
{
leakage = dataArray[5];
index2 = 1;
if (dataArray[5].Contains("-"))
{
leakage = dataArray[5].Remove(0, 1);
index2 = -1;
}
else
{
leakage = dataArray[5];
index2 = 1;
}
sealFloat[1] = float.Parse(leakage);
}
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;
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}");
}
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}");
}
catch (Exception ex)
{
LogExecute.logNet.WriteError($"通过气密仪获取到压力参数失败,错误原因{ex.Message}");
}
});
}
// 在初始化组件的方法中添加按钮
@ -1775,10 +1813,13 @@ namespace WindowsFormsApp1
{
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)
@ -1789,7 +1830,8 @@ namespace WindowsFormsApp1
var statusResult = statusApiClient.CallFunctionByName("Status", new plcdata(), statusOtherData);
if (statusResult.Success)
{
MES_MsgfORM("Status", statusResult, statusResult.Requesttime);
beginScrewReportTimer = 0;
//MES_MsgfORM("Status", statusResult, statusResult.Requesttime);
// 更新最后上报时间
Init.Plcstatus_LastTime = DateTime.Now;
@ -1810,33 +1852,74 @@ namespace WindowsFormsApp1
//螺丝扭力上传定时器
private void ScrewReportTimer_Tick(object sender, EventArgs e)
{
SQLiteHelper<t_materialupload> sQLiteHelper_upload = new db.SQLiteHelper<t_materialupload>();
var material_sqlresult = sQLiteHelper_upload
.Query(x => x.datacollectionUploaded == 1);
if (material_sqlresult.Success)
// 螺丝站
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".ToLower().Contains(Init.t_Line.lineremark2.ToLower()))
{
ApiClient apiClient = new ApiClient();
var materialList = material_sqlresult.Data.Take(5);
foreach(var material in materialList)
SQLiteHelper<t_materialupload> sQLiteHelper_upload = new db.SQLiteHelper<t_materialupload>();
var material_sqlresult = sQLiteHelper_upload
.Query(x => x.datacollectionUploaded == 1 && !string.IsNullOrEmpty(x.sn));
if (material_sqlresult.Success)
{
otherdata OtherData = new otherdata();
OtherData.material = material;
var result = apiClient.CallFunctionByName("Data_Collection", new plcdata(), OtherData);
if (result.Success)
ApiClient apiClient = new ApiClient();
var materialList = material_sqlresult.Data.Where(x => (DateTime.Now - x.outtime).TotalHours > 1).Take(5);
foreach (var material in materialList)
{
MES_MsgfORM("Data_Collection", result, result.Requesttime);
if(result.Mesresult == mesresult.PASS)
otherdata OtherData = new otherdata();
OtherData.material = material;
var result = apiClient.CallFunctionByName("Data_Collection", new plcdata(), OtherData);
if (result.Success)
{
//标记该物料已上传
material.datacollectionUploaded = 2;
sQLiteHelper_upload.Update(material);
LogExecute.OEElogNet.WriteDebug($"{material.sn} 扭力上报成功!");
//MES_MsgfORM("Data_Collection", result, result.Requesttime);
if (result.Mesresult == mesresult.PASS)
{
//标记该物料已上传
material.datacollectionUploaded = 2;
sQLiteHelper_upload.Update(material);
LogExecute.logNet.WriteDebug($"{material.sn} 扭力上报成功!");
}
}
}
}
}
}
// 定时扫描 周期扫描未上传 图片,视频等 sn,然后调用上传文件接口 todo
private void FileUploadTimer_Tick(object sender, EventArgs e)
{
SQLiteHelper<t_materialupload> sQLiteHelper_upload = new db.SQLiteHelper<t_materialupload>();
var material_sqlresult = sQLiteHelper_upload
.Query(x => (x.imageUploaded == 1) && x.sn != "");
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} 文件上传成功!");
}
}
}
}
}
#endregion 定时器
/// <summary>
@ -1889,43 +1972,48 @@ namespace WindowsFormsApp1
}
}
}
//plc心跳
private void plcheart(t_plc Plc, CancellationToken token)
{
while (!token.IsCancellationRequested)
Task.Factory.StartNew(() =>
{
try
while (!token.IsCancellationRequested)
{
SiemensHelp siemensHelp = Plc.plchelp;
List<t_plcaddress> plcaddress = Init.t_Plcaddresses.FindAll(a => a.plcid == Plc.id);
plcdata PlcData = new plcdata();
var resdresult = siemensHelp.ReadAddress(plcaddress, PlcData);
if (!resdresult.Success)
try
{
LogExecute.logNet.WriteError($"{Plc.plcname}:{Plc.plcip}读取全部地址处理错误!");
SiemensHelp siemensHelp = Plc.plchelp;
List<t_plcaddress> plcaddress = Init.t_Plcaddresses.FindAll(a => a.plcid == Plc.id
&& a.code.Contains("Heartbeat"));
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;
//LogExecute.logNet.WriteDebug($"{Plc.plcname}:{Plc.plcip}写入心跳{PlcData.Write_Heartbeat}!");
var haertresult = siemensHelp.WriteAddress(plcaddress, PlcData);
if (!haertresult.Success)
{
LogExecute.logNet.WriteError($"{Plc.plcname}:{Plc.plcip}写入心跳错误!");
}
}
//写入心跳
PlcData.Write_Heartbeat = PlcData.Write_Heartbeat == 0 ? (short)1 : (short)0;
//LogExecute.logNet.WriteDebug($"{Plc.plcname}:{Plc.plcip}写入心跳{PlcData.Write_Heartbeat}!");
var haertresult = siemensHelp.WriteAddress(plcaddress, PlcData);
if (!haertresult.Success)
catch (Exception)
{
LogExecute.logNet.WriteError($"{Plc.plcname}:{Plc.plcip}写入心跳错误!");
}
finally
{
Thread.Sleep(1000);
}
}
catch (Exception)
{
}
finally
{
Thread.Sleep(1000);
}
}
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default
);
}
}
}

View File

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -16,5 +16,6 @@ namespace WindowsFormsApp1.mod
public int vedioUploaded { get; set; }
public int datacollectionUploaded { get; set; }
public string date { get; set; }
public DateTime outtime { get; set; }
}
}

View File

@ -157,7 +157,8 @@ namespace WindowsFormsApp1.server
var response = _httpClient.PostAsync(url, httpContent).Result;
// 检查响应状态码
if (response.StatusCode == System.Net.HttpStatusCode.OK)
if (response.StatusCode == System.Net.HttpStatusCode.OK
|| response.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
// 读取响应内容
string responseContent = response.Content.ReadAsStringAsync().Result;
@ -174,14 +175,15 @@ namespace WindowsFormsApp1.server
if (res.Result != null && !string.IsNullOrEmpty(res.Result.Value))
{
var result = res.Result.Value == "PASS";
if(!string.IsNullOrEmpty( res?.Need_Work?.Value) && res?.Need_Work?.Value == "PASS")
result = true;
if (eventName == "SN_Release" || eventName == "SN_CheckIN")
PlcData.Write_stSN = res.SN.Value;
if (result)
{
// 回写对应PLC
if (statusCode > 0)
PlcData.Write_Status = (short)statusCode;
if (eventName == "SN_Release" || eventName == "SN_CheckIN")
PlcData.Write_stSN = res.SN.Value;
if (eventName == "SN_FeedingCheck")
{
var station = Init.t_Line.lineremark2.ToLower();
@ -447,7 +449,7 @@ namespace WindowsFormsApp1.server
//判断站
var station = Init.t_Line.lineremark2.ToLower();
var fixsn_1 = "";
var locationindex = 1;
var locationindex = "";
switch (station)
{
case "potting"://灌胶
@ -457,7 +459,7 @@ namespace WindowsFormsApp1.server
break;
default:
fixsn_1 = "CompSN";
locationindex = OtherData.locationindex;
locationindex = OtherData.locationindex.ToString();
break;
}
@ -468,13 +470,13 @@ namespace WindowsFormsApp1.server
StationID = _stationID,
MachineID = _machineID,
OPID = OtherData.opindex,
Token = locationindex.ToString() ?? "",//判断站,胶水不用传
Token = locationindex ?? "",//判断站,胶水不用传
FixSN = fixsn_1,//判断站,胶水不用传
SN = OtherData.JS_SN ?? "",
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
};
return CallApi(url, request, "Glue_CheckOut", PlcData, PLC_Status.Glue_CheckOut);
return CallApi(url, request, "Glue_CheckOut", PlcData, 0);
}
/// <summary>
@ -525,7 +527,7 @@ namespace WindowsFormsApp1.server
else if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".ToLower().Contains(station))
{
// 扭力 读马头服务器
var geturl = $"http://10.50.12.41/getdata/v2/tighteningresults?startTime={OtherData.material.date}&endTime={DateTime.Now.AddDays(1).ToString("yyyy-MM-dd")}&vin={OtherData.material.sn}&controllerName={Init.t_Line.lineremark2}@{Init.t_Line.linecode}&includeCurve=true&includeSteps=false";
var geturl = $"http://10.50.12.41/getdata/v2/tighteningresults?startTime={OtherData.material.date.Substring(0,10)}&endTime={DateTime.Now.AddDays(1).ToString("yyyy-MM-dd")}&vin={OtherData.material.sn}&controllerName={Init.t_Line.lineremark2}@{Init.t_Line.linecode}&includeCurve=true&includeSteps=false";
//var geturl = "http://10.50.12.41/getdata/v2/tighteningresults?startTime=2025-04-11&endTime=2025-04-12&vin=ok&controllerName=OP1260%4010.50.247.110&includeCurve=true&includeSteps=false";
var res = _httpClient.GetAsync(geturl).Result;
@ -582,15 +584,17 @@ namespace WindowsFormsApp1.server
LogExecute.logNet.WriteError($"解析马头数据,发生错误: {ex.Message}");
}
}
else
{
return ApiFormResult.Sucess(mesresult.FAIL, false, "请求马头服务器获取数据失败", PlcData, DateTime.Now);
}
if(request.DC_INFO.Count == 0)
{
return ApiFormResult.Sucess(mesresult.FAIL, false, "请求马头服务器获取数据失败", PlcData, DateTime.Now);
}
}
return CallApi(url, request, "Data_Collection", PlcData, statusCode);
//if(result.Success && result.Mesresult == mesresult.PASS)
//{
// OtherData.material.datacollectionUploaded = 2;
// var dbhelper = new SQLiteHelper<t_materialupload>();
// dbhelper.Update(OtherData.material);
//}
}
public ApiFormResult Status(string url, plcdata PlcData, otherdata OtherData)
@ -620,7 +624,7 @@ namespace WindowsFormsApp1.server
StationID = _stationID,
MachineID = _machineID,
OPID = _opID,
AlarmID = Init.ErrorCode,
AlarmID = Init.ErrorCode ?? "",
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
ResetTime = ""
};
@ -638,21 +642,30 @@ namespace WindowsFormsApp1.server
public ApiFormResult SN_FileUpload(string url, plcdata PlcData, otherdata OtherData)
{
// 准备文件 视频/图片 目的路径拼接
var month = DateTime.Now.ToString("yyyyMM");
var day = DateTime.Now.ToString("dd");
var month = OtherData.material.date.Substring(0,6);
var day = OtherData.material.date.Substring(6, 2);
var monthDay = DateTime.Now.ToString("MMdd");
var time = DateTime.Now.ToString("HHmmss");
var result = PlcData.Read_Result == 1 ? "OK" : "NG";
var result = OtherData.material.result;
var targetDirectory = $"{OtherData.FileUploadAddress}{_line.Substring(0, 2)}\\{month}\\{day}\\Line{_line.Substring(_line.Length - 2)}\\{_stationID}\\{_machineID}\\{result}";
var fileName = "";
try
{
string[] sourceFolders = new string[] {
string[] sourceFolders = new string[]
{
OtherData.ImageAddress,
OtherData.VedioAddress
};
if (OtherData.material.imageUploaded != 1)
{
sourceFolders[0] = "";
}
if (OtherData.material.vedioUploaded != 1)
{
sourceFolders[1] = "";
}
// 使用分号分隔多个源文件夹
string targetFolder = targetDirectory;
List<string> fileList = new List<string>();
@ -666,11 +679,6 @@ namespace WindowsFormsApp1.server
return ApiFormResult.Error(mesresult.FAIL, false, "SN号为空", PlcData, DateTime.Now);
}
if (!Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
foreach (string folder in sourceFolders)
{
if (string.IsNullOrEmpty(folder))
@ -678,32 +686,32 @@ namespace WindowsFormsApp1.server
continue;
}
//判断此sn需要传哪些数据 图片 或视频 todo
string sourceFolder = sourceFolders[0];
if (sourceFolder == folder)
string sourceFolder = "";
if (OtherData.ImageAddress == folder)
{
// 图片
// 组装路径 可能需要从数据库读 result和sn和日期
sourceFolder = Path.Combine(sourceFolder, OtherData.material.date, "DCDC", result);
sourceFolder = Path.Combine(OtherData.ImageAddress, OtherData.material.date, "DCDC", result);
}
else
{
// 视频
sourceFolder = Path.Combine(sourceFolder, DateTime.Now.ToString("yyyy-MM-dd"));
sourceFolder = Path.Combine(OtherData.VedioAddress, DateTime.Now.ToString("yyyy-MM-dd"));
}
if (Directory.Exists(sourceFolder.Trim()))
{
string[] files = Directory.GetFiles(sourceFolder.Trim());
int num = 1;
var extensionstr = "";
foreach (string file in files)
foreach (string file in files.Where(x => x.Contains(snNumber)))
{
string fileName1 = Path.GetFileName(file);
string filePath = "";
if (!fileName1.Contains(snNumber))
{
continue;
}
extensionstr = Path.GetExtension(file);
var datetime = Directory.GetLastWriteTime(file);
monthDay = datetime.ToString("MMdd");
time = datetime.ToString("HHmmss");
fileName = $"{month}{day}_{_stationID}_{result}_{snNumber}_{monthDay}_{time}_{_machineID}_01_Detection_{num}{extensionstr}";
filePath = Path.Combine(sourceFolder, fileName1);
CopyFileToDirectory(filePath, targetFolder, fileName);
@ -736,7 +744,7 @@ namespace WindowsFormsApp1.server
{
new
{
SN = PlcData.Write_stSN,
SN = snNumber,
FileInfo = fileList.Select(x => new
{
FileName = x,
@ -747,7 +755,7 @@ namespace WindowsFormsApp1.server
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
};
return CallApi(url, request, "SN_FileUpload", PlcData, PLC_Status.SN_FileUpload);
return CallApi(url, request, "SN_FileUpload", PlcData, 0);
}
catch (Exception ex)
{
@ -893,7 +901,8 @@ namespace WindowsFormsApp1.server
CarrierID = PlcData.Read_MaterialCode1,
datacollectionUploaded = 1,
result = logresult,
date = DateTime.Now.ToString("yyyy-MM-dd")
date = DateTime.Now.ToString("yyyy-MM-dd"),
outtime = DateTime.Now
};
materialuploadHelper.Insert(material);
}
@ -1039,7 +1048,8 @@ namespace WindowsFormsApp1.server
sn = PlcData.Write_stSN,
imageUploaded = 1,
result = logresult,
date = DateTime.Now.ToString("yyyyMMdd")
date = DateTime.Now.ToString("yyyyMMdd"),
outtime = DateTime.Now
};
materialuploadHelper.Insert(material);
}
@ -1062,7 +1072,8 @@ namespace WindowsFormsApp1.server
sn = PlcData.Write_stSN,
vedioUploaded = 1,
result = logresult,
date = DateTime.Now.ToString("yyyy-MM-dd")
date = DateTime.Now.ToString("yyyy-MM-dd"),
outtime = DateTime.Now
};
materialuploadHelper.Insert(material);
}
@ -1139,6 +1150,7 @@ namespace WindowsFormsApp1.server
return CallApi(url, request, "OEEDataCollection", PlcData, PLC_Status.OEEDataCollection);
}
#region 暂时不用
public ApiFormResult Test(string url, plcdata PlcData, otherdata OtherData)
{
@ -1257,6 +1269,7 @@ namespace WindowsFormsApp1.server
}
}
#region 辅助实体类
/// <summary>
/// checkout dcinfo item
/// </summary>
@ -1424,7 +1437,9 @@ namespace WindowsFormsApp1.server
public double angle { get; set; }
}
#endregion 马头扭力角度数据 类
#endregion 辅助实体类
// 文件copy方法
public bool CopyFileToDirectory(string sourceFilePath, string targetDirectory, string fileName)
{
@ -1439,7 +1454,11 @@ namespace WindowsFormsApp1.server
{
Directory.CreateDirectory(targetDirectory);
}
// 判断是否重复上传
if (Directory.GetFiles(targetDirectory).Any(x => x.Contains(fileName)))
{
return true;
}
string targetPath = Path.Combine(targetDirectory, fileName);
try

View File

@ -13,7 +13,7 @@ namespace WindowsFormsApp1.server
public static ILogNet PlclogNet = new LogNetDateTime("C:\\Log\\PlcLogs", GenerateMode.ByEveryDay);
public static ILogNet ApilogNet = new LogNetDateTime("C:\\Log\\Apilogs", GenerateMode.ByEveryHour);
public static ILogNet SNlogNet = new LogNetDateTime("C:\\Log\\SNlogs", GenerateMode.ByEveryDay);
public static ILogNet OEElogNet = new LogNetDateTime("C:\\Log\\Apilogs", GenerateMode.ByEveryDay);
public static ILogNet OEElogNet = new LogNetDateTime("C:\\Log\\OEElogs", GenerateMode.ByEveryDay);
public static HslCommunication.BasicFramework.SoftNumericalOrder softNumericalOrder = new HslCommunication.BasicFramework.SoftNumericalOrder("", "yyyyMMdd", 4, @"\numericalOrder.txt");

View File

@ -7,10 +7,16 @@ using System.Threading.Tasks;
namespace WindowsFormsApp1.server
{
public class ThreadHelp
public class ThreadHelp :IDisposable
{
public Thread Thread { get; set; }
public bool isrunning1 = false;
public CancellationTokenSource cancellationTokenSource1;
public bool isrunning1 {get;set;}= false;
public CancellationTokenSource cancellationTokenSource1{get;set;}
public void Dispose()
{
cancellationTokenSource1?.Cancel();
cancellationTokenSource1?.Dispose();
Thread = null;
}
}
}