FinsProtocolPlc.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. using Aitex.Core.RT.DataCenter;
  2. using Aitex.Core.RT.Event;
  3. using Aitex.Core.RT.IOCore;
  4. using Aitex.Core.RT.Log;
  5. using Aitex.Core.RT.OperationCenter;
  6. using Aitex.Core.RT.SCCore;
  7. using Aitex.Core.Util;
  8. using HslCommunication;
  9. using HslCommunication.Profinet.Omron;
  10. using MECF.Framework.Common.Communications;
  11. using MECF.Framework.RT.Core.IoProviders;
  12. using MECF.Framework.RT.Core.IoProviders.Mitsubishis;
  13. using System;
  14. using System.Collections;
  15. using System.Collections.Generic;
  16. using System.Diagnostics;
  17. using System.Linq;
  18. using System.Net;
  19. using System.Net.Sockets;
  20. using System.Text;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using System.Xml;
  24. namespace FurnaceRT.Equipments.Systems
  25. {
  26. public class FinsProtocolPlc : IoProvider, IConnection
  27. {
  28. public string Address
  29. {
  30. get { return $"{_ip}:{_port}"; }
  31. }
  32. public bool IsConnected
  33. {
  34. get { return IsOpened; }
  35. }
  36. public bool Connect()
  37. {
  38. return true;
  39. }
  40. public bool Disconnect()
  41. {
  42. return true;
  43. }
  44. private string _ip = "127.0.0.1";
  45. private string _localIp = "127.0.0.1";
  46. private int _port = 6731;
  47. private int _socketId = 101;
  48. private int _stationId = 102;
  49. private byte[] _bufferIn;
  50. private byte[] _bufferOut;
  51. private OmronFinsUdp _omronFinsUdp = null;
  52. private string _aiStoragename = "R";
  53. private string _aoStoragename = "R";
  54. private string _diStoragename = "B";
  55. private string _doStoragename = "B";
  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 R_TRIG _trigReadDoAndAo = new R_TRIG();
  67. private int _diStartAddress;
  68. private int _doStartAddress;
  69. private int _aiStartAddress;
  70. private int _aoStartAddress;
  71. //private List<IoBlockItem> _blockSectionsDemand;
  72. public override void Initialize(string module, string name, List<IoBlockItem> lstBuffers, IIoBuffer buffer, XmlElement nodeParameter, Dictionary<int, string> ioMappingPathFile)
  73. {
  74. Module = module;
  75. Name = name;
  76. _source = module + "." + name;
  77. _buffer = buffer;
  78. _nodeParameter = nodeParameter;
  79. SetParameter(nodeParameter);
  80. _blockSections = lstBuffers;
  81. buffer.SetBufferBlock(_source, lstBuffers);
  82. buffer.SetIoMap(_source, ioMappingPathFile);
  83. State = IoProviderStateEnum.Uninitialized;
  84. _thread = new PeriodicJob(30, OnTimer, name);
  85. ConnectionManager.Instance.Subscribe(Name, this);
  86. OP.Subscribe($"{Name}.Reconnect", (string cmd, object[] args) =>
  87. {
  88. Close();
  89. Open();
  90. return true;
  91. });
  92. }
  93. protected override bool OnTimer()
  94. {
  95. if (State == IoProviderStateEnum.Uninitialized)
  96. {
  97. SetState(IoProviderStateEnum.Opening);
  98. Open();
  99. }
  100. if (State == IoProviderStateEnum.Opened)
  101. {
  102. try
  103. {
  104. stopwatchTotal.Start();
  105. foreach (var bufferSection in _blockSections)
  106. {
  107. if (bufferSection.Type == IoType.DI)
  108. {
  109. stopwatchDi.Start();
  110. bool[] diBuffer = ReadDi(bufferSection.Offset, bufferSection.Size);
  111. if (diBuffer != null)
  112. {
  113. _buffer.SetDiBuffer(_source, bufferSection.Offset, diBuffer);
  114. //TraceArray(diBuffer);
  115. }
  116. stopwatchDi.Stop();
  117. }
  118. else if (bufferSection.Type == IoType.DO)
  119. {
  120. stopwatchDo.Start();
  121. if (!_trigReadDoAndAo.M)
  122. {
  123. bool[] doBuffer = ReadDo(bufferSection.Offset, bufferSection.Size);
  124. if (doBuffer != null)
  125. {
  126. _buffer.SetDoBuffer(_source, bufferSection.Offset, doBuffer);
  127. //TraceArray(diBuffer);
  128. }
  129. }
  130. stopwatchDo.Stop();
  131. }
  132. else if (bufferSection.Type == IoType.AI)
  133. {
  134. stopwatchAi.Start();
  135. short[] aiBuffer = ReadAi(bufferSection.Offset, bufferSection.Size);
  136. if (aiBuffer != null)
  137. {
  138. _buffer.SetAiBuffer(_source, bufferSection.Offset, aiBuffer);
  139. }
  140. stopwatchAi.Stop();
  141. }
  142. else if (bufferSection.Type == IoType.AO)
  143. {
  144. stopwatchAo.Start();
  145. if (!_trigReadDoAndAo.M)
  146. {
  147. short[] aoBuffer = ReadAo(bufferSection.Offset, bufferSection.Size);
  148. if (aoBuffer != null)
  149. {
  150. _buffer.SetAoBuffer(_source, bufferSection.Offset, aoBuffer);
  151. }
  152. }
  153. stopwatchAo.Stop();
  154. }
  155. }
  156. if (!_trigReadDoAndAo.M)
  157. _trigReadDoAndAo.CLK = true;
  158. comunicationSpanDi = (int)stopwatchDi.ElapsedMilliseconds;
  159. stopwatchDi.Reset();
  160. comunicationSpanDo = (int)stopwatchDo.ElapsedMilliseconds;
  161. stopwatchDo.Reset();
  162. comunicationSpanAi = (int)stopwatchAi.ElapsedMilliseconds;
  163. stopwatchAi.Reset();
  164. comunicationSpanAo = (int)stopwatchAo.ElapsedMilliseconds;
  165. stopwatchAo.Reset();
  166. stopwatchAo.Start();
  167. Dictionary<int, short[]> aos = _buffer.GetAoBuffer(_source);
  168. if (aos != null)
  169. {
  170. foreach (var ao in aos)
  171. {
  172. WriteAo(ao.Key, ao.Value);
  173. }
  174. }
  175. stopwatchAo.Stop();
  176. comunicationSpanAo = (int)stopwatchAo.ElapsedMilliseconds;
  177. stopwatchAo.Reset();
  178. stopwatchDo.Start();
  179. Dictionary<int, bool[]> dos = _buffer.GetDoBuffer(_source);
  180. if (dos != null)
  181. {
  182. foreach (var doo in dos)
  183. {
  184. WriteDo(doo.Key, doo.Value);
  185. }
  186. }
  187. stopwatchDo.Stop();
  188. comunicationSpanDo = (int)stopwatchDo.ElapsedMilliseconds;
  189. stopwatchDo.Reset();
  190. stopwatchTotal.Stop();
  191. comunicationSpanTotal = (int)stopwatchTotal.ElapsedMilliseconds;
  192. stopwatchTotal.Reset();
  193. }
  194. catch (Exception ex)
  195. {
  196. LOG.Write($"{Name} {ex}");
  197. //SetState(IoProviderStateEnum.Error);
  198. Thread.Sleep(1000);
  199. Close();
  200. Open();
  201. }
  202. }
  203. _trigError.CLK = State == IoProviderStateEnum.Error;
  204. if (_trigError.Q)
  205. {
  206. EV.PostAlarmLog(Module, $"{_source} PLC {_ip}:{_port} error");
  207. }
  208. _trigNotConnected.CLK = State != IoProviderStateEnum.Opened;
  209. if (_trigNotConnected.T)
  210. {
  211. EV.PostInfoLog(Module, $"{_source} connected");
  212. }
  213. if (_trigNotConnected.R)
  214. {
  215. EV.PostAlarmLog(Module, $"{_source} PLC {_ip}:{_port} not connected");
  216. }
  217. return true;
  218. }
  219. protected override void SetParameter(XmlElement nodeParameter)
  220. {
  221. string strIp = nodeParameter.GetAttribute("ip");
  222. //_localIp = nodeParameter.GetAttribute("localIp");
  223. string strPort = nodeParameter.GetAttribute("port");
  224. string networkId = nodeParameter.GetAttribute("network_id");
  225. string stationId = nodeParameter.GetAttribute("station_id");
  226. _aiStoragename = nodeParameter.GetAttribute("aiStoragename");
  227. _aoStoragename = nodeParameter.GetAttribute("aoStoragename");
  228. _diStoragename = nodeParameter.GetAttribute("diStoragename");
  229. _doStoragename = nodeParameter.GetAttribute("doStoragename");
  230. int.TryParse(nodeParameter.GetAttribute("doStartAddress"), out _doStartAddress);
  231. int.TryParse(nodeParameter.GetAttribute("diStartAddress"), out _diStartAddress);
  232. int.TryParse(nodeParameter.GetAttribute("aoStartAddress"), out _aoStartAddress);
  233. int.TryParse(nodeParameter.GetAttribute("aiStartAddress"), out _aiStartAddress);
  234. _port = int.Parse(strPort);
  235. _ip = strIp;
  236. _socketId = int.Parse(networkId);
  237. _stationId = int.Parse(stationId);
  238. }
  239. protected override void Open()
  240. {
  241. _bufferOut = new byte[2048];
  242. _bufferIn = new byte[2048];
  243. _omronFinsUdp = new OmronFinsUdp(_ip, _port);
  244. SetState(IoProviderStateEnum.Opened);
  245. }
  246. protected override void Close()
  247. {
  248. SetState(IoProviderStateEnum.Closed);
  249. }
  250. protected override bool[] ReadDi(int offset, int size)
  251. {
  252. bool[] ret = new bool[size];
  253. string address = $"{_diStoragename}{offset + _diStartAddress}";
  254. if (_diStoragename == "B")
  255. {
  256. address = $"{_diStoragename}{(offset + _diStartAddress).ToString("X")}";
  257. }
  258. ushort readsize = (ushort)(size / 16);
  259. if (size % 16 != 0) readsize += 1;
  260. OperateResult<ushort[]> result = _omronFinsUdp.ReadUInt16(address, (ushort)readsize);
  261. if (!result.IsSuccess)
  262. {
  263. LOG.Write($"PLC {_omronFinsUdp.IpAddress} read DI failed:{result.Message}.");
  264. return null;
  265. }
  266. for (int i = 0; i < size; i++)
  267. {
  268. int valueIndex = i / 16;
  269. int valueOffset = i % 16;
  270. ret[i] = ((result.Content[valueIndex] & (short)Math.Pow(2, valueOffset)) == Math.Pow(2, valueOffset));
  271. }
  272. return ret;
  273. }
  274. protected bool[] ReadDo(int offset, int size)
  275. {
  276. bool[] ret = new bool[size];
  277. string address = $"{_doStoragename}{offset + _doStartAddress}";
  278. if (_doStoragename == "B")
  279. {
  280. address = $"{_doStoragename}{(offset + _doStartAddress).ToString("X")}";
  281. }
  282. ushort readsize = (ushort)(size / 16);
  283. if (size % 16 != 0) readsize += 1;
  284. OperateResult<ushort[]> result = _omronFinsUdp.ReadUInt16(address, (ushort)readsize);
  285. if (!result.IsSuccess)
  286. {
  287. LOG.Write($"PLC {_omronFinsUdp.IpAddress} read DO failed:{result.Message}.");
  288. return null;
  289. }
  290. for (int i = 0; i < size; i++)
  291. {
  292. int valueIndex = i / 16;
  293. int valueOffset = i % 16;
  294. ret[i] = ((result.Content[valueIndex] & (short)Math.Pow(2, valueOffset)) == Math.Pow(2, valueOffset));
  295. }
  296. return ret;
  297. }
  298. protected override short[] ReadAi(int offset, int size)
  299. {
  300. OperateResult<short[]> result = _omronFinsUdp.ReadInt16($"{_aiStoragename}{offset + _aiStartAddress}", (ushort)size);
  301. if (result.IsSuccess)
  302. return result.Content;
  303. LOG.Write($"PLC {_omronFinsUdp.IpAddress} read AI failed,error code:{result.ErrorCode},{result.Message}.");
  304. return null;
  305. }
  306. protected short[] ReadAo(int offset, int size)
  307. {
  308. OperateResult<short[]> result = _omronFinsUdp.ReadInt16($"{_aoStoragename}{offset + _aoStartAddress}", (ushort)size);
  309. if (result.IsSuccess)
  310. return result.Content;
  311. LOG.Write($"PLC {_omronFinsUdp.IpAddress} read AO failed,error code:{result.ErrorCode},{result.Message}.");
  312. return null;
  313. }
  314. protected override void WriteDo(int offset, bool[] buffer)
  315. {
  316. string address;
  317. OperateResult result = new OperateResult();
  318. int shortsize = (buffer.Length - 1) / 16 + 1;
  319. ushort[] value = new ushort[shortsize];
  320. for (int i = 0; i < shortsize; i++)
  321. {
  322. value[i] = 0;
  323. for (int j = i * 16; j < (i + 1) * 16; j++)
  324. {
  325. if (buffer.Length > j && buffer[j])
  326. {
  327. value[i] += (ushort)Math.Pow(2, j - (16 * i));
  328. }
  329. }
  330. }
  331. address = $"{_doStoragename}{offset + _doStartAddress}";
  332. if (_doStoragename == "B")
  333. {
  334. address = $"{_doStoragename}{(offset + _doStartAddress).ToString("X")}";
  335. }
  336. result = _omronFinsUdp.Write(address, value);
  337. if (result.IsSuccess)
  338. return;
  339. LOG.Write($"PLC {_omronFinsUdp.IpAddress} write DO failed:{result.Message}.");
  340. }
  341. protected override void WriteAo(int offset, short[] buffer)
  342. {
  343. OperateResult result;
  344. int startAddress = offset + _aoStartAddress;
  345. int blockCount = (buffer.Length - 1) / 960 + 1;
  346. for (int i = 0; i < blockCount; i++)
  347. {
  348. if (i == blockCount - 1)
  349. {
  350. result = _omronFinsUdp.Write($"{_aoStoragename}{startAddress + i * 960}", buffer.Skip(i * 960).Take(buffer.Length - 960 * i).ToArray());
  351. }
  352. else
  353. {
  354. result = _omronFinsUdp.Write($"{_aoStoragename}{startAddress + i * 960}", buffer.Skip(i * 960).Take(960).ToArray());
  355. }
  356. if (!result.IsSuccess)
  357. LOG.Write($"PLC {_omronFinsUdp.IpAddress} write AO failed:{result.Message}.");
  358. }
  359. }
  360. }
  361. }