MesService.cs 37 KB

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