2025-02-19 16:28:25 +08:00

518 lines
20 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using WindowsFormsApp1.mod;
using WindowsFormsApp1.mod.server;
using Polly;
using Polly.Timeout;
using System.Net.Http;
using WindowsFormsApp1.db;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using Newtonsoft.Json;
namespace WindowsFormsApp1.server
{
public class ApiClient
{
private readonly HttpClient _httpClient;
private readonly Dictionary<string,string> apiUrlDict;
public ApiClient()
{
_httpClient = new HttpClient();
SQLiteHelper<t_interface> helper = new db.SQLiteHelper<t_interface>();
var apiList = helper.QueryAll().Data.ToList();
apiUrlDict = apiList.ToDictionary(x => x.code, x => x.url);
}
public ApiFormResult SN_CheckIN(string url,plcdata PlcData, otherdata OtherData)
{
// 组装 request json
var request = new
{
EventID = "SN_CheckIN",
Line = "Testline",
StationID = "TestStation",
MachineID = "TestMachine",
OPID = "OPID",
Token = "",
FixSN = "",
SN = PlcData.Read_MaterialCode0,
CarrierID = PlcData.Read_MaterialCode1,
SendTime = DateTime.Now
};
// 使用 Newtonsoft.Json 进行序列化
string jsonPayload = JsonConvert.SerializeObject(request);
// 创建 StringContent 对象,将 JSON 字符串作为请求体,指定编码和媒体类型
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// 调用接口
try
{
var response = _httpClient.PostAsync(url, httpContent).Result;
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseContent = response.Content.ReadAsStringAsync().Result;
// 使用 Newtonsoft.Json 将响应内容反序列化为动态对象
dynamic res = JsonConvert.DeserializeObject(responseContent);
// 访问动态对象的属性
if (res != null)
{
// 成功!
if (!string.IsNullOrEmpty(res.RESULT))
{
// 回写对应PLC
return res.RESULT == "pass" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG, PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG, PlcData, DateTime.Now);
}
}
}
else
{
throw new Exception($"请求失败,状态码:{response.StatusCode}");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult Carrier_Check(string url, plcdata PlcData, otherdata OtherData)
{
// 组装 request json
var request = new
{
EventID = "Carrier_Check",
Line = "Testline",
StationID = "TestStation",
MachineID = "TestMachine",
OPID = "OPID",
Token = "",
FixSN = "",
CarrierID = PlcData.Read_MaterialCode1,
SendTime = DateTime.Now
};
// 使用 Newtonsoft.Json 进行序列化
string jsonPayload = JsonConvert.SerializeObject(request);
// 创建 StringContent 对象,将 JSON 字符串作为请求体,指定编码和媒体类型
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// 调用接口
try
{
var response = _httpClient.PostAsync(url, httpContent).Result;
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseContent = response.Content.ReadAsStringAsync().Result;
// 使用 Newtonsoft.Json 将响应内容反序列化为动态对象
dynamic res = JsonConvert.DeserializeObject(responseContent);
// 访问动态对象的属性
if (res != null)
{
// 成功!
if (!string.IsNullOrEmpty(res.RESULT))
{
// 回写对应PLC
return res.RESULT == "pass" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG, PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG, PlcData, DateTime.Now);
}
}
}
else
{
throw new Exception($"请求失败,状态码:{response.StatusCode}");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult SN_FeedingCheck(string url, plcdata PlcData, otherdata OtherData)
{
// 组装 request json
var request = new
{
EventID = "Carrier_Check",
Line = "Testline",
StationID = "TestStation",
MachineID = "TestMachine",
OPID = "OPID",
Token = "",
FixSN = "",
SN = PlcData.Read_MaterialCode0,
SendTime = DateTime.Now
};
// 使用 Newtonsoft.Json 进行序列化
string jsonPayload = JsonConvert.SerializeObject(request);
// 创建 StringContent 对象,将 JSON 字符串作为请求体,指定编码和媒体类型
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// 调用接口
try
{
var response = _httpClient.PostAsync(url, httpContent).Result;
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseContent = response.Content.ReadAsStringAsync().Result;
// 使用 Newtonsoft.Json 将响应内容反序列化为动态对象
dynamic res = JsonConvert.DeserializeObject(responseContent);
// 访问动态对象的属性
if (res != null)
{
// 成功!
if (!string.IsNullOrEmpty(res.RESULT))
{
// 回写对应PLC
return res.RESULT == "pass" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG, PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG, PlcData, DateTime.Now);
}
}
}
else
{
throw new Exception($"请求失败,状态码:{response.StatusCode}");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult Link_Comp(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult SN_Release(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult Glue_CheckOut(string url, plcdata PlcData, otherdata OtherData)
{
// 组装 request json
var request = new
{
EventID = "Glue_CheckOut",
Line = "Testline",
StationID = "TestStation",
MachineID = "TestMachine",
OPID = "",//判断站,胶水不用传
Token = "",//判断站,胶水不用传
FixSN = "",//判断站,胶水不用传
SN = PlcData.Read_MaterialCode0,
SendTime = DateTime.Now
};
// 使用 Newtonsoft.Json 进行序列化
string jsonPayload = JsonConvert.SerializeObject(request);
// 创建 StringContent 对象,将 JSON 字符串作为请求体,指定编码和媒体类型
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// 调用接口
try
{
var response = _httpClient.PostAsync(url, httpContent).Result;
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseContent = response.Content.ReadAsStringAsync().Result;
// 使用 Newtonsoft.Json 将响应内容反序列化为动态对象
dynamic res = JsonConvert.DeserializeObject(responseContent);
// 访问动态对象的属性
if (res != null)
{
// 成功!
if (!string.IsNullOrEmpty(res.RESULT))
{
// 回写对应PLC
return res.RESULT == "pass" ? ApiFormResult.Sucess(mesresult.PASS, true, res.MSG, PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG, PlcData, DateTime.Now);
}
}
}
else
{
throw new Exception($"请求失败,状态码:{response.StatusCode}");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult Get_Para(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult DispatchPara(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult Data_Collection(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult Status(string url, plcdata PlcData, otherdata OtherData)
{
// 组装 request json
var request = new
{
EventID = "Carrier_Check",
Line = "Testline",
StationID = "TestStation",
MachineID = "TestMachine",
OPID = "OPID",
STATUS = OtherData.Plc_Status,
SendTime = DateTime.Now
};
// 使用 Newtonsoft.Json 进行序列化
string jsonPayload = JsonConvert.SerializeObject(request);
// 创建 StringContent 对象,将 JSON 字符串作为请求体,指定编码和媒体类型
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// 调用接口
try
{
var response = _httpClient.PostAsync(url, httpContent).Result;
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseContent = response.Content.ReadAsStringAsync().Result;
// 使用 Newtonsoft.Json 将响应内容反序列化为动态对象
dynamic res = JsonConvert.DeserializeObject(responseContent);
// 访问动态对象的属性
if (res != null)
{
// 成功!
if (!string.IsNullOrEmpty(res.RESULT))
{
// 回写对应PLC
return res.RESULT == "pass" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG, PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG, PlcData, DateTime.Now);
}
}
}
else
{
throw new Exception($"请求失败,状态码:{response.StatusCode}");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult Alarm(string url, plcdata PlcData, otherdata OtherData)
{
// 组装 request json
var request = new
{
EventID = "Carrier_Check",
Line = "Testline",
StationID = "TestStation",
MachineID = "TestMachine",
OPID = "OPID",
AlarmID = OtherData.Plc_ErrorMsg,
SendTime = DateTime.Now,
ResetTime = ""
};
// 使用 Newtonsoft.Json 进行序列化
string jsonPayload = JsonConvert.SerializeObject(request);
// 创建 StringContent 对象,将 JSON 字符串作为请求体,指定编码和媒体类型
var httpContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// 调用接口
try
{
var response = _httpClient.PostAsync(url, httpContent).Result;
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseContent = response.Content.ReadAsStringAsync().Result;
// 使用 Newtonsoft.Json 将响应内容反序列化为动态对象
dynamic res = JsonConvert.DeserializeObject(responseContent);
// 访问动态对象的属性
if (res != null)
{
// 成功!
if (!string.IsNullOrEmpty(res.RESULT))
{
// 回写对应PLC
return res.RESULT == "pass" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG, PlcData, DateTime.Now)
: ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG, PlcData, DateTime.Now);
}
}
}
else
{
throw new Exception($"请求失败,状态码:{response.StatusCode}");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult OEEDataCollection(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData,DateTime.Now);
}
public ApiFormResult SN_FileUpload(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData,DateTime.Now);
}
public ApiFormResult Test(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData,DateTime.Now);
}
public ApiFormResult SN_Checkout(string url, plcdata PlcData, otherdata OtherData)
{
return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData,DateTime.Now);
}
public ApiFormResult Initialization(string url, plcdata PlcData, otherdata OtherData)
{
PlcData.Write_Status = 3;
return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now);
}
public ApiFormResult CallFunctionByName(string functionName, plcdata plcdata,otherdata otherdata)
{
// 定义重试策略
var retryPolicy = Policy
.Handle<Exception>() // 处理HTTP请求异常
.WaitAndRetry(2, retryAttempt =>
{
// 自定义重试间隔
switch (retryAttempt)
{
case 1:
return TimeSpan.FromSeconds(3); // 第一次重试间隔3秒
case 2:
return TimeSpan.FromSeconds(5); // 第二次重试间隔5秒
default:
return TimeSpan.FromSeconds(0); // 默认间隔0秒
}
}, (exception, timeSpan, retryCount, context) =>
{
LogExecute.logNet.WriteError($"重试第 {retryCount} 次,异常信息: {exception.Message}");
});
// 定义超时策略
var timeoutPolicy = Policy
.Timeout(5, // 超时时间3秒
TimeoutStrategy.Pessimistic); // 使用悲观超时策略
// 获取当前类的类型
Type type = this.GetType();
// 使用反射调用指定名称的方法
MethodInfo methodInfo = type.GetMethod(functionName);
try
{
// 打印调用开始日志
LogExecute.logNet.WriteError("开始调用API...");
// 使用同步方法调用API,并结合重试策略
var result = retryPolicy.Execute(() =>
{
LogExecute.logNet.WriteError("正在尝试调用API...");
// 调用该方法
return (ApiFormResult)methodInfo.Invoke(this, new object[] { apiUrlDict[functionName], plcdata, otherdata });
});
// 打印调用结束日志
LogExecute.logNet.WriteError("API调用成功。");
return result;
}
catch (Exception)
{
// 如果所有调用都失败,打印失败日志
LogExecute.logNet.WriteError("所有调用都失败了!");
return ApiFormResult.Error(mesresult.FAIL, false, "", null,DateTime.Now);
}
/*
// 获取当前类的类型
Type type = this.GetType();
// 使用反射调用指定名称的方法
MethodInfo methodInfo = type.GetMethod(functionName);
if (methodInfo != null)
{
// 调用该方法
return (ApiFormResult)methodInfo.Invoke(this, new object[] { plcdata, otherdata });
}
else
{
LogExecute.logNet.WriteError($"未找到对应的函数{functionName}");
return ApiFormResult.Error(mesresult.NONE, false, $"未找到对应的函数{functionName}", null,DateTime.Now);
}
*/
}
}
}