MesService.cs 31 KB

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