MesService.cs 10 KB

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