MesService.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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=message,sn,wo,model_num,color";
  101. }
  102. else
  103. {
  104. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=message,sn,wo,model_num,color";
  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. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(string sn, string comp, double timeoutInSeconds)
  141. {
  142. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  143. {
  144. return await StationGetExAsync(sn, comp, cts.Token);
  145. }
  146. }
  147. /// <summary>
  148. /// 向 MES 发起站点查询请求,使用超时(秒)作为便捷重载。
  149. /// </summary>
  150. /// <param name="sn">序列号(SN)。</param>
  151. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  152. /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
  153. public async Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, string comp, double timeoutInSeconds)
  154. {
  155. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  156. {
  157. return await StationGetAsync(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();
  184. if (device == null || !device.EnableMES)
  185. {
  186. return (true, "MES功能未启用!");
  187. }
  188. if (string.IsNullOrWhiteSpace(device.MesUrl))
  189. {
  190. return (false, "Missing MES station URL");
  191. }
  192. string url = "";
  193. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=sn,message";
  194. LogHelper.WriteLogMes($"【询问URL】{url}");
  195. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  196. (bool IsSuccess, string Response) result = (false, string.Empty);
  197. for (int i = 0; i < 3; i++)
  198. {
  199. try
  200. {
  201. using (var rsp = await _httpClient.GetAsync(url))
  202. {
  203. var text = await rsp.Content.ReadAsStringAsync();
  204. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  205. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  206. // "SFC_OK" 代表和 MES 连接成功
  207. if (text.Contains("SFC_OK"))
  208. {
  209. if (text.Contains("message=OK"))
  210. {
  211. return (true, text);
  212. }
  213. }
  214. result = (false, text);
  215. }
  216. }
  217. catch (OperationCanceledException)
  218. {
  219. result = (false, "Canceled");
  220. }
  221. catch (Exception ex)
  222. {
  223. result = (false, ex.Message);
  224. }
  225. }
  226. return result;
  227. }
  228. /// <summary>
  229. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
  230. /// </summary>
  231. /// <param name="sn">要查询的序列号(SN)。</param>
  232. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  233. /// <returns>
  234. /// 返回元组 (IsSuccess, Response):
  235. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  236. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  237. /// </returns>
  238. /// <remarks>
  239. /// 行为说明:
  240. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  241. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  242. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  243. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  244. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  245. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  246. /// </remarks>
  247. public async Task<(bool IsSuccess, string Response)> StationGetAsync(string sn, string comp, CancellationToken cancellationToken = default)
  248. {
  249. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  250. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  251. var device = _configService.GetDeviceInfo();
  252. if (device == null || !device.EnableMES)
  253. {
  254. return (true, "MES功能未启用!");
  255. }
  256. if (string.IsNullOrWhiteSpace(device.MesUrl))
  257. {
  258. return (false, "Missing MES station URL");
  259. }
  260. if (device.F == "PTL")
  261. {
  262. if (string.IsNullOrEmpty(device.comp))
  263. {
  264. return (false, "PTL模式下comp不能为空");
  265. }
  266. }
  267. string url = "";
  268. if (device.F == "PTL")
  269. {
  270. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&comp={device.comp}:{comp}&p=message,sn,wo,model_num,color";
  271. }
  272. else
  273. {
  274. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=message,sn,wo,model_num,color";
  275. }
  276. LogHelper.WriteLogMes($"【询问URL】{url}");
  277. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  278. (bool IsSuccess, string Response) result = (false, string.Empty);
  279. for (int i = 0; i < 3; i++)
  280. {
  281. try
  282. {
  283. using (var rsp = await _httpClient.GetAsync(url))
  284. {
  285. var text = await rsp.Content.ReadAsStringAsync();
  286. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  287. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  288. // "SFC_OK" 代表和 MES 连接成功
  289. if (text.Contains("SFC_OK"))
  290. {
  291. if (text.Contains("message=OK"))
  292. {
  293. return (true, text);
  294. }
  295. }
  296. result = (false, text);
  297. }
  298. }
  299. catch (OperationCanceledException)
  300. {
  301. result = (false, "Canceled");
  302. }
  303. catch (Exception ex)
  304. {
  305. result = (false, ex.Message);
  306. }
  307. }
  308. return result;
  309. }
  310. /// <summary>
  311. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
  312. /// </summary>
  313. /// <param name="sn">要查询的序列号(SN)。</param>
  314. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  315. /// <returns>
  316. /// 返回元组 (IsSuccess, Response):
  317. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  318. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  319. /// </returns>
  320. /// <remarks>
  321. /// 行为说明:
  322. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  323. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  324. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  325. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  326. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  327. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  328. /// </remarks>
  329. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, CancellationToken cancellationToken = default)
  330. {
  331. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  332. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  333. var device = _configService.GetDeviceInfo(deviceNo);
  334. if (device == null)
  335. device = _configService.GetDeviceInfo();
  336. if (device == null || !device.EnableMES)
  337. {
  338. return (true, "MES功能未启用!");
  339. }
  340. if (string.IsNullOrWhiteSpace(device.MesUrl))
  341. return (false, "Missing MES station URL");
  342. string url = "";
  343. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=message,sn,wo";
  344. LogHelper.WriteLogMes($"【询问URL】{url}");
  345. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  346. (bool IsSuccess, string Response) result = (false, string.Empty);
  347. for (int i = 0; i < 3; i++)
  348. {
  349. try
  350. {
  351. using (var rsp = await _httpClient.GetAsync(url))
  352. {
  353. var text = await rsp.Content.ReadAsStringAsync();
  354. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  355. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  356. // "SFC_OK" 代表和 MES 连接成功
  357. if (text.Contains("SFC_OK"))
  358. {
  359. if (text.Contains("message=OK"))
  360. {
  361. return (true, text);
  362. }
  363. }
  364. result = (false, text);
  365. }
  366. }
  367. catch (OperationCanceledException)
  368. {
  369. result = (false, "Canceled");
  370. }
  371. catch (Exception ex)
  372. {
  373. result = (false, ex.Message);
  374. }
  375. }
  376. return result;
  377. }
  378. /// <summary>
  379. /// 向 MES 发起站点查询请求,使用超时(秒)作为便捷重载。
  380. /// </summary>
  381. /// <param name="sn">序列号(SN)。</param>
  382. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  383. /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
  384. public async Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, double timeoutInSeconds)
  385. {
  386. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  387. {
  388. return await StationGetAsync(deviceNo, sn, comp, cts.Token);
  389. }
  390. }
  391. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, double timeoutInSeconds)
  392. {
  393. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  394. {
  395. return await StationGetExAsync(deviceNo, sn, comp, cts.Token);
  396. }
  397. }
  398. /// <summary>
  399. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  400. /// </summary>
  401. /// <param name="sn">要提交的序列号(SN)。</param>
  402. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  403. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  404. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  405. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  406. /// <returns>
  407. /// 返回元组 (IsSuccess, Response):
  408. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  409. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  410. /// </returns>
  411. /// <remarks>
  412. /// 行为说明:
  413. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  414. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  415. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  416. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  417. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  418. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  419. /// </remarks>
  420. 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)
  421. {
  422. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  423. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  424. var device = _configService.GetDeviceInfo(deviceNo);
  425. if (device == null)
  426. device = _configService.GetDeviceInfo();
  427. if (device == null || !device.EnableMES)
  428. {
  429. return (true, "MES功能未启用!");
  430. }
  431. if (string.IsNullOrWhiteSpace(device.MesUrl))
  432. return (false, "Missing MES submit URL");
  433. if (device.F == "PTL")
  434. {
  435. if (string.IsNullOrEmpty(device.comp))
  436. {
  437. return (false, "PTL模式下comp不能为空");
  438. }
  439. }
  440. //string res = isSuccess ? "PASS" : "FAIL";
  441. string res = "PASS";
  442. string url = "";
  443. if (device.F == "PTL")
  444. {
  445. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  446. $"&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")}";
  447. }
  448. else
  449. {
  450. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  451. $"&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")}";
  452. }
  453. LogHelper.WriteLogMes($"【上传URL】{url}");
  454. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  455. (bool IsSuccess, string Response) result = (false, string.Empty);
  456. for (int i = 0; i < 3; i++)
  457. {
  458. try
  459. {
  460. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  461. {
  462. var text = await rsp.Content.ReadAsStringAsync();
  463. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  464. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  465. // "SFC_OK" 代表和 MES 连接成功
  466. if (text.Contains("SFC_OK"))
  467. {
  468. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  469. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  470. {
  471. return (false, text);
  472. }
  473. return (true, text);
  474. }
  475. result = (false, text);
  476. }
  477. }
  478. catch (OperationCanceledException)
  479. {
  480. result = (false, "Canceled");
  481. }
  482. catch (Exception ex)
  483. {
  484. result = (false, ex.Message);
  485. }
  486. }
  487. return result;
  488. }
  489. /// <summary>
  490. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  491. /// </summary>
  492. /// <param name="sn">要提交的序列号(SN)。</param>
  493. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  494. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  495. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  496. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  497. /// <returns>
  498. /// 返回元组 (IsSuccess, Response):
  499. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  500. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  501. /// </returns>
  502. /// <remarks>
  503. /// 行为说明:
  504. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  505. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  506. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  507. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  508. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  509. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  510. /// </remarks>
  511. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(string sn, string comp, string torque, string pressure, string turn, bool isSuccess, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
  512. {
  513. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  514. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  515. var device = _configService.GetDeviceInfo();
  516. if (device == null || !device.EnableMES)
  517. {
  518. return (true, "MES功能未启用!");
  519. }
  520. if (string.IsNullOrWhiteSpace(device.MesUrl))
  521. return (false, "Missing MES submit URL");
  522. if (device.F == "PTL")
  523. {
  524. if (string.IsNullOrEmpty(device.comp))
  525. {
  526. return (false, "PTL模式下comp不能为空");
  527. }
  528. }
  529. //string res = isSuccess ? "PASS" : "FAIL";
  530. string res = "PASS";
  531. string url = "";
  532. if (device.F == "PTL")
  533. {
  534. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  535. $"&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")}";
  536. }
  537. else
  538. {
  539. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  540. $"&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")}";
  541. }
  542. LogHelper.WriteLogMes($"【上传URL】{url}");
  543. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  544. (bool IsSuccess, string Response) result = (false, string.Empty);
  545. for (int i = 0; i < 3; i++)
  546. {
  547. try
  548. {
  549. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  550. {
  551. var text = await rsp.Content.ReadAsStringAsync();
  552. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  553. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  554. // "SFC_OK" 代表和 MES 连接成功
  555. if (text.Contains("SFC_OK"))
  556. {
  557. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  558. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  559. {
  560. return (false, text);
  561. }
  562. return (true, text);
  563. }
  564. result = (false, text);
  565. }
  566. }
  567. catch (OperationCanceledException)
  568. {
  569. result = (false, "Canceled");
  570. }
  571. catch (Exception ex)
  572. {
  573. result = (false, ex.Message);
  574. }
  575. }
  576. return result;
  577. }
  578. /// <summary>
  579. /// 向 MES 提交请求的超时重载,使用超时(秒)作为便捷参数。
  580. /// </summary>
  581. /// <param name="sn">序列号(SN)。</param>
  582. /// <param name="isSuccess">是否通过(PASS/FAIL)。</param>
  583. /// <param name="start_time">开始时间。</param>
  584. /// <param name="stop_time">结束时间。</param>
  585. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  586. /// <returns>与 <see cref="SubmitGetAsync(int deviceNo, string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
  587. 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)
  588. {
  589. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  590. {
  591. return await SubmitGetAsync(deviceNo,sn, comp, torque, pressure, turn, isSuccess, start_time, stop_time, cts.Token);
  592. }
  593. }
  594. /// <summary>
  595. /// 获取服务器当前时间
  596. /// </summary>
  597. /// <param name="sn"></param>
  598. /// <param name="timeoutInSeconds"></param>
  599. /// <returns></returns>
  600. public async Task<(bool IsSuccess, DateTime Now)> GetServerTimeAsync(int deviceNo, string sn, double timeoutInSeconds)
  601. {
  602. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  603. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  604. var device = _configService.GetDeviceInfo(deviceNo);
  605. if (device == null)
  606. device = _configService.GetDeviceInfo();
  607. if (device == null || !device.EnableMES)
  608. {
  609. return (true, DateTime.Now);
  610. }
  611. if (string.IsNullOrWhiteSpace(device.MesUrl))
  612. return (false, DateTime.Now);
  613. string url = "";
  614. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=mes_server_time";
  615. LogHelper.WriteLogMes($"【询问URL】{url}");
  616. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  617. (bool IsSuccess, DateTime Now) result = (false, DateTime.Now);
  618. for (int i = 0; i < 3; i++)
  619. {
  620. try
  621. {
  622. using (var rsp = await _httpClient.GetAsync(url))
  623. {
  624. var text = await rsp.Content.ReadAsStringAsync();
  625. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  626. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  627. // "SFC_OK" 代表和 MES 连接成功
  628. if (text.Contains("SFC_OK"))
  629. {
  630. //按照分隔符'/n'分割字符串
  631. string[] lines = text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  632. //通过linq查找是否包含"mes_server_time"的行
  633. var timeLine = lines.FirstOrDefault(l => l.Contains("mes_server_time"));
  634. if (timeLine != null)
  635. {
  636. // 提取时间字符串
  637. var timeString = timeLine.Split('=')[1].Trim();
  638. if (DateTime.TryParse(timeString, out DateTime serverTime))
  639. {
  640. return (true, serverTime);
  641. }
  642. }
  643. }
  644. result = (false, DateTime.Now);
  645. }
  646. }
  647. catch (OperationCanceledException)
  648. {
  649. result = (false, DateTime.Now);
  650. }
  651. catch (Exception ex)
  652. {
  653. result = (false, DateTime.Now);
  654. }
  655. }
  656. return result;
  657. }
  658. /// <summary>
  659. /// 上传log服务器
  660. /// </summary>
  661. /// <param name="sn"></param>
  662. /// <param name="name"></param>
  663. /// <param name="cancellationToken"></param>
  664. /// <returns></returns>
  665. /// <exception cref="ObjectDisposedException"></exception>
  666. public async Task<(bool IsSuccess, string Response)> SendFtpFileAsync(string sn,string name,CancellationToken cancellationToken = default)
  667. {
  668. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  669. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  670. var device = _configService.GetDeviceInfo();
  671. if (device == null || !device.EnableMES)
  672. {
  673. return (true, "MES功能未启用!");
  674. }
  675. if (string.IsNullOrWhiteSpace(device.LogUrl))
  676. {
  677. return (false, "Missing MES station LogUrl");
  678. }
  679. 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\"}}";
  680. LogHelper.WriteLogMes($"【上传FTP的URL】{url}");
  681. SendTaskMessage($"【上传FTP的URL】{url}", MessageLevel.Info);
  682. (bool IsSuccess, string Response) result = (false, string.Empty);
  683. for (int i = 0; i < 3; i++)
  684. {
  685. try
  686. {
  687. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  688. {
  689. var text = await rsp.Content.ReadAsStringAsync();
  690. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  691. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  692. // "SFC_OK" 代表和 MES 连接成功
  693. if (text.Contains("SFC_OK"))
  694. {
  695. return (true, text);
  696. }
  697. result = (false, text);
  698. }
  699. }
  700. catch (OperationCanceledException)
  701. {
  702. result = (false, "Canceled");
  703. }
  704. catch (Exception ex)
  705. {
  706. result = (false, ex.Message);
  707. }
  708. }
  709. return result;
  710. }
  711. /// <summary>
  712. /// 释放服务占用的托管资源(当前仅 <see cref="_httpClient"/>)。
  713. /// <para>本方法为幂等操作,重复调用不会产生异常。调用后实例不可再用于发起请求,尝试使用将抛出 <see cref="ObjectDisposedException"/>。</para>
  714. /// </summary>
  715. public void Dispose()
  716. {
  717. if (!_disposed)
  718. {
  719. _httpClient.Dispose();
  720. _disposed = true;
  721. }
  722. }
  723. public void SendTaskMessage(string msg, MessageLevel level)
  724. {
  725. App.Current.Dispatcher.Invoke(() =>
  726. {
  727. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  728. });
  729. }
  730. }
  731. }