From 8d679bf00c61c6baf5089972a5b42bd01d6a9ea3 Mon Sep 17 00:00:00 2001 From: zhougf Date: Wed, 19 Feb 2025 16:28:25 +0800 Subject: [PATCH] =?UTF-8?q?apiclient=20=E9=83=A8=E5=88=86=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WindowsFormsApp1/App.config | 15 + WindowsFormsApp1/MES_PLC_Control.csproj | 24 ++ WindowsFormsApp1/MainForm.cs | 15 +- WindowsFormsApp1/db/MES_PLC.db | Bin 139264 -> 139264 bytes WindowsFormsApp1/packages.config | 8 + WindowsFormsApp1/server/ApiClient.cs | 475 ++++++++++++++++++++++-- 6 files changed, 503 insertions(+), 34 deletions(-) diff --git a/WindowsFormsApp1/App.config b/WindowsFormsApp1/App.config index 7c0a716..1e7e073 100644 --- a/WindowsFormsApp1/App.config +++ b/WindowsFormsApp1/App.config @@ -14,4 +14,19 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/WindowsFormsApp1/MES_PLC_Control.csproj b/WindowsFormsApp1/MES_PLC_Control.csproj index a99a225..443b226 100644 --- a/WindowsFormsApp1/MES_PLC_Control.csproj +++ b/WindowsFormsApp1/MES_PLC_Control.csproj @@ -38,13 +38,37 @@ ..\packages\HslCommunication.7.0.1\lib\net451\HslCommunication.dll + + ..\packages\Microsoft.Bcl.AsyncInterfaces.6.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + + + ..\packages\Microsoft.Bcl.TimeProvider.8.0.0\lib\net462\Microsoft.Bcl.TimeProvider.dll + ..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll + + ..\packages\Polly.8.5.2\lib\net472\Polly.dll + + + ..\packages\Polly.Core.8.5.2\lib\net472\Polly.Core.dll + + + ..\packages\System.ComponentModel.Annotations.4.5.0\lib\net461\System.ComponentModel.Annotations.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + ..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll + diff --git a/WindowsFormsApp1/MainForm.cs b/WindowsFormsApp1/MainForm.cs index 2c05e3b..efc6a81 100644 --- a/WindowsFormsApp1/MainForm.cs +++ b/WindowsFormsApp1/MainForm.cs @@ -63,6 +63,15 @@ namespace WindowsFormsApp1 continue; } + // test + ApiClient apiClient = new ApiClient(); + otherdata otherdata = new otherdata(); + otherdata.JS_SN = "12345"; + plcdata PlcData = new plcdata(); + + var res = apiClient.CallFunctionByName("SN_CheckIN", PlcData, otherdata); + + SiemensHelp siemensHelp = Plc.plchelp; var openresult = siemensHelp.OpenConn(); @@ -75,7 +84,7 @@ namespace WindowsFormsApp1 } List plcaddress = Init.t_Plcaddresses.FindAll(a => a.plcid == Plc.id); - plcdata PlcData = new plcdata(); + var resdresult = siemensHelp.ReadAddress(plcaddress, PlcData); if (!resdresult.Success) @@ -123,9 +132,7 @@ namespace WindowsFormsApp1 } continue; } - ApiClient apiClient = new ApiClient(); - otherdata otherdata = new otherdata(); - otherdata.JS_SN = "12345"; + diff --git a/WindowsFormsApp1/db/MES_PLC.db b/WindowsFormsApp1/db/MES_PLC.db index fbf34b1662205a6e887b910577189685c93afd70..15b4cabf0769bfd4863e145a4a5b95d7cef816ee 100644 GIT binary patch delta 100 zcmV-q0Gt1SzzBfA2#^~AsF55)1*iZnc8IZLoxceSBmfW!A{GjMlM28Z1_~ky)Cy;_ zAt3k(2U-sX06imblPk+o3Qu)(QUL}4F(GY}gvv_-Nluf}%2EUX003K&ky(R*%eR5c G0e@5#xgcHu delta 129 zcmZoTz|nAkV}dl}vWYUztjiem{A)L+%-zq)z`!8DRV&6-JDKZ%6dSh+*A=ex&58=b zTpS^cYz&5q`TUdHPASO(m5Bi{DhLUND4E=P%9}aAv}E$7Q$g&J{A>)i%DIy@PX$fB QaEhh5@$~k_(~R{Y08+Fg1^@s6 diff --git a/WindowsFormsApp1/packages.config b/WindowsFormsApp1/packages.config index 175d40e..2cdf5ec 100644 --- a/WindowsFormsApp1/packages.config +++ b/WindowsFormsApp1/packages.config @@ -1,6 +1,14 @@  + + + + + + + + \ No newline at end of file diff --git a/WindowsFormsApp1/server/ApiClient.cs b/WindowsFormsApp1/server/ApiClient.cs index c900c8e..b27cb8e 100644 --- a/WindowsFormsApp1/server/ApiClient.cs +++ b/WindowsFormsApp1/server/ApiClient.cs @@ -8,72 +8,429 @@ 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 { - public ApiFormResult SN_CheckIN(plcdata PlcData, otherdata OtherData) + 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) + { + // 成功! + 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 Carrier_Check(plcdata PlcData, otherdata OtherData) + + public ApiFormResult SN_Release(string url, plcdata PlcData, otherdata OtherData) { return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); } - public ApiFormResult SN_FeedingCheck(plcdata PlcData, otherdata OtherData) + + 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 Link_Comp(plcdata PlcData, otherdata OtherData) + + public ApiFormResult DispatchPara(string url, plcdata PlcData, otherdata OtherData) { return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); } - public ApiFormResult SN_Release(plcdata PlcData, otherdata OtherData) + + public ApiFormResult Data_Collection(string url, plcdata PlcData, otherdata OtherData) { return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); } - public ApiFormResult Glue_CheckOut(plcdata PlcData, otherdata OtherData) + + public ApiFormResult Status(string url, plcdata PlcData, otherdata OtherData) { - return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); + // 组装 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 Get_Para(plcdata PlcData, otherdata OtherData) + + public ApiFormResult Alarm(string url, plcdata PlcData, otherdata OtherData) { - return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); + // 组装 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 DispatchPara(plcdata PlcData, otherdata OtherData) - { - return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); - } - public ApiFormResult Data_Collection(plcdata PlcData, otherdata OtherData) - { - return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); - } - public ApiFormResult Status(plcdata PlcData, otherdata OtherData) - { - return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); - } - public ApiFormResult Alarm(plcdata PlcData, otherdata OtherData) - { - return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); - } - public ApiFormResult OEEDataCollection(plcdata PlcData, otherdata OtherData) + + public ApiFormResult OEEDataCollection(string url, plcdata PlcData, otherdata OtherData) { return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData,DateTime.Now); } - public ApiFormResult SN_FileUpload(plcdata PlcData, otherdata OtherData) + + public ApiFormResult SN_FileUpload(string url, plcdata PlcData, otherdata OtherData) { return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData,DateTime.Now); } - public ApiFormResult Test(plcdata PlcData, otherdata OtherData) + + public ApiFormResult Test(string url, plcdata PlcData, otherdata OtherData) { return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData,DateTime.Now); } - public ApiFormResult SN_Checkout(plcdata PlcData, otherdata OtherData) + + public ApiFormResult SN_Checkout(string url, plcdata PlcData, otherdata OtherData) { return ApiFormResult.Sucess(mesresult.PASS, false, "", PlcData,DateTime.Now); } - public ApiFormResult Initialization(plcdata PlcData, otherdata OtherData) + + public ApiFormResult Initialization(string url, plcdata PlcData, otherdata OtherData) { PlcData.Write_Status = 3; return ApiFormResult.Sucess(mesresult.PASS,false,"", PlcData,DateTime.Now); @@ -81,6 +438,62 @@ namespace WindowsFormsApp1.server 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(); @@ -97,6 +510,8 @@ namespace WindowsFormsApp1.server LogExecute.logNet.WriteError($"未找到对应的函数{functionName}"); return ApiFormResult.Error(mesresult.NONE, false, $"未找到对应的函数{functionName}", null,DateTime.Now); } + */ } + } }