using JinYuan.Helper;
using JinYuan.MES.Enums;
using JinYuan.MES.Models;
using JinYuan.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using static System.Runtime.CompilerServices.RuntimeHelpers;
namespace JinYuan.MES
{
public class MesDataProcess : IMes
{
#region 1、登录验证 √
/// 账号密码登录(异步方法)
///
/// API地址
/// 站点代码
/// 线体代码
/// 设备编号
/// 用户名
/// 密码
/// 用户卡ID
/// 返回结果(是否成功、消息) userCardID = UserCardID
public async Task<(bool Success, string Message, string MesUserLevel)> LoginAsync(string url, string siteCode, string lineCode, string equipNum, string userName, string passWord)
{
bool res = false; // 操作结果
string resJson = ""; // 日志信息
string message = ""; // 消息
string mesUserName = "";//mes返回登陆权限
try
{
// 创建请求模型
var model = new LoginEntity
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
userName = userName,
passWord = passWord,
};
// 序列化请求数据
var nowDate = DateTime.Now;
var postData = JsonConvert.SerializeObject(model);
// 记录请求开始时间
var sw = Stopwatch.StartNew();
// 调用异步API
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postData, false);
// 记录请求结束时间
sw.Stop();
// 如果返回结果为空,记录日志并返回
if (string.IsNullOrEmpty(result))
{
string resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口:{url},请求数据为:{postData},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
return (res, message, mesUserName);
}
// 解析返回结果
var res1 = JsonConvert.DeserializeObject(result);
// 如果操作成功
if (res1 != null && res1.success && string.IsNullOrEmpty(res1.code) && string.IsNullOrEmpty(res1.message))
{
//mes登陆权限赋值
//if (res1.rows[0].username == userName) { mesUserName = res1.rows[0].permissionLevel; }
if (res1.rows[0] == userName) { mesUserName = res1.rows[0]; }
res = true;
message = res1.message;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口:{url},请求数据为:{postData}\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
}
else
{
// 如果操作失败,记录日志
var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
message = res1?.message ?? "未知错误";
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口:{url},请求数据为:{postData}\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
}
}
catch (Exception ex)
{
// 捕获异常并记录日志
message = "调用员工权限校验接口发生异常";
resJson = $"调用员工权限校验接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("调用员工权限校验接口", ex);
}
// 返回结果
return (res, message, mesUserName);
}
///
/// 刷卡登录
///
///
///
///
///
///
///
public async Task<(bool Success, string Message)> LoginAsync(string url, string siteCode, string lineCode, string equipNum, string UserCardID)
{
bool res = false; // 操作结果
string resJson = ""; // 日志信息
string message = ""; // 消息
try
{
// 创建请求模型
var model = new LoginEntity
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
userCardID = UserCardID,
};
// 序列化请求数据
var nowDate = DateTime.Now;
var postData = JsonConvert.SerializeObject(model);
// 记录请求开始时间
var sw = Stopwatch.StartNew();
// 调用异步API
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postData, false);
// 记录请求结束时间
sw.Stop();
// 如果返回结果为空,记录日志并返回
if (string.IsNullOrEmpty(result))
{
string resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口:{url},请求数据为:{postData},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
return (res, message);
}
// 解析返回结果
var res1 = JsonConvert.DeserializeObject(result);
// 如果操作成功
if (res1 != null && res1.success && string.IsNullOrEmpty(res1.code) && string.IsNullOrEmpty(res1.message))
{
res = true;
message = res1.message;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口:{url},请求数据为:{postData}\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
}
else
{
// 如果操作失败,记录日志
var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
message = res1?.message ?? "未知错误";
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口:{url},请求数据为:{postData}\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
}
}
catch (Exception ex)
{
// 捕获异常并记录日志
message = "调用员工权限校验接口发生异常";
resJson = $"调用员工权限校验接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("调用员工权限校验接口", ex);
}
// 返回结果
return (res, message);
}
#endregion
#region 2、获取MES参数请求
///
/// 获取MES参数请求
///
///
///
///
///
///
///
///
///
public async Task<(ParamReturnData Data, string Mesage)> GetParamSetRequestAsync(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName)
{
string resJson = "";
string mesage = ""; // 用于存储消息
try
{
var model = new
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
materialCode = materialCode,
userName = userName
};
var nowDate = DateTime.Now;
var postcontent = JsonConvert.SerializeObject(model);
var sw = new Stopwatch();
sw.Start();
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
sw.Stop();
if (string.IsNullOrEmpty(result))
{
string resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备参数设定值请求接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备参数设定值请求\{nowDate.ToString("HH")}.txt", resJson);
return (null, mesage);
}
var res1 = ReturnMesMsg(result);
if (res1.success)
{
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备参数设定值请求接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备参数设定值请求\{nowDate.ToString("HH")}.txt", resJson);
}
else
{
var resData = res1 == null ? "" : result;
mesage = "MES返回结果为空";
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备参数设定值请求接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备参数设定值请求\{nowDate.ToString("HH")}.txt", resJson);
}
return (res1, mesage);
}
catch (Exception ex)
{
mesage = $"设备参数设定值请求接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("设备参数设定值请求接口", ex);
return (null, mesage);
}
}
#endregion
#region 3、参数变更请求
///
/// 参数变更请求
///
///
///
///
///
///
///
///
///
///
public async Task ParamChange(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List paramChangeItems)
{
bool res = false;
string resJson = "";
try
{
var model = new ParamChange
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
materialCode = materialCode,
userName = userName,
};
var nowDate = DateTime.Now;
var postcontent = JsonConvert.SerializeObject(model);
var sw = new Stopwatch();
sw.Start();
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
sw.Stop();
var resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用参数设定值变更接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\MesLogs\{nowDate.ToString("yyyyMMdd")}\参数设定值变更\{nowDate.ToString("HH")}.txt", resJson);
}
catch (Exception ex)
{
resJson = $"参数设定值变更接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("参数设定值变更接口", ex);
}
return res;
}
#endregion
///
/// 将MES返回的category转换为MesResType
///
private MesResType GetMesResType(string category)
{
if (string.IsNullOrEmpty(category))
return MesResType.B;
switch (category.ToUpper())
{
case "A":
return MesResType.A; // 停线
case "B":
return MesResType.B; // 排出
case "C":
return MesResType.C; // 忽略(需警示)
case "D":
return MesResType.D; // 成功
default:
return MesResType.B; // 默认排出
}
}
#region 箱唛信息获取
///
/// 箱唛信息获取
///
/// API地址 /api/public/equip/auto/cartonquery
/// 工厂代码
/// 产线编号
/// 设备编号
/// 卡板码(箱唛号)
/// 返回结果(是否成功、消息列表、响应类型列表)
public async Task<(bool success, string mesMessage, MesResType mesResType, List cartonTagInfos)> QueryCartonAsync(string url, string siteCode, string lineCode, string equipNum, string containerCode)
{
bool success = false; // 操作结果
string rawJson = ""; //
string message = ""; // 消息列表
MesResType mesResType = MesResType.C;
List cartonTagInfos = new List();
try
{
// 参数验证
if (string.IsNullOrEmpty(containerCode))
{
message = "容器码为空";
return (success, message, mesResType, cartonTagInfos);
}
// 创建请求模型
var model = new QueryCartonPalletParam
{
siteCode = siteCode,
equipNum = equipNum,
lineCode = lineCode,
containerCode = containerCode
};
// 序列化请求数据
var nowDate = DateTime.Now;
var postcontent = JsonConvert.SerializeObject(model);
// 记录请求开始时间
var sw = Stopwatch.StartNew();
// 调用异步API
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
// 记录请求结束时间
sw.Stop();
rawJson = result;
// 如果请求耗时超过1秒,记录日志
long outTime = sw.ElapsedMilliseconds;
if (outTime > 1000)
{
//LogHelper.Instance.WriteLog($"进站PC<=>MES上传耗时:{outTime}ms,电芯码:{listBar[0]},{listBar[1]},{listBar[2]},{listBar[3]}", "MESTime");
LogHelper.Instance.WriteLog($"箱唛信息获取PC<=>MES耗时:{outTime}ms", "MESTime");
}
// 记录请求日志
string requestLog = $"{nowDate:yyyy-MM-dd HH:mm:ss.fff}:调用箱唛信息获取接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds):yyyy-MM-dd HH:mm:ss.fff}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate:yyyyMMdd}\箱唛信息获取\{nowDate:HH}.txt", requestLog);
// 如果返回结果为空,记录日志并返回
if (string.IsNullOrEmpty(result))
{
//string resData = result == "" ? "" : result;
//resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用箱唛信息获取接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
//TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\箱唛信息获取\{nowDate.ToString("HH")}.txt", resJson);
//return (success, mesMessage, mesResType, cartonTagInfos);
message = "MES接口返回空结果";
return (success, message, mesResType, cartonTagInfos);
}
// 解析返回结果
var response = JsonConvert.DeserializeObject(result);
// 如果操作成功
if (response != null && response.success)
{
success = true;
ProcessCartonResponse(response, ref message, ref mesResType, ref cartonTagInfos); // 处理返回结果
//resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用箱唛信息获取接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
//TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\箱唛信息获取\{nowDate.ToString("HH")}.txt", resJson);
if (success && mesResType == MesResType.D)
{
message = $"箱唛信息获取成功,共获取 {cartonTagInfos?.Count ?? 0} 个标签信息";
return (success, message, mesResType, cartonTagInfos);
}
else
{
return (success, message, mesResType, cartonTagInfos);
}
}
else
{
//// 如果操作失败,记录日志
//var resData = response == null ? "" : result;
//resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用箱唛信息获取接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
//TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\箱唛信息获取\{nowDate.ToString("HH")}.txt", resJson);
// 如果操作失败
message = response?.message ?? "MES接口返回失败状态";
mesResType = GetMesResType(response?.category);
return (success, message, mesResType, cartonTagInfos);//MesResult>.Fail(message, mesResType, rawJson);
}
}
catch (Exception ex)
{
// 捕获异常并记录日志
message = $"箱唛信息获取接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("箱唛信息获取接口", ex);
}
// 返回结果
return (success, message, mesResType, cartonTagInfos);
}
///
/// 箱唛信息获取返回数据处理
///
///
///
///
///
private void ProcessCartonResponse(MesResponseCarton response, ref string message, ref MesResType mesResType, ref List cartonTagInfos)
{
if (response != null)
{
cartonTagInfos = response.rows ?? new List();
message = response.message;
if (response.success)
{
mesResType = MesResType.D;
message = "MES箱唛信息获取成功 ";
// 检查数据完整性
if (cartonTagInfos.Count == 0)
{
message = "未获取到箱唛标签信息";
mesResType = MesResType.B;
}
}
else
{
mesResType = GetMesResType(response.category);
}
}
else
{
message = "响应数据为空";
mesResType = MesResType.B;
}
}
#endregion
#region 栈板获取
///
/// 栈板信息获取
///
/// API地址 /api/public/equip/auto/palletquery
/// 工厂代码
/// 产线编号
/// 设备编号
/// 卡板码(箱唛号)
/// 返回结果(是否成功、消息列表、响应类型列表)
public async Task<(bool success, string mesMessage, MesResType mesResType, string palletCode, List palletTagInfos)> QueryPalletAsync(string url, string siteCode, string lineCode, string equipNum, string containerCode)
{
bool success = false; // 操作结果
string rawJson = ""; // 日志信息
string message = ""; // 消息列表
string palletCode = ""; // 栈板编码
MesResType mesResType = MesResType.C;
List palletTagInfos = new List();
try
{
if (string.IsNullOrEmpty(containerCode))
{
message = "容器码为空";
return (success, message, mesResType, palletCode, palletTagInfos);
}
var model = new QueryCartonPalletParam
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
containerCode = containerCode
};
var nowDate = DateTime.Now;
var postcontent = JsonConvert.SerializeObject(model);
var sw = Stopwatch.StartNew();
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
sw.Stop();
rawJson = result;
// 如果请求耗时超过1秒,记录日志
long outTime = sw.ElapsedMilliseconds;
if (outTime > 1000)
{
LogHelper.Instance.WriteLog($"栈板信息获取PC<=>MES耗时:{outTime}ms", "MESTime");
}
// 记录请求日志
string requestLog = $"{nowDate:yyyy-MM-dd HH:mm:ss.fff}:调用栈板信息获取接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds):yyyy-MM-dd HH:mm:ss.fff}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate:yyyyMMdd}\栈板信息获取\{nowDate:HH}.txt", requestLog);
// 如果返回结果为空,记录日志并返回
if (string.IsNullOrEmpty(result))
{
message = "MES接口返回空结果";
return (success, message, mesResType, palletCode, palletTagInfos);
}
// 解析返回结果
var response = JsonConvert.DeserializeObject(result);
if (response != null && response.success)
{
success = true;
ProcessPalletResponse(response, ref message, ref mesResType, ref palletCode, ref palletTagInfos); // 处理返回结果
if (success && mesResType == MesResType.D)
{
message = $"栈板信息获取成功,共获取 {palletTagInfos?.Count ?? 0} 个标签信息";
}
}
else
{
message = response?.message ?? "MES接口返回失败状态";
mesResType = GetMesResType(response?.category);
}
}
catch (Exception ex)
{
message = $"栈板信息获取接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("栈板信息获取接口", ex);
}
// 返回结果
return (success, message, mesResType, palletCode, palletTagInfos);
}
///
/// 栈板信息获取返回数据处理
///
///
///
///
///
private void ProcessPalletResponse(MesResponsePallet response, ref string message, ref MesResType mesResType, ref string palletCode, ref List palletTagInfos)
{
if (response == null || response.rows == null || response.rows.Count == 0)
{
message = "响应数据为空或无有效行数据";
mesResType = MesResType.B;
return;
}
PalletRow firstRow = response.rows[0];
palletCode = firstRow?.palletCode ?? string.Empty;
palletTagInfos = firstRow?.tagList ?? new List();
if (response.success)
{
mesResType = MesResType.D;
message = "MES栈板信息获取成功 ";
// 检查数据完整性
if (palletTagInfos.Count == 0)
{
message = "未获取到栈板标签信息";
mesResType = MesResType.B;
}
else
{
message = "栈板信息获取成功";
}
}
else
{
mesResType = GetMesResType(response.category);
message = response.message ?? "MES接口返回失败";
}
}
#endregion
#region 客户标签与系统标签绑定
///
/// 客户标签与系统标签绑定
///
/// API地址 /api/public/equip/auto/ //TODO 待补充!
/// 工厂代码
/// 产线编号
/// 设备编号
/// 卡板码(箱唛号)
/// 栈板码
/// 客户箱唛码
/// 客户栈板码
/// 客户箱唛信息
/// 客户栈板信息
/// 返回结果(是否成功、消息列表、响应类型列表)
public async Task<(bool success, string mesMessage, MesResType mesResType)> BindingAsync(string url, string siteCode, string lineCode, string equipNum, string containerCode, string palletCode, string custcartonCode, string custpalletCode, List custcarton, List custpallet)
{
bool success = false; // 操作结果
string rawJson = ""; // 日志信息
string message = ""; // 消息列表
MesResType mesResType = MesResType.C;
try
{
// 参数验证
if (string.IsNullOrEmpty(containerCode))
{
message = "容器码为空";
return (success, message, mesResType);
}
// 创建请求模型
var model = new BindingParam
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
containerCode = containerCode,
palletCode = palletCode,
custcartonCode = custcartonCode,
custpalletCode = custpalletCode,
custcarton = custcarton,
custpallet = custpallet
};
// 序列化请求数据
var nowDate = DateTime.Now;
var postcontent = JsonConvert.SerializeObject(model);
// 记录请求开始时间
var sw = Stopwatch.StartNew();
// 调用异步API
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
// 记录请求结束时间
sw.Stop();
rawJson = result;
// 如果请求耗时超过1秒,记录日志
long outTime = sw.ElapsedMilliseconds;
if (outTime > 1000)
{
//LogHelper.Instance.WriteLog($"进站PC<=>MES上传耗时:{outTime}ms,电芯码:{listBar[0]},{listBar[1]},{listBar[2]},{listBar[3]}", "MESTime");
LogHelper.Instance.WriteLog($"客户标签与系统标签绑定PC<=>MES耗时:{outTime}ms", "MESTime");
}
// 记录请求日志
string requestLog = $"{nowDate:yyyy-MM-dd HH:mm:ss.fff}:调用客户标签与系统标签绑定接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds):yyyy-MM-dd HH:mm:ss.fff}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate:yyyyMMdd}\客户标签与系统标签绑定\{nowDate:HH}.txt", requestLog);
// 如果返回结果为空,记录日志并返回
if (string.IsNullOrEmpty(result))
{
//string resData = result == "" ? "" : result;
//resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用客户标签与系统标签绑定接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
//TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\客户标签与系统标签绑定\{nowDate.ToString("HH")}.txt", resJson);
//return (res, mesMessage, mesResType);
message = "MES接口返回空结果";
//return MesResult.Fail(message, MesResType.B, rawJson);
return (success, message, mesResType);
}
// 解析返回结果
var response = JsonConvert.DeserializeObject(result);
// 如果操作成功
if (response != null && response.success)
{
success = true;
ProcessBindingResponse(response, ref message, ref mesResType); // 处理返回结果
//resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用客户标签与系统标签绑定接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
//TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\卡板电芯信息上传(装箱)\{nowDate.ToString("HH")}.txt", resJson);
if (success && mesResType == MesResType.D)
{
message = "客户标签与系统标签绑定成功";
//return MesResult.Ok(true, message, rawJson);
return (success, message, mesResType);
}
else
{
//return MesResult.Fail(message, mesResType, rawJson);
return (success, message, mesResType);
}
}
else
{
//// 如果操作失败,记录日志
//var resData = res1 == null ? "" : result;
//resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用客户标签与系统标签绑定接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
//TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\客户标签与系统标签绑定\{nowDate.ToString("HH")}.txt", resJson);
// 如果操作失败
message = response?.message ?? "MES接口返回失败状态";
//mesResType = GetMesResType(response?.category);
//return MesResult.Fail(message, mesResType, rawJson);
return (success, message, mesResType);
}
}
catch (Exception ex)
{
//// 捕获异常并记录日志
//resJson = $"客户标签与系统标签绑定接口发生异常:{ex.Message}";
//LoggerHelp.WriteLog($"客户标签与系统标签绑定接口{ex}");
// 捕获异常并记录日志
message = $"客户标签与系统标签绑定接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("客户标签与系统标签绑定接口", ex);
//return MesResult.Fail(message, MesResType.B, rawJson);
return (success, message, mesResType);
}
// 返回结果
//return (res, mesMessage, mesResType);
}
///
/// 客户标签与系统标签绑定返回数据处理
///
///
///
///
///
private void ProcessBindingResponse(MesResponse response, ref string message, ref MesResType mesResType)
{
if (response != null)
{
message = response.message;
if (response.success)
{
mesResType = MesResType.D;
message = "MES客户标签与系统标签绑定成功";
}
else
{
//mesResType = GetMesResType(response.category);
}
}
else
{
message = "响应数据为空";
mesResType = MesResType.B;
}
}
#endregion
private List GetTagDataVOList(BGearEntity m, string insertTime, string equipNum,Payload1 payload1)
{
//var AGearList =
List datavolist = new List();
string strFileName = System.Environment.CurrentDirectory + "\\采集项目表.csv";
FileStream fileStream = new FileStream(strFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader streamReader = new StreamReader(fileStream);
_ = streamReader.ReadLine();
while (!streamReader.EndOfStream)
{
string line = streamReader.ReadLine();
string[] keys = line.Split(new string[] { "," },StringSplitOptions.RemoveEmptyEntries);
if (keys.Length == 3)
{
var temp = m.GetType().GetProperty(keys[1]).GetValue(m, null);
if (keys[1] == "TestTime" && string.IsNullOrEmpty(insertTime))
{
datavolist.Add(new TagDataVOListItem()
{
tagCode = keys[0],
tagValue = insertTime,//m
tagTime = DateTime.Now.ToString(),
tagCalculateResult = "Y",
tagRemark = keys[2]
});
}
else
{
datavolist.Add(new TagDataVOListItem()
{
tagCode = keys[0],
tagValue = temp == null ? "0" : temp.ToString(),//m
tagTime = DateTime.Now.ToString(),
tagCalculateResult = "Y",
tagRemark = keys[2]
});
}
}
}
//return datavolist;
//}
//#region 本地字段没有,手动赋值
//{//非Y项//工序名称
// // 产线名称
// // 设备编号
// //操作员
// //班次
// //生产型号
// // 工厂名称
// datavolist.Add(new TagDataVOListItem()
// {
// tagCode = "factory_name",
// tagValue = payload1.siteCode,
// tagTime = DateTime.Now.ToString(),
// tagCalculateResult = "",
// tagRemark = "工厂名称"
// });
// // 工序名称
// datavolist.Add(new TagDataVOListItem()
// {
// tagCode = "process_name",
// tagValue = m.CSBYHPROCESSNAME,
// tagTime = DateTime.Now.ToString(),
// tagCalculateResult = "",
// tagRemark = "工序名称"
// });
// // 产线名称
// datavolist.Add(new TagDataVOListItem()
// {
// tagCode = "production_line_name",
// tagValue = payload1.lineCode,
// tagTime = DateTime.Now.ToString(),
// tagCalculateResult = "",
// tagRemark = "产线名称"
// });
// // 设备编码
// datavolist.Add(new TagDataVOListItem()
// {
// tagCode = "equipment_id",
// tagValue = equipNum,
// tagTime = DateTime.Now.ToString(),
// tagCalculateResult = "",
// tagRemark = "设备编码"
// });
// // 操作员
// datavolist.Add(new TagDataVOListItem()
// {
// tagCode = "operator",
// tagValue = payload1.userName,
// tagTime = DateTime.Now.ToString(),
// tagCalculateResult = "",
// tagRemark = "操作员"
// });
// // 班次
// datavolist.Add(new TagDataVOListItem()
// {
// tagCode = "work_shift",
// tagValue = m.CSBYHSCHEDULE,
// tagTime = DateTime.Now.ToString(),
// tagCalculateResult = "",
// tagRemark = "班次"
// });
// // 生产型号
// datavolist.Add(new TagDataVOListItem()
// {
// tagCode = "product_model",
// tagValue = payload1.materialCode,
// tagTime = DateTime.Now.ToString(),
// tagCalculateResult = "",
// tagRemark = "生产型号"
// });
//}
//#endregion
return datavolist;
}
#region 12、设备状态
///
/// 设备状态
///
/// API URL
/// 站点代码
/// 生产线代码
/// 设备编号
/// 物料代码
/// 用户名
/// 唯一标识
/// 状态代码
/// 故障代码列表
/// 返回操作结果和消息
public async Task<(bool Success, string ResJson)> UploadEquStatusAsync(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, string guid, string statusCode, List faultCodes)
{
bool res = false;
string resJson = "";
try
{
DateTime nowDate = DateTime.Now;
string sNowDate = nowDate.ToString("yyyy-MM-dd HH:mm:ss");
var parameters = new EqpStatusParam
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
materialCode = materialCode,
userName = userName,
seatId = "",
recordDate = sNowDate,
statusCode = statusCode.ToString(),
uploadTime = sNowDate,
guid = guid
};
// 设置故障代码列表
parameters.faultCodeList = faultCodes;
var postcontent = JsonConvert.SerializeObject(parameters);
var sw = Stopwatch.StartNew();
// 异步调用
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
sw.Stop();
if (string.IsNullOrEmpty(result))
{
string resData = result == "" ? "" : result;
resJson = $"{sNowDate}:调用设备运行状态接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备运行状态\{nowDate.ToString("HH")}.txt", resJson);
return (res, resJson);
}
var res1 = ReturnMesMsg(result);
if (!res1.success)
{
var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
resJson = $"{sNowDate}:调用设备运行状态接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备运行状态\{nowDate.ToString("HH")}.txt", resJson);
}
else
{
res = true;
resJson = $"{sNowDate}:调用设备运行状态接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备运行状态\{nowDate.ToString("HH")}.txt", resJson);
}
}
catch (Exception ex)
{
resJson = $"设备运行状态接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("设备运行状态接口", ex);
}
return (res, resJson);
}
#endregion
#region 13、设备报警上传接口
///
/// 设备报警上传接口
///
/// API URL
/// 站点代码
/// 生产线代码
/// 设备编号
/// 物料代码
/// 用户名
/// 报警数据列表
/// 唯一标识
/// 返回操作结果和消息
public async Task<(bool Success, string Mesage)> UploadEquAlarmAsync(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List alarmObj, string guid)
{
bool res = false;
string resJson = "";
string mesage = ""; // 用于存储消息
try
{
var nowDate = DateTime.Now;
if (alarmObj.Count > 0)
{
Console.WriteLine($"{nowDate}: 开始处理报警数据,数量:{alarmObj.Count}");
var model = new UploadAlarmParam
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
materialCode = materialCode,
userName = userName,
recordDate = nowDate.ToString("yyyy-MM-dd HH:mm:ss"),
guid = guid,
seatId = ""
};
model.alarmLineList = new List();
for (int j = 0; j < alarmObj.Count; j++)
{
AlarmLineListItem alarmList = new AlarmLineListItem
{
alarmEndTime = System.Convert.ToString(alarmObj[j].EndTime),
alarmType = alarmObj[j].AlarmType,
alarmName = alarmObj[j].AlarmContent,
alarmStartTime = System.Convert.ToString(alarmObj[j].StartTime),
faultCode = alarmObj[j].AlarmCode
};
model.alarmLineList.Add(alarmList);
Console.WriteLine($"{nowDate}: 添加报警数据 - 报警类型:{alarmObj[j].AlarmType}, 报警内容:{alarmObj[j].AlarmContent}");
}
var postcontent = JsonConvert.SerializeObject(model);
Console.WriteLine($"{nowDate}: 请求数据已序列化:{postcontent}");
var sw = Stopwatch.StartNew();
Console.WriteLine($"{nowDate}: 开始调用设备报警信息接口");
// 异步调用
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
sw.Stop();
Console.WriteLine($"{nowDate}: 接口调用完成,耗时:{sw.ElapsedMilliseconds}ms");
if (string.IsNullOrEmpty(result))
{
string resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备报警信息接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\报警信息\{nowDate.ToString("HH")}.txt", resJson);
Console.WriteLine($"{nowDate}: 接口返回结果为空");
return (res, mesage);
}
var res1 = ReturnMesMsg(result);
if (!res1.success)
{
var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
mesage = res1.message;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备报警信息接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\报警信息\{nowDate.ToString("HH")}.txt", resJson);
Console.WriteLine($"{nowDate}: 接口调用失败,消息:{mesage}");
}
else
{
res = true;
mesage = res1.message;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备报警信息接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\报警信息\{nowDate.ToString("HH")}.txt", resJson);
Console.WriteLine($"{nowDate}: 接口调用成功,消息:{mesage}");
}
}
else
{
Console.WriteLine($"{nowDate}: 报警数据为空,无需处理");
}
}
catch (Exception ex)
{
resJson = $"调用设备报警信息接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("调用设备报警信息接口", ex);
Console.WriteLine($"{DateTime.Now}: 发生异常:{ex.Message}");
}
return (res, mesage);
}
#endregion
#region 14、上传设备能耗数据
///
/// 上传设备能耗数据
///
/// API URL
/// 站点代码
/// 生产线代码
/// 设备编号
/// 用户名
/// 电表编号列表
/// 能耗数据列表
/// 返回操作结果和日志信息
public async Task<(bool Success, string Mesage)> UploadEquEnergyAsync(string url, string siteCode, string lineCode, string equipNum, string userName, List electricMeterNum, List wattrs)
{
bool res = false;
string mesage = "";
try
{
var nowDate = DateTime.Now;
Console.WriteLine($"{nowDate}: 开始处理设备能耗数据");
// 序列化请求数据
var postcontent = JsonConvert.SerializeObject(wattrs);
Console.WriteLine($"{nowDate}: 请求数据已序列化:{postcontent}");
var sw = Stopwatch.StartNew();
Console.WriteLine($"{nowDate}: 开始调用设备能耗信息接口");
// 异步调用
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
sw.Stop();
Console.WriteLine($"{nowDate}: 接口调用完成,耗时:{sw.ElapsedMilliseconds}ms");
if (string.IsNullOrEmpty(result))
{
string resData = result == "" ? "" : result;
mesage = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备能耗信息接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备能耗信息\{nowDate.ToString("HH")}.txt", mesage);
Console.WriteLine($"{nowDate}: 接口返回结果为空");
return (res, mesage);
}
var res1 = ReturnMesMsg(result);
if (!res1.success)
{
var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
mesage = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备能耗信息接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备能耗信息\{nowDate.ToString("HH")}.txt", mesage);
Console.WriteLine($"{nowDate}: 接口调用失败,返回结果:{resData}");
}
else
{
res = true;
mesage = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备能耗信息接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备能耗信息\{nowDate.ToString("HH")}.txt", mesage);
Console.WriteLine($"{nowDate}: 接口调用成功,返回结果:{result}");
}
}
catch (Exception ex)
{
mesage = $"调用设备能耗信息接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("调用设备能耗信息接口", ex);
Console.WriteLine($"{DateTime.Now}: 发生异常:{ex.Message}");
}
return (res, mesage);
}
#endregion
#region 15、风速仪数据上传至MES
///
/// 风速仪数据上传至MES
///
/// API URL
/// 设备编号
/// 风速仪编号列表
/// 采集数据列表
/// 返回操作结果和消息
public async Task<(bool Success, string Mesage)> UploadDeviceCollectDataAsync(string url, string equipNum, List antiDustAirSpeedNum, List collectData)
{
bool res = false;
string resJson = "";
string mesage = ""; // 用于存储消息
try
{
if (collectData == null || collectData.Count == 0)
{
mesage = "采集数据为空,无需处理";
Console.WriteLine($"{DateTime.Now}: {mesage}");
return (res, mesage);
}
var nowDate = DateTime.Now;
Console.WriteLine($"{nowDate}: 开始处理风速仪数据");
// 创建请求模型
UploadDeviceCollectData uploadDevice = new UploadDeviceCollectData
{
appid = "e1012966a936170c6fcab98e24042d10",
device_code = equipNum,
collect_time = GetUnixTimestamp()
};
// 填充采集数据
List list = new List();
for (int i = 0; i < collectData.Count; i++)
{
Collect_code_value_list _Value_List = new Collect_code_value_list
{
target_code = 5,
target_value = collectData[i].ToString(),
target_value_tag = antiDustAirSpeedNum[i]
};
list.Add(_Value_List);
Console.WriteLine($"{nowDate}: 添加采集数据 - 风速仪编号:{antiDustAirSpeedNum[i]}, 采集值:{collectData[i]}");
}
uploadDevice.collect_code_value_list = list;
// 序列化请求数据
string postcontent = JsonConvert.SerializeObject(uploadDevice);
Console.WriteLine($"{nowDate}: 请求数据已序列化:{postcontent}");
var sw = Stopwatch.StartNew();
Console.WriteLine($"{nowDate}: 开始调用风速接口");
// 异步调用
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
sw.Stop();
Console.WriteLine($"{nowDate}: 接口调用完成,耗时:{sw.ElapsedMilliseconds}ms");
if (string.IsNullOrEmpty(result))
{
string resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用风速接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\风速信息\{nowDate.ToString("HH")}.txt", resJson);
mesage = "接口返回结果为空";
Console.WriteLine($"{nowDate}: {mesage}");
return (res, mesage);
}
var res1 = ReturnMesMsg(result);
if (!res1.success)
{
var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
mesage = res1.message;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用风速接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\风速信息\{nowDate.ToString("HH")}.txt", resJson);
Console.WriteLine($"{nowDate}: 接口调用失败,消息:{mesage}");
}
else
{
res = true;
mesage = res1.message;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用风速接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\风速信息\{nowDate.ToString("HH")}.txt", resJson);
Console.WriteLine($"{nowDate}: 接口调用成功,消息:{mesage}");
}
}
catch (Exception ex)
{
resJson = $"调用风速接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("调用风速接口", ex);
Console.WriteLine($"{DateTime.Now}: 发生异常:{ex.Message}");
}
return (res, mesage);
}
#endregion
///
/// 序列化各类返回
///
///
///
///
private T ReturnMesMsg(string ret)
{
try
{
return JsonConvert.DeserializeObject(ret);
}
catch (System.Exception ex)
{
return default(T);
}
}
public List GetMesType(int Num)
{
List mesResTypes = new List();
for (int i = 0; i < Num; i++)
{
mesResTypes.Add(MesResType.B);
}
return mesResTypes;
}
public List GetListString(int Num, string str)
{
List mesResTypes = new List();
for (int i = 0; i < Num; i++)
{
mesResTypes.Add(str);
}
return mesResTypes;
}
///
///本地时间为Unix时间戳
///
///
public static long GetUnixTimestamp()
{
return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}
public Task<(bool Success, string ResJson)> ParamChangeAsync(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List paramChangeItems)
{
throw new NotImplementedException();
}
//public Task<(bool Success, string ResJson)> ProductProcessParamAsync(string url, string siteCode, string userName, string equipNum, string lineCode, string materialCode, MesUploadType unloadType, List productProcessParam)
//{
// throw new NotImplementedException();
//}
//#endregion
#region 17、自动分档接口
public async Task<(bool Success, List MesLevel, List MesPassage, List MesMessage)> GetOCVShiftAsync(string url, string siteCode, string lineCode, string equipNum, string containerCode, string materialCode, string userName, List barCodeList)
{
bool res = false;
string resJson = "";
List mesLevel = GetListString(barCodeList.Count, "1");
List mesPassage = GetListString(barCodeList.Count, ""); // 通道
List mesMessage = GetListString(barCodeList.Count, "");// 信息
//List mesPassagewayNum = GetListString(barCodeList.Count, ""); //
try
{
DateTime nowDate = DateTime.Now;
string sNowDate = nowDate.ToString("yyyy/MM/dd HH:mm:ss");
var parameters = new GetOCVShift
{
siteCode = siteCode,
lineCode = lineCode,
equipNum = equipNum,
recordDate = sNowDate,
qty = barCodeList.Count.ToString(),
containerCode = containerCode,
materialCode = materialCode,
userName = userName,
materiallotCodeList = barCodeList,
};
var postcontent = JsonConvert.SerializeObject(parameters);
var sw = Stopwatch.StartNew();
// 异步调用
string result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, postcontent, false);
sw.Stop();
if (string.IsNullOrEmpty(result))
{
string resData = result == "" ? "" : result;
resJson = $"{sNowDate}:调用自动分档接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\自动分档\{nowDate.ToString("HH")}.txt", resJson);
return (res, mesLevel, mesPassage, mesMessage);
}
var res1 = ReturnMesMsg(result);
if (!res1.success)
{
var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
resJson = $"{sNowDate}:调用自动分档接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\自动分档\{nowDate.ToString("HH")}.txt", resJson);
}
else
{
res = true;
//GetDMCMesResData(res1, barCodeList, ref mesLevel, ref mesPassage, ref mesMessage);
resJson = $"{sNowDate}:调用自动分档接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\自动分档\{nowDate.ToString("HH")}.txt", resJson);
}
}
catch (Exception ex)
{
resJson = $"自动分档接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("自动分档接口", ex);
}
return (res, mesLevel, mesPassage, mesMessage);
}
#endregion
#region 18、获取OCV数据
public async Task<(bool Success, string Mesage, MesData data)> GetOcvListAsync(string url, string warehouseCode, string customerCode, List barCodeList)
{
bool res = false; // 操作结果
string mesage = ""; // 消息
string result = string.Empty;
var nowDate = DateTime.Now;
MesData mesData = new MesData();
string resJson = "";
try
{
var request = new
{
warehouseCode = warehouseCode,
customerCode = customerCode,
stdSnList = barCodeList
};
var sw = Stopwatch.StartNew();
// 异步调用
result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, request, true);
sw.Stop();
if (string.IsNullOrEmpty(result))
{
var resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用获取OCV信息接口:{url},请求数据为:{JsonConvert.SerializeObject(request)},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\获取OCV信息\{nowDate.ToString("HH")}.txt", resJson);
mesage = "MES未返回数据";
return (res, mesage, null);
}
res = true;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用获取OCV信息接口:{url},请求数据为:{JsonConvert.SerializeObject(request)},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\获取OCV信息\{nowDate.ToString("HH")}.txt", resJson);
// 处理MES响应数据
//var data = ProcessMESResponse(result);
//if (data == null)
//{
// mesage = $"条码{barCodeList[0]}的MES数据处理失败";
// return (res, mesage, data);
//}
//else
//{
// //处理成功
// return (res, mesage, data);
//}
}
catch (Exception ex)
{
resJson = $"获取OCV信息异常:{ex.Message}";
mesage = $"获取OCV信息异常:{ex.Message}";
LogHelper.Instance.WriteEX("获取OCV接口", ex);
}
return (res, mesage, mesData);
}
#endregion
#region 19、翻包设备上传绑定信息接口-内箱翻内箱(适用于G11仓)
public async Task<(bool Success, string MesMessage, MesResType MesResType)> GetAroundBagListAsync(string url, string warehouseCode, string customerCode, string CardBarcode, List InnerBoxLabelLists)
{
bool res = false; // 操作结果
string mesage = ""; // 用于存储消息
MesResType mesResType = MesResType.A; // 默认为 NG
string result = string.Empty;
var nowDate = DateTime.Now;
string resJson = "";
try
{
var model = new WmsUpload
{
warehouseCode = warehouseCode,
customerCode = customerCode,
equipmentCode = "0019",
equipmentName = "19号翻包机",
trayLabel = CardBarcode,
};
//托盘详细信息
model.innerBoxLabelList = InnerBoxLabelLists;
var sw = Stopwatch.StartNew();
// 异步调用
result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, model, true);
sw.Stop();
if (string.IsNullOrEmpty(result))
{
var resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:翻包设备上传绑定信息接口(内箱翻内箱):{url},请求数据为:{JsonConvert.SerializeObject(model)},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\翻包上传绑定信息\{nowDate.ToString("HH")}.txt", resJson);
mesage = "WMS返回数据为空";
return (res, mesage, mesResType);
}
// 处理MES响应数据
var res1 = ReturnMesMsg(result);
res = true;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:翻包设备上传绑定信息接口(内箱翻内箱):{url},请求数据为:{JsonConvert.SerializeObject(model)},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\翻包上传绑定信息\{nowDate.ToString("HH")}.txt", resJson);
mesage = res1.message;
if (res1.result)
{
mesResType = MesResType.D; //MES OK
}
}
catch (Exception ex)
{
resJson = $"翻包上传绑定信息异常:{ex.Message}";
LogHelper.Instance.WriteEX("翻包上传绑定信息", ex);
}
return (res, mesage, mesResType);
}
#endregion
#region 18、获取VDA数据
public async Task<(bool Success, string Mesage, DataItem data)> GetVDAListAsync(string url, string warehouseCode, string customerCode, string CardBarcode)
{
bool res = false; // 操作结果
string mesage = ""; // 消息
string result = string.Empty;
var nowDate = DateTime.Now;
DataItem mesData = new DataItem();
string resJson = "";
try
{
var request = new VdaGetData
{
warehouseCode = warehouseCode,
customerCode = customerCode,
labelTemplateCode = "VDA-C",
codeDataList = new List
{
new CodeData { trayLabel = CardBarcode }
}
};
var sw = Stopwatch.StartNew();
// 异步调用
result = await MESApiHelper.SendRequestStringAsync(url, HttpMethod.Post, request, true);
sw.Stop();
if (string.IsNullOrEmpty(result))
{
var resData = result == "" ? "" : result;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用翻包拉取不完整VDA信息接口:{url},请求数据为:{JsonConvert.SerializeObject(request)},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\拉取不完整VDA信息\{nowDate.ToString("HH")}.txt", resJson);
mesage = "MES未返回数据";
return (res, mesage, null);
}
res = true;
resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用翻包拉取不完整VDA信息接口:{url},请求数据为:{JsonConvert.SerializeObject(request)},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\拉取不完整VDA信息\{nowDate.ToString("HH")}.txt", resJson);
// 处理MES响应数据
var data = ProcessMESResponse(result);
if (data == null)
{
mesage = $"底托卡板条码{CardBarcode}获取VDA接口dataList失败";
return (res, mesage, mesData);
}
else
{
//处理成功
return (res, mesage, data);
}
}
catch (Exception ex)
{
resJson = $"拉取不完整VDA信息异常:{ex.Message}";
mesage = $"拉取不完整VDA信息异常:{ex.Message}";
LogHelper.Instance.WriteEX("拉取不完整VDA接口", ex);
}
return (res, mesage, mesData);
}
///
/// 处理MES系统返回的数据
///
///
///
private DataItem ProcessMESResponse(string response)
{
if (string.IsNullOrEmpty(response))
{
return null;
}
try
{
var (success, data) = ParseMESData(response);
return success ? data : null;
}
catch (Exception ex)
{
LogHelper.Instance.WriteEX("处理MES响应时发生错误", ex);
return null;
}
}
private (bool success, DataItem data) ParseMESData(in string jsonResponse)
{
// 使用 JObject 动态解析 JSON 数据
var jsonObject = JObject.Parse(jsonResponse);
// 使用模式匹配和空值检查
if (!(jsonObject["result"] is JToken resultToken) ||
//!resultToken.ToObject() ||
!(jsonObject["dataList"] is JArray dataList) ||
dataList.Count == 0)
{
return (false, null);
}
var dataObject = dataList[0] as JObject;
if (dataObject == null)
{
return (false, null);
}
return (true, new DataItem
{
receiver = GetStringValue(dataObject, "receiver"),//1
unloading = GetStringValue(dataObject, "unloading"),//2
adciveNo = GetStringValue(dataObject, "adciveNo"),//3 暂时不使用 数字+条形码(格式为39码)
supplier = GetStringValue(dataObject, "supplier"),//4
netWeight = GetStringValue(dataObject, "netWeight"),//5
groWeight = GetStringValue(dataObject, "groWeight"),//6
noBoxes = GetStringValue(dataObject, "noBoxes"),//7
partNo = GetStringValue(dataObject, "partNo"),//8 数字+条形码(格式为39码)
bmwDmc = GetStringValue(dataObject, "bmwDmc"),//8-1 二维码
bmwDmcJYA = GetStringValue(dataObject, "bmwDmcJYA"),//8-1 二维码(解析后)
quantity = GetStringValue(dataObject, "quantity"),//9 数字+条形码(格式为39码)
skuDescr = GetStringValue(dataObject, "skuDescr"),//10
sku = GetStringValue(dataObject, "sku"),//11.1
packageNo = GetStringValue(dataObject, "packageNo"),//11.2
spid = GetStringValue(dataObject, "spid"),//12 数字+条形码(格式为39码)
date = GetStringValue(dataObject, "date"),//13
drawNo = GetStringValue(dataObject, "drawNo"),//14
serialNo = GetStringValue(dataObject, "serialNo"),//15 数字+条形码(格式为39码)
batchNo = GetStringValue(dataObject, "batchNo"),//16 数字+条形码(格式为39码)
//TestTime = GetDateTimeValue(dataObject, "TestTime"),
//OCV5 = GetDoubleValue(dataObject, "OCV5"),
//OCVTIME1 = GetDateTimeValue(dataObject, "OCVTIME1"),
});
}
// 辅助方法,使用 C# 7.3 的 in 参数
private string GetStringValue(in JObject obj, in string propertyName)
=> obj[propertyName]?.ToString();
private double? GetDoubleValue(in JObject obj, in string propertyName)
{
if (obj[propertyName] is JToken token && token.Type != JTokenType.Null)
{
try
{
return token.ToObject();
}
catch
{
//LogError($"转换属性 {propertyName} 到 double 类型失败");
return null;
}
}
return null;
}
private DateTime? GetDateTimeValue(in JObject obj, in string propertyName)
{
if (obj[propertyName] is JToken token && token.Type != JTokenType.Null)
{
try
{
return token.ToObject();
}
catch
{
//LogError($"转换属性 {propertyName} 到 DateTime 类型失败");
return null;
}
}
return null;
}
#endregion
}
}