Files
1257B_DB/JinYuan.MES/MesDataProcess.cs
T
2026-08-06 09:23:30 +08:00

1727 lines
81 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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、登录验证 √
/// 账号密码登录(异步方法)
/// </summary>
/// <param name="url">API地址</param>
/// <param name="siteCode">站点代码</param>
/// <param name="lineCode">线体代码</param>
/// <param name="equipNum">设备编号</param>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
/// <param name="UserCardID">用户卡ID</param>
/// <returns>返回结果(是否成功、消息)</returns> 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<MesResponseLogin>(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);
}
/// <summary>
/// 刷卡登录
/// </summary>
/// <param name="url"></param>
/// <param name="siteCode"></param>
/// <param name="lineCode"></param>
/// <param name="equipNum"></param>
/// <param name="UserCardID"></param>
/// <returns></returns>
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<MesResponse>(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参数请求
/// <summary>
/// 获取MES参数请求
/// </summary>
/// <param name="url"></param>
/// <param name="equipNum"></param>
/// <param name="siteCode"></param>
/// <param name="lineCode"></param>
/// <param name="materialCode"></param>
/// <param name="userName"></param>
/// <param name="resJson"></param>
/// <returns></returns>
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<ParamReturnData>(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、参数变更请求
/// <summary>
/// 参数变更请求
/// </summary>
/// <param name="url"></param>
/// <param name="siteCode"></param>
/// <param name="lineCode"></param>
/// <param name="equipNum"></param>
/// <param name="materialCode"></param>
/// <param name="userName"></param>
/// <param name="paramChangeItems"></param>
/// <param name="Mesage"></param>
/// <returns></returns>
public async Task<bool> ParamChange(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List<TagListItem> 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
/// <summary>
/// 将MES返回的category转换为MesResType
/// </summary>
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 箱唛信息获取
/// <summary>
/// 箱唛信息获取
/// </summary>
/// <param name="url">API地址 /api/public/equip/auto/cartonquery</param>
/// <param name="siteCode">工厂代码</param>
/// <param name="lineCode">产线编号</param>
/// <param name="equipNum">设备编号</param>
/// <param name="containerCode">卡板码(箱唛号)</param>
/// <returns>返回结果(是否成功、消息列表、响应类型列表)</returns>
public async Task<(bool success, string mesMessage, MesResType mesResType, List<TagInfo> cartonTagInfos)> QueryCartonAsync(string url, string siteCode, string lineCode, string equipNum, string containerCode)
{
bool success = false; // 操作结果
string rawJson = ""; //
string message = ""; // 消息列表
MesResType mesResType = MesResType.C;
List<TagInfo> cartonTagInfos = new List<TagInfo>();
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<MesResponseCarton>(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<List<TagInfo>>.Fail(message, mesResType, rawJson);
}
}
catch (Exception ex)
{
// 捕获异常并记录日志
message = $"箱唛信息获取接口发生异常:{ex.Message}";
LogHelper.Instance.WriteEX("箱唛信息获取接口", ex);
}
// 返回结果
return (success, message, mesResType, cartonTagInfos);
}
/// <summary>
/// 箱唛信息获取返回数据处理
/// </summary>
/// <param name="res1"></param>
/// <param name="BarCode"></param>
/// <param name="MesMessage"></param>
/// <param name="mesResType"></param>
private void ProcessCartonResponse(MesResponseCarton response, ref string message, ref MesResType mesResType, ref List<TagInfo> cartonTagInfos)
{
if (response != null)
{
cartonTagInfos = response.rows ?? new List<TagInfo>();
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 栈板获取
/// <summary>
/// 栈板信息获取
/// </summary>
/// <param name="url">API地址 /api/public/equip/auto/palletquery</param>
/// <param name="siteCode">工厂代码</param>
/// <param name="lineCode">产线编号</param>
/// <param name="equipNum">设备编号</param>
/// <param name="containerCode">卡板码(箱唛号)</param>
/// <returns>返回结果(是否成功、消息列表、响应类型列表)</returns>
public async Task<(bool success, string mesMessage, MesResType mesResType, string palletCode, List<TagInfo> 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<TagInfo> palletTagInfos = new List<TagInfo>();
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<MesResponsePallet>(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);
}
/// <summary>
/// 栈板信息获取返回数据处理
/// </summary>
/// <param name="res1"></param>
/// <param name="BarCode"></param>
/// <param name="MesMessage"></param>
/// <param name="mesResType"></param>
private void ProcessPalletResponse(MesResponsePallet response, ref string message, ref MesResType mesResType, ref string palletCode, ref List<TagInfo> 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<TagInfo>();
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 客户标签与系统标签绑定
/// <summary>
/// 客户标签与系统标签绑定
/// </summary>
/// <param name="url">API地址 /api/public/equip/auto/</param> //TODO 待补充!
/// <param name="siteCode">工厂代码</param>
/// <param name="lineCode">产线编号</param>
/// <param name="equipNum">设备编号</param>
/// <param name="containerCode">卡板码(箱唛号)</param>
/// <param name="palletCode">栈板码</param>
/// <param name="custcartonCode">客户箱唛码</param>
/// <param name="custpalletCode">客户栈板码</param>
/// <param name="custcarton">客户箱唛信息</param>
/// <param name="custpallet">客户栈板信息</param>
/// <returns>返回结果(是否成功、消息列表、响应类型列表)</returns>
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<TagInfo> custcarton, List<TagInfo> 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<bool>.Fail(message, MesResType.B, rawJson);
return (success, message, mesResType);
}
// 解析返回结果
var response = JsonConvert.DeserializeObject<MesResponse>(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<bool>.Ok(true, message, rawJson);
return (success, message, mesResType);
}
else
{
//return MesResult<bool>.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<bool>.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<bool>.Fail(message, MesResType.B, rawJson);
return (success, message, mesResType);
}
// 返回结果
//return (res, mesMessage, mesResType);
}
/// <summary>
/// 客户标签与系统标签绑定返回数据处理
/// </summary>
/// <param name="res1"></param>
/// <param name="BarCode"></param>
/// <param name="MesMessage"></param>
/// <param name="mesResType"></param>
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<TagDataVOListItem> GetTagDataVOList(BGearEntity m, string insertTime, string equipNum,Payload1 payload1)
{
//var AGearList =
List<TagDataVOListItem> datavolist = new List<TagDataVOListItem>();
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、设备状态
/// <summary>
/// 设备状态
/// </summary>
/// <param name="url">API URL</param>
/// <param name="siteCode">站点代码</param>
/// <param name="lineCode">生产线代码</param>
/// <param name="equipNum">设备编号</param>
/// <param name="materialCode">物料代码</param>
/// <param name="userName">用户名</param>
/// <param name="guid">唯一标识</param>
/// <param name="statusCode">状态代码</param>
/// <param name="faultCodes">故障代码列表</param>
/// <returns>返回操作结果和消息</returns>
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<FaultCodeList> 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<MesResponse>(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、设备报警上传接口
/// <summary>
/// 设备报警上传接口
/// </summary>
/// <param name="url">API URL</param>
/// <param name="siteCode">站点代码</param>
/// <param name="lineCode">生产线代码</param>
/// <param name="equipNum">设备编号</param>
/// <param name="materialCode">物料代码</param>
/// <param name="userName">用户名</param>
/// <param name="alarmObj">报警数据列表</param>
/// <param name="guid">唯一标识</param>
/// <returns>返回操作结果和消息</returns>
public async Task<(bool Success, string Mesage)> UploadEquAlarmAsync(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List<AlarmData> 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<AlarmLineListItem>();
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<MesResponse>(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、上传设备能耗数据
/// <summary>
/// 上传设备能耗数据
/// </summary>
/// <param name="url">API URL</param>
/// <param name="siteCode">站点代码</param>
/// <param name="lineCode">生产线代码</param>
/// <param name="equipNum">设备编号</param>
/// <param name="userName">用户名</param>
/// <param name="electricMeterNum">电表编号列表</param>
/// <param name="wattrs">能耗数据列表</param>
/// <returns>返回操作结果和日志信息</returns>
public async Task<(bool Success, string Mesage)> UploadEquEnergyAsync(string url, string siteCode, string lineCode, string equipNum, string userName, List<string> electricMeterNum, List<WattrMeter> 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<MesResponse>(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
/// <summary>
/// 风速仪数据上传至MES
/// </summary>
/// <param name="url">API URL</param>
/// <param name="equipNum">设备编号</param>
/// <param name="antiDustAirSpeedNum">风速仪编号列表</param>
/// <param name="collectData">采集数据列表</param>
/// <returns>返回操作结果和消息</returns>
public async Task<(bool Success, string Mesage)> UploadDeviceCollectDataAsync(string url, string equipNum, List<string> antiDustAirSpeedNum, List<float> 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<Collect_code_value_list> list = new List<Collect_code_value_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<MesResponse>(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
/// <summary>
/// 序列化各类返回
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ret"></param>
/// <returns></returns>
private T ReturnMesMsg<T>(string ret)
{
try
{
return JsonConvert.DeserializeObject<T>(ret);
}
catch (System.Exception ex)
{
return default(T);
}
}
public List<MesResType> GetMesType(int Num)
{
List<MesResType> mesResTypes = new List<MesResType>();
for (int i = 0; i < Num; i++)
{
mesResTypes.Add(MesResType.B);
}
return mesResTypes;
}
public List<string> GetListString(int Num, string str)
{
List<string> mesResTypes = new List<string>();
for (int i = 0; i < Num; i++)
{
mesResTypes.Add(str);
}
return mesResTypes;
}
/// <summary>
///本地时间为Unix时间戳
/// </summary>
/// <returns></returns>
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<TagListItem> 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> productProcessParam)
//{
// throw new NotImplementedException();
//}
//#endregion
#region 17、自动分档接口
public async Task<(bool Success, List<string> MesLevel, List<string> MesPassage, List<string> MesMessage)> GetOCVShiftAsync(string url, string siteCode, string lineCode, string equipNum, string containerCode, string materialCode, string userName, List<string> barCodeList)
{
bool res = false;
string resJson = "";
List<string> mesLevel = GetListString(barCodeList.Count, "1");
List<string> mesPassage = GetListString(barCodeList.Count, ""); // 通道
List<string> mesMessage = GetListString(barCodeList.Count, "");// 信息
//List<string> 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<MesResponseGrad>(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<string> 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<InnerBoxLabelInfo> 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<WMSResponse>(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<CodeData>
{
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);
}
/// <summary>
/// 处理MES系统返回的数据
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
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<bool>() ||
!(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<double>();
}
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<DateTime>();
}
catch
{
//LogError($"转换属性 {propertyName} 到 DateTime 类型失败");
return null;
}
}
return null;
}
#endregion
}
}