1208 lines
47 KiB
C#
1208 lines
47 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Reflection;
|
||
using System.Security.Claims;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using System.Xml.Linq;
|
||
using WindowsFormsApp1.mod;
|
||
using WindowsFormsApp1.mod.server;
|
||
using Polly;
|
||
using Polly.Timeout;
|
||
using System.Net.Http;
|
||
using WindowsFormsApp1.db;
|
||
using Newtonsoft.Json.Linq;
|
||
using System.Security.Cryptography;
|
||
using Newtonsoft.Json;
|
||
using HslCommunication.BasicFramework;
|
||
using System.IO;
|
||
using static WindowsFormsApp1.server.ApiClient;
|
||
using System.Security.Policy;
|
||
using System.Diagnostics;
|
||
|
||
namespace WindowsFormsApp1.server
|
||
{
|
||
public class ApiClient
|
||
{
|
||
private readonly HttpClient _httpClient;
|
||
private readonly Dictionary<string, string> apiUrlDict;
|
||
private readonly string _line;
|
||
private readonly string _stationID;
|
||
private readonly string _machineID;
|
||
private readonly string _opID;
|
||
private readonly string _mold;
|
||
private readonly string _token;
|
||
private readonly string _fixsn;
|
||
private readonly string _logBasePath;
|
||
|
||
|
||
public ApiClient()
|
||
{
|
||
_httpClient = new HttpClient();
|
||
// 设置超时时间
|
||
_httpClient.Timeout = TimeSpan.FromSeconds(10);
|
||
|
||
SQLiteHelper<t_interface> helper = new db.SQLiteHelper<t_interface>();
|
||
var apiList = helper.QueryAll().Data.Select(x => new { x.code, url = x.url + x.code }).ToList();
|
||
apiUrlDict = apiList.ToDictionary(x => x.code, x => x.url);
|
||
|
||
// 从配置中读取通用参数
|
||
_line = Init.t_Line.lineremark1;
|
||
_stationID = Init.t_Line.lineremark2;
|
||
_machineID = Init.t_Line.lineremark3;
|
||
_token = Init.t_Line.lineremark4;
|
||
_fixsn = Init.t_Line.lineremark5;
|
||
_mold = Init.t_Line.lineremark6;
|
||
|
||
_opID = Init.t_User.username;
|
||
|
||
// 初始化 CsvLogger
|
||
// 初始化日志路径
|
||
_logBasePath = Path.Combine(@"D:\", "Logs", $"logs.csv");
|
||
|
||
// 初始化CSV日志记录器
|
||
CsvLogger.Initialize(_logBasePath);
|
||
|
||
// 根据站别设置不同的表头
|
||
List<string> headers = GetStationSpecificHeaders();
|
||
CsvLogger.SetHeaders(headers);
|
||
}
|
||
|
||
// 根据站别获取特定的表头
|
||
private List<string> GetStationSpecificHeaders()
|
||
{
|
||
// 基础表头,所有站别都需要的
|
||
List<string> headers = new List<string>
|
||
{
|
||
"SN"
|
||
};
|
||
|
||
// 根据站别或产线代码添加特定表头
|
||
var station = Init.t_Line.lineremark2.ToLower();
|
||
switch (station)
|
||
{
|
||
case "wat":
|
||
headers.Add("充气压力");
|
||
headers.Add("泄漏量");
|
||
break;
|
||
case "potting":
|
||
case "thermalaste":
|
||
headers.Add("胶重");
|
||
break;
|
||
case "vacuum":
|
||
headers.Add("腔体压力");
|
||
headers.Add("保压时间");
|
||
break;
|
||
case "sealant":
|
||
headers.Add("重量");
|
||
headers.Add("宽度");
|
||
break;
|
||
case "curing":
|
||
headers.Add("固化温度");
|
||
headers.Add("固化时间");
|
||
break;
|
||
}
|
||
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".ToLower().Contains(station))
|
||
{
|
||
headers.Add("角度");
|
||
headers.Add("扭矩");
|
||
}
|
||
|
||
if ("Assy2,Assy3,AOI,Assy5,Sealant,CCD,PrintLabel".ToLower().Contains(station))
|
||
{
|
||
headers.Add("CCD");
|
||
}
|
||
return headers;
|
||
}
|
||
|
||
// 通用API调用方法,减少代码重复
|
||
private ApiFormResult CallApi(string url, object request, string eventName, plcdata PlcData, int statusCode = 0)
|
||
{
|
||
// 使用 Newtonsoft.Json 进行序列化
|
||
string jsonPayload = JsonConvert.SerializeObject(request);
|
||
|
||
// 创建 StringContent 对象,将 JSON 字符串作为请求体,指定编码和媒体类型
|
||
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
|
||
|
||
// 调用接口
|
||
try
|
||
{
|
||
#region MES交互
|
||
|
||
var response = _httpClient.PostAsync(url, httpContent).Result;
|
||
// 检查响应状态码
|
||
if (response.IsSuccessStatusCode)
|
||
{
|
||
// 读取响应内容
|
||
string responseContent = response.Content.ReadAsStringAsync().Result;
|
||
|
||
// 使用 Newtonsoft.Json 将响应内容反序列化为动态对象
|
||
dynamic res = JsonConvert.DeserializeObject(responseContent);
|
||
|
||
// 访问动态对象的属性
|
||
if (res != null)
|
||
{
|
||
LogExecute.logNet.WriteDebug($"{eventName} 接口请求成功\n请求:{jsonPayload}\n 返回: {responseContent}");
|
||
|
||
// 成功!
|
||
if (res.Result != null && !string.IsNullOrEmpty(res.Result.Value))
|
||
{
|
||
var result = res.Result.Value == "PASS";
|
||
|
||
if (result)
|
||
{
|
||
// 回写对应PLC
|
||
if (statusCode > 0)
|
||
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
|
||
{
|
||
// 判断此站是否有胶水。返回fail,执行胶水下线
|
||
if (eventName == "SN_FeedingCheck")
|
||
{
|
||
//执行胶水下线操作
|
||
}
|
||
}
|
||
return result
|
||
? ApiFormResult.Sucess(mesresult.PASS, true, res.Msg?.Value ?? "", PlcData, DateTime.Now)
|
||
: ApiFormResult.Sucess(mesresult.FAIL, true, res.Msg?.Value ?? "", PlcData, DateTime.Now);
|
||
}
|
||
else if (res.IsSuccess != null) // 打印 mes不返回result
|
||
{
|
||
// 回写对应PLC
|
||
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, true, res.Msg?.Value ?? "", PlcData, DateTime.Now);
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
throw new Exception($"请求失败,状态码:{response.StatusCode}");
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogExecute.logNet.WriteError($"{eventName} 接口请求失败: {ex.Message}");
|
||
return ApiFormResult.Sucess(mesresult.PASS, true, "PASS", PlcData, DateTime.Now);
|
||
|
||
//throw new Exception(ex.Message);
|
||
}
|
||
return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData, DateTime.Now);
|
||
}
|
||
|
||
public ApiFormResult SN_CheckIN(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 换盘 老化上线 SN需要调用扫码的值 Init.Sn
|
||
var sn = "";
|
||
var stationid = Init.t_Line.lineremark2.ToLower();
|
||
if ("loadaging,exchange2,exchange1".Contains(stationid))
|
||
{
|
||
sn = Init.SN;
|
||
}
|
||
else
|
||
{
|
||
sn = PlcData.Read_MaterialCode1;
|
||
}
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
EventID = "SN_CheckIN",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
Token = _token,
|
||
FixSN = _fixsn,
|
||
SN = sn,
|
||
CarrierID = "",
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
return CallApi(url, request, "SN_CheckIN", PlcData, PLC_Status.SN_CheckIN);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 核对载具合法性
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="PlcData"></param>
|
||
/// <param name="OtherData"></param>
|
||
/// <returns></returns>
|
||
public ApiFormResult Carrier_Check(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
EventID = "Carrier_Check",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
Token = _token,
|
||
FixSN = _fixsn,
|
||
CarrierID = PlcData.Read_MaterialCode1,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
return CallApi(url, request, "Carrier_Check", PlcData, PLC_Status.Carrier_Check);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 核对材料,核对胶水寿命
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="PlcData"></param>
|
||
/// <param name="OtherData"></param>
|
||
/// <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
|
||
{
|
||
EventID = "SN_FeedingCheck",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
Token = _token,
|
||
FixSN = _fixsn,
|
||
SN = OtherData.JS_SN ?? "",//扫码
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
var result = CallApi(url, request, "SN_FeedingCheck", PlcData, PLC_Status.SN_FeedingCheck);
|
||
if (result.Success && result.Mesresult != mesresult.PASS)
|
||
{
|
||
// 判断是否是胶水站,FAIL 直接下线 todo
|
||
if ("Potting,ThermalPaste,Sel_Soldering,UVCoating,Sealant".Contains(station))
|
||
{
|
||
OtherData.opindex = 2;
|
||
return CallFunctionByName("Glue_CheckOut", PlcData, OtherData);
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 追溯码+材料绑定
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="PlcData"></param>
|
||
/// <param name="OtherData"></param>
|
||
/// <returns></returns>
|
||
public ApiFormResult Link_Comp(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
EventID = "Link_Comp",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
CompList = new List<CompListItem>()
|
||
{
|
||
new CompListItem()
|
||
{
|
||
// 安装主板 端子
|
||
CompID = OtherData.JS_SN ?? Init.ScanString,
|
||
Qty = "1"
|
||
}
|
||
},
|
||
SN = Init.SN,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
return CallApi(url, request, "Link_Comp", PlcData, PLC_Status.Link_Comp);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 扫描机壳码,返回MES SN号,写入PLC
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="PlcData"></param>
|
||
/// <param name="OtherData"></param>
|
||
/// <returns></returns>
|
||
public ApiFormResult SN_Release(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
EventID = "SN_Release",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
Token = _token,
|
||
FixSN = _fixsn,
|
||
SN = Init.ScanString,
|
||
//CarrierID = PlcData.Read_MaterialCode1,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
// 特殊处理:需要设置Write_stSN
|
||
return CallApi(url, request, "SN_Release", PlcData, PLC_Status.SN_Release);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 胶水、三防漆,材料 上下线
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="PlcData"></param>
|
||
/// <param name="OtherData"></param>
|
||
/// <returns></returns>
|
||
public ApiFormResult Glue_CheckOut(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 组装 request json
|
||
//判断站
|
||
var station = Init.t_Line.lineremark2.ToLower();
|
||
var fixsn_1 = "";
|
||
var locationindex = 1;
|
||
switch (station)
|
||
{
|
||
case "potting"://灌胶
|
||
case "thermalpaste"://点胶&CCD检测
|
||
case "uvcoating"://三防漆涂覆
|
||
case "sealant"://点密封胶&CCD
|
||
break;
|
||
default:
|
||
fixsn_1 = "CompSN";
|
||
locationindex = OtherData.locationindex;
|
||
break;
|
||
}
|
||
|
||
var request = new
|
||
{
|
||
EventID = "Glue_CheckOut",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = OtherData.opindex,
|
||
Token = locationindex.ToString(),//判断站,胶水不用传
|
||
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);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 压力曲线 扭力曲线
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="PlcData"></param>
|
||
/// <param name="OtherData"></param>
|
||
/// <returns></returns>
|
||
public ApiFormResult Data_Collection(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
EventID = "Data_Collection",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
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);
|
||
}
|
||
|
||
public ApiFormResult Status(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
EventID = "Status",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
STATUS = OtherData.Plc_Status,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
return CallApi(url, request, "Status", PlcData, 0);
|
||
}
|
||
|
||
public ApiFormResult Alarm(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
EventID = "Alarm",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
AlarmID = OtherData.Plc_ErrorMsgs[0],
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
|
||
ResetTime = ""
|
||
};
|
||
|
||
return CallApi(url, request, "Alarm", PlcData, 0);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 视频、图片上传
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="PlcData"></param>
|
||
/// <param name="OtherData"></param>
|
||
/// <returns></returns>
|
||
public ApiFormResult SN_FileUpload(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 准备文件 视频/图片
|
||
var month = DateTime.Now.ToString("yyyyMM");
|
||
var day = DateTime.Now.ToString("dd");
|
||
var monthDay = DateTime.Now.ToString("MMdd");
|
||
var time = DateTime.Now.ToString("HHmmss");
|
||
var result = PlcData.Read_Result == 1 ? "OK" : "NG";
|
||
|
||
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[] {
|
||
OtherData.ImageAddress,
|
||
OtherData.VedioAddress
|
||
};
|
||
// 使用分号分隔多个源文件夹
|
||
string targetFolder = targetDirectory;
|
||
List<string> fileList = new List<string>();
|
||
|
||
//从数据库读 未上传的 todo
|
||
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 sourceFolder1 in sourceFolders)
|
||
{
|
||
if (string.IsNullOrEmpty(sourceFolder1))
|
||
{
|
||
continue;
|
||
}
|
||
string sourceFolder = sourceFolders[0];
|
||
if (sourceFolder == sourceFolder1)
|
||
{
|
||
// 图片
|
||
// 组装路径 可能需要从数据库读 result和sn和日期
|
||
sourceFolder = Path.Combine(sourceFolder, DateTime.Now.ToString("yyyyMMdd"), "DCDC", result);
|
||
}
|
||
else
|
||
{
|
||
// 视频
|
||
}
|
||
if (Directory.Exists(sourceFolder.Trim()))
|
||
{
|
||
string[] files = Directory.GetFiles(sourceFolder.Trim());
|
||
int num = 1;
|
||
var extensionstr = "";
|
||
foreach (string file in files)
|
||
{
|
||
string fileName1 = Path.GetFileName(file);
|
||
string filePath = "";
|
||
if (!fileName1.Contains(snNumber))
|
||
{
|
||
continue;
|
||
}
|
||
extensionstr = Path.GetExtension(file);
|
||
fileName = $"{month}{day}_{_stationID}_{result}_{PlcData.Read_MaterialCode0}_{monthDay}_{time}_{_machineID}_01_Original{num}{extensionstr}";
|
||
filePath = Path.Combine(sourceFolder, fileName1);
|
||
//string targetPath = Path.Combine(targetFolder, fileName);
|
||
//File.Copy(file, targetPath, true);
|
||
CopyFileToDirectory(filePath, targetFolder, fileName);
|
||
fileList.Add(fileName);
|
||
num++;
|
||
LogExecute.logNet.WriteDebug($"文件 {fileName} 已从 {sourceFolder.Trim()} 复制到 {targetFolder}");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
LogExecute.logNet.WriteDebug($"源文件夹 {sourceFolder.Trim()} 不存在");
|
||
}
|
||
}
|
||
|
||
if (fileList.Count == 0)
|
||
{
|
||
LogExecute.logNet.WriteDebug($"在所有源文件夹中未找到包含SN号 {snNumber} 的文件");
|
||
return ApiFormResult.Error(mesresult.FAIL, false, "", PlcData, DateTime.Now);
|
||
}
|
||
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
SNList = new List<dynamic>()
|
||
{
|
||
new
|
||
{
|
||
SN = PlcData.Read_MaterialCode0,
|
||
FileInfo = fileList.Select(x => new
|
||
{
|
||
FileName = x,
|
||
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);
|
||
}
|
||
|
||
|
||
/*
|
||
// 查找源文件 可能会有多张照片或视频
|
||
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
|
||
{
|
||
CopyFileToDirectory(sourceFile, targetDirectory, fileName);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return ApiFormResult.Error(mesresult.FAIL, false, ex.Message, PlcData, DateTime.Now);
|
||
}
|
||
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
SNList = new List<dynamic>()
|
||
{
|
||
new
|
||
{
|
||
SN = OtherData.JS_SN,
|
||
FileInfo = new List<dynamic>()
|
||
{
|
||
//new
|
||
//{
|
||
// FileName = OtherData.FileUploadAddress,
|
||
// FilePath = OtherData.FileUploadAddress
|
||
//}
|
||
}
|
||
}
|
||
},
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
// 多个视频或图片
|
||
// 动态添加 FileInfo
|
||
|
||
|
||
return CallApi(url, request, "SN_FileUpload", PlcData, PLC_Status.SN_FileUpload);
|
||
*/
|
||
}
|
||
|
||
/// <summary>
|
||
/// 触发MES打印
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="PlcData"></param>
|
||
/// <param name="OtherData"></param>
|
||
/// <returns></returns>
|
||
public ApiFormResult CodeSoftPrint(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 组装 request json
|
||
var request = new
|
||
{
|
||
Line = _line, // 特殊值,不使用_line
|
||
Station = _stationID,
|
||
MachineID = _machineID,
|
||
SN = PlcData.Read_MaterialCode0
|
||
};
|
||
|
||
return CallApi(url, request, "CodeSoftPrint", PlcData, PLC_Status.CodeSoftPrint);
|
||
}
|
||
|
||
public ApiFormResult SN_Checkout(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 根据不同的lineCode构建不同的请求
|
||
var lineCode = Init.t_Line.linecode;
|
||
var stationid = Init.t_Line.lineremark2;
|
||
|
||
var result = PlcData.Read_Result == 1 ? "PASS" : "FAIL";
|
||
var logresult = PlcData.Read_Result == 1 ? "OK" : "NG";
|
||
// 基础请求对象
|
||
var request = new CheckOutObject()
|
||
{
|
||
EventID = "SN_Checkout",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
SNInfo = new List<SNInfoItem>()
|
||
{
|
||
new SNInfoItem()
|
||
{
|
||
SN = PlcData.Read_MaterialCode0,
|
||
Result = result,
|
||
DC_INFO = new List<DCInfoItem>(),
|
||
CompList = new List<CompListItem>()
|
||
}
|
||
},
|
||
Qty = "",
|
||
CarrierID = PlcData.Read_MaterialCode1,
|
||
Mold = _mold,
|
||
Token = _token,
|
||
FixSN = _fixsn,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
// 根据不同的lineCode可以在这里扩展request对象
|
||
var dcInfo = new DCInfoItem();
|
||
var sninfo = request.SNInfo[0];
|
||
var compListItem = new CompListItem();
|
||
|
||
//气密
|
||
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 ?? "0",
|
||
Result = result
|
||
});
|
||
sninfo.DC_INFO.Add(new DCInfoItem
|
||
{
|
||
Item = OutItem.泄漏量,
|
||
Value = Init.airtight.Leak_Value ?? "0",
|
||
Result = result
|
||
});
|
||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{Init.airtight.Airtight_Value},{Init.airtight.Leak_Value}");
|
||
}
|
||
//扭力,角度
|
||
if ("ScrewE,Assy2,Assy3,ScrewS,ScrewM,ScrewTC".Contains(stationid))
|
||
{
|
||
var count = OtherData.FinalAngleValue.Count(x => x > 0);
|
||
for(int i = 0; i < count; i++)
|
||
{
|
||
if ("Assy2,Assy3".Contains(stationid))
|
||
{
|
||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{OtherData.FinalAngleValue[i]},{OtherData.FinalTorqueValue[i]},{PlcData.Read_UploadData0.ToString()}");
|
||
}
|
||
else
|
||
{
|
||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{OtherData.FinalAngleValue[i]},{OtherData.FinalTorqueValue[i]}");
|
||
}
|
||
}
|
||
|
||
var AngleCount = 1;
|
||
foreach (var item in OtherData.FinalAngleValue.Where(x => x > 0))
|
||
{
|
||
//角度
|
||
dcInfo = new DCInfoItem();
|
||
dcInfo.Item = $"{Init.t_Line.lineremark2}_Angle{AngleCount}";
|
||
dcInfo.Value = item.ToString();
|
||
dcInfo.Result = result;
|
||
|
||
sninfo.DC_INFO.Add(dcInfo);
|
||
AngleCount++;
|
||
}
|
||
var TorqueCount = 1;
|
||
foreach (var item in OtherData.FinalTorqueValue.Where(x => x > 0))
|
||
{
|
||
//扭力
|
||
dcInfo = new DCInfoItem();
|
||
dcInfo.Item = $"{Init.t_Line.lineremark2}_Torque{TorqueCount}";
|
||
dcInfo.Value = item.ToString();
|
||
dcInfo.Result = result;
|
||
|
||
sninfo.DC_INFO.Add(dcInfo);
|
||
TorqueCount++;
|
||
}
|
||
}
|
||
|
||
//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;
|
||
sninfo.DC_INFO.Add(dcInfo);
|
||
if (!"Assy2,Assy3".Contains(stationid))
|
||
{
|
||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{PlcData.Read_UploadData0.ToString()}");
|
||
}
|
||
//LogExecute.SNlogNet.WriteDebug($"追溯码:{PlcData.Read_MaterialCode0},检测结果:{logresult}");
|
||
}
|
||
//抽真空 压力
|
||
if ("Vacuum".Contains(stationid))
|
||
{
|
||
var str = "";
|
||
var Chamber_Pressure = OtherData.FinalPressureCurve.First();
|
||
dcInfo = new DCInfoItem();
|
||
dcInfo.Item = $"Chamber_Pressure";
|
||
dcInfo.Value = Chamber_Pressure.ToString();
|
||
dcInfo.Result = result;
|
||
sninfo.DC_INFO.Add(dcInfo);
|
||
|
||
str += $"{PlcData.Read_MaterialCode0},{dcInfo.Value}";
|
||
|
||
dcInfo = new DCInfoItem();
|
||
dcInfo.Item = $"Hold_Time";
|
||
dcInfo.Value = PlcData.Read_Other0.ToString() ?? "0";
|
||
dcInfo.Result = result;
|
||
|
||
sninfo.DC_INFO.Add(dcInfo);
|
||
str += $",{dcInfo.Value},";
|
||
CsvLogger.Log(str);
|
||
}
|
||
//固化 时间
|
||
if ("Curing".Contains(stationid))
|
||
{
|
||
SQLiteHelper<t_materialcall> materialHelper = new db.SQLiteHelper<t_materialcall>();
|
||
var material = materialHelper.QuerySingle(x => x.materialid == PlcData.Read_MaterialCode0);
|
||
if (material.Success)
|
||
{
|
||
// 计算加热时间
|
||
var time = ((TimeSpan)(material.Data.checkin2 - material.Data.checkout1)).TotalMinutes;
|
||
var jrTime = Convert.ToInt32(time).ToString();
|
||
sninfo.DC_INFO.Add(new DCInfoItem
|
||
{
|
||
Item = OutItem.固化时间,
|
||
Value = jrTime,
|
||
Result = result
|
||
});
|
||
sninfo.DC_INFO.Add(new DCInfoItem
|
||
{
|
||
Item = OutItem.固化温度,
|
||
Value = PlcData.Read_UploadData0.ToString(),
|
||
Up = "85",
|
||
Down = "75",
|
||
Result = result
|
||
});
|
||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{PlcData.Read_UploadData0.ToString()},{jrTime}");
|
||
}
|
||
else
|
||
{
|
||
//报错,没有这个物料
|
||
}
|
||
}
|
||
//胶重
|
||
if ("Potting,ThermalPaste".Contains(stationid))
|
||
{
|
||
dcInfo = new DCInfoItem();
|
||
dcInfo.Item = $"{stationid}_Weight";
|
||
dcInfo.Value = PlcData.Read_UploadData0.ToString();
|
||
dcInfo.Result = result;
|
||
//LogExecute.SNlogNet.WriteDebug($"{PlcData.Read_MaterialCode0},{dcInfo.Item},{dcInfo.Value}");
|
||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{dcInfo.Value}");
|
||
|
||
sninfo.DC_INFO.Add(dcInfo);
|
||
}
|
||
//胶重 胶宽
|
||
if ("Sealant".Contains(stationid))
|
||
{
|
||
dcInfo = new DCInfoItem();
|
||
dcInfo.Item = $"{stationid}_Weight";
|
||
dcInfo.Value = PlcData.Read_UploadData0.ToString();
|
||
dcInfo.Result = result;
|
||
|
||
sninfo.DC_INFO.Add(dcInfo);
|
||
|
||
dcInfo = new DCInfoItem();
|
||
dcInfo.Item = $"{stationid}_Width";
|
||
dcInfo.Value = PlcData.Read_UploadData1.ToString();
|
||
dcInfo.Result = result;
|
||
CsvLogger.Log($"{PlcData.Read_MaterialCode0},{PlcData.Read_UploadData0.ToString()},{PlcData.Read_UploadData1.ToString()}");
|
||
|
||
sninfo.DC_INFO.Add(dcInfo);
|
||
}
|
||
//胶水 材料码
|
||
if ("Potting,ThermalPaste,Sel_Soldering,UVCoating,Sealant".Contains(stationid))
|
||
{
|
||
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);
|
||
}
|
||
}
|
||
else //其他不传
|
||
{
|
||
compListItem.CompID = "";
|
||
compListItem.Qty = "1";
|
||
|
||
sninfo.CompList.Add(compListItem);
|
||
}
|
||
return CallApi(url, request, "SN_Checkout", PlcData, PLC_Status.SN_Checkout);
|
||
}
|
||
|
||
public ApiFormResult Initialization(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
// 直接设置状态码
|
||
PlcData.Write_Status = PLC_Status.Initialization;
|
||
return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData, DateTime.Now);
|
||
}
|
||
|
||
#region 暂时不用
|
||
public ApiFormResult Test(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
var request = new
|
||
{
|
||
EventID = "Test",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
return CallApi(url, request, "Test", PlcData, PLC_Status.Test);
|
||
}
|
||
|
||
public ApiFormResult OEEDataCollection(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
var request = new
|
||
{
|
||
EventID = "OEEDataCollection",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
return CallApi(url, request, "OEEDataCollection", PlcData, PLC_Status.OEEDataCollection);
|
||
}
|
||
|
||
public ApiFormResult Get_Para(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
var request = new
|
||
{
|
||
EventID = "Get_Para",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
return CallApi(url, request, "Get_Para", PlcData, PLC_Status.Get_Para);
|
||
}
|
||
|
||
public ApiFormResult DispatchPara(string url, plcdata PlcData, otherdata OtherData)
|
||
{
|
||
var request = new
|
||
{
|
||
EventID = "DispatchPara",
|
||
Line = _line,
|
||
StationID = _stationID,
|
||
MachineID = _machineID,
|
||
OPID = _opID,
|
||
SendTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
|
||
};
|
||
|
||
return CallApi(url, request, "DispatchPara", PlcData, PLC_Status.DispatchPara);
|
||
}
|
||
#endregion 暂时不用
|
||
|
||
public ApiFormResult CallFunctionByName(string functionName, plcdata plcdata, otherdata otherdata)
|
||
{
|
||
// 定义重试策略
|
||
var retryPolicy = Policy
|
||
.Handle<Exception>() // 处理HTTP请求异常
|
||
.WaitAndRetry(2, retryAttempt =>
|
||
{
|
||
// 自定义重试间隔
|
||
switch (retryAttempt)
|
||
{
|
||
case 1:
|
||
return TimeSpan.FromSeconds(3); // 第一次重试间隔3秒
|
||
case 2:
|
||
return TimeSpan.FromSeconds(5); // 第二次重试间隔5秒
|
||
default:
|
||
return TimeSpan.FromSeconds(0); // 默认间隔0秒
|
||
}
|
||
}, (exception, timeSpan, retryCount, context) =>
|
||
{
|
||
LogExecute.logNet.WriteError($"重试第 {retryCount} 次,异常信息: {exception.Message}");
|
||
});
|
||
|
||
// 定义超时策略
|
||
var timeoutPolicy = Policy
|
||
.Timeout(5, // 超时时间3秒
|
||
TimeoutStrategy.Pessimistic); // 使用 pessimistic 超时策略
|
||
|
||
// 获取当前类的类型
|
||
Type type = this.GetType();
|
||
|
||
// 使用反射调用指定名称的方法
|
||
MethodInfo methodInfo = type.GetMethod(functionName);
|
||
|
||
if (methodInfo == null)
|
||
{
|
||
LogExecute.logNet.WriteError($"未找到对应的函数 {functionName}");
|
||
return ApiFormResult.Error(mesresult.FAIL, false, $"未找到对应的函数 {functionName}", null, DateTime.Now);
|
||
}
|
||
|
||
try
|
||
{
|
||
// 打印调用开始日志
|
||
LogExecute.logNet.WriteDebug($"开始调用API: {functionName}...");
|
||
|
||
// 检查API URL是否存在
|
||
if (!apiUrlDict.ContainsKey(functionName))
|
||
{
|
||
LogExecute.logNet.WriteError($"未找到API URL配置: {functionName}");
|
||
return ApiFormResult.Error(mesresult.FAIL, false, $"未找到API URL配置: {functionName}", null, DateTime.Now);
|
||
}
|
||
|
||
// 使用同步方法调用API,并结合重试策略
|
||
var result = retryPolicy.Execute(() =>
|
||
{
|
||
LogExecute.logNet.WriteDebug($"正在尝试调用API: {functionName}...");
|
||
// 调用该方法
|
||
return (ApiFormResult)methodInfo.Invoke(this, new object[] { apiUrlDict[functionName], plcdata, otherdata });
|
||
});
|
||
|
||
// 打印调用结束日志
|
||
LogExecute.logNet.WriteDebug($"API调用成功: {functionName}");
|
||
return result;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// 如果所有调用都失败,打印失败日志
|
||
LogExecute.logNet.WriteError($"API调用失败: {functionName}, 错误: {ex.Message}");
|
||
return ApiFormResult.Error(mesresult.FAIL, false, ex.Message, null, DateTime.Now);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// checkout dcinfo item
|
||
/// </summary>
|
||
public sealed class OutItem
|
||
{
|
||
public const string 充气压力 = "Set_Fill";
|
||
public const string 泄漏量 = "Leakage_Rate";
|
||
public const string 灌胶重量 = "Glue_Weight";
|
||
public const string 点胶重量 = "ThermalPaste_Weight";
|
||
public const string 腔体压力 = "Chamber_Pressure";
|
||
public const string 保压时间 = "Hold_Time";
|
||
public const string 固化温度 = "Cure_Temperature";
|
||
public const string 固化时间 = "Curing_Time";
|
||
public const string 重量 = "Sealant_Weight";
|
||
public const string 宽度 = "Sealant_Width";
|
||
}
|
||
public sealed class PLC_Status
|
||
{
|
||
public const int SN_CheckIN = 10;
|
||
public const int Carrier_Check = 20;
|
||
public const int SN_FeedingCheck = 30;
|
||
public const int Link_Comp = 40;
|
||
public const int SN_Release = 50;
|
||
public const int Glue_CheckOut = 60;
|
||
public const int Get_Para = 70;
|
||
public const int DispatchPara = 80;
|
||
public const int Data_Collection = 90;
|
||
public const int Status = 100;
|
||
public const int Alarm = 110;
|
||
public const int OEEDataCollection = 120;
|
||
public const int SN_FileUpload = 130;
|
||
public const int Test = 140;
|
||
public const int GetLaserpara = 150;
|
||
public const int Order_Get = 160;
|
||
public const int CodeSoftPrint = 170;
|
||
public const int SN_Checkout = 200;
|
||
public const int Initialization = 3;
|
||
|
||
public const int Fail = 1001;
|
||
}
|
||
|
||
|
||
#region checkout class
|
||
// 根对象类
|
||
public class CheckOutObject
|
||
{
|
||
public List<SNInfoItem> SNInfo { get; set; }
|
||
public string Qty { get; set; }
|
||
public string Mold { get; set; }
|
||
public string EventID { get; set; }
|
||
public string Line { get; set; }
|
||
public string StationID { get; set; }
|
||
public string MachineID { get; set; }
|
||
public string CarrierID { get; set; }
|
||
public string OPID { get; set; }
|
||
public string SendTime { get; set; }
|
||
public string Token { get; set; }
|
||
public string FixSN { get; set; }
|
||
}
|
||
|
||
// SNInfo 列表中的每个元素类
|
||
public class SNInfoItem
|
||
{
|
||
public string SN { get; set; }
|
||
public string Result { get; set; }
|
||
public List<DCInfoItem> DC_INFO { get; set; }
|
||
public List<CompListItem> CompList { get; set; }
|
||
}
|
||
|
||
// DC_INFO 列表中的每个元素类
|
||
public class DCInfoItem
|
||
{
|
||
public string Item { get; set; }
|
||
public string Value { get; set; }
|
||
public string Up { get; set; } = "";
|
||
public string Down { get; set; } = "";
|
||
public string Result { get; set; }
|
||
}
|
||
|
||
// CompList 列表中的每个元素类
|
||
public class CompListItem
|
||
{
|
||
public string CompID { get; set; }
|
||
public string Qty { get; set; }
|
||
}
|
||
#endregion checkout class
|
||
|
||
// 文件copy方法
|
||
public bool CopyFileToDirectory(string sourceFilePath, string targetDirectory, string fileName)
|
||
{
|
||
// 检查源文件是否存在
|
||
if (!File.Exists(sourceFilePath))
|
||
{
|
||
throw new FileNotFoundException("源文件不存在", sourceFilePath);
|
||
}
|
||
|
||
// 如果目标目录不存在,则创建
|
||
if (!Directory.Exists(targetDirectory))
|
||
{
|
||
Directory.CreateDirectory(targetDirectory);
|
||
}
|
||
|
||
string targetPath = Path.Combine(targetDirectory, fileName);
|
||
|
||
try
|
||
{
|
||
// 复制文件
|
||
File.Copy(sourceFilePath, targetPath, true);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw new Exception(ex.Message);
|
||
}
|
||
|
||
return true;
|
||
}
|
||
}
|
||
}
|