PlcAdapter.cs 19 KB

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