PlcAdapter.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Xml;
  7. using Aitex.Core.RT.DataCenter;
  8. using Aitex.Core.RT.Event;
  9. using Aitex.Core.RT.IOCore;
  10. using Aitex.Core.RT.Log;
  11. using Aitex.Core.RT.OperationCenter;
  12. using Aitex.Core.RT.SCCore;
  13. using Aitex.Core.Util;
  14. using MECF.Framework.Common.Communications;
  15. using MECF.Framework.Common.PLC;
  16. using MECF.Framework.RT.Core.IoProviders;
  17. using MECF.Framework.RT.Core.IoProviders.Common;
  18. namespace JetVirgoPM.Devices
  19. {
  20. public class PlcAdapter : IoProvider, IConnection
  21. {
  22. public string Address
  23. {
  24. get { return $"{_ip}:{_port}"; }
  25. }
  26. public bool IsConnected
  27. {
  28. get { return IsOpened; }
  29. }
  30. public bool Connect()
  31. {
  32. return true;
  33. }
  34. public bool Disconnect()
  35. {
  36. return true;
  37. }
  38. private string _localIp = "127.0.0.1";
  39. private int _socketId = 101;
  40. private int _stationId = 102;
  41. private byte[] _bufferIn;
  42. private byte[] _bufferOut;
  43. private IPlc _plc = null;
  44. private bool _isOpened = false;
  45. private string _ip = "192.168.10.10";
  46. private int _port = 9600;
  47. private int _aoBlockStartPosition = 1000;
  48. private int _aiBlockStartPosition = 2000;
  49. private int _doBlockStartPosition = 0;
  50. private int _diBlockStartPosition = 20;
  51. private string _diBlockType = "W";
  52. private string _doBlockType = "W";
  53. private string _aiBlockType = "D";
  54. private string _aoBlockType = "D";
  55. R_TRIG _failedTrigger = new R_TRIG();
  56. private Stopwatch stopwatchDi = new Stopwatch();
  57. private Stopwatch stopwatchDo = new Stopwatch();
  58. private Stopwatch stopwatchAi = new Stopwatch();
  59. private Stopwatch stopwatchAo = new Stopwatch();
  60. private int comunicationSpanDi;
  61. private int comunicationSpanDo;
  62. private int comunicationSpanAi;
  63. private int comunicationSpanAo;
  64. protected int comunicationSpanTotal;
  65. private Stopwatch stopwatchTotal = new Stopwatch();
  66. //private int diStartAddress;
  67. //private int doStartAddress;
  68. //private int aiStartAddress;
  69. //private int aoStartAddress;
  70. //private List<IoBlockItem> _blockSectionsDemand;
  71. private int plcCollectionInterval;
  72. private R_TRIG _trigConnected = new R_TRIG();
  73. public override void Initialize(string module, string name, List<IoBlockItem> lstBuffers, IIoBuffer buffer, XmlElement nodeParameter, string ioMappingPathFile, string ioModule)
  74. {
  75. Module = module;
  76. Name = name;
  77. _source = module + "." + name;
  78. _buffer = buffer;
  79. _nodeParameter = nodeParameter;
  80. _blockSections = lstBuffers;
  81. buffer.SetBufferBlock(_source, lstBuffers);
  82. buffer.SetIoMapByModule(_source, 0, ioMappingPathFile, ioModule);
  83. SetParameter(nodeParameter);
  84. State = IoProviderStateEnum.Uninitialized;
  85. plcCollectionInterval = SC.ContainsItem("System.PlcCollectionInterval") ? SC.GetValue<int>("System.PlcCollectionInterval") : 50;
  86. _thread = new PeriodicJob(plcCollectionInterval, OnTimer, name);
  87. ConnectionManager.Instance.Subscribe(Name, this);
  88. DATA.Subscribe($"{Module}.{Name}.IsConnected", () => _plc == null ? false : _plc.CheckIsConnected());
  89. OP.Subscribe($"{Module}.{Name}.Reconnect", (string cmd, object[] args) =>
  90. {
  91. Close();
  92. Open();
  93. return true;
  94. });
  95. //if (SC.GetValue<bool>("System.IsSimulatorMode"))
  96. //{
  97. // Open();
  98. //}
  99. }
  100. protected override bool OnTimer()
  101. {
  102. if (_plc == null)
  103. {
  104. Open();
  105. }
  106. if (State != IoProviderStateEnum.Opened || _plc == null || !_plc.CheckIsConnected())
  107. return true;
  108. _trigConnected.CLK = _plc.CheckIsConnected();
  109. try
  110. {
  111. stopwatchTotal.Start();
  112. foreach (var bufferSection in _blockSections)
  113. {
  114. if (bufferSection.Type == IoType.DI)
  115. {
  116. stopwatchDi.Start();
  117. bool[] diBuffer = ReadDi(bufferSection.Offset, bufferSection.Size);
  118. if (diBuffer != null)
  119. {
  120. _buffer.SetDiBuffer(_source, bufferSection.Offset, diBuffer);
  121. //TraceArray(diBuffer);
  122. }
  123. stopwatchDi.Stop();
  124. }
  125. else if (bufferSection.Type == IoType.AI)
  126. {
  127. stopwatchAi.Start();
  128. if (bufferSection.AIOType == typeof(float))
  129. {
  130. float[] aiBuffer = ReadAiFloat(bufferSection.Offset, bufferSection.Size);
  131. if (aiBuffer != null)
  132. {
  133. _buffer.SetAiBufferFloat(_source, bufferSection.Offset, aiBuffer);
  134. }
  135. }
  136. else
  137. {
  138. short[] aiBuffer = ReadAi(bufferSection.Offset, bufferSection.Size);
  139. if (aiBuffer != null)
  140. {
  141. _buffer.SetAiBuffer(_source, bufferSection.Offset, aiBuffer);
  142. }
  143. }
  144. stopwatchAi.Stop();
  145. }
  146. else if (bufferSection.Type == IoType.DO)
  147. {
  148. if (SC.GetValue<bool>("System.IsSimulatorMode"))
  149. {
  150. Dictionary<int, bool[]> dos = _buffer.GetDoBuffer(_source);
  151. if (dos != null)
  152. {
  153. foreach (var doo in dos)
  154. {
  155. WriteDo(_doBlockStartPosition, doo.Value);
  156. }
  157. }
  158. continue;
  159. }
  160. if (_trigConnected.Q)
  161. {
  162. bool[] doBuffer = ReadDo(bufferSection.Offset, bufferSection.Size);
  163. if (doBuffer != null)
  164. {
  165. _buffer.SetDoBuffer(_source, bufferSection.Offset, doBuffer);
  166. }
  167. }
  168. }
  169. else if (bufferSection.Type == IoType.AO)
  170. {
  171. if (bufferSection.AIOType == typeof(float))
  172. {
  173. if (SC.GetValue<bool>("System.IsSimulatorMode"))
  174. {
  175. Dictionary<int, float[]> aos = _buffer.GetAoBufferFloat(_source);
  176. if (aos != null)
  177. {
  178. foreach (var ao in aos)
  179. {
  180. WriteAoFloat(_aoBlockStartPosition, ao.Value);
  181. }
  182. }
  183. continue;
  184. }
  185. if (_trigConnected.Q)
  186. {
  187. float[] aoBuffer = ReadAoFloat(bufferSection.Offset, bufferSection.Size);
  188. if (aoBuffer != null)
  189. {
  190. _buffer.SetAoBufferFloat(_source, bufferSection.Offset, aoBuffer);
  191. }
  192. }
  193. }
  194. else
  195. {
  196. if (_trigConnected.Q)
  197. {
  198. short[] aoBuffer = ReadAo(bufferSection.Offset, bufferSection.Size);
  199. if (aoBuffer != null)
  200. {
  201. _buffer.SetAoBuffer(_source, bufferSection.Offset, aoBuffer);
  202. }
  203. }
  204. }
  205. }
  206. }
  207. comunicationSpanDi = (int)stopwatchDi.ElapsedMilliseconds;
  208. stopwatchDi.Reset();
  209. comunicationSpanAi = (int)stopwatchAi.ElapsedMilliseconds;
  210. stopwatchAi.Reset();
  211. //stopwatchAo.Start();
  212. //Dictionary<int, short[]> aos = _buffer.GetAoBuffer(_source);
  213. //if (aos != null)
  214. //{
  215. // foreach (var ao in aos)
  216. // {
  217. // WriteAo(aoStartAddress, ao.Value);
  218. // }
  219. //}
  220. //stopwatchAo.Stop();
  221. //comunicationSpanAo = (int)stopwatchAo.ElapsedMilliseconds;
  222. //stopwatchAo.Reset();
  223. //stopwatchDo.Start();
  224. //Dictionary<int, bool[]> dos = _buffer.GetDoBuffer(_source);
  225. //if (dos != null)
  226. //{
  227. // foreach (var doo in dos)
  228. // {
  229. // WriteDo(doStartAddress, doo.Value);
  230. // }
  231. //}
  232. //stopwatchDo.Stop();
  233. //comunicationSpanDo = (int)stopwatchDo.ElapsedMilliseconds;
  234. //stopwatchDo.Reset();
  235. stopwatchTotal.Stop();
  236. comunicationSpanTotal = (int)stopwatchTotal.ElapsedMilliseconds;
  237. stopwatchTotal.Reset();
  238. }
  239. catch (Exception ex)
  240. {
  241. LOG.Error($"{Name} {ex}");
  242. //SetState(IoProviderStateEnum.Error);
  243. Thread.Sleep(1000);
  244. Close();
  245. Open();
  246. }
  247. _trigError.CLK = State == IoProviderStateEnum.Error;
  248. if (_trigError.Q)
  249. {
  250. EV.PostAlarmLog(Module, $"{_source} PLC {_ip}:{_port} error");
  251. }
  252. _trigNotConnected.CLK = State != IoProviderStateEnum.Opened;
  253. if (_trigNotConnected.T)
  254. {
  255. EV.PostInfoLog(Module, $"{_source} connected");
  256. }
  257. if (_trigNotConnected.R)
  258. {
  259. EV.PostAlarmLog(Module, $"{_source} PLC {_ip}:{_port} not connected");
  260. }
  261. return true;
  262. }
  263. protected override void SetParameter(XmlElement nodeParameter)
  264. {
  265. string strIp = nodeParameter.GetAttribute("ip");
  266. string strPort = nodeParameter.GetAttribute("port");
  267. string localIp = nodeParameter.GetAttribute("localIp");
  268. string diBlockType = nodeParameter.GetAttribute("diBlockType");
  269. string doBlockType = nodeParameter.GetAttribute("doBlockType");
  270. string aiBlockType = nodeParameter.GetAttribute("aiBlockType");
  271. string aoBlockType = nodeParameter.GetAttribute("aoBlockType");
  272. string diStartPosition = nodeParameter.GetAttribute("diStartPosition");
  273. string doStartPosition = nodeParameter.GetAttribute("doStartPosition");
  274. string aiStartPosition = nodeParameter.GetAttribute("aiStartPosition");
  275. string aoStartPosition = nodeParameter.GetAttribute("aoStartPosition");
  276. _port = int.Parse(strPort);
  277. _ip = strIp;
  278. _localIp = localIp;
  279. //if (!Enum.TryParse(diBlockType, out _diBlockType))
  280. //{
  281. // LOG.Error($"plc config error, block type {diBlockType} not valid");
  282. //}
  283. //if (!Enum.TryParse(doBlockType, out _doBlockType))
  284. //{
  285. // LOG.Error($"plc config error, block type {doBlockType} not valid");
  286. //}
  287. //if (!Enum.TryParse(aiBlockType, out _aiBlockType))
  288. //{
  289. // LOG.Error($"plc config error, block type {aiBlockType} not valid");
  290. //}
  291. //if (!Enum.TryParse(aoBlockType, out _aoBlockType))
  292. //{
  293. // LOG.Error($"plc config error, block type {aoBlockType} not valid");
  294. //}
  295. _diBlockType = nodeParameter.GetAttribute("diBlockType").Substring(0, 1);
  296. _doBlockType = nodeParameter.GetAttribute("doBlockType").Substring(0, 1);
  297. _aiBlockType = nodeParameter.GetAttribute("aiBlockType").Substring(0, 1);
  298. _aoBlockType = nodeParameter.GetAttribute("aoBlockType").Substring(0, 1);
  299. if (!int.TryParse(diStartPosition, out _diBlockStartPosition))
  300. {
  301. LOG.Error($"plc config error, start position {diStartPosition} not valid");
  302. }
  303. if (!int.TryParse(doStartPosition, out _doBlockStartPosition))
  304. {
  305. LOG.Error($"plc config error, start position {doStartPosition} not valid");
  306. }
  307. if (!int.TryParse(aiStartPosition, out _aiBlockStartPosition))
  308. {
  309. LOG.Error($"plc config error, start position {aiStartPosition} not valid");
  310. }
  311. if (!int.TryParse(aoStartPosition, out _aoBlockStartPosition))
  312. {
  313. LOG.Error($"plc config error, start position {aoStartPosition} not valid");
  314. }
  315. }
  316. protected override void Open()
  317. {
  318. if (SC.GetValue<bool>("System.IsSimulatorMode"))
  319. {
  320. _plc = new WcfPlc(Module, Name, $"WcfPlc_{Module}");
  321. _plc.Initialize();
  322. }
  323. else
  324. {
  325. _plc = new FinsTcpPlc(_ip, _port, _localIp);
  326. }
  327. _bufferOut = new byte[2048];
  328. _bufferIn = new byte[2048];
  329. try
  330. {
  331. OperateResult connect = _plc.Connect() ? OperateResult.CreateSuccessResult() : new OperateResult();
  332. if (connect.IsSuccess)
  333. {
  334. SetState(IoProviderStateEnum.Opened);
  335. }
  336. }
  337. catch (Exception ex)
  338. {
  339. LOG.Error(ex.Message);
  340. }
  341. }
  342. protected override void Close()
  343. {
  344. _plc.Disconnect();
  345. SetState(IoProviderStateEnum.Closed);
  346. }
  347. protected override bool[] ReadDi(int offset, int size)
  348. {
  349. bool[] buff = DoReadDi(offset, (ushort)size);
  350. return buff;
  351. }
  352. protected bool[] ReadDo(int offset, int size)
  353. {
  354. bool[] buff = DoReadDo(offset, (ushort)size);
  355. return buff;
  356. }
  357. protected override short[] ReadAi(int offset, int size)
  358. {
  359. short[] buff = DoReadAi(offset, (ushort)size);
  360. return buff;
  361. }
  362. protected override float[] ReadAiFloat(int offset, int size)
  363. {
  364. float[] buff = DoReadAiFloat(offset, (ushort)size);
  365. return buff;
  366. }
  367. protected float[] ReadAoFloat(int offset, int size)
  368. {
  369. float[] buff = DoReadAoFloat(offset, (ushort)size);
  370. return buff;
  371. }
  372. protected short[] ReadAo(int offset, int size)
  373. {
  374. short[] buff = DoReadAo(offset, (ushort)size);
  375. return buff;
  376. }
  377. protected override void WriteDo(int offset, bool[] data)
  378. {
  379. DoWriteDo(offset, data);
  380. }
  381. protected override void WriteAo(int offset, short[] data)
  382. {
  383. DoWriteAo(offset, data);
  384. }
  385. protected override void WriteAoFloat(int offset, float[] data)
  386. {
  387. DoWriteAoFloat(offset, data);
  388. }
  389. #region PLC read write
  390. private short[] DoReadAi(int offset, ushort size)
  391. {
  392. if (_plc.ReadInt16($"{_aiBlockType}{_aiBlockStartPosition + offset}", out short[] result, size, out string reason))
  393. {
  394. return result;
  395. }
  396. LOG.Write(reason);
  397. return null;
  398. }
  399. private float[] DoReadAiFloat(int offset, ushort size)
  400. {
  401. if (_plc.ReadFloat($"{_aiBlockType}{_aiBlockStartPosition + offset}", out float[] result, size, out string reason))
  402. {
  403. return result;
  404. }
  405. LOG.Write(reason);
  406. return null;
  407. }
  408. private short[] DoReadAo(int offset, ushort size)
  409. {
  410. if (_plc.ReadInt16($"{_aoBlockType}{_aoBlockStartPosition + offset}", out short[] result, size, out string reason))
  411. {
  412. return result;
  413. }
  414. LOG.Write(reason);
  415. return null;
  416. }
  417. private float[] DoReadAoFloat(int offset, ushort size)
  418. {
  419. if (_plc.ReadFloat($"{_aoBlockType}{_aoBlockStartPosition + offset}", out float[] result, size, out string reason))
  420. {
  421. return result;
  422. }
  423. LOG.Write(reason);
  424. return null;
  425. }
  426. private bool DoWriteAoFloat(int offset, float[] data, int total = 0, int count = 100)
  427. {
  428. if (_plc.WriteFloat($"{_aoBlockType}{_aoBlockStartPosition + offset}", data, out string reason))
  429. {
  430. return true;
  431. }
  432. LOG.Write(reason);
  433. return false;
  434. }
  435. private bool DoWriteAo(int offset, short[] data, int total = 0, int count = 100)
  436. {
  437. if (_plc.WriteInt16($"{_aoBlockType}{_aoBlockStartPosition + offset}", data, out string reason))
  438. {
  439. return true;
  440. }
  441. LOG.Write(reason);
  442. return false;
  443. }
  444. private bool[] DoReadDi(int offset, ushort size)
  445. {
  446. if (_plc.ReadBool($"{_diBlockType}{_diBlockStartPosition + (offset >> 4)}.{offset & 0x0f}", out bool[] result, size, out string reason))
  447. {
  448. return result;
  449. }
  450. LOG.Write(reason);
  451. return null;
  452. }
  453. private bool[] DoReadDo(int offset, ushort size)
  454. {
  455. if (_plc.ReadBool($"{_doBlockType}{_doBlockStartPosition + (offset >> 4)}.{offset & 0x0f}", out bool[] result, size, out string reason))
  456. {
  457. return result;
  458. }
  459. LOG.Write(reason);
  460. return null;
  461. }
  462. private bool DoWriteDo(int offset, bool[] data)
  463. {
  464. if (_plc.WriteBool($"{_doBlockType}{_doBlockStartPosition + (offset >> 4)}.{offset & 0x0f}", data, out string reason))
  465. {
  466. return true;
  467. }
  468. LOG.Write(reason);
  469. return false;
  470. }
  471. #endregion
  472. public override bool SetValue(AOAccessor aoItem, short value)
  473. {
  474. if (State != IoProviderStateEnum.Opened)
  475. return false;
  476. return true;
  477. }
  478. public override bool SetValueFloat(AOAccessor aoItem, float value)
  479. {
  480. if (State != IoProviderStateEnum.Opened)
  481. return false;
  482. return DoWriteAoFloat(aoItem.Index << 1, new[] { value });
  483. }
  484. public override bool SetValue(DOAccessor doItem, bool value)
  485. {
  486. if (State != IoProviderStateEnum.Opened)
  487. return false;
  488. return DoWriteDo(doItem.Index, new[] { value });
  489. }
  490. }
  491. }