MesService.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. using NPOI.SS.Formula.Functions;
  2. using Prism.Events;
  3. using Prism.Ioc;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using TeamAAS_VP.Core;
  12. using TeamAAS_VP.Enums;
  13. using TeamAAS_VP.Events;
  14. using TeamAAS_VP.Interfaces;
  15. using TeamAAS_VP.Models;
  16. using TeamAAS_VP.Resources.Languages;
  17. namespace TeamAAS_VP.Services
  18. {
  19. /// <summary>
  20. /// 基于 <see cref="HttpClient"/> 的 MES 通信服务实现。
  21. /// <para>
  22. /// 本服务通过注入的 <see cref="IConfigService"/> 获取设备配置(包含 MES 接口地址),
  23. /// 提供对站点查询(StationGetAsync)和提交(SubmitGetAsync)的 GET 请求封装并带有重试逻辑。
  24. /// </para>
  25. /// <para>
  26. /// 注意:
  27. /// - <see cref="_httpClient"/> 为可复用的单一实例,建议在服务生命周期内重用以避免端口耗尽。
  28. /// - 本类实现了显式的 <see cref="Dispose"/> 方法以释放内部 <see cref="HttpClient"/> 资源,调用后实例不可再用。
  29. /// </para>
  30. /// </summary>
  31. public class MesService : IMesService
  32. {
  33. IEventAggregator _eventAggregator;
  34. /// <summary>
  35. /// 用于执行 HTTP 请求的客户端实例。建议在服务生命周期内重用,避免频繁创建导致套接字/端口耗尽。
  36. /// </summary>
  37. private readonly HttpClient _httpClient;
  38. /// <summary>
  39. /// 配置服务,用于获取设备信息(包含 MES URL、是否启用 MES 等)。
  40. /// </summary>
  41. private readonly IConfigService _configService;
  42. /// <summary>
  43. /// 标记实例是否已释放,防止重复释放和在释放后继续使用导致未定义行为。
  44. /// </summary>
  45. private bool _disposed;
  46. /// <summary>
  47. /// 使用指定的配置服务创建 <see cref="MesService"/> 实例。
  48. /// </summary>
  49. /// <param name="configService">用于获取设备配置信息的实现,不能为空。</param>
  50. /// <exception cref="ArgumentNullException">当 <paramref name="configService"/> 为 null 时抛出。</exception>
  51. public MesService(IConfigService configService, IContainerProvider container, IEventAggregator ea)
  52. {
  53. _configService = configService ?? throw new ArgumentNullException(nameof(configService));
  54. _httpClient = new HttpClient();
  55. _disposed = false;
  56. _eventAggregator = ea;
  57. }
  58. /// <summary>
  59. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
  60. /// </summary>
  61. /// <param name="sn">要查询的序列号(SN)。</param>
  62. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  63. /// <returns>
  64. /// 返回元组 (IsSuccess, Response):
  65. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  66. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  67. /// </returns>
  68. /// <remarks>
  69. /// 行为说明:
  70. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  71. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  72. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  73. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  74. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  75. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  76. /// </remarks>
  77. public async Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, CancellationToken cancellationToken = default)
  78. {
  79. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  80. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  81. var device = _configService.GetDeviceInfo(deviceNo);
  82. if (device == null)
  83. device = _configService.GetDeviceInfo();
  84. if (device == null || !device.EnableMES)
  85. {
  86. return (true, "MES功能未启用!");
  87. }
  88. if (string.IsNullOrWhiteSpace(device.MesUrl))
  89. return (false, "Missing MES station URL");
  90. if (device.F == "PTL")
  91. {
  92. if (string.IsNullOrEmpty(device.comp))
  93. {
  94. return (false, "PTL模式下comp不能为空");
  95. }
  96. }
  97. string url = "";
  98. if (device.F == "PTL")
  99. {
  100. 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";
  101. }
  102. else
  103. {
  104. 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";
  105. }
  106. LogHelper.WriteLogMes($"【询问URL】{url}");
  107. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  108. (bool IsSuccess, string Response) result = (false, string.Empty);
  109. for (int i = 0; i < 3; i++)
  110. {
  111. try
  112. {
  113. using (var rsp = await _httpClient.GetAsync(url))
  114. {
  115. var text = await rsp.Content.ReadAsStringAsync();
  116. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  117. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  118. // "SFC_OK" 代表和 MES 连接成功
  119. if (text.Contains("SFC_OK"))
  120. {
  121. if (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 站点 URL 发起 GET 请求(用于过站查询)。
  142. /// </summary>
  143. /// <param name="sn">要查询的序列号(SN)。</param>
  144. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  145. /// <returns>
  146. /// 返回元组 (IsSuccess, Response):
  147. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  148. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  149. /// </returns>
  150. /// <remarks>
  151. /// 行为说明:
  152. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  153. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  154. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  155. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  156. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  157. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  158. /// </remarks>
  159. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, CancellationToken cancellationToken = default)
  160. {
  161. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  162. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  163. var device = _configService.GetDeviceInfo(deviceNo);
  164. if (device == null)
  165. device = _configService.GetDeviceInfo();
  166. if (device == null || !device.EnableMES)
  167. {
  168. return (true, "MES功能未启用!");
  169. }
  170. if (string.IsNullOrWhiteSpace(device.MesUrl))
  171. return (false, "Missing MES station URL");
  172. string url = "";
  173. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=message,sn,wo";
  174. LogHelper.WriteLogMes($"【询问URL】{url}");
  175. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  176. (bool IsSuccess, string Response) result = (false, string.Empty);
  177. for (int i = 0; i < 3; i++)
  178. {
  179. try
  180. {
  181. using (var rsp = await _httpClient.GetAsync(url))
  182. {
  183. var text = await rsp.Content.ReadAsStringAsync();
  184. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  185. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  186. // "SFC_OK" 代表和 MES 连接成功
  187. if (text.Contains("SFC_OK"))
  188. {
  189. if (text.Contains("message=OK"))
  190. {
  191. return (true, text);
  192. }
  193. }
  194. result = (false, text);
  195. }
  196. }
  197. catch (OperationCanceledException)
  198. {
  199. result = (false, "Canceled");
  200. }
  201. catch (Exception ex)
  202. {
  203. result = (false, ex.Message);
  204. }
  205. }
  206. return result;
  207. }
  208. /// <summary>
  209. /// 向 MES 发起站点查询请求,使用超时(秒)作为便捷重载。
  210. /// </summary>
  211. /// <param name="sn">序列号(SN)。</param>
  212. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  213. /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
  214. public async Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, double timeoutInSeconds)
  215. {
  216. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  217. {
  218. return await StationGetAsync(deviceNo, sn, comp, cts.Token);
  219. }
  220. }
  221. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, double timeoutInSeconds)
  222. {
  223. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  224. {
  225. return await StationGetExAsync(deviceNo, sn, comp, cts.Token);
  226. }
  227. }
  228. /// <summary>
  229. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  230. /// </summary>
  231. /// <param name="sn">要提交的序列号(SN)。</param>
  232. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  233. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  234. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  235. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  236. /// <returns>
  237. /// 返回元组 (IsSuccess, Response):
  238. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  239. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  240. /// </returns>
  241. /// <remarks>
  242. /// 行为说明:
  243. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  244. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  245. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  246. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  247. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  248. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  249. /// </remarks>
  250. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo, string sn, string comp, string torque, string pressure, string turn, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
  251. {
  252. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  253. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  254. var device = _configService.GetDeviceInfo(deviceNo);
  255. if (device == null)
  256. device = _configService.GetDeviceInfo();
  257. if (device == null || !device.EnableMES)
  258. {
  259. return (true, "MES功能未启用!");
  260. }
  261. if (string.IsNullOrWhiteSpace(device.MesUrl))
  262. return (false, "Missing MES submit URL");
  263. if (device.F == "PTL")
  264. {
  265. if (string.IsNullOrEmpty(device.comp))
  266. {
  267. return (false, "PTL模式下comp不能为空");
  268. }
  269. }
  270. //string res = isSuccess ? "PASS" : "FAIL";
  271. string res = "PASS";
  272. string url = "";
  273. if (device.F == "PTL")
  274. {
  275. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  276. $"&torque={torque}&pressure={pressure}&turn={turn}&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  277. }
  278. else
  279. {
  280. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  281. $"&torque={torque}&pressure={pressure}&turn={turn}&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}";
  282. }
  283. LogHelper.WriteLogMes($"【上传URL】{url}");
  284. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  285. (bool IsSuccess, string Response) result = (false, string.Empty);
  286. for (int i = 0; i < 3; i++)
  287. {
  288. try
  289. {
  290. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  291. {
  292. var text = await rsp.Content.ReadAsStringAsync();
  293. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  294. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  295. // "SFC_OK" 代表和 MES 连接成功
  296. if (text.Contains("SFC_OK"))
  297. {
  298. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  299. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  300. {
  301. return (false, text);
  302. }
  303. return (true, text);
  304. }
  305. result = (false, text);
  306. }
  307. }
  308. catch (OperationCanceledException)
  309. {
  310. result = (false, "Canceled");
  311. }
  312. catch (Exception ex)
  313. {
  314. result = (false, ex.Message);
  315. }
  316. }
  317. return result;
  318. }
  319. /// <summary>
  320. /// 向 MES 提交请求的超时重载,使用超时(秒)作为便捷参数。
  321. /// </summary>
  322. /// <param name="sn">序列号(SN)。</param>
  323. /// <param name="isSuccess">是否通过(PASS/FAIL)。</param>
  324. /// <param name="start_time">开始时间。</param>
  325. /// <param name="stop_time">结束时间。</param>
  326. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  327. /// <returns>与 <see cref="SubmitGetAsync(int deviceNo, string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
  328. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo, string sn, string comp, string torque, string pressure, string turn, bool isSuccess, DateTime start_time, DateTime stop_time, double timeoutInSeconds)
  329. {
  330. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  331. {
  332. return await SubmitGetAsync(deviceNo,sn, comp, torque, pressure, turn, isSuccess, start_time, stop_time, cts.Token);
  333. }
  334. }
  335. /// <summary>
  336. /// 获取服务器当前时间
  337. /// </summary>
  338. /// <param name="sn"></param>
  339. /// <param name="timeoutInSeconds"></param>
  340. /// <returns></returns>
  341. public async Task<(bool IsSuccess, DateTime Now)> GetServerTimeAsync(int deviceNo, string sn, double timeoutInSeconds)
  342. {
  343. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  344. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  345. var device = _configService.GetDeviceInfo(deviceNo);
  346. if (device == null)
  347. device = _configService.GetDeviceInfo();
  348. if (device == null || !device.EnableMES)
  349. {
  350. return (true, DateTime.UtcNow);
  351. }
  352. if (string.IsNullOrWhiteSpace(device.MesUrl))
  353. return (false, DateTime.UtcNow);
  354. string url = "";
  355. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=mes_server_time";
  356. LogHelper.WriteLogMes($"【询问URL】{url}");
  357. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  358. (bool IsSuccess, DateTime Now) result = (false, DateTime.UtcNow);
  359. for (int i = 0; i < 3; i++)
  360. {
  361. try
  362. {
  363. using (var rsp = await _httpClient.GetAsync(url))
  364. {
  365. var text = await rsp.Content.ReadAsStringAsync();
  366. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  367. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  368. // "SFC_OK" 代表和 MES 连接成功
  369. if (text.Contains("SFC_OK"))
  370. {
  371. //按照分隔符'/n'分割字符串
  372. string[] lines = text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  373. //通过linq查找是否包含"mes_server_time"的行
  374. var timeLine = lines.FirstOrDefault(l => l.Contains("mes_server_time"));
  375. if (timeLine != null)
  376. {
  377. // 提取时间字符串
  378. var timeString = timeLine.Split('=')[1].Trim();
  379. if (DateTime.TryParse(timeString, out DateTime serverTime))
  380. {
  381. return (true, serverTime);
  382. }
  383. }
  384. }
  385. result = (false, DateTime.UtcNow);
  386. }
  387. }
  388. catch (OperationCanceledException)
  389. {
  390. result = (false, DateTime.UtcNow);
  391. }
  392. catch (Exception ex)
  393. {
  394. result = (false, DateTime.UtcNow);
  395. }
  396. }
  397. return result;
  398. }
  399. /// <summary>
  400. /// 释放服务占用的托管资源(当前仅 <see cref="_httpClient"/>)。
  401. /// <para>本方法为幂等操作,重复调用不会产生异常。调用后实例不可再用于发起请求,尝试使用将抛出 <see cref="ObjectDisposedException"/>。</para>
  402. /// </summary>
  403. public void Dispose()
  404. {
  405. if (!_disposed)
  406. {
  407. _httpClient.Dispose();
  408. _disposed = true;
  409. }
  410. }
  411. public void SendTaskMessage(string msg, MessageLevel level)
  412. {
  413. App.Current.Dispatcher.Invoke(() =>
  414. {
  415. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  416. });
  417. }
  418. }
  419. }