PlcService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. if (p.Index==number)
  198. {
  199. id = kvp.Key;
  200. plc = kvp.Value;
  201. return true;
  202. }
  203. }
  204. }
  205. id = Guid.Empty;
  206. plc = null;
  207. return false;
  208. }
  209. public void Dispose()
  210. {
  211. List<IPlc> plcs;
  212. lock (_sync)
  213. {
  214. plcs = _plcCollection.Values.ToList();
  215. _plcCollection.Clear();
  216. }
  217. foreach (var p in plcs)
  218. {
  219. try
  220. {
  221. p.Dispose();
  222. }
  223. catch
  224. {
  225. // 忽略单个释放异常
  226. }
  227. }
  228. GC.SuppressFinalize(this);
  229. }
  230. public (bool IsSucceed, string Message) InitializePlc(PlcInfo[] plcs)
  231. {
  232. if (plcs == null)
  233. {
  234. return (false, "plcs 参数为 null。");
  235. }
  236. if (plcs.Length == 0)
  237. {
  238. return (true, "没有需要初始化的 PLC。");
  239. }
  240. var failures = new List<string>();
  241. var successes = 0;
  242. for (var i = 0; i < plcs.Length; i++)
  243. {
  244. var info = plcs[i];
  245. if (info == null)
  246. {
  247. failures.Add($"索引 {i}: PlcInfo 为 null。");
  248. continue;
  249. }
  250. // 尝试从 plcInfo 中提取编号(若有)
  251. int? number = null;
  252. try
  253. {
  254. var infoType = info.GetType();
  255. var numberProp = infoType.GetProperty("PlcNo") ?? infoType.GetProperty("PlcNumber") ?? infoType.GetProperty("Number") ?? infoType.GetProperty("No");
  256. if (numberProp != null)
  257. {
  258. var raw = numberProp.GetValue(info);
  259. if (raw != null)
  260. {
  261. if (raw is int ri) number = ri;
  262. else
  263. {
  264. try
  265. {
  266. number = Convert.ToInt32(raw);
  267. }
  268. catch
  269. {
  270. number = null;
  271. }
  272. }
  273. }
  274. }
  275. }
  276. catch
  277. {
  278. number = null;
  279. }
  280. // 如果存在相同编号的 PLC,则先卸载它
  281. try
  282. {
  283. if (number.HasValue)
  284. {
  285. if (TryFindPlcByNumber(number.Value, out var existingId, out var existingPlc))
  286. {
  287. try
  288. {
  289. UnRegisterPlc(existingId);
  290. }
  291. catch
  292. {
  293. // 忽略单个卸载异常,之后尝试创建新的实例
  294. }
  295. }
  296. }
  297. }
  298. catch
  299. {
  300. // 忽略查找/卸载过程中的异常,继续尝试创建
  301. }
  302. var id = Guid.NewGuid();
  303. bool created;
  304. try
  305. {
  306. created = CreatePlc(id, info);
  307. }
  308. catch (Exception ex)
  309. {
  310. created = false;
  311. failures.Add($"索引 {i}{(number.HasValue ? $" (编号 {number.Value})" : "")}: 创建 PLC 时抛出异常:{ex.Message}");
  312. }
  313. if (!created)
  314. {
  315. failures.Add($"索引 {i}{(number.HasValue ? $" (编号 {number.Value})" : "")}: 创建 PLC 失败。");
  316. }
  317. else
  318. {
  319. successes++;
  320. }
  321. }
  322. if (failures.Count == 0)
  323. {
  324. return (true, $"已成功初始化 {successes} 个 PLC。");
  325. }
  326. var message = $"初始化完成:成功 {successes},失败 {failures.Count}。失败原因:{string.Join(" | ", failures)}";
  327. return (false, message);
  328. }
  329. public Task<(bool IsSucceed, string Message)> InitializePlcAsync(PlcInfo[] plcs)
  330. {
  331. return Task.Run(() => InitializePlc(plcs));
  332. }
  333. public bool RemoveAllPlcs()
  334. {
  335. List<IPlc> plcs;
  336. lock (_sync)
  337. {
  338. if (_plcCollection.Count == 0) return false;
  339. plcs = _plcCollection.Values.ToList();
  340. _plcCollection.Clear();
  341. }
  342. var removedAny = false;
  343. foreach (var p in plcs)
  344. {
  345. if (p == null) continue;
  346. try
  347. {
  348. p.Dispose();
  349. removedAny = true;
  350. }
  351. catch
  352. {
  353. // 忽略单个释放异常
  354. removedAny = true; // 已尝试移除,仍视为移除过
  355. }
  356. }
  357. return removedAny;
  358. }
  359. public Task<bool> RemoveAllPlcsAsync()
  360. {
  361. var result = RemoveAllPlcs();
  362. return Task.FromResult(result);
  363. }
  364. /// <summary>
  365. /// 更新PLC编号
  366. /// </summary>
  367. /// <param name="id"></param>
  368. /// <param name="newNumber"></param>
  369. public void UpdatePlcNumber(Guid id, int newNumber)
  370. {
  371. lock (_sync)
  372. {
  373. if (_plcCollection.TryGetValue(id, out var plc))
  374. {
  375. if (plc != null)
  376. {
  377. plc.Index=newNumber;
  378. }
  379. }
  380. }
  381. }
  382. }
  383. }