MesService.cs 29 KB

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