MesService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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(int num, 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. string[] station = new string[3];
  93. string[] fixtureId = new string[3];
  94. station = device.Station.Split(',');
  95. fixtureId = device.FixtureId.Split(',');
  96. if (num == 0)//组装站
  97. {
  98. if (device.F == "PTL")
  99. {
  100. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&comp={device.comp}:{comp}&p=unit_process_check,message,model";
  101. }
  102. else
  103. {
  104. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&p=unit_process_check,message,model";
  105. }
  106. }
  107. else//保压站
  108. {
  109. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&p=unit_process_check,message,model";
  110. }
  111. LogHelper.WriteLogMes($"【询问URL】{url}");
  112. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  113. (bool IsSuccess, string Response) result = (false, string.Empty);
  114. for (int i = 0; i < 3; i++)
  115. {
  116. try
  117. {
  118. using (var rsp = await _httpClient.GetAsync(url))
  119. {
  120. var text = await rsp.Content.ReadAsStringAsync();
  121. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  122. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  123. // "SFC_OK" 代表和 MES 连接成功
  124. if (text.Contains("SFC_OK"))
  125. {
  126. if (text.Contains("unit_process_check=OK"))
  127. {
  128. return (true, text);
  129. }
  130. }
  131. result = (false, text);
  132. }
  133. }
  134. catch (OperationCanceledException)
  135. {
  136. result = (false, "Canceled");
  137. }
  138. catch (Exception ex)
  139. {
  140. result = (false, ex.Message);
  141. }
  142. }
  143. return result;
  144. }
  145. /// <summary>
  146. /// 向 MES 发起站点查询请求,使用超时(秒)作为便捷重载。
  147. /// </summary>
  148. /// <param name="sn">序列号(SN)。</param>
  149. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  150. /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
  151. public async Task<(bool IsSuccess, string Response)> StationGetAsync(int num, string sn, string comp, double timeoutInSeconds)
  152. {
  153. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  154. {
  155. return await StationGetAsync(num, sn, comp, cts.Token);
  156. }
  157. }
  158. /// <summary>
  159. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  160. /// </summary>
  161. /// <param name="sn">要提交的序列号(SN)。</param>
  162. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  163. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  164. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  165. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  166. /// <returns>
  167. /// 返回元组 (IsSuccess, Response):
  168. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  169. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  170. /// </returns>
  171. /// <remarks>
  172. /// 行为说明:
  173. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  174. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  175. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  176. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  177. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  178. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  179. /// </remarks>
  180. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int num, string sn, string comp, string gap, string press, string presstime, string assypress, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
  181. {
  182. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  183. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  184. var device = _configService.GetDeviceInfo();
  185. if (device == null || !device.EnableMES)
  186. {
  187. return (true, "MES功能未启用!");
  188. }
  189. if (string.IsNullOrWhiteSpace(device.MesUrl))
  190. return (false, "Missing MES submit URL");
  191. if (device.F == "PTL")
  192. {
  193. if (string.IsNullOrEmpty(device.comp))
  194. {
  195. return (false, "PTL模式下comp不能为空");
  196. }
  197. }
  198. string res = isSuccess ? "PASS" : "FAIL";
  199. string url = "";
  200. string[] station = new string[3];
  201. string[] fixtureId = new string[3];
  202. station = device.Station.Split(',');
  203. fixtureId = device.FixtureId.Split(',');
  204. if (num == 0)//组装站
  205. {
  206. if (device.F == "PTL")
  207. {
  208. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  209. $"&gap={gap}&assy_pressure={assypress}" +
  210. $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  211. }
  212. else
  213. {
  214. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&f=PQC" +
  215. $"&gap={gap}&assy_pressure={assypress}" +
  216. $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  217. }
  218. }
  219. else
  220. {
  221. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={station[num]}&fixtureid={fixtureId[num]}&sn={sn}&f=PQC" +
  222. $"&pressure={press}&pressure_time={presstime}" +
  223. $"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  224. }
  225. LogHelper.WriteLogMes($"【上传URL】{url}");
  226. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  227. (bool IsSuccess, string Response) result = (false, string.Empty);
  228. for (int i = 0; i < 3; i++)
  229. {
  230. try
  231. {
  232. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  233. {
  234. var text = await rsp.Content.ReadAsStringAsync();
  235. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  236. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  237. // "SFC_OK" 代表和 MES 连接成功
  238. if (text.Contains("SFC_OK"))
  239. {
  240. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  241. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  242. {
  243. return (false, text);
  244. }
  245. return (true, text);
  246. }
  247. result = (false, text);
  248. }
  249. }
  250. catch (OperationCanceledException)
  251. {
  252. result = (false, "Canceled");
  253. }
  254. catch (Exception ex)
  255. {
  256. result = (false, ex.Message);
  257. }
  258. }
  259. return result;
  260. }
  261. /// <summary>
  262. /// 向 MES 提交请求的超时重载,使用超时(秒)作为便捷参数。
  263. /// </summary>
  264. /// <param name="sn">序列号(SN)。</param>
  265. /// <param name="isSuccess">是否通过(PASS/FAIL)。</param>
  266. /// <param name="start_time">开始时间。</param>
  267. /// <param name="stop_time">结束时间。</param>
  268. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  269. /// <returns>与 <see cref="SubmitGetAsync(string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
  270. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int num, string sn, string comp, string gap, string press, string presstime, string assypress, bool isSuccess, DateTime start_time, DateTime stop_time, double timeoutInSeconds)
  271. {
  272. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  273. {
  274. return await SubmitGetAsync(num, sn, comp, gap, press, presstime, assypress, isSuccess, start_time, stop_time, cts.Token);
  275. }
  276. }
  277. /// <summary>
  278. /// 释放服务占用的托管资源(当前仅 <see cref="_httpClient"/>)。
  279. /// <para>本方法为幂等操作,重复调用不会产生异常。调用后实例不可再用于发起请求,尝试使用将抛出 <see cref="ObjectDisposedException"/>。</para>
  280. /// </summary>
  281. public void Dispose()
  282. {
  283. if (!_disposed)
  284. {
  285. _httpClient.Dispose();
  286. _disposed = true;
  287. }
  288. }
  289. public void SendTaskMessage(string msg, MessageLevel level)
  290. {
  291. App.Current.Dispatcher.Invoke(() =>
  292. {
  293. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  294. });
  295. }
  296. }
  297. }