MesService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using Prism.Events;
  2. using Prism.Ioc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Net.Http;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using TeamAAS_VP.Enums;
  10. using TeamAAS_VP.Events;
  11. using TeamAAS_VP.Interfaces;
  12. using TeamAAS_VP.Models;
  13. namespace TeamAAS_VP.Services
  14. {
  15. /// <summary>
  16. /// 基于 <see cref="HttpClient"/> 的 MES 通信服务实现。
  17. /// <para>
  18. /// 本服务通过注入的 <see cref="IConfigService"/> 获取设备配置(包含 MES 接口地址),
  19. /// 提供对站点查询(StationGetAsync)和提交(SubmitGetAsync)的 GET 请求封装并带有重试逻辑。
  20. /// </para>
  21. /// <para>
  22. /// 注意:
  23. /// - <see cref="_httpClient"/> 为可复用的单一实例,建议在服务生命周期内重用以避免端口耗尽。
  24. /// - 本类实现了显式的 <see cref="Dispose"/> 方法以释放内部 <see cref="HttpClient"/> 资源,调用后实例不可再用。
  25. /// </para>
  26. /// </summary>
  27. public class MesService : IMesService
  28. {
  29. IEventAggregator _eventAggregator;
  30. /// <summary>
  31. /// 用于执行 HTTP 请求的客户端实例。建议在服务生命周期内重用,避免频繁创建导致套接字/端口耗尽。
  32. /// </summary>
  33. private readonly HttpClient _httpClient;
  34. /// <summary>
  35. /// 配置服务,用于获取设备信息(包含 MES URL、是否启用 MES 等)。
  36. /// </summary>
  37. private readonly IConfigService _configService;
  38. /// <summary>
  39. /// 标记实例是否已释放,防止重复释放和在释放后继续使用导致未定义行为。
  40. /// </summary>
  41. private bool _disposed;
  42. /// <summary>
  43. /// 使用指定的配置服务创建 <see cref="MesService"/> 实例。
  44. /// </summary>
  45. /// <param name="configService">用于获取设备配置信息的实现,不能为空。</param>
  46. /// <exception cref="ArgumentNullException">当 <paramref name="configService"/> 为 null 时抛出。</exception>
  47. public MesService(IConfigService configService, IContainerProvider container, IEventAggregator ea)
  48. {
  49. _configService = configService ?? throw new ArgumentNullException(nameof(configService));
  50. _httpClient = new HttpClient();
  51. _disposed = false;
  52. _eventAggregator = ea;
  53. }
  54. /// <summary>
  55. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
  56. /// </summary>
  57. /// <param name="sn">要查询的序列号(SN)。</param>
  58. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  59. /// <returns>
  60. /// 返回元组 (IsSuccess, Response):
  61. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  62. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  63. /// </returns>
  64. /// <remarks>
  65. /// 行为说明:
  66. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  67. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  68. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  69. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  70. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  71. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  72. /// </remarks>
  73. public async Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, string comp, CancellationToken cancellationToken = default)
  74. {
  75. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  76. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  77. var device = _configService.GetDeviceInfo();
  78. if (device == null || !device.EnableMES)
  79. {
  80. return (true, "MES功能未启用!");
  81. }
  82. if (string.IsNullOrWhiteSpace(device.MesUrl))
  83. return (false, "Missing MES station URL");
  84. if (device.F == "PTL")
  85. {
  86. if (string.IsNullOrEmpty(device.comp))
  87. {
  88. return (false, "PTL模式下comp不能为空");
  89. }
  90. }
  91. string url = "";
  92. if (device.F == "PTL")
  93. {
  94. 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";
  95. }
  96. else
  97. {
  98. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=unit_process_check,message,model";
  99. }
  100. LogHelper.WriteLogMes($"【询问URL】{url}");
  101. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  102. (bool IsSuccess, string Response) result = (false, string.Empty);
  103. for (int i = 0; i < 3; i++)
  104. {
  105. try
  106. {
  107. using (var rsp = await _httpClient.GetAsync(url))
  108. {
  109. var text = await rsp.Content.ReadAsStringAsync();
  110. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  111. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  112. // "SFC_OK" 代表和 MES 连接成功
  113. if (text.Contains("SFC_OK"))
  114. {
  115. if (text.Contains("unit_process_check=OK"))
  116. {
  117. return (true, text);
  118. }
  119. }
  120. result = (false, text);
  121. }
  122. }
  123. catch (OperationCanceledException)
  124. {
  125. result = (false, "Canceled");
  126. }
  127. catch (Exception ex)
  128. {
  129. result = (false, ex.Message);
  130. }
  131. }
  132. return result;
  133. }
  134. /// <summary>
  135. /// 向 MES 发起站点查询请求,使用超时(秒)作为便捷重载。
  136. /// </summary>
  137. /// <param name="sn">序列号(SN)。</param>
  138. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  139. /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
  140. public async Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, string comp, double timeoutInSeconds)
  141. {
  142. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  143. {
  144. return await StationGetAsync(sn, comp, cts.Token);
  145. }
  146. }
  147. /// <summary>
  148. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  149. /// </summary>
  150. /// <param name="sn">要提交的序列号(SN)。</param>
  151. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  152. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  153. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  154. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  155. /// <returns>
  156. /// 返回元组 (IsSuccess, Response):
  157. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  158. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  159. /// </returns>
  160. /// <remarks>
  161. /// 行为说明:
  162. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  163. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  164. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  165. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  166. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  167. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  168. /// </remarks>
  169. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, string comp, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
  170. {
  171. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  172. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  173. var device = _configService.GetDeviceInfo();
  174. if (device == null || !device.EnableMES)
  175. {
  176. return (true, "MES功能未启用!");
  177. }
  178. if (string.IsNullOrWhiteSpace(device.MesUrl))
  179. return (false, "Missing MES submit URL");
  180. if (device.F == "PTL")
  181. {
  182. if (string.IsNullOrEmpty(device.comp))
  183. {
  184. return (false, "PTL模式下comp不能为空");
  185. }
  186. }
  187. string res = isSuccess ? "PASS" : "FAIL";
  188. string url = "";
  189. if (device.F == "PTL")
  190. {
  191. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  192. $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  193. }
  194. else
  195. {
  196. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  197. $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  198. }
  199. LogHelper.WriteLogMes($"【上传URL】{url}");
  200. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  201. (bool IsSuccess, string Response) result = (false, string.Empty);
  202. for (int i = 0; i < 3; i++)
  203. {
  204. try
  205. {
  206. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  207. {
  208. var text = await rsp.Content.ReadAsStringAsync();
  209. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  210. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  211. // "SFC_OK" 代表和 MES 连接成功
  212. if (text.Contains("SFC_OK"))
  213. {
  214. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  215. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  216. {
  217. return (false, text);
  218. }
  219. return (true, text);
  220. }
  221. result = (false, text);
  222. }
  223. }
  224. catch (OperationCanceledException)
  225. {
  226. result = (false, "Canceled");
  227. }
  228. catch (Exception ex)
  229. {
  230. result = (false, ex.Message);
  231. }
  232. }
  233. return result;
  234. }
  235. /// <summary>
  236. /// 向 MES 提交请求的超时重载,使用超时(秒)作为便捷参数。
  237. /// </summary>
  238. /// <param name="sn">序列号(SN)。</param>
  239. /// <param name="isSuccess">是否通过(PASS/FAIL)。</param>
  240. /// <param name="start_time">开始时间。</param>
  241. /// <param name="stop_time">结束时间。</param>
  242. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  243. /// <returns>与 <see cref="SubmitGetAsync(string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
  244. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, string comp, bool isSuccess, DateTime start_time, DateTime stop_time, double timeoutInSeconds)
  245. {
  246. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  247. {
  248. return await SubmitGetAsync(sn, comp, isSuccess, start_time, stop_time, cts.Token);
  249. }
  250. }
  251. /// <summary>
  252. /// 释放服务占用的托管资源(当前仅 <see cref="_httpClient"/>)。
  253. /// <para>本方法为幂等操作,重复调用不会产生异常。调用后实例不可再用于发起请求,尝试使用将抛出 <see cref="ObjectDisposedException"/>。</para>
  254. /// </summary>
  255. public void Dispose()
  256. {
  257. if (!_disposed)
  258. {
  259. _httpClient.Dispose();
  260. _disposed = true;
  261. }
  262. }
  263. public void SendTaskMessage(string msg, MessageLevel level)
  264. {
  265. App.Current.Dispatcher.Invoke(() =>
  266. {
  267. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  268. });
  269. }
  270. }
  271. }