MesService.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. using Prism.Events;
  2. using Prism.Ioc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Windows.Media.Media3D;
  11. using TeamAAS_VP.Enums;
  12. using TeamAAS_VP.Events;
  13. using TeamAAS_VP.Interfaces;
  14. using TeamAAS_VP.Models;
  15. namespace TeamAAS_VP.Services
  16. {
  17. /// <summary>
  18. /// 基于 <see cref="HttpClient"/> 的 MES 通信服务实现。
  19. /// <para>
  20. /// 本服务通过注入的 <see cref="IConfigService"/> 获取设备配置(包含 MES 接口地址),
  21. /// 提供对站点查询(StationGetAsync)和提交(SubmitGetAsync)的 GET 请求封装并带有重试逻辑。
  22. /// </para>
  23. /// <para>
  24. /// 注意:
  25. /// - <see cref="_httpClient"/> 为可复用的单一实例,建议在服务生命周期内重用以避免端口耗尽。
  26. /// - 本类实现了显式的 <see cref="Dispose"/> 方法以释放内部 <see cref="HttpClient"/> 资源,调用后实例不可再用。
  27. /// </para>
  28. /// </summary>
  29. public class MesService : IMesService
  30. {
  31. IEventAggregator _eventAggregator;
  32. /// <summary>
  33. /// 用于执行 HTTP 请求的客户端实例。建议在服务生命周期内重用,避免频繁创建导致套接字/端口耗尽。
  34. /// </summary>
  35. private readonly HttpClient _httpClient;
  36. /// <summary>
  37. /// 配置服务,用于获取设备信息(包含 MES URL、是否启用 MES 等)。
  38. /// </summary>
  39. private readonly IConfigService _configService;
  40. /// <summary>
  41. /// 标记实例是否已释放,防止重复释放和在释放后继续使用导致未定义行为。
  42. /// </summary>
  43. private bool _disposed;
  44. /// <summary>
  45. /// 使用指定的配置服务创建 <see cref="MesService"/> 实例。
  46. /// </summary>
  47. /// <param name="configService">用于获取设备配置信息的实现,不能为空。</param>
  48. /// <exception cref="ArgumentNullException">当 <paramref name="configService"/> 为 null 时抛出。</exception>
  49. public MesService(IConfigService configService, IContainerProvider container, IEventAggregator ea)
  50. {
  51. _configService = configService ?? throw new ArgumentNullException(nameof(configService));
  52. _httpClient = new HttpClient();
  53. _disposed = false;
  54. _eventAggregator = ea;
  55. }
  56. /// <summary>
  57. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
  58. /// </summary>
  59. /// <param name="sn">要查询的序列号(SN)。</param>
  60. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  61. /// <returns>
  62. /// 返回元组 (IsSuccess, Response):
  63. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  64. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  65. /// </returns>
  66. /// <remarks>
  67. /// 行为说明:
  68. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  69. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  70. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  71. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  72. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  73. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  74. /// </remarks>
  75. public async Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, string comp, CancellationToken cancellationToken = default)
  76. {
  77. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  78. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  79. var device = _configService.GetDeviceInfo(0);
  80. if (device == null || !device.EnableMES)
  81. {
  82. return (true, "MES功能未启用!");
  83. }
  84. if (string.IsNullOrWhiteSpace(device.MesUrl))
  85. return (false, "Missing MES station URL");
  86. if (device.F == "PTL")
  87. {
  88. if (string.IsNullOrEmpty(device.comp))
  89. {
  90. return (false, "PTL模式下comp不能为空");
  91. }
  92. }
  93. string url = "";
  94. if (device.F == "PTL")
  95. {
  96. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&comp={device.comp}:{comp}&p=unit_process_check,message,model,sn,wo,model_num,color,ppid,stage,KB";
  97. }
  98. else
  99. {
  100. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=unit_process_check,message,model,sn,wo,model_num,color,ppid,stage,KB";
  101. }
  102. LogHelper.WriteLogMes($"【询问URL】{url}");
  103. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  104. (bool IsSuccess, string Response) result = (false, string.Empty);
  105. for (int i = 0; i < 3; i++)
  106. {
  107. try
  108. {
  109. using (var rsp = await _httpClient.GetAsync(url))
  110. {
  111. var text = await rsp.Content.ReadAsStringAsync();
  112. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  113. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  114. // "SFC_OK" 代表和 MES 连接成功
  115. if (text.Contains("SFC_OK"))
  116. {
  117. string[] item = text.Split('\n');
  118. //获取产品主sn和wo用于后续上传数据使用
  119. string snItem = item.FirstOrDefault(f => f.Contains("sn="));
  120. string woItem = item.FirstOrDefault(f => f.Contains("wo="));
  121. if (snItem != null && woItem != null && text.Contains("message=OK"))
  122. {
  123. return (true, text); ;
  124. }
  125. }
  126. result = (false, text);
  127. }
  128. }
  129. catch (OperationCanceledException)
  130. {
  131. result = (false, "Canceled");
  132. }
  133. catch (Exception ex)
  134. {
  135. result = (false, ex.Message);
  136. }
  137. }
  138. return result;
  139. }
  140. /// <summary>
  141. /// 向 MES 发起站点查询请求,使用超时(秒)作为便捷重载。
  142. /// </summary>
  143. /// <param name="sn">序列号(SN)。</param>
  144. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  145. /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
  146. public async Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, string comp, double timeoutInSeconds)
  147. {
  148. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  149. {
  150. return await StationGetAsync(sn, comp, cts.Token);
  151. }
  152. }
  153. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(string sn, string comp, double timeoutInSeconds)
  154. {
  155. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  156. {
  157. return await StationGetExAsync(sn, comp, cts.Token);
  158. }
  159. }
  160. /// <summary>
  161. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
  162. /// </summary>
  163. /// <param name="sn">要查询的序列号(SN)。</param>
  164. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  165. /// <returns>
  166. /// 返回元组 (IsSuccess, Response):
  167. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  168. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  169. /// </returns>
  170. /// <remarks>
  171. /// 行为说明:
  172. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  173. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  174. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  175. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  176. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  177. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  178. /// </remarks>
  179. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(string sn, string comp, CancellationToken cancellationToken = default)
  180. {
  181. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  182. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  183. var device = _configService.GetDeviceInfo(0);
  184. if (device == null || !device.EnableMES)
  185. {
  186. return (true, "MES功能未启用!");
  187. }
  188. if (string.IsNullOrWhiteSpace(device.MesUrl))
  189. return (false, "Missing MES station URL");
  190. string url = "";
  191. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=sn,message";
  192. LogHelper.WriteLogMes($"【询问URL】{url}");
  193. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  194. (bool IsSuccess, string Response) result = (false, string.Empty);
  195. for (int i = 0; i < 3; i++)
  196. {
  197. try
  198. {
  199. using (var rsp = await _httpClient.GetAsync(url))
  200. {
  201. var text = await rsp.Content.ReadAsStringAsync();
  202. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  203. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  204. // "SFC_OK" 代表和 MES 连接成功
  205. if (text.Contains("SFC_OK"))
  206. {
  207. if (text.Contains("message=OK"))
  208. {
  209. return (true, text);
  210. }
  211. }
  212. result = (false, text);
  213. }
  214. }
  215. catch (OperationCanceledException)
  216. {
  217. result = (false, "Canceled");
  218. }
  219. catch (Exception ex)
  220. {
  221. result = (false, ex.Message);
  222. }
  223. }
  224. return result;
  225. }
  226. /// <summary>
  227. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  228. /// </summary>
  229. /// <param name="sn">要提交的序列号(SN)。</param>
  230. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  231. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  232. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  233. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  234. /// <returns>
  235. /// 返回元组 (IsSuccess, Response):
  236. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  237. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  238. /// </returns>
  239. /// <remarks>
  240. /// 行为说明:
  241. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  242. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  243. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  244. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  245. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  246. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  247. /// </remarks>
  248. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo,string sn, string comp, string mesdata, bool isSuccess,string submitDataError, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
  249. {
  250. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  251. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  252. string ErrorData = submitDataError;
  253. var device = _configService.GetDeviceInfo(deviceNo);
  254. if (device == null)
  255. device = _configService.GetDeviceInfo();
  256. if (device == null || !device.EnableMES)
  257. {
  258. return (true, "MES功能未启用!");
  259. }
  260. if (string.IsNullOrWhiteSpace(device.MesUrl))
  261. return (false, "Missing MES submit URL");
  262. if (device.F == "PTL")
  263. {
  264. if (string.IsNullOrEmpty(device.comp))
  265. {
  266. return (false, "PTL模式下comp不能为空");
  267. }
  268. }
  269. string res = isSuccess ? "PASS" : "FAIL";
  270. //if (res == "FAIL")
  271. //{
  272. // res = ErrorData;
  273. // //res = "A1-gap-Ctrl2_4_Fail";
  274. //}
  275. string url = "";
  276. if (device.F == "PTL")
  277. {
  278. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  279. $"&Mesdata{mesdata}result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  280. }
  281. else
  282. {
  283. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  284. $"&Mesdata{mesdata}result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  285. }
  286. LogHelper.WriteLogMes($"【上传URL】{url}");
  287. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  288. (bool IsSuccess, string Response) result = (false, string.Empty);
  289. for (int i = 0; i < 3; i++)
  290. {
  291. try
  292. {
  293. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  294. {
  295. var text = await rsp.Content.ReadAsStringAsync();
  296. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  297. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  298. // "SFC_OK" 代表和 MES 连接成功
  299. if (text.Contains("SFC_OK"))
  300. {
  301. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  302. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  303. {
  304. return (false, text);
  305. }
  306. return (true, text);
  307. }
  308. result = (false, text);
  309. }
  310. }
  311. catch (OperationCanceledException)
  312. {
  313. result = (false, "Canceled");
  314. }
  315. catch (Exception ex)
  316. {
  317. result = (false, ex.Message);
  318. }
  319. }
  320. return result;
  321. }
  322. /// <summary>
  323. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  324. /// </summary>
  325. /// <param name="sn">要提交的序列号(SN)。</param>
  326. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  327. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  328. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  329. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  330. /// <returns>
  331. /// 返回元组 (IsSuccess, Response):
  332. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  333. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  334. /// </returns>
  335. /// <remarks>
  336. /// 行为说明:
  337. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  338. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  339. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  340. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  341. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  342. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  343. /// </remarks>
  344. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, string comp, string assypress, string cc, string height, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
  345. {
  346. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  347. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  348. var device = _configService.GetDeviceInfo(0);
  349. if (device == null || !device.EnableMES)
  350. {
  351. return (true, "MES功能未启用!");
  352. }
  353. if (string.IsNullOrWhiteSpace(device.MesUrl))
  354. return (false, "Missing MES submit URL");
  355. if (device.F == "PTL")
  356. {
  357. if (string.IsNullOrEmpty(device.comp))
  358. {
  359. return (false, "PTL模式下comp不能为空");
  360. }
  361. }
  362. //string res = isSuccess ? "PASS" : "FAIL";
  363. string res = "PASS";
  364. string url = "";
  365. if (device.F == "PTL")
  366. {
  367. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  368. $"&cc={cc}&laser_height={height}&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  369. }
  370. else
  371. {
  372. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  373. $"&cc={cc}&laser_height={height}&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  374. }
  375. LogHelper.WriteLogMes($"【上传URL】{url}");
  376. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  377. (bool IsSuccess, string Response) result = (false, string.Empty);
  378. for (int i = 0; i < 3; i++)
  379. {
  380. try
  381. {
  382. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  383. {
  384. var text = await rsp.Content.ReadAsStringAsync();
  385. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  386. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  387. // "SFC_OK" 代表和 MES 连接成功
  388. if (text.Contains("SFC_OK"))
  389. {
  390. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  391. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  392. {
  393. return (false, text);
  394. }
  395. return (true, text);
  396. }
  397. result = (false, text);
  398. }
  399. }
  400. catch (OperationCanceledException)
  401. {
  402. result = (false, "Canceled");
  403. }
  404. catch (Exception ex)
  405. {
  406. result = (false, ex.Message);
  407. }
  408. }
  409. return result;
  410. }
  411. /// <summary>
  412. /// 向 MES 提交请求的超时重载,使用超时(秒)作为便捷参数。
  413. /// </summary>
  414. /// <param name="sn">序列号(SN)。</param>
  415. /// <param name="isSuccess">是否通过(PASS/FAIL)。</param>
  416. /// <param name="start_time">开始时间。</param>
  417. /// <param name="stop_time">结束时间。</param>
  418. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  419. /// <returns>与 <see cref="SubmitGetAsync(string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
  420. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, string comp, string assypress, string cc, string height, bool isSuccess, DateTime start_time, DateTime stop_time, double timeoutInSeconds)
  421. {
  422. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  423. {
  424. return await SubmitGetAsync(sn, comp, assypress, cc, height, isSuccess, start_time, stop_time, cts.Token);
  425. }
  426. }
  427. /// <summary>
  428. /// 获取服务器当前时间
  429. /// </summary>
  430. /// <param name="sn"></param>
  431. /// <param name="timeoutInSeconds"></param>
  432. /// <returns></returns>
  433. public async Task<(bool IsSuccess, DateTime Now)> GetServerTimeAsync(string sn, double timeoutInSeconds)
  434. {
  435. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  436. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  437. var device = _configService.GetDeviceInfo(0);
  438. if (device == null)
  439. device = _configService.GetDeviceInfo(0);
  440. if (device == null || !device.EnableMES)
  441. {
  442. return (true, DateTime.UtcNow);
  443. }
  444. if (string.IsNullOrWhiteSpace(device.MesUrl))
  445. return (false, DateTime.UtcNow);
  446. string url = "";
  447. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=mes_server_time";
  448. LogHelper.WriteLogMes($"【询问URL】{url}");
  449. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  450. (bool IsSuccess, DateTime Now) result = (false, DateTime.UtcNow);
  451. for (int i = 0; i < 3; i++)
  452. {
  453. try
  454. {
  455. using (var rsp = await _httpClient.GetAsync(url))
  456. {
  457. var text = await rsp.Content.ReadAsStringAsync();
  458. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  459. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  460. // "SFC_OK" 代表和 MES 连接成功
  461. if (text.Contains("SFC_OK"))
  462. {
  463. //按照分隔符'/n'分割字符串
  464. string[] lines = text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  465. //通过linq查找是否包含"mes_server_time"的行
  466. var timeLine = lines.FirstOrDefault(l => l.Contains("mes_server_time"));
  467. if (timeLine != null)
  468. {
  469. // 提取时间字符串
  470. var timeString = timeLine.Split('=')[1].Trim();
  471. if (DateTime.TryParse(timeString, out DateTime serverTime))
  472. {
  473. return (true, serverTime);
  474. }
  475. }
  476. }
  477. result = (false, DateTime.UtcNow);
  478. }
  479. }
  480. catch (OperationCanceledException)
  481. {
  482. result = (false, DateTime.UtcNow);
  483. }
  484. catch (Exception ex)
  485. {
  486. result = (false, DateTime.UtcNow);
  487. }
  488. }
  489. return result;
  490. }
  491. /// <summary>
  492. /// 释放服务占用的托管资源(当前仅 <see cref="_httpClient"/>)。
  493. /// <para>本方法为幂等操作,重复调用不会产生异常。调用后实例不可再用于发起请求,尝试使用将抛出 <see cref="ObjectDisposedException"/>。</para>
  494. /// </summary>
  495. public void Dispose()
  496. {
  497. if (!_disposed)
  498. {
  499. _httpClient.Dispose();
  500. _disposed = true;
  501. }
  502. }
  503. public void SendTaskMessage(string msg, MessageLevel level)
  504. {
  505. App.Current.Dispatcher.Invoke(() =>
  506. {
  507. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  508. });
  509. }
  510. /// <summary>
  511. /// 上传log服务器
  512. /// </summary>
  513. /// <param name="sn"></param>
  514. /// <param name="name"></param>
  515. /// <param name="cancellationToken"></param>
  516. /// <returns></returns>
  517. /// <exception cref="ObjectDisposedException"></exception>
  518. public async Task<(bool IsSuccess, string Response)> SendFtpFileAsync(string sn, string name, CancellationToken cancellationToken = default)
  519. {
  520. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  521. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  522. var device = _configService.GetDeviceInfo(0);
  523. if (device == null || !device.EnableMES)
  524. {
  525. return (true, "MES功能未启用!");
  526. }
  527. if (string.IsNullOrWhiteSpace(device.LogUrl))
  528. {
  529. return (false, "Missing MES station LogUrl");
  530. }
  531. string url = $"{device.LogUrl}?db=mysql&ApiKey={device.ApiKey}&jsondata={{\"SN\":\"{sn}\",\"LINE\":\"{device.Line}\",\"STATION\":\"{device.Station}\",\"TESTRESULT\":\"PASS\",\"FIXTUREID\":\"{device.FixtureId}\",\"TESTDATETIME\":\"{DateTime.Now.ToString()}\",\"LOGFILENAME\":\"{name}.zip\",\"STATIONTYPE\":\"AE\"}}";
  532. LogHelper.WriteLogMes($"【上传LogData的URL】{url}");
  533. SendTaskMessage($"【上传LogData的URL】{url}", MessageLevel.Info);
  534. (bool IsSuccess, string Response) result = (false, string.Empty);
  535. for (int i = 0; i < 3; i++)
  536. {
  537. try
  538. {
  539. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  540. {
  541. var text = await rsp.Content.ReadAsStringAsync();
  542. LogHelper.WriteLogMes($"【上传LogData的HTTP接收】{text}");
  543. SendTaskMessage($"【上传LogData的HTTP接收】{text}", MessageLevel.Info);
  544. // "SFC_OK" 代表和 MES 连接成功
  545. if (text.Contains("\"Code\":1"))
  546. {
  547. return (true, text);
  548. }
  549. result = (false, text);
  550. }
  551. }
  552. catch (OperationCanceledException)
  553. {
  554. result = (false, "Canceled");
  555. }
  556. catch (Exception ex)
  557. {
  558. result = (false, ex.Message);
  559. }
  560. }
  561. return result;
  562. }
  563. }
  564. }