PlcService.cs 12 KB

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