MesService.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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(0);
  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,model_num,color,ppid,stage";
  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,model_num,color,ppid,stage";
  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(0);
  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(int deviceNo,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(deviceNo);
  253. if (device == null)
  254. device = _configService.GetDeviceInfo();
  255. if (device == null || !device.EnableMES)
  256. {
  257. return (true, "MES功能未启用!");
  258. }
  259. if (string.IsNullOrWhiteSpace(device.MesUrl))
  260. return (false, "Missing MES submit URL");
  261. if (device.F == "PTL")
  262. {
  263. if (string.IsNullOrEmpty(device.comp))
  264. {
  265. return (false, "PTL模式下comp不能为空");
  266. }
  267. }
  268. string res = isSuccess ? "PASS" : "FAIL";
  269. string url = "";
  270. if (device.F == "PTL")
  271. {
  272. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  273. $"&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")}";
  274. }
  275. else
  276. {
  277. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  278. $"&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")}";
  279. }
  280. LogHelper.WriteLogMes($"【上传URL】{url}");
  281. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  282. (bool IsSuccess, string Response) result = (false, string.Empty);
  283. for (int i = 0; i < 3; i++)
  284. {
  285. try
  286. {
  287. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  288. {
  289. var text = await rsp.Content.ReadAsStringAsync();
  290. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  291. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  292. // "SFC_OK" 代表和 MES 连接成功
  293. if (text.Contains("SFC_OK"))
  294. {
  295. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  296. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  297. {
  298. return (false, text);
  299. }
  300. return (true, text);
  301. }
  302. result = (false, text);
  303. }
  304. }
  305. catch (OperationCanceledException)
  306. {
  307. result = (false, "Canceled");
  308. }
  309. catch (Exception ex)
  310. {
  311. result = (false, ex.Message);
  312. }
  313. }
  314. return result;
  315. }
  316. /// <summary>
  317. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  318. /// </summary>
  319. /// <param name="sn">要提交的序列号(SN)。</param>
  320. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  321. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  322. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  323. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  324. /// <returns>
  325. /// 返回元组 (IsSuccess, Response):
  326. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  327. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  328. /// </returns>
  329. /// <remarks>
  330. /// 行为说明:
  331. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  332. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  333. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  334. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  335. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  336. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  337. /// </remarks>
  338. 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)
  339. {
  340. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  341. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  342. var device = _configService.GetDeviceInfo(0);
  343. if (device == null || !device.EnableMES)
  344. {
  345. return (true, "MES功能未启用!");
  346. }
  347. if (string.IsNullOrWhiteSpace(device.MesUrl))
  348. return (false, "Missing MES submit URL");
  349. if (device.F == "PTL")
  350. {
  351. if (string.IsNullOrEmpty(device.comp))
  352. {
  353. return (false, "PTL模式下comp不能为空");
  354. }
  355. }
  356. //string res = isSuccess ? "PASS" : "FAIL";
  357. string res = "PASS";
  358. string url = "";
  359. if (device.F == "PTL")
  360. {
  361. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  362. $"&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")}";
  363. }
  364. else
  365. {
  366. url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  367. $"&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")}";
  368. }
  369. LogHelper.WriteLogMes($"【上传URL】{url}");
  370. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  371. (bool IsSuccess, string Response) result = (false, string.Empty);
  372. for (int i = 0; i < 3; i++)
  373. {
  374. try
  375. {
  376. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  377. {
  378. var text = await rsp.Content.ReadAsStringAsync();
  379. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  380. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  381. // "SFC_OK" 代表和 MES 连接成功
  382. if (text.Contains("SFC_OK"))
  383. {
  384. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  385. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  386. {
  387. return (false, text);
  388. }
  389. return (true, text);
  390. }
  391. result = (false, text);
  392. }
  393. }
  394. catch (OperationCanceledException)
  395. {
  396. result = (false, "Canceled");
  397. }
  398. catch (Exception ex)
  399. {
  400. result = (false, ex.Message);
  401. }
  402. }
  403. return result;
  404. }
  405. /// <summary>
  406. /// 向 MES 提交请求的超时重载,使用超时(秒)作为便捷参数。
  407. /// </summary>
  408. /// <param name="sn">序列号(SN)。</param>
  409. /// <param name="isSuccess">是否通过(PASS/FAIL)。</param>
  410. /// <param name="start_time">开始时间。</param>
  411. /// <param name="stop_time">结束时间。</param>
  412. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  413. /// <returns>与 <see cref="SubmitGetAsync(string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
  414. 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)
  415. {
  416. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  417. {
  418. return await SubmitGetAsync(sn, comp, assypress, cc, height, isSuccess, start_time, stop_time, cts.Token);
  419. }
  420. }
  421. /// <summary>
  422. /// 获取服务器当前时间
  423. /// </summary>
  424. /// <param name="sn"></param>
  425. /// <param name="timeoutInSeconds"></param>
  426. /// <returns></returns>
  427. public async Task<(bool IsSuccess, DateTime Now)> GetServerTimeAsync(string sn, double timeoutInSeconds)
  428. {
  429. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  430. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  431. var device = _configService.GetDeviceInfo(0);
  432. if (device == null)
  433. device = _configService.GetDeviceInfo(0);
  434. if (device == null || !device.EnableMES)
  435. {
  436. return (true, DateTime.UtcNow);
  437. }
  438. if (string.IsNullOrWhiteSpace(device.MesUrl))
  439. return (false, DateTime.UtcNow);
  440. string url = "";
  441. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=mes_server_time";
  442. LogHelper.WriteLogMes($"【询问URL】{url}");
  443. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  444. (bool IsSuccess, DateTime Now) result = (false, DateTime.UtcNow);
  445. for (int i = 0; i < 3; i++)
  446. {
  447. try
  448. {
  449. using (var rsp = await _httpClient.GetAsync(url))
  450. {
  451. var text = await rsp.Content.ReadAsStringAsync();
  452. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  453. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  454. // "SFC_OK" 代表和 MES 连接成功
  455. if (text.Contains("SFC_OK"))
  456. {
  457. //按照分隔符'/n'分割字符串
  458. string[] lines = text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  459. //通过linq查找是否包含"mes_server_time"的行
  460. var timeLine = lines.FirstOrDefault(l => l.Contains("mes_server_time"));
  461. if (timeLine != null)
  462. {
  463. // 提取时间字符串
  464. var timeString = timeLine.Split('=')[1].Trim();
  465. if (DateTime.TryParse(timeString, out DateTime serverTime))
  466. {
  467. return (true, serverTime);
  468. }
  469. }
  470. }
  471. result = (false, DateTime.UtcNow);
  472. }
  473. }
  474. catch (OperationCanceledException)
  475. {
  476. result = (false, DateTime.UtcNow);
  477. }
  478. catch (Exception ex)
  479. {
  480. result = (false, DateTime.UtcNow);
  481. }
  482. }
  483. return result;
  484. }
  485. /// <summary>
  486. /// 释放服务占用的托管资源(当前仅 <see cref="_httpClient"/>)。
  487. /// <para>本方法为幂等操作,重复调用不会产生异常。调用后实例不可再用于发起请求,尝试使用将抛出 <see cref="ObjectDisposedException"/>。</para>
  488. /// </summary>
  489. public void Dispose()
  490. {
  491. if (!_disposed)
  492. {
  493. _httpClient.Dispose();
  494. _disposed = true;
  495. }
  496. }
  497. public void SendTaskMessage(string msg, MessageLevel level)
  498. {
  499. App.Current.Dispatcher.Invoke(() =>
  500. {
  501. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  502. });
  503. }
  504. /// <summary>
  505. /// 上传log服务器
  506. /// </summary>
  507. /// <param name="sn"></param>
  508. /// <param name="name"></param>
  509. /// <param name="cancellationToken"></param>
  510. /// <returns></returns>
  511. /// <exception cref="ObjectDisposedException"></exception>
  512. public async Task<(bool IsSuccess, string Response)> SendFtpFileAsync(string sn, string name, CancellationToken cancellationToken = default)
  513. {
  514. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  515. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  516. var device = _configService.GetDeviceInfo(0);
  517. if (device == null || !device.EnableMES)
  518. {
  519. return (true, "MES功能未启用!");
  520. }
  521. if (string.IsNullOrWhiteSpace(device.LogUrl))
  522. {
  523. return (false, "Missing MES station LogUrl");
  524. }
  525. 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\",\"STATIONTYPE\":\"AE\"}}";
  526. LogHelper.WriteLogMes($"【上传LogData的URL】{url}");
  527. SendTaskMessage($"【上传LogData的URL】{url}", MessageLevel.Info);
  528. (bool IsSuccess, string Response) result = (false, string.Empty);
  529. for (int i = 0; i < 3; i++)
  530. {
  531. try
  532. {
  533. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  534. {
  535. var text = await rsp.Content.ReadAsStringAsync();
  536. LogHelper.WriteLogMes($"【上传LogData的HTTP接收】{text}");
  537. SendTaskMessage($"【上传LogData的HTTP接收】{text}", MessageLevel.Info);
  538. // "SFC_OK" 代表和 MES 连接成功
  539. if (text.Contains("\"Code\":1"))
  540. {
  541. return (true, text);
  542. }
  543. result = (false, text);
  544. }
  545. }
  546. catch (OperationCanceledException)
  547. {
  548. result = (false, "Canceled");
  549. }
  550. catch (Exception ex)
  551. {
  552. result = (false, ex.Message);
  553. }
  554. }
  555. return result;
  556. }
  557. }
  558. }