图片测试,csv文件日志,文件复制半成品

This commit is contained in:
zhougf committed 2025-03-27 20:37:21 +08:00
1 parent d9a3f19678
commit 57299c0b55
13 files changed
+1064 -85

No files matched your search

+260 -71
View File
@@ -19,6 +19,7 @@ using HslCommunication.BasicFramework;
using System.IO;
using static WindowsFormsApp1.server.ApiClient;
using System.Security.Policy;
using System.Diagnostics;
namespace WindowsFormsApp1.server
{
@@ -54,7 +55,12 @@ namespace WindowsFormsApp1.server
_opID = Init.t_User.username;
// 初始化 CsvLogger
CsvLogger.Initialize("D:/Logs/logs.csv");
// 设置自定义表头
//var customHeaders = new List<string> { "SN", "值1", "消息", "异常" };
//CsvLogger.SetHeaders(customHeaders);
//线别.Text = "线别:" + Init.t_Line.linename;
//段别.Text = "段别:" + Init.t_Line.linemode;
//机台编号.Text = "机台编号:" + Init.t_Line.linecode;
@@ -74,34 +80,34 @@ namespace WindowsFormsApp1.server
try
{
// 测试
LogExecute.logNet.WriteDebug($"{eventName} 接口请求模拟测试成功\n请求:{jsonPayload}");
//LogExecute.logNet.WriteDebug($"{eventName} 接口请求模拟测试成功\n请求:{jsonPayload}");
// 回写对应PLC
if (statusCode > 0)
PlcData.Write_Status = (short)statusCode;
if (eventName == "SN_Release")
PlcData.Write_stSN = "testsn";
if(eventName == "Glue_CheckOut")
{
var station = Init.t_Line.lineremark2.ToLower();
switch (station)
{
case "potting"://灌胶
case "thermalpaste"://点胶&CCD检测
case "uvcoating"://三防漆涂覆
case "sealant"://点密封胶&CCD
var power = Init.t_Keyvalues.First(x => x.key == "Power");
power.value = DateTime.Now.Millisecond.ToString();
SQLiteHelper<t_keyvalue> kvHelper = new db.SQLiteHelper<t_keyvalue>();
kvHelper.Update(power);
//if (statusCode > 0)
// PlcData.Write_Status = (short)statusCode;
//if (eventName == "SN_Release")
// PlcData.Write_stSN = "testsn";
//if(eventName == "Glue_CheckOut")
//{
// var station = Init.t_Line.lineremark2.ToLower();
// switch (station)
// {
// case "potting"://灌胶
// case "thermalpaste"://点胶&CCD检测
// case "uvcoating"://三防漆涂覆
// case "sealant"://点密封胶&CCD
// var power = Init.t_Keyvalues.First(x => x.key == "Power");
// power.value = DateTime.Now.Millisecond.ToString();
// SQLiteHelper<t_keyvalue> kvHelper = new db.SQLiteHelper<t_keyvalue>();
// kvHelper.Update(power);
break;
}
}
return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData, DateTime.Now);
// break;
// }
//}
//return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData, DateTime.Now);
#region 测试不用
/*
#region MES交互
var response = _httpClient.PostAsync(url, httpContent).Result;
// 检查响应状态码
if (response.IsSuccessStatusCode)
@@ -129,6 +135,23 @@ namespace WindowsFormsApp1.server
PlcData.Write_Status = (short)statusCode;
if (eventName == "SN_Release")
PlcData.Write_stSN = res.SN.Value;
if (eventName == "SN_FeedingCheck")
{
var station = Init.t_Line.lineremark2.ToLower();
switch (station)
{
case "potting"://灌胶
case "thermalpaste"://点胶&CCD检测
case "uvcoating"://三防漆涂覆
case "sealant"://点密封胶&CCD
var power = Init.t_Keyvalues.First(x => x.key == "Power");
power.value = res.SN.Value.ToString();
SQLiteHelper<t_keyvalue> kvHelper = new db.SQLiteHelper<t_keyvalue>();
kvHelper.Update(power);
break;
}
}
}
else
{
@@ -139,8 +162,8 @@ namespace WindowsFormsApp1.server
}
}
return result
? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG.Value, PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, true, res.MSG.Value, PlcData, DateTime.Now);
? ApiFormResult.Sucess(mesresult.PASS, false, res.Msg.Value, PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, true, res.Msg.Value, PlcData, DateTime.Now);
}
else if (res.IsSuccess != null) // 打印 mes不返回result
{
@@ -148,8 +171,8 @@ namespace WindowsFormsApp1.server
if (statusCode > 0)
PlcData.Write_Status = (short)statusCode;
return res.IsSuccess.Value == true
? ApiFormResult.Sucess(mesresult.PASS, true, res.MSG?.Value ?? "", PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG?.Value ?? "", PlcData, DateTime.Now);
? ApiFormResult.Sucess(mesresult.PASS, true, res.Msg?.Value ?? "", PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, false, res.Msg?.Value ?? "", PlcData, DateTime.Now);
}
}
}
@@ -157,7 +180,7 @@ namespace WindowsFormsApp1.server
{
throw new Exception($"请求失败,状态码:{response.StatusCode}");
}
*/
#endregion 测试不用
}
catch (Exception ex)
@@ -223,6 +246,23 @@ namespace WindowsFormsApp1.server
/// <returns></returns>
public ApiFormResult SN_FeedingCheck(string url, plcdata PlcData, otherdata OtherData)
{
//判断是否为胶水站,是查询materialscan中上线的胶水码
var station = Init.t_Line.lineremark2.ToLower();
switch (station)
{
case "potting"://灌胶
case "thermalpaste"://点胶&CCD检测
case "uvcoating"://三防漆涂覆
case "sealant"://点密封胶&CCD
SQLiteHelper<t_materialscan> glueHelper = new db.SQLiteHelper<t_materialscan>();
var glue = glueHelper.QuerySingle(x => x.isonline);
if (glue.Success)
{
OtherData.JS_SN = glue.Data.scancode;
OtherData.locationindex = int.Parse(glue.Data.position);
}
break;
}
// 组装 request json
var request = new
{
@@ -233,7 +273,7 @@ namespace WindowsFormsApp1.server
OPID = _opID,
Token = _token,
FixSN = _fixsn,
SN = OtherData.JS_SN,//扫码
SN = OtherData.JS_SN??"test",//扫码
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
};
@@ -241,12 +281,13 @@ namespace WindowsFormsApp1.server
if (result.Success && result.Mesresult != mesresult.PASS)
{
// 判断是否是胶水站,FAIL 直接下线 todo
return CallFunctionByName("Glue_CheckOut", PlcData, OtherData);
}
else
{
return result;
if ("Potting,ThermalPaste,Sel_Soldering,UVCoating,Sealant".Contains(station))
{
OtherData.opindex = 2;
return CallFunctionByName("Glue_CheckOut", PlcData, OtherData);
}
}
return result;
}
/// <summary>
@@ -275,7 +316,7 @@ namespace WindowsFormsApp1.server
Qty = "1"
}
},
SN = OtherData.JS_SN,
SN = Init.SN,
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
};
@@ -301,8 +342,8 @@ namespace WindowsFormsApp1.server
OPID = _opID,
Token = _token,
FixSN = _fixsn,
SN = OtherData.JS_SN,
CarrierID = "",
SN = Init.ScanString,
CarrierID = PlcData.Read_MaterialCode1,
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
};
// 特殊处理:需要设置Write_stSN
@@ -331,7 +372,7 @@ namespace WindowsFormsApp1.server
case "sealant"://点密封胶&CCD
break;
default:
fixsn_1 = "CompPN";
fixsn_1 = "CompSN";
locationindex = OtherData.locationindex;
break;
}
@@ -369,9 +410,31 @@ namespace WindowsFormsApp1.server
StationID = _stationID,
MachineID = _machineID,
OPID = _opID,
SN = OtherData.JS_SN,
SN = OtherData.JS_SN ?? PlcData.Read_MaterialCode0 ?? "test",
CarrierID = PlcData.Read_MaterialCode1,
DC_INFO = new List<DCInfoItem>(),
CompList = new List<CompListItem>(),
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
};
request.CompList.Add(new CompListItem
{
CompID = "",
Qty = "1"
});
var station = Init.t_Line.lineremark2.ToLower();
if (station == "vacuum")
{
// 抽真空
foreach(var val in OtherData.FinalPressureCurve.Where(x => x > 0))
{
request.DC_INFO.Add(new DCInfoItem
{
Item = "Chamber_Pressure",
Value = val.ToString()
});
}
}
// 扭力 读马头服务器 todo
return CallApi(url, request, "Data_Collection", PlcData, PLC_Status.Data_Collection);
}
@@ -427,12 +490,117 @@ namespace WindowsFormsApp1.server
var time = DateTime.Now.ToString("HHmmss");
var result = PlcData.Read_Result == 1 ? "OK" : "NG";
var sourceDirectory = @"";
var targetDirectory = $"{OtherData.FileUploadAddress}\\{_line.Substring(0, 2)}\\{month}\\{day}\\line{_line.Substring(_line.Length - 2)}\\{_stationID}\\{_machineID}\\{result}";
var fileName = $"{month}{day}_{_stationID}_{result}_{PlcData.Write_stSN}_{monthDay}_{time}_{_machineID}_Original01.png";
OtherData.FileUploadAddress = @"W:\\";
var sourceDirectory = @"D:\\";
var targetDirectory = $"{OtherData.FileUploadAddress}{_line.Substring(0, 2)}\\{month}\\{day}\\Line{_line.Substring(_line.Length - 2)}\\{_stationID}\\{_machineID}\\{result}";
var fileName = "";
try
{
string[] sourceFolders = OtherData.FileUploadAddress.Split(';'); // 使用分号分隔多个源文件夹
string targetFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UploadFiles");
List<string> fileList = new List<string>();
string snNumber = PlcData.Read_MaterialCode0;
if (string.IsNullOrEmpty(snNumber))
{
LogExecute.logNet.WriteError("SN号为空,无法处理文件");
return ApiFormResult.Error(mesresult.FAIL, false, "SN号为空", PlcData, DateTime.Now);
}
if (!Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
foreach (string sourceFolder in sourceFolders)
{
if (Directory.Exists(sourceFolder.Trim()))
{
string[] files = Directory.GetFiles(sourceFolder.Trim());
foreach (string file in files)
{
string fileName1 = Path.GetFileName(file);
if (!fileName1.Contains(snNumber))
{
continue;
}
string targetPath = Path.Combine(targetFolder, fileName);
File.Copy(file, targetPath, true);
fileList.Add(fileName);
LogExecute.logNet.WriteDebug($"文件 {fileName} 已从 {sourceFolder.Trim()} 复制到 {targetPath}");
}
}
else
{
LogExecute.logNet.WriteDebug($"源文件夹 {sourceFolder.Trim()} 不存在");
}
}
if (fileList.Count == 0)
{
LogExecute.logNet.WriteDebug($"在所有源文件夹中未找到包含SN号 {snNumber} 的文件");
}
// 组装 request json
var request = new
{
Line = _line,
StationID = _stationID,
MachineID = _machineID,
OPID = _opID,
SNList = new List<dynamic>()
{
new
{
SN = OtherData.JS_SN,
FileInfo = fileList.Select(x => new
{
FileName = fileName,
FilePath = targetFolder
}).ToList()
}
},
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
};
return CallApi(url, request, "SN_FileUpload", PlcData, PLC_Status.SN_FileUpload);
}
catch (Exception ex)
{
LogExecute.logNet.WriteError($"文件上传处理失败: {ex.Message}");
return ApiFormResult.Error(mesresult.FAIL, false, ex.Message, PlcData, DateTime.Now);
}
/*
// 查找源文件 可能会有多张照片或视频
string sourceFile = Path.Combine(sourceDirectory, "source.png");
//string targetDir = Path.Combine(targetDirectory, "target");
var filelist = Directory.GetFiles(sourceDirectory);
var copyedFileList = new List<string>();
string sourceFile = "";
var num = 1;
foreach (var file in filelist)
{
// 分别处理每张图片
var sourceName = Path.GetFileNameWithoutExtension(file);
if (sourceName.Contains(PlcData.Read_MaterialCode0))
{
sourceFile = Path.Combine(sourceDirectory, sourceName);
var extensionstr = Path.GetExtension(file);
fileName = $"{month}{day}_{_stationID}_{result}_{PlcData.Read_MaterialCode0}_{monthDay}_{time}_{_machineID}_01_Original{num}.{extensionstr}";
//执行复制
var copyResult = CopyFileToDirectory(sourceFile, targetDirectory, fileName);
if (copyResult)
{
copyedFileList.Add(fileName);
num++;
}
}
}
// 执行复制
try
{
@@ -470,21 +638,10 @@ namespace WindowsFormsApp1.server
// 多个视频或图片
// 动态添加 FileInfo
/*
var newFileInfo = new
{
FileName = "NewFileName.txt",
FilePath = "C:\\path\\to\\newfile.txt"
};
// 获取 SNList 的第一个元素(假设只有一个 SN 元素)
dynamic snElement = request.SNList[0];
// 将 newFileInfo 添加到 FileInfo 列表中
snElement.FileInfo.Add(newFileInfo);
*/
return CallApi(url, request, "SN_FileUpload", PlcData, PLC_Status.SN_FileUpload);
*/
}
/// <summary>
@@ -500,7 +657,7 @@ namespace WindowsFormsApp1.server
var request = new
{
Line = _line, // 特殊值,不使用_line
StationID = _stationID,
Station = _stationID,
MachineID = _machineID,
SN = PlcData.Read_MaterialCode0
};
@@ -512,7 +669,7 @@ namespace WindowsFormsApp1.server
{
// 根据不同的lineCode构建不同的请求
var lineCode = Init.t_Line.linecode;
var stationid = Init.t_Line.lineremark2.ToLower();
var stationid = Init.t_Line.lineremark2;
var result = PlcData.Read_Result == 1 ? "PASS" : "FAIL";
var logresult = PlcData.Read_Result == 1 ? "OK" : "NG";
@@ -550,26 +707,29 @@ namespace WindowsFormsApp1.server
//气密
if ("WAT,Leakage".Contains(stationid))
{
var customHeaders = new List<string> { "SN", { OutItem.充气压力 }, { OutItem.泄漏量 }, "时间" };
CsvLogger.SetHeaders(customHeaders);
sninfo.DC_INFO.Add(new DCInfoItem
{
Item = OutItem.充气压力,
Value = Init.airtight.Airtight_Value,
Value = Init.airtight.Airtight_Value ?? "0",
Result = result
});
sninfo.DC_INFO.Add(new DCInfoItem
{
Item = OutItem.泄漏量,
Value = Init.airtight.Leak_Value,
Value = Init.airtight.Leak_Value ?? "0",
Result = result
});
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{Init.airtight.Airtight_Value},{Init.airtight.Leak_Value}");
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{Init.airtight.Airtight_Value},{Init.airtight.Leak_Value},{DateTime.Now}");
}
//扭力,角度
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM".Contains(stationid))
{
var AngleCount = 1;
OtherData.FinalAngleValue[0] = (float)12.8888;
OtherData.FinalAngleValue[1] = (float)11.9999;
foreach (var item in OtherData.FinalAngleValue.Where(x => x > 0))
{
//角度
@@ -579,9 +739,13 @@ namespace WindowsFormsApp1.server
dcInfo.Result = result;
sninfo.DC_INFO.Add(dcInfo);
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
AngleCount++;
}
var TorqueCount = 1;
OtherData.FinalTorqueValue[0] = (float)120;
OtherData.FinalTorqueValue[1] = (float)110;
foreach (var item in OtherData.FinalTorqueValue.Where(x => x > 0))
{
//扭力
@@ -591,6 +755,8 @@ namespace WindowsFormsApp1.server
dcInfo.Result = result;
sninfo.DC_INFO.Add(dcInfo);
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
TorqueCount++;
}
}
@@ -598,6 +764,7 @@ namespace WindowsFormsApp1.server
//CCD
if ("Assy2,Assy3,AOI,Assy5,Sealant,CCD,PrintLabel".Contains(stationid))
{
dcInfo = new DCInfoItem();
dcInfo.Item = stationid == "CCD"? "CCD" : $"{Init.t_Line.lineremark2}_CCD";
dcInfo.Value = PlcData.Read_UploadData0.ToString();
dcInfo.Result = result;
@@ -608,7 +775,21 @@ namespace WindowsFormsApp1.server
//抽真空 压力
if ("Vacuum".Contains(stationid))
{
var Chamber_Pressure = OtherData.FinalPressureCurve.First();
dcInfo = new DCInfoItem();
dcInfo.Item = $"Chamber_Pressure";
dcInfo.Value = Chamber_Pressure.ToString();
dcInfo.Result = result;
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
sninfo.DC_INFO.Add(dcInfo);
dcInfo = new DCInfoItem();
dcInfo.Item = $"Hold_Time";
dcInfo.Value = PlcData.Read_Other0.ToString();
dcInfo.Result = result;
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
}
//固化 时间
if ("Curing".Contains(stationid))
@@ -618,7 +799,7 @@ namespace WindowsFormsApp1.server
if (material.Success)
{
// 计算加热时间
var time = ((TimeSpan)(material.Data.checkin2 - material.Data.checkout2)).TotalMinutes;
var time = ((TimeSpan)(material.Data.checkin2 - material.Data.checkout1)).TotalMilliseconds;
var jrTime = Convert.ToInt32(time).ToString();
sninfo.DC_INFO.Add(new DCInfoItem
{
@@ -647,6 +828,8 @@ namespace WindowsFormsApp1.server
dcInfo.Item = $"{stationid}_Weight";
dcInfo.Value = PlcData.Read_UploadData0.ToString();
dcInfo.Result = result;
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
sninfo.DC_INFO.Add(dcInfo);
}
//胶宽
@@ -655,17 +838,23 @@ namespace WindowsFormsApp1.server
dcInfo.Item = $"{stationid}_Width";
dcInfo.Value = PlcData.Read_UploadData1.ToString();
dcInfo.Result = result;
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
sninfo.DC_INFO.Add(dcInfo);
}
//胶水 材料码
if ("Potting,ThermalPaste,Sel_Soldering,UVCoating,Sealant".Contains(stationid))
{
compListItem.CompID = OtherData.JS_SN;
compListItem.Qty = "1";
SQLiteHelper<t_materialscan> materialHelper = new db.SQLiteHelper<t_materialscan>();
var glue = materialHelper.QuerySingle(x => x.isonline);
if (glue.Success)
{
compListItem.CompID = glue.Data.scancode;
compListItem.Qty = "1";
sninfo.CompList.Add(compListItem);
LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},胶水码:{OtherData.JS_SN},胶重:{PlcData.Read_UploadData0}");
sninfo.CompList.Add(compListItem);
}
//LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},胶水码:{OtherData.JS_SN},胶重:{PlcData.Read_UploadData0}");
}
else //其他不传
{
+85
View File
@@ -0,0 +1,85 @@
using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace WindowsFormsApp1
{
// 定义日志条目类
public class LogEntry
{
public DateTime Timestamp { get; set; }
public string Level { get; set; }
public string Message { get; set; }
public string Exception { get; set; }
}
// 封装 CsvHelper 的日志记录类,设为静态类
public static class CsvLogger
{
private static string _baseFilePath;
private static List<string> _customHeaders = new List<string>();
public static void Initialize(string baseFilePath)
{
_baseFilePath = baseFilePath;
}
// 设置自定义表头
public static void SetHeaders(List<string> headers)
{
_customHeaders = headers;
}
private static string GetCurrentLogFilePath()
{
var date = DateTime.Now.ToString("yyyy-MM-dd");
var fileExtension = Path.GetExtension(_baseFilePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(_baseFilePath);
if (!Directory.Exists(Path.GetDirectoryName(_baseFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(_baseFilePath));
}
return $"{Path.GetDirectoryName(_baseFilePath)}/{fileNameWithoutExtension}_{date}{fileExtension}";
}
public static void Log(string csvFormattedString)
{
var filePath = GetCurrentLogFilePath();
// 检查文件是否存在,如果不存在则创建并写入表头
if (!File.Exists(filePath))
{
using (var writer = new StreamWriter(filePath))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
if (_customHeaders.Count > 0)
{
foreach (var header in _customHeaders)
{
csv.WriteField(header);
}
csv.NextRecord();
}
else
{
csv.WriteHeader<LogEntry>();
csv.NextRecord();
}
}
}
// 追加日志条目到文件
using (var writer = new StreamWriter(filePath, true))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
var fields = csvFormattedString.Split(',');
foreach (var field in fields)
{
csv.WriteField(field);
}
csv.NextRecord();
}
}
}
}