CognexAsyncSocket.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. using Aitex.Core.RT.Event;
  2. using Aitex.Core.RT.Log;
  3. using MECF.Framework.Common.Equipment;
  4. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.Cognex
  14. {
  15. public class CognexAsyncSocket : ICommunication, IDisposable
  16. {
  17. public delegate void ErrorHandler(ErrorEventArgs args);
  18. public event ErrorHandler OnErrorHappened;
  19. public delegate void MessageHandler(string message);
  20. public event MessageHandler OnDataChanged;
  21. private static Object _locker = new Object();
  22. public class ClientStateObject
  23. {
  24. // Client socket.
  25. public Socket workSocket = null;
  26. // Size of receive buffer.
  27. public static int BufferSize = 256;
  28. // Receive buffer.
  29. public byte[] buffer = new byte[BufferSize];
  30. // Received data string.
  31. public StringBuilder sb = new StringBuilder();
  32. public ClientStateObject(int bufferSize = 256)
  33. {
  34. BufferSize = bufferSize;
  35. buffer = new byte[bufferSize];
  36. }
  37. }
  38. public string NewLine { get; set; }
  39. public bool NeedLog { get; set; } = true;
  40. private Socket _socket;
  41. private string _ip;
  42. private int _port;
  43. private string _address;
  44. private int _bufferSize = 256;
  45. public bool IsConnected { get { return (_socket != null && _socket.Connected); } } //&& !_socket.Poll(100, SelectMode.SelectRead)); } }
  46. public bool IsHstConnected { get { return (_socket != null && IsSocketConnected(_socket)); } }
  47. private bool IsSocketConnected(Socket client)
  48. {
  49. try
  50. {
  51. byte[] tmp = new byte[] { 0x0 };
  52. //int a= newclient.Receive(tmp);
  53. int a = client.Send(tmp);
  54. if (a == 1)
  55. return true;
  56. else
  57. return false;
  58. }
  59. catch (SocketException e)
  60. {
  61. LOG.Write(e.Message);
  62. return false;
  63. }
  64. }
  65. public CognexAsyncSocket(string address, string newline = "\r")
  66. {
  67. // Connect(address);
  68. _socket = null;
  69. NewLine = newline;
  70. _address = address;
  71. }
  72. public CognexAsyncSocket(string address, int bufferSize, string newline = "\r")
  73. {
  74. _socket = null;
  75. NewLine = newline;
  76. _address = address;
  77. _bufferSize = bufferSize;
  78. }
  79. ~CognexAsyncSocket()
  80. {
  81. Dispose();
  82. }
  83. public void Connect(string address)
  84. {
  85. try
  86. {
  87. _ip = address.Split(':')[0];
  88. _port = int.Parse(address.Split(':')[1]);
  89. IPAddress ipAddress = IPAddress.Parse(_ip);
  90. IPEndPoint remoteEP = new IPEndPoint(ipAddress, _port);
  91. lock (_locker)
  92. {
  93. //Dispose current socket and create a TCP/IP socket.
  94. Dispose();
  95. if (_socket == null)
  96. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  97. // Connect to the remote endpoint.
  98. _socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), _socket);
  99. }
  100. }
  101. catch (Exception e)
  102. {
  103. LOG.Write(e);
  104. throw new Exception(e.ToString());
  105. }
  106. }
  107. private void ConnectCallback(IAsyncResult ar)
  108. {
  109. try
  110. {
  111. // Retrieve the socket from the state object.
  112. Socket client = (Socket)ar.AsyncState;
  113. // Complete the connection.
  114. client.EndConnect(ar);
  115. EV.PostMessage(ModuleName.Robot.ToString(), EventEnum.TCPConnSucess, _ip, _port.ToString());
  116. // Receive the response from the remote device.
  117. Receive(_socket);
  118. }
  119. catch (Exception e)
  120. {
  121. LOG.Write(e);
  122. string reason = string.Format("Communication {0}:{1:D} {2}.", _ip, _port, e.Message);
  123. LOG.Error(reason);
  124. // EV.PostMessage(UnitName.Transfer.ToString(), EventEnum.RobotCommandFailed, reason);
  125. //OnErrorHappened(new ErrorEventArgs(reason));
  126. Thread.Sleep(1000);
  127. Connect(_address);
  128. }
  129. }
  130. private void Receive(Socket client)
  131. {
  132. try
  133. {
  134. // Create the state object.
  135. ClientStateObject state = new ClientStateObject(_bufferSize);
  136. state.workSocket = client;
  137. // Begin receiving the data from the remote device.
  138. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  139. }
  140. catch (Exception e)
  141. {
  142. LOG.Write(e);
  143. string reason = string.Format("TCP connection error:{0}", e.Message);
  144. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  145. OnErrorHappened(new ErrorEventArgs(reason));
  146. }
  147. }
  148. private void ReceiveCallback(IAsyncResult ar)
  149. {
  150. try
  151. {
  152. if (!IsConnected) { return; }
  153. // Retrieve the state object and the client socket
  154. // from the asynchronous state object.
  155. ClientStateObject state = (ClientStateObject)ar.AsyncState;
  156. Socket client = state.workSocket;
  157. // Read data from the remote device.
  158. int bytesRead = client.EndReceive(ar);
  159. if (bytesRead > 0)
  160. {
  161. // There might be more data, so store the data received so far.
  162. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  163. if (state.sb.Length > NewLine.Length)
  164. {
  165. if (state.sb.ToString().Substring(state.sb.Length - NewLine.Length).Equals(NewLine))
  166. {
  167. string msg = state.sb.ToString();
  168. if (NeedLog)
  169. LOG.Info(string.Format("Communication {0}:{1:D} receive {2}.", _ip, _port, msg.TrimEnd('\n').TrimEnd('\r')));
  170. OnDataChanged(state.sb.ToString());
  171. state.sb.Clear();
  172. }
  173. }
  174. // Get the rest of the data.
  175. client.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  176. }
  177. }
  178. catch (Exception ex)
  179. {
  180. LOG.Write(ex);
  181. string reason = string.Format("TCP Socket recevice data failed:{0}", ex.Message);
  182. LOG.Error(string.Format("Communication {0}:{1:D} {2}.", _ip, _port, reason));
  183. OnErrorHappened(new ErrorEventArgs(reason));
  184. }
  185. }
  186. public bool Write(string data)
  187. {
  188. try
  189. {
  190. lock (_locker)
  191. {
  192. // Convert the string data to byte data using ASCII encoding.
  193. byte[] byteData = Encoding.ASCII.GetBytes(data);
  194. _socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _socket);
  195. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}.", _ip, _port, data));
  196. }
  197. return true;
  198. }
  199. catch (Exception ex)
  200. {
  201. LOG.Write(ex);
  202. LOG.Info(string.Format("Communication {0}:{1:D} Send {2}. failed", _ip, _port, data));
  203. string reason = string.Format("Send command failed:{0}", ex.Message);
  204. OnErrorHappened(new ErrorEventArgs(reason));
  205. }
  206. return false;
  207. }
  208. private void SendCallback(IAsyncResult ar)
  209. {
  210. try
  211. {
  212. // Retrieve the socket from the state object.
  213. Socket client = (Socket)ar.AsyncState;
  214. // Complete sending the data to the remote device.
  215. int bytesSent = client.EndSend(ar);
  216. }
  217. catch (Exception ex)
  218. {
  219. LOG.Write(ex);
  220. string reason = string.Format("Send command failed:{0}", ex.Message);
  221. OnErrorHappened(new ErrorEventArgs(reason));
  222. }
  223. }
  224. /// <summary>
  225. /// 释放资源(Dispose)
  226. /// </summary>
  227. public void Dispose()
  228. {
  229. try
  230. {
  231. if (_socket != null)
  232. {
  233. if (IsConnected)
  234. {
  235. _socket.Shutdown(SocketShutdown.Both);
  236. }
  237. _socket.Close();
  238. _socket.Dispose();
  239. _socket = null;
  240. }
  241. }
  242. catch (Exception ex)
  243. {
  244. LOG.Write(ex);
  245. string reason = string.Format("释放socket资源失败:{0}", ex.Message);
  246. OnErrorHappened(new ErrorEventArgs(reason));
  247. }
  248. }
  249. }
  250. }