PlcService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. using OxyPlot;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using TeamAAS_VP.Core.PLCs;
  8. using TeamAAS_VP.Core.Robots;
  9. using TeamAAS_VP.Interfaces;
  10. using TeamAAS_VP.Models;
  11. namespace TeamAAS_VP.Services
  12. {
  13. public class PlcService : IPlcService, IDisposable
  14. {
  15. private readonly Dictionary<Guid, IPlc> _plcCollection;
  16. private readonly object _sync = new object();
  17. public PlcService()
  18. {
  19. _plcCollection = new Dictionary<Guid, IPlc>();
  20. }
  21. public bool CreatePlc(Guid id, PlcInfo plcInfo)
  22. {
  23. if (plcInfo == null) throw new ArgumentNullException(nameof(plcInfo));
  24. var plc = CreatePlcInstance(plcInfo);
  25. if (plc == null) return false;
  26. lock (_sync)
  27. {
  28. if (_plcCollection.ContainsKey(id))
  29. {
  30. try
  31. {
  32. _plcCollection[id].Dispose();
  33. }
  34. catch
  35. {
  36. // 忽略单个 Dispose 异常
  37. }
  38. }
  39. _plcCollection[id] = plc;
  40. }
  41. return true;
  42. }
  43. public Task<bool> CreatePlcAsync(Guid id, PlcInfo plcInfo)
  44. {
  45. return Task.Run(() => CreatePlc(id, plcInfo));
  46. }
  47. public IPlc GetPlc(Guid id)
  48. {
  49. lock (_sync)
  50. {
  51. if (_plcCollection.TryGetValue(id, out var plc)) return plc;
  52. }
  53. return null;
  54. }
  55. public Task<IPlc> GetPlcAsync(Guid id)
  56. {
  57. var plc = GetPlc(id);
  58. return Task.FromResult(plc);
  59. }
  60. public void UnRegisterPlc(Guid id)
  61. {
  62. IPlc plc = null;
  63. lock (_sync)
  64. {
  65. if (_plcCollection.TryGetValue(id, out plc))
  66. {
  67. _plcCollection.Remove(id);
  68. }
  69. }
  70. if (plc != null)
  71. {
  72. try
  73. {
  74. plc.Dispose();
  75. }
  76. catch
  77. {
  78. // 忽略释放异常
  79. }
  80. }
  81. }
  82. public Task UnRegisterPlcAsync(Guid id)
  83. {
  84. UnRegisterPlc(id);
  85. return Task.CompletedTask;
  86. }
  87. public IReadOnlyCollection<IPlc> GetAllPlcs()
  88. {
  89. lock (_sync)
  90. {
  91. return _plcCollection.Values.ToList().AsReadOnly();
  92. }
  93. }
  94. public Task<IReadOnlyCollection<IPlc>> GetAllPlcsAsync()
  95. {
  96. var snapshot = GetAllPlcs();
  97. return Task.FromResult(snapshot);
  98. }
  99. public bool TryGetPlc(Guid id, out IPlc plc)
  100. {
  101. lock (_sync)
  102. {
  103. return _plcCollection.TryGetValue(id, out plc);
  104. }
  105. }
  106. public Task<(bool found, IPlc plc)> TryGetPlcAsync(Guid id)
  107. {
  108. IPlc plc;
  109. bool found;
  110. lock (_sync)
  111. {
  112. found = _plcCollection.TryGetValue(id, out plc);
  113. }
  114. return Task.FromResult((found, plc));
  115. }
  116. public bool ContainsPlc(Guid id)
  117. {
  118. lock (_sync)
  119. {
  120. return _plcCollection.ContainsKey(id);
  121. }
  122. }
  123. public Task<bool> ContainsPlcAsync(Guid id)
  124. {
  125. var exists = ContainsPlc(id);
  126. return Task.FromResult(exists);
  127. }
  128. public bool RemovePlc(Guid id)
  129. {
  130. IPlc plc = null;
  131. lock (_sync)
  132. {
  133. if (_plcCollection.TryGetValue(id, out plc))
  134. {
  135. _plcCollection.Remove(id);
  136. }
  137. }
  138. if (plc != null)
  139. {
  140. try
  141. {
  142. plc.Dispose();
  143. }
  144. catch
  145. {
  146. // 忽略释放异常
  147. }
  148. return true;
  149. }
  150. return false;
  151. }
  152. public Task<bool> RemovePlcAsync(Guid id)
  153. {
  154. var removed = RemovePlc(id);
  155. return Task.FromResult(removed);
  156. }
  157. public IPlc GetPlcByNumber(int number)
  158. {
  159. if (TryFindPlcByNumber(number, out _, out var plc))
  160. return plc;
  161. return null;
  162. }
  163. public Task<IPlc> GetPlcByNumberAsync(int number)
  164. {
  165. var plc = GetPlcByNumber(number);
  166. return Task.FromResult(plc);
  167. }
  168. public Task UnRegisterPlcByNumberAsync(int number)
  169. {
  170. UnRegisterPlcByNumber(number);
  171. return Task.CompletedTask;
  172. }
  173. public void UnRegisterPlcByNumber(int number)
  174. {
  175. if (TryFindPlcByNumber(number, out var id, out var plc))
  176. {
  177. UnRegisterPlc(id);
  178. }
  179. }
  180. private IPlc CreatePlcInstance(PlcInfo plcInfo)
  181. {
  182. if (plcInfo == null) return null;
  183. if (plcInfo.CommunicationType == Enums.CommunicationType.OPC_UA_Client)
  184. {
  185. return new OpcUaClientPLC(plcInfo);
  186. }
  187. return null;
  188. }
  189. private bool TryFindPlcByNumber(int number, out Guid id, out IPlc plc)
  190. {
  191. lock (_sync)
  192. {
  193. foreach (var kvp in _plcCollection)
  194. {
  195. var p = kvp.Value;
  196. if (p == null) continue;
  197. object rawValue = null;
  198. var type = p.GetType();
  199. var prop = type.GetProperty("PlcNo") ?? type.GetProperty("Number") ?? type.GetProperty("No");
  200. if (prop != null)
  201. {
  202. try
  203. {
  204. rawValue = prop.GetValue(p);
  205. }
  206. catch
  207. {
  208. rawValue = null;
  209. }
  210. }
  211. if (rawValue == null)
  212. {
  213. var infoProp = type.GetProperty("PlcInfo") ?? type.GetProperty("Info");
  214. if (infoProp != null)
  215. {
  216. try
  217. {
  218. var infoObj = infoProp.GetValue(p);
  219. if (infoObj != null)
  220. {
  221. var infoType = infoObj.GetType();
  222. var numberProp = infoType.GetProperty("PlcNo") ?? infoType.GetProperty("PlcNumber") ?? infoType.GetProperty("Number") ?? infoType.GetProperty("No");
  223. if (numberProp != null)
  224. {
  225. try
  226. {
  227. rawValue = numberProp.GetValue(infoObj);
  228. }
  229. catch
  230. {
  231. rawValue = null;
  232. }
  233. }
  234. }
  235. }
  236. catch
  237. {
  238. rawValue = null;
  239. }
  240. }
  241. }
  242. if (rawValue != null)
  243. {
  244. int parsed;
  245. try
  246. {
  247. if (rawValue is int) parsed = (int)rawValue;
  248. else parsed = Convert.ToInt32(rawValue);
  249. }
  250. catch
  251. {
  252. continue;
  253. }
  254. if (parsed == number)
  255. {
  256. id = kvp.Key;
  257. plc = p;
  258. return true;
  259. }
  260. }
  261. }
  262. }
  263. id = Guid.Empty;
  264. plc = null;
  265. return false;
  266. }
  267. public void Dispose()
  268. {
  269. List<IPlc> plcs;
  270. lock (_sync)
  271. {
  272. plcs = _plcCollection.Values.ToList();
  273. _plcCollection.Clear();
  274. }
  275. foreach (var p in plcs)
  276. {
  277. try
  278. {
  279. p.Dispose();
  280. }
  281. catch
  282. {
  283. // 忽略单个释放异常
  284. }
  285. }
  286. GC.SuppressFinalize(this);
  287. }
  288. public (bool IsSucceed, string Message) InitializePlc(PlcInfo[] plcs)
  289. {
  290. if (plcs == null)
  291. {
  292. return (false, "plcs 参数为 null。");
  293. }
  294. if (plcs.Length == 0)
  295. {
  296. return (true, "没有需要初始化的 PLC。");
  297. }
  298. var failures = new List<string>();
  299. var successes = 0;
  300. for (var i = 0; i < plcs.Length; i++)
  301. {
  302. var info = plcs[i];
  303. if (info == null)
  304. {
  305. failures.Add($"索引 {i}: PlcInfo 为 null。");
  306. continue;
  307. }
  308. // 尝试从 plcInfo 中提取编号(若有)
  309. int? number = null;
  310. try
  311. {
  312. var infoType = info.GetType();
  313. var numberProp = infoType.GetProperty("PlcNo") ?? infoType.GetProperty("PlcNumber") ?? infoType.GetProperty("Number") ?? infoType.GetProperty("No");
  314. if (numberProp != null)
  315. {
  316. var raw = numberProp.GetValue(info);
  317. if (raw != null)
  318. {
  319. if (raw is int ri) number = ri;
  320. else
  321. {
  322. try
  323. {
  324. number = Convert.ToInt32(raw);
  325. }
  326. catch
  327. {
  328. number = null;
  329. }
  330. }
  331. }
  332. }
  333. }
  334. catch
  335. {
  336. number = null;
  337. }
  338. // 如果存在相同编号的 PLC,则先卸载它
  339. try
  340. {
  341. if (number.HasValue)
  342. {
  343. if (TryFindPlcByNumber(number.Value, out var existingId, out var existingPlc))
  344. {
  345. try
  346. {
  347. UnRegisterPlc(existingId);
  348. }
  349. catch
  350. {
  351. // 忽略单个卸载异常,之后尝试创建新的实例
  352. }
  353. }
  354. }
  355. }
  356. catch
  357. {
  358. // 忽略查找/卸载过程中的异常,继续尝试创建
  359. }
  360. var id = Guid.NewGuid();
  361. bool created;
  362. try
  363. {
  364. created = CreatePlc(id, info);
  365. }
  366. catch (Exception ex)
  367. {
  368. created = false;
  369. failures.Add($"索引 {i}{(number.HasValue ? $" (编号 {number.Value})" : "")}: 创建 PLC 时抛出异常:{ex.Message}");
  370. }
  371. if (!created)
  372. {
  373. failures.Add($"索引 {i}{(number.HasValue ? $" (编号 {number.Value})" : "")}: 创建 PLC 失败。");
  374. }
  375. else
  376. {
  377. successes++;
  378. }
  379. }
  380. if (failures.Count == 0)
  381. {
  382. return (true, $"已成功初始化 {successes} 个 PLC。");
  383. }
  384. var message = $"初始化完成:成功 {successes},失败 {failures.Count}。失败原因:{string.Join(" | ", failures)}";
  385. return (false, message);
  386. }
  387. public Task<(bool IsSucceed, string Message)> InitializePlcAsync(PlcInfo[] plcs)
  388. {
  389. return Task.Run(() => InitializePlc(plcs));
  390. }
  391. public bool RemoveAllPlcs()
  392. {
  393. List<IPlc> plcs;
  394. lock (_sync)
  395. {
  396. if (_plcCollection.Count == 0) return false;
  397. plcs = _plcCollection.Values.ToList();
  398. _plcCollection.Clear();
  399. }
  400. var removedAny = false;
  401. foreach (var p in plcs)
  402. {
  403. if (p == null) continue;
  404. try
  405. {
  406. p.Dispose();
  407. removedAny = true;
  408. }
  409. catch
  410. {
  411. // 忽略单个释放异常
  412. removedAny = true; // 已尝试移除,仍视为移除过
  413. }
  414. }
  415. return removedAny;
  416. }
  417. public Task<bool> RemoveAllPlcsAsync()
  418. {
  419. var result = RemoveAllPlcs();
  420. return Task.FromResult(result);
  421. }
  422. /// <summary>
  423. /// 更新PLC编号
  424. /// </summary>
  425. /// <param name="id"></param>
  426. /// <param name="newNumber"></param>
  427. public void UpdatePlcNumber(Guid id, int newNumber)
  428. {
  429. lock (_sync)
  430. {
  431. if (_plcCollection.TryGetValue(id, out var plc))
  432. {
  433. if (plc != null)
  434. {
  435. plc.Index=newNumber;
  436. }
  437. }
  438. }
  439. }
  440. }
  441. }