using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using WindowsFormsApp1.mod; using WindowsFormsApp1.mod.server; using Polly; using Polly.Timeout; using System.Net.Http; using WindowsFormsApp1.db; using Newtonsoft.Json.Linq; using System.Security.Cryptography; using Newtonsoft.Json; using HslCommunication.BasicFramework; using System.IO; namespace WindowsFormsApp1.server { public class ApiClient { private readonly HttpClient _httpClient; private readonly Dictionary apiUrlDict; public ApiClient() { _httpClient = new HttpClient(); SQLiteHelper helper = new db.SQLiteHelper(); 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) { LogExecute.logNet.WriteDebug($"SN_CheckIN 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.RESULT.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.SN_CheckIN; return res.RESULT.Value == "PASS" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG.Value, 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) { LogExecute.logNet.WriteDebug($"Carrier_Check 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.RESULT.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.Carrier_Check; return res.RESULT.Value == "PASS" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG.Value, 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 = "SN_FeedingCheck", Line = "Testline", StationID = "TestStation", MachineID = "TestMachine", OPID = "OPID", Token = "", FixSN = "", SN = OtherData.JS_SN,//扫码 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) { LogExecute.logNet.WriteDebug($"SN_FeedingCheck 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.RESULT.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.SN_FeedingCheck; return res.RESULT.Value == "PASS" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG.Value, 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) { // 组装 request json var request = new { EventID = "SN_Release", Line = "Testline", StationID = "TestStation", MachineID = "TestMachine", OPID = "OPID", Token = "", FixSN = "", SN = OtherData.JS_SN, CarrierID = "", 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) { LogExecute.logNet.WriteDebug($"SN_Release 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.RESULT.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.SN_Release; PlcData.Write_stSN = res.MSG.Value; return res.RESULT.Value == "PASS" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG.Value, 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 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) { LogExecute.logNet.WriteDebug($"Glue_CheckOut 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.RESULT.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.Glue_CheckOut; return res.RESULT.Value == "PASS" ? ApiFormResult.Sucess(mesresult.PASS, true, res.MSG.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG.Value, 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 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 = "Status", 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) { LogExecute.logNet.WriteDebug($"Status 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.RESULT.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.Status; return res.RESULT.Value == "PASS" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG.Value, 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 = "Alarm", Line = "Testline", StationID = "TestStation", MachineID = "TestMachine", OPID = "OPID", AlarmID = OtherData.Plc_ErrorMsgs[0], 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) { LogExecute.logNet.WriteDebug($"Alarm 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.RESULT.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.Alarm; return res.RESULT.Value == "PASS" ? ApiFormResult.Sucess(mesresult.PASS, false, res.MSG.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.MSG.Value, 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_FileUpload(string url, plcdata PlcData, otherdata OtherData) { // 组装 request json var request = new { Line = "Testline", StationID = "TestStation", MachineID = "TestMachine", OPID = "OPID", SNList = new List() { new { SN = OtherData.JS_SN, FileInfo = new List() { new{ FileName = OtherData.FileUploadAddress, FilePath = OtherData.FileUploadAddress } } } }, 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) { LogExecute.logNet.WriteDebug($"SN_FileUpload 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.ErrorMessage.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.SN_FileUpload; return res.IsSuccess.Value == true ? ApiFormResult.Sucess(mesresult.PASS, true, res.ErrorMessage.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.ErrorMessage.Value, 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 CodeSoftPrint(string url, plcdata PlcData, otherdata OtherData) { // 组装 request json var request = new { Line = "CodeSoftPrint", StationID = "TestStation", MachineID = "TestMachine", SN = PlcData.Read_MaterialCode0 }; // 使用 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) { LogExecute.logNet.WriteDebug($"SN_FileUpload 接口请求成功\n请求:{jsonPayload}\n 返回: {res}"); // 成功! if (!string.IsNullOrEmpty(res.ErrorMessage.Value)) { // 回写对应PLC PlcData.Write_Status = PLC_Status.CodeSoftPrint; return res.IsSuccess.Value == true ? ApiFormResult.Sucess(mesresult.PASS, true, res.ErrorMessage.Value, PlcData, DateTime.Now) : ApiFormResult.Sucess(mesresult.FAIL, false, res.ErrorMessage.Value, 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_Checkout(string url, plcdata PlcData, otherdata OtherData) { var lineCode = Init.t_Line.linecode; switch (lineCode) { case "OP1060": // 追溯码+载具,默认(todo) case "OP1120": case "OP1170": case "OP1190": case "OP1220": case "OP1250": break; case "OP1010":// 传气密 case "OP1330": break; case "OP1050":// 胶水码 case "OP1210":// 三防漆码 break; case "OP1070":// 传螺丝 角度,扭力,【扭力曲线(datacollection)】 case "OP1080": case "OP1090": case "OP1100": case "OP1130": case "OP1260": break; case "OP1140"://压力值,压力曲线 break; case "OP1160"://加热,冷却温度 break; case "OP1110"://CCD检测结果 case "OP1200"://AOI检测结果 case "OP1240"://CCD检测结果 case "OP1340"://CCD检测结果 break; case "OP1360"://产品码 break; // case "OP1180"://助焊剂批次码 // break; case "OP1230"://AOI检测结果,三防漆涂胶胶宽 break; default: break; } 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); } #region 暂时不用 public ApiFormResult Test(string url, plcdata PlcData, otherdata OtherData) { 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 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); } #endregion 暂时不用 public ApiFormResult CallFunctionByName(string functionName, plcdata plcdata, otherdata otherdata) { // 定义重试策略 var retryPolicy = Policy .Handle() // 处理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); } */ } public sealed class PLC_Status { public const int SN_CheckIN = 10; public const int Carrier_Check = 20; public const int SN_FeedingCheck = 30; public const int Link_Comp = 40; public const int SN_Release = 50; public const int Glue_CheckOut = 60; public const int Get_Para = 70; public const int DispatchPara = 80; public const int Data_Collection = 90; public const int Status = 100; public const int Alarm = 110; public const int OEEDataCollection = 120; public const int SN_FileUpload = 130; public const int Test = 140; public const int GetLaserpara = 150; public const int Order_Get = 160; public const int CodeSoftPrint = 170; public const int SN_Checkout = 200; public const int Initialization = 3; public const int Fail = 1001; } } }