MesService.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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 TeamAAS_VP.Enums;
  11. using TeamAAS_VP.Events;
  12. using TeamAAS_VP.Interfaces;
  13. using TeamAAS_VP.Models;
  14. namespace TeamAAS_VP.Services
  15. {
  16. /// <summary>
  17. /// 基于 <see cref="HttpClient"/> 的 MES 通信服务实现。
  18. /// <para>
  19. /// 本服务通过注入的 <see cref="IConfigService"/> 获取设备配置(包含 MES 接口地址),
  20. /// 提供对站点查询(StationGetAsync)和提交(SubmitGetAsync)的 GET 请求封装并带有重试逻辑。
  21. /// </para>
  22. /// <para>
  23. /// 注意:
  24. /// - <see cref="_httpClient"/> 为可复用的单一实例,建议在服务生命周期内重用以避免端口耗尽。
  25. /// - 本类实现了显式的 <see cref="Dispose"/> 方法以释放内部 <see cref="HttpClient"/> 资源,调用后实例不可再用。
  26. /// </para>
  27. /// </summary>
  28. public class MesService : IMesService
  29. {
  30. IEventAggregator _eventAggregator;
  31. /// <summary>
  32. /// 用于执行 HTTP 请求的客户端实例。建议在服务生命周期内重用,避免频繁创建导致套接字/端口耗尽。
  33. /// </summary>
  34. private readonly HttpClient _httpClient;
  35. /// <summary>
  36. /// 配置服务,用于获取设备信息(包含 MES URL、是否启用 MES 等)。
  37. /// </summary>
  38. private readonly IConfigService _configService;
  39. /// <summary>
  40. /// 标记实例是否已释放,防止重复释放和在释放后继续使用导致未定义行为。
  41. /// </summary>
  42. private bool _disposed;
  43. /// <summary>
  44. /// 使用指定的配置服务创建 <see cref="MesService"/> 实例。
  45. /// </summary>
  46. /// <param name="configService">用于获取设备配置信息的实现,不能为空。</param>
  47. /// <exception cref="ArgumentNullException">当 <paramref name="configService"/> 为 null 时抛出。</exception>
  48. public MesService(IConfigService configService, IContainerProvider container, IEventAggregator ea)
  49. {
  50. _configService = configService ?? throw new ArgumentNullException(nameof(configService));
  51. _httpClient = new HttpClient();
  52. _disposed = false;
  53. _eventAggregator = ea;
  54. }
  55. /// <summary>
  56. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
  57. /// </summary>
  58. /// <param name="sn">要查询的序列号(SN)。</param>
  59. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  60. /// <returns>
  61. /// 返回元组 (IsSuccess, Response):
  62. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  63. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  64. /// </returns>
  65. /// <remarks>
  66. /// 行为说明:
  67. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  68. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  69. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  70. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  71. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  72. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  73. /// </remarks>
  74. public async Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, string comp2, CancellationToken cancellationToken = default)
  75. {
  76. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  77. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  78. var device = _configService.GetDeviceInfo(deviceNo);
  79. if (device == null)
  80. device = _configService.GetDeviceInfo();
  81. if (device == null || !device.EnableMES)
  82. {
  83. return (false, "MES功能未启用!");
  84. }
  85. if (string.IsNullOrWhiteSpace(device.MesUrl))
  86. return (false, "Missing MES station URL");
  87. if (device.F == "PTL")
  88. {
  89. if (string.IsNullOrEmpty(device.comp))
  90. {
  91. return (false, "PTL模式下comp不能为空");
  92. }
  93. }
  94. string url = "";
  95. if (device.F == "PTL")
  96. {
  97. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&comp={device.comp}:{comp},{device.comp2}:{comp2}&p=message,sn,wo,model_num,color,ppid,stage";
  98. }
  99. else
  100. {
  101. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=message,sn,wo,model_num,color,ppid,stage";
  102. }
  103. LogHelper.WriteLogMes($"【询问URL】{url}");
  104. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  105. (bool IsSuccess, string Response) result = (false, string.Empty);
  106. for (int i = 0; i < 3; i++)
  107. {
  108. try
  109. {
  110. using (var rsp = await _httpClient.GetAsync(url))
  111. {
  112. var text = await rsp.Content.ReadAsStringAsync();
  113. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  114. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  115. // "SFC_OK" 代表和 MES 连接成功
  116. if (text.Contains("SFC_OK"))
  117. {
  118. if (text.Contains("message=OK"))
  119. {
  120. return (true, text);
  121. }
  122. }
  123. result = (false, text);
  124. }
  125. }
  126. catch (OperationCanceledException)
  127. {
  128. result = (false, "Canceled");
  129. }
  130. catch (Exception ex)
  131. {
  132. result = (false, ex.Message);
  133. }
  134. }
  135. return result;
  136. }
  137. /// <summary>
  138. /// 向 MES 发起站点查询请求,使用超时(秒)作为便捷重载。
  139. /// </summary>
  140. /// <param name="sn">序列号(SN)。</param>
  141. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  142. /// <returns>与 <see cref="StationGetAsync(string, CancellationToken)"/> 相同的返回语义。</returns>
  143. public async Task<(bool IsSuccess, string Response)> StationGetAsync(int deviceNo, string sn, string comp, string comp2, double timeoutInSeconds)
  144. {
  145. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  146. {
  147. return await StationGetAsync(deviceNo, sn, comp,comp2, cts.Token);
  148. }
  149. }
  150. /// <summary>
  151. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于过站查询)。
  152. /// </summary>
  153. /// <param name="sn">要查询的序列号(SN)。</param>
  154. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  155. /// <returns>
  156. /// 返回元组 (IsSuccess, Response):
  157. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  158. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  159. /// </returns>
  160. /// <remarks>
  161. /// 行为说明:
  162. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  163. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  164. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  165. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  166. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  167. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  168. /// </remarks>
  169. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, CancellationToken cancellationToken = default)
  170. {
  171. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  172. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  173. var device = _configService.GetDeviceInfo(deviceNo);
  174. if (device == null)
  175. device = _configService.GetDeviceInfo();
  176. if (device == null || !device.EnableMES)
  177. {
  178. return (false, "MES功能未启用!");
  179. }
  180. if (string.IsNullOrWhiteSpace(device.MesUrl))
  181. return (false, "Missing MES station URL");
  182. string url = "";
  183. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=message,sn,wo";
  184. LogHelper.WriteLogMes($"【询问URL】{url}");
  185. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  186. (bool IsSuccess, string Response) result = (false, string.Empty);
  187. for (int i = 0; i < 3; i++)
  188. {
  189. try
  190. {
  191. using (var rsp = await _httpClient.GetAsync(url))
  192. {
  193. var text = await rsp.Content.ReadAsStringAsync();
  194. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  195. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  196. // "SFC_OK" 代表和 MES 连接成功
  197. if (text.Contains("SFC_OK"))
  198. {
  199. if (text.Contains("message=OK"))
  200. {
  201. return (true, text);
  202. }
  203. }
  204. result = (false, text);
  205. }
  206. }
  207. catch (OperationCanceledException)
  208. {
  209. result = (false, "Canceled");
  210. }
  211. catch (Exception ex)
  212. {
  213. result = (false, ex.Message);
  214. }
  215. }
  216. return result;
  217. }
  218. /// <summary>
  219. /// 向配置中指定的 MES 站点 URL 发起 GET 请求(用于零件使用查询)。
  220. /// </summary>
  221. /// <param name="partSN">要查询的序列号(SN)。</param>
  222. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  223. /// <returns>
  224. /// 返回元组 (IsSuccess, Response):
  225. /// - IsSuccess: 请求是否视为成功(即 MES 返回了预期的 "SFC_OK" 且包含 "unit_process_check=OK")。
  226. /// - Response: 原始响应文本或错误信息说明(如 "MES功能未启用!"、"Missing MES station URL"、"Canceled" 等)。
  227. /// </returns>
  228. /// <remarks>
  229. /// 行为说明:
  230. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  231. /// - 若未配置 MES URL 则返回 IsSuccess=false 与错误文本。
  232. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 填充 sn)发起 GET 请求,最多重试 10 次。
  233. /// - 只有当响应包含 "SFC_OK" 且包含 "unit_process_check=OK" 时视为成功并立即返回。
  234. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  235. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  236. /// </remarks>
  237. public async Task<(bool IsSuccess, string Response)> StationGetEx2Async(int deviceNo, string partSN, string comp, CancellationToken cancellationToken = default)
  238. {
  239. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  240. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  241. var device = _configService.GetDeviceInfo(deviceNo);
  242. if (device == null)
  243. device = _configService.GetDeviceInfo();
  244. if (device == null || !device.EnableMES)
  245. {
  246. return (false, "MES功能未启用!");
  247. }
  248. if (string.IsNullOrWhiteSpace(device.MesUrl))
  249. return (false, "Missing MES station URL");
  250. string url = "";
  251. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={partSN}&p=sn,message";
  252. LogHelper.WriteLogMes($"【询问URL】{url}");
  253. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  254. (bool IsSuccess, string Response) result = (false, string.Empty);
  255. for (int i = 0; i < 3; i++)
  256. {
  257. try
  258. {
  259. using (var rsp = await _httpClient.GetAsync(url))
  260. {
  261. var text = await rsp.Content.ReadAsStringAsync();
  262. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  263. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  264. // "SFC_OK" 代表和 MES 连接成功
  265. if (text.Contains("SFC_OK"))
  266. {
  267. string[] item = text.Split('\n');
  268. string snItem = item.FirstOrDefault(f => f.Contains("sn="));
  269. if (snItem != null)
  270. {
  271. if (snItem.Replace("sn=", "").Length == 0)//如果零件没做过
  272. {
  273. return (true, text);
  274. }
  275. else//如果零件已做过
  276. {
  277. string ProductMainSN_Temp = snItem.Replace("sn=", "").Trim();
  278. SendTaskMessage($"零件已绑定sn:{ProductMainSN_Temp}", MessageLevel.Error);
  279. return (false, text);
  280. }
  281. }
  282. }
  283. result = (false, text);
  284. }
  285. }
  286. catch (OperationCanceledException)
  287. {
  288. result = (false, "Canceled");
  289. }
  290. catch (Exception ex)
  291. {
  292. result = (false, ex.Message);
  293. }
  294. }
  295. return result;
  296. }
  297. public async Task<(bool IsSuccess, string Response)> StationGetExAsync(int deviceNo, string sn, string comp, double timeoutInSeconds)
  298. {
  299. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  300. {
  301. return await StationGetExAsync(deviceNo, sn, comp, cts.Token);
  302. }
  303. }
  304. public async Task<(bool IsSuccess, string Response)> StationGetEx2Async(int deviceNo, string partSN, string comp, double timeoutInSeconds)
  305. {
  306. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  307. {
  308. return await StationGetEx2Async(deviceNo, partSN, comp, cts.Token);
  309. }
  310. }
  311. /// <summary>
  312. /// 向配置中指定的 MES 提交 URL 发起 GET 请求(用于提交测试结果/记录)。
  313. /// </summary>
  314. /// <param name="sn">要提交的序列号(SN)。</param>
  315. /// <param name="isSuccess">表示此次记录是否通过(true => PASS,false => FAIL)。</param>
  316. /// <param name="start_time">开始时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  317. /// <param name="stop_time">结束时间,提交时使用 "yyyy-MM-dd HH:mm:ss" 格式。</param>
  318. /// <param name="cancellationToken">可选的取消令牌,用于请求超时或取消。</param>
  319. /// <returns>
  320. /// 返回元组 (IsSuccess, Response):
  321. /// - IsSuccess: 提交是否被 MES 视为成功(收到 "SFC_OK" 且响应中无额外多行信息)。
  322. /// - Response: MES 返回文本或错误说明;当 MES 返回 "SFC_OK" 但包含额外多行信息(代表 SN 数据问题)时,IsSuccess 为 false 且 Response 为该文本。
  323. /// </returns>
  324. /// <remarks>
  325. /// 行为说明:
  326. /// - 从配置获取设备信息,若 MES 未启用则直接返回 IsSuccess=true 且 Response 为提示文本(不视为错误)。
  327. /// - 若未配置 MES 提交 URL 则返回 IsSuccess=false 与错误文本。
  328. /// - 使用配置的 URL(通过 <see cref="string.Format"/> 按顺序填充 sn、PASS/FAIL、start_time、stop_time)发起 GET 请求,最多重试 10 次。
  329. /// - 在收到包含 "SFC_OK" 的响应时,如果返回文本包含多行(有附加信息)则视为提交失败并返回该文本,否则视为提交成功。
  330. /// - 捕获 <see cref="OperationCanceledException"/> 返回 "Canceled",捕获其它异常则返回异常消息。
  331. /// - 若实例已被释放则抛出 <see cref="ObjectDisposedException"/>。
  332. /// </remarks>
  333. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo, string sn, string comp, string comp2, bool isSuccess, Dictionary<string, string> data, List<string> fieresult, DateTime start_time, DateTime stop_time, CancellationToken cancellationToken = default)
  334. {
  335. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  336. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  337. var device = _configService.GetDeviceInfo(deviceNo);
  338. if (device == null)
  339. device = _configService.GetDeviceInfo();
  340. if (device == null || !device.EnableMES)
  341. {
  342. return (false, "MES功能未启用!");
  343. }
  344. if (string.IsNullOrWhiteSpace(device.MesUrl))
  345. return (false, "Missing MES submit URL");
  346. if (device.F == "PTL")
  347. {
  348. if (string.IsNullOrEmpty(device.comp))
  349. {
  350. return (false, "PTL模式下comp不能为空");
  351. }
  352. if (string.IsNullOrEmpty(device.comp2))
  353. {
  354. return (false, "PTL模式下comp2不能为空");
  355. }
  356. }
  357. string res = isSuccess ? "Pass" : "Fail";
  358. if (res == "Fail")
  359. {
  360. res = string.Join(",", fieresult);
  361. }
  362. StringBuilder sb = new StringBuilder();
  363. if (device.F == "PTL")
  364. {
  365. sb.Append($"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp},{device.comp2}:{comp2}");
  366. foreach (var item in data)
  367. {
  368. sb.Append($"&{item.Key}={item.Value}");
  369. }
  370. sb.Append($"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}");
  371. }
  372. else
  373. {
  374. sb.Append($"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC");
  375. foreach (var item in data)
  376. {
  377. sb.Append($"&{item.Key}={item.Value}");
  378. }
  379. sb.Append($"&result={res}&start_time={start_time.ToString("yyyy-MM-dd HH:mm:ss")}&stop_time={stop_time.ToString("yyyy-MM-dd HH:mm:ss")}");
  380. }
  381. string url = sb.ToString();
  382. //if (device.F == "PTL")
  383. //{
  384. // url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PTL&comp={device.comp}:{comp}" +
  385. // $"&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")}";
  386. //}
  387. //else
  388. //{
  389. // url = $"{device.MesUrl}?c=ADD_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&f=PQC" +
  390. // $"&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")}";
  391. //}
  392. LogHelper.WriteLogMes($"【上传URL】{url}");
  393. SendTaskMessage($"【上传URL】{url}", MessageLevel.Info);
  394. (bool IsSuccess, string Response) result = (false, string.Empty);
  395. for (int i = 0; i < 3; i++)
  396. {
  397. try
  398. {
  399. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  400. {
  401. var text = await rsp.Content.ReadAsStringAsync();
  402. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  403. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  404. // "SFC_OK" 代表和 MES 连接成功
  405. if (text.Contains("SFC_OK"))
  406. {
  407. // 如果有附加信息(多行),代表此 SN 数据有问题,视为失败并返回该文本
  408. if (text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length > 1)
  409. {
  410. return (false, text);
  411. }
  412. return (true, text);
  413. }
  414. result = (false, text);
  415. }
  416. }
  417. catch (OperationCanceledException)
  418. {
  419. result = (false, "Canceled");
  420. }
  421. catch (Exception ex)
  422. {
  423. result = (false, ex.Message);
  424. }
  425. }
  426. return result;
  427. }
  428. public async Task<(bool IsSuccess, string Response)> StationGetBindingAsync(string sn, string bindingData, uint bindingModel, double timeoutInSeconds)
  429. {
  430. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  431. {
  432. return await StationGetBindingAsync(sn, bindingData, bindingModel, cts.Token);
  433. }
  434. }
  435. /// <summary>
  436. /// 绑定交互
  437. /// </summary>
  438. /// <param name="sn"></param>
  439. /// <param name="bindingData"></param>
  440. /// <param name="bindingModel"> 0=查询,1=绑定,2=解绑</param>
  441. /// <param name="cancellationToken"></param>
  442. /// <returns></returns>
  443. /// <exception cref="ObjectDisposedException"></exception>
  444. public async Task<(bool IsSuccess, string Response)> StationGetBindingAsync(string sn, string bindingData, uint bindingModel, CancellationToken cancellationToken = default)
  445. {
  446. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  447. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  448. var device = _configService.GetDeviceInfo();
  449. if (device == null || !device.EnableMES)
  450. {
  451. return (false, "MES功能未启用!");
  452. }
  453. if (string.IsNullOrWhiteSpace(device.MesUrl))
  454. return (false, "Missing MES station URL");
  455. string url = "";
  456. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=message,sn,wo";
  457. LogHelper.WriteLogMes($"【询问URL】{url}");
  458. SendTaskMessage($"【询问URL】{url}", MessageLevel.Info);
  459. (bool IsSuccess, string Response) result = (false, string.Empty);
  460. for (int i = 0; i < 3; i++)
  461. {
  462. try
  463. {
  464. using (var rsp = await _httpClient.GetAsync(url))
  465. {
  466. var text = await rsp.Content.ReadAsStringAsync();
  467. LogHelper.WriteLogMes($"【HTTP接收】{text}");
  468. SendTaskMessage($"【HTTP接收】{text}", MessageLevel.Info);
  469. // "SFC_OK" 代表和 MES 连接成功
  470. if (text.Contains("SFC_OK"))
  471. {
  472. if (text.Contains("message=OK"))
  473. {
  474. return (true, text);
  475. }
  476. }
  477. result = (false, text);
  478. }
  479. }
  480. catch (OperationCanceledException)
  481. {
  482. result = (false, "Canceled");
  483. }
  484. catch (Exception ex)
  485. {
  486. result = (false, ex.Message);
  487. }
  488. }
  489. return result;
  490. }
  491. /// <summary>
  492. /// 向 MES 提交请求的超时重载,使用超时(秒)作为便捷参数。
  493. /// </summary>
  494. /// <param name="sn">序列号(SN)。</param>
  495. /// <param name="isSuccess">是否通过(PASS/FAIL)。</param>
  496. /// <param name="start_time">开始时间。</param>
  497. /// <param name="stop_time">结束时间。</param>
  498. /// <param name="timeoutInSeconds">请求超时,单位为秒。</param>
  499. /// <returns>与 <see cref="SubmitGetAsync(string, bool, DateTime, DateTime, CancellationToken)"/> 相同的返回语义。</returns>
  500. public async Task<(bool IsSuccess, string Response)> SubmitGetAsync(int deviceNo, string sn, string comp, string comp2, bool isSuccess, Dictionary<string, string> data, List<string> fieresult, DateTime start_time, DateTime stop_time, double timeoutInSeconds)
  501. {
  502. using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)))
  503. {
  504. return await SubmitGetAsync(deviceNo, sn, comp,comp2, isSuccess, data,fieresult, start_time, stop_time, cts.Token);
  505. }
  506. }
  507. /// <summary>
  508. /// 获取服务器当前时间
  509. /// </summary>
  510. /// <param name="sn"></param>
  511. /// <param name="timeoutInSeconds"></param>
  512. /// <returns></returns>
  513. public async Task<(bool IsSuccess, DateTime Now)> GetServerTimeAsync(int deviceNo, string sn, double timeoutInSeconds)
  514. {
  515. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  516. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  517. var device = _configService.GetDeviceInfo(deviceNo);
  518. if (device == null)
  519. device = _configService.GetDeviceInfo();
  520. if (device == null || !device.EnableMES)
  521. {
  522. return (true, DateTime.Now);
  523. }
  524. if (string.IsNullOrWhiteSpace(device.MesUrl))
  525. return (false, DateTime.Now);
  526. string url = "";
  527. url = $"{device.MesUrl}?c=QUERY_RECORD&line={device.Line}&station={device.Station}&fixtureid={device.FixtureId}&sn={sn}&p=mes_server_time";
  528. LogHelper.WriteLogMes($"【询问MES Time】{url}");
  529. SendTaskMessage($"【询问MES Time】{url}", MessageLevel.Info);
  530. (bool IsSuccess, DateTime Now) result = (false, DateTime.Now);
  531. for (int i = 0; i < 3; i++)
  532. {
  533. try
  534. {
  535. using (var rsp = await _httpClient.GetAsync(url))
  536. {
  537. var text = await rsp.Content.ReadAsStringAsync();
  538. LogHelper.WriteLogMes($"【HTTP接收到MES Time】{text}");
  539. SendTaskMessage($"【HTTP接收MES Time】{text}", MessageLevel.Info);
  540. // "SFC_OK" 代表和 MES 连接成功
  541. if (text.Contains("SFC_OK"))
  542. {
  543. //按照分隔符'/n'分割字符串
  544. string[] lines = text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  545. //通过linq查找是否包含"mes_server_time"的行
  546. var timeLine = lines.FirstOrDefault(l => l.Contains("mes_server_time"));
  547. if (timeLine != null)
  548. {
  549. // 提取时间字符串
  550. var timeString = timeLine.Split('=')[1].Trim();
  551. if (DateTime.TryParse(timeString, out DateTime serverTime))
  552. {
  553. return (true, serverTime);
  554. }
  555. }
  556. }
  557. result = (false, DateTime.Now);
  558. }
  559. }
  560. catch (OperationCanceledException)
  561. {
  562. result = (false, DateTime.Now);
  563. }
  564. catch (Exception)
  565. {
  566. result = (false, DateTime.Now);
  567. }
  568. }
  569. return result;
  570. }
  571. /// <summary>
  572. /// 释放服务占用的托管资源(当前仅 <see cref="_httpClient"/>)。
  573. /// <para>本方法为幂等操作,重复调用不会产生异常。调用后实例不可再用于发起请求,尝试使用将抛出 <see cref="ObjectDisposedException"/>。</para>
  574. /// </summary>
  575. public void Dispose()
  576. {
  577. if (!_disposed)
  578. {
  579. _httpClient.Dispose();
  580. _disposed = true;
  581. }
  582. }
  583. public void SendTaskMessage(string msg, MessageLevel level)
  584. {
  585. App.Current.Dispatcher.Invoke(() =>
  586. {
  587. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  588. });
  589. }
  590. /// <summary>
  591. /// 上传log服务器
  592. /// </summary>
  593. /// <param name="sn"></param>
  594. /// <param name="name"></param>
  595. /// <param name="cancellationToken"></param>
  596. /// <returns></returns>
  597. /// <exception cref="ObjectDisposedException"></exception>
  598. public async Task<(bool IsSuccess, string Response)> SendFtpFileAsync(string sn, string name,DeviceInfo device, CancellationToken cancellationToken = default)
  599. {
  600. // 如果已经释放,则抛出异常,防止在已释放资源上继续操作。
  601. if (_disposed) throw new ObjectDisposedException(nameof(MesService));
  602. //var device = _configService.GetDeviceInfo();
  603. if (device == null || !device.EnableMES)
  604. {
  605. return (true, "MES功能未启用!");
  606. }
  607. if (string.IsNullOrWhiteSpace(device.LogUrl))
  608. {
  609. return (false, "Missing MES station LogUrl");
  610. }
  611. 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\":\"aelog\"}}";
  612. LogHelper.WriteLogMes($"【上传LogData的URL】{url}");
  613. SendTaskMessage($"【上传LogData的URL】{url}", MessageLevel.Info);
  614. (bool IsSuccess, string Response) result = (false, string.Empty);
  615. for (int i = 0; i < 3; i++)
  616. {
  617. try
  618. {
  619. using (var rsp = await _httpClient.GetAsync(url, cancellationToken))
  620. {
  621. var text = await rsp.Content.ReadAsStringAsync();
  622. LogHelper.WriteLogMes($"【上传LogData的HTTP接收】{text}");
  623. SendTaskMessage($"【上传LogData的HTTP接收】{text}", MessageLevel.Info);
  624. // "SFC_OK" 代表和 MES 连接成功
  625. if (text.Contains("\"Code\":1"))
  626. {
  627. return (true, text);
  628. }
  629. result = (false, text);
  630. }
  631. }
  632. catch (OperationCanceledException)
  633. {
  634. result = (false, "Canceled");
  635. }
  636. catch (Exception ex)
  637. {
  638. result = (false, ex.Message);
  639. }
  640. }
  641. return result;
  642. }
  643. }
  644. }