MesService.cs 25 KB

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