MCProtocolPlcSimulator.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Runtime.InteropServices;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Windows;
  15. using Aitex.Core.RT.Log;
  16. using Aitex.Core.Util;
  17. using MECF.Framework.RT.Core.IoProviders;
  18. namespace MECF.Framework.Simulator.Core.IoProviders
  19. {
  20. public class PlcBuffer
  21. {
  22. public IoType Type;
  23. public int Offset;
  24. public int Size;
  25. public byte[] Buffer;
  26. public bool[] BoolValue;
  27. public ushort[] ShortValue;
  28. }
  29. public class MCProtocolPlcSimulator
  30. {
  31. public event Action<string> NotifyEvent;
  32. private PeriodicJob _threadSocket;
  33. private PeriodicJob _threadTimer;
  34. private Socket _socketServer;
  35. private string _ip;
  36. private bool _stopFlag;
  37. protected List<PlcBuffer> _buffers = new List<PlcBuffer>();
  38. private int _port = 6731;
  39. private int _socketId = 101;
  40. private int _stationId = 102;
  41. private byte[] _bufferIn;
  42. private byte[] _bufferOut;
  43. private MCProtocol.MC_RESPONSE_HEADER _response;
  44. public MCProtocolPlcSimulator(string ip, int port)
  45. {
  46. _ip = ip;
  47. _port = port;
  48. _response = new MCProtocol.MC_RESPONSE_HEADER()
  49. {
  50. ProtocolId = MCProtocol.MC_SUBHEADER_RESPONSE_MESSAGE,
  51. NetworkId = (byte)_socketId,
  52. StationId = (byte)_stationId,
  53. RequestIoNumber = MCProtocol.MC_REQUEST_MODULE_IO_NUMBER,
  54. RequestStationNumber = MCProtocol.MC_REQUEST_MODULE_STATION_NUMBER,
  55. ResponseDataLen = 0,
  56. CompleteCode = (ushort)(MCProtocol.MC_COMPLETE_CODE_SUCCESS ),
  57. };
  58. _bufferOut = new byte[2048];
  59. _bufferIn = new byte[2048];
  60. _socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  61. _threadSocket = new PeriodicJob(50, OnMonitor, "MCProtocolPlcSimulator",true);
  62. _threadTimer = new PeriodicJob(1000, OnTimer, "MCProtocolPlcSimulatorTimer", true);
  63. }
  64. protected virtual bool OnTimer()
  65. {
  66. return true;
  67. }
  68. private void PerformNotifyEvent(string msg)
  69. {
  70. if (NotifyEvent != null)
  71. {
  72. NotifyEvent(msg);
  73. }
  74. }
  75. private bool OnMonitor()
  76. {
  77. try
  78. {
  79. EndPoint ep = new IPEndPoint(IPAddress.Loopback, _port);
  80. _socketServer.Bind(ep);
  81. _socketServer.Listen(3);
  82. Socket s;
  83. while (!_stopFlag)
  84. {
  85. PerformNotifyEvent("Waiting for connection ...");
  86. s = _socketServer.Accept();
  87. PerformNotifyEvent("Connected.");
  88. s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
  89. try
  90. {
  91. while (!_stopFlag && OnTransmission(s))
  92. {
  93. PerformNotifyEvent("Waiting for another command ...");
  94. }
  95. PerformNotifyEvent("receive error buffer content and exit ...");
  96. }
  97. catch (Exception ex)
  98. {
  99. LOG.WriteExeption(ex);
  100. return true;
  101. }
  102. PerformNotifyEvent("A client disconnected from port " + _port);
  103. s = null;
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. LOG.WriteExeption(ex);
  109. try
  110. {
  111. _socketServer.Close();
  112. }
  113. catch (Exception )
  114. {
  115. }
  116. _socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  117. return true;
  118. }
  119. return true;
  120. }
  121. public void Start()
  122. {
  123. _threadSocket.Start();
  124. }
  125. public void Stop()
  126. {
  127. _stopFlag = true;
  128. _threadSocket.Stop();
  129. }
  130. protected bool OnTransmission(Socket s)
  131. {
  132. int size = s.Receive(_bufferIn, 0, MCProtocol.MC_QHEADER_COMMAND_SIZE, SocketFlags.None);
  133. if (size < MCProtocol.MC_QHEADER_COMMAND_SIZE)
  134. {
  135. return false;
  136. }
  137. MCProtocol.MC_COMMAND_HEADER header = MCProtocol.ToStruct<MCProtocol.MC_COMMAND_HEADER>(_bufferIn);
  138. int dataLength = header.RequestDataLen - MCProtocol.MC_BATCH_COMMAND_SIZE - MCProtocol.JUNK_SIZE;
  139. if (dataLength < 0)
  140. {
  141. return false;
  142. }
  143. size = s.Receive(_bufferIn, 0, MCProtocol.MC_BATCH_COMMAND_SIZE, SocketFlags.None);
  144. if (size < MCProtocol.MC_BATCH_COMMAND_SIZE)
  145. {
  146. return false;
  147. }
  148. MCProtocol.MC_BATCH_COMMAND cmd = MCProtocol.ToStruct<MCProtocol.MC_BATCH_COMMAND>(_bufferIn);
  149. if (dataLength > 0)
  150. {
  151. size = s.Receive(_bufferIn, 0, dataLength, SocketFlags.None);
  152. if (size < dataLength)
  153. {
  154. return false;
  155. }
  156. }
  157. int offset = cmd.Reserved * (0xFFFF+1) + cmd.HeadAddr;
  158. byte[] data = null;
  159. if (cmd.Command == MCProtocol.MC_COMMAND_BATCH_READ)
  160. {
  161. data = GetData(offset, cmd.DevicePoints, cmd.SubCommand == MCProtocol.MC_SUBCOMMAND_BIT_UNITS);
  162. }
  163. else
  164. {
  165. SetData(offset, _bufferIn, dataLength, cmd.SubCommand == MCProtocol.MC_SUBCOMMAND_BIT_UNITS);
  166. }
  167. _response.ResponseDataLen = (ushort)(MCProtocol.JUNK_SIZE + (data == null ? 0 : data.Length));
  168. byte[] response = MCProtocol.Struct2Bytes(_response);
  169. Array.Copy(response, 0, _bufferOut, 0, response.Length);
  170. s.Send(_bufferOut, response.Length, SocketFlags.None);
  171. if (data != null)
  172. {
  173. Array.Copy(data, 0, _bufferOut, 0, data.Length);
  174. s.Send(_bufferOut, data.Length, SocketFlags.None);
  175. }
  176. return true;
  177. }
  178. protected void SetData(int headAddr, byte[] data, int length, bool isBit)
  179. {
  180. IoType ioType = isBit ? IoType.DO : IoType.AO;
  181. if (ioType == IoType.DO)
  182. {
  183. bool[] boolData = MCProtocol.TransByteDataToBoolArray(data, 0, length);
  184. PlcBuffer buffer = _buffers.Find(x => x.Offset == headAddr && x.Type == ioType && x.Size == boolData.Length);
  185. if (buffer != null)
  186. {
  187. buffer.BoolValue = boolData;
  188. }
  189. }
  190. else
  191. {
  192. ushort[] shortValue = MCProtocol.Byte2Ushort(data, 0, length);
  193. PlcBuffer buffer = _buffers.Find(x => x.Offset == headAddr && x.Type == ioType && x.Size == shortValue.Length);
  194. if (buffer != null)
  195. {
  196. buffer.ShortValue = shortValue;
  197. }
  198. }
  199. }
  200. protected void SetDi(int headAddr, int offset, bool value)
  201. {
  202. PlcBuffer buffer = _buffers.Find(x => x.Offset == headAddr && x.Type == IoType.DI );
  203. if (buffer != null)
  204. {
  205. buffer.BoolValue[offset] = value;
  206. }
  207. }
  208. protected void SetAi(int headAddr, int offset, ushort value)
  209. {
  210. PlcBuffer buffer = _buffers.Find(x => x.Offset == headAddr && x.Type == IoType.AI );
  211. if (buffer != null)
  212. {
  213. buffer.ShortValue[offset] = value;
  214. }
  215. }
  216. protected virtual byte[] GetData(int headAddr, ushort length, bool isBit)
  217. {
  218. IoType ioType = isBit ? IoType.DI : IoType.AI;
  219. PlcBuffer buffer = _buffers.Find(x => x.Offset == headAddr && x.Type == ioType && x.Size == length);
  220. if (buffer == null)
  221. {
  222. return null;
  223. }
  224. byte[] result = null;
  225. if (ioType == IoType.DI)
  226. {
  227. bool[] value = buffer.BoolValue;
  228. int size = (value.Length + 1) / 2;
  229. result = new byte[size];
  230. for (int i = 0; i < size; i++)
  231. {
  232. if (value[i * 2 + 0])
  233. result[i] += 0x10;
  234. if ((i * 2 + 1) < value.Length)
  235. {
  236. if (value[i * 2 + 1])
  237. result[i] += 0x01;
  238. }
  239. }
  240. //result = MCProtocol.TransBoolArrayToByteData(buffer.BoolValue);
  241. }
  242. else
  243. {
  244. result = MCProtocol.Ushort2Byte(buffer.ShortValue);
  245. }
  246. return result;
  247. }
  248. }
  249. }