using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Globalization; namespace AGVSystem.Cls { class OmrlonHostlink { public string IPAdress; public bool connected = false; public Socket clientSocket; private IPEndPoint hostEndPoint; private Byte[] SendDataPro; private Byte[] RecvDataPro; private Byte[] SendData; private Byte[] RecvData; private Byte SendOrRecv; private AutoResetEvent autoConnectEvent = new AutoResetEvent(false); private SocketAsyncEventArgs lisnterSocketAsyncEventArgs; public delegate void StartListeHandler(); public event StartListeHandler StartListen; public delegate void ReceiveMsgHandler(byte[] info); public event ReceiveMsgHandler OnMsgReceived; private List s_lst = new List(); public OmrlonHostlink(string hostName, int port) { IPAdress = hostName; IPAddress[] hostAddresses = Dns.GetHostAddresses(hostName); this.hostEndPoint = new IPEndPoint(hostAddresses[hostAddresses.Length - 1], port); this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } /// /// 连接服务端 /// /// private bool Connect() { using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.UserToken = this.clientSocket; args.RemoteEndPoint = this.hostEndPoint; args.Completed += new EventHandler(this.OnConnect); this.clientSocket.ConnectAsync(args); bool flag = autoConnectEvent.WaitOne(1000); if (flag) { this.lisnterSocketAsyncEventArgs = new SocketAsyncEventArgs(); byte[] buffer = new byte[50]; this.lisnterSocketAsyncEventArgs.UserToken = this.clientSocket; this.lisnterSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length); this.lisnterSocketAsyncEventArgs.Completed += new EventHandler(this.OnReceive); this.StartListen(); return true; } return false; } } /// /// 判断有没有连接上 /// /// /// private void OnConnect(object sender, SocketAsyncEventArgs e) { this.connected = (e.SocketError == SocketError.Success); autoConnectEvent.Set(); } /// /// 发送 /// /// public void Send(string mes) { if (this.connected) { EventHandler handler = null; byte[] buffer = Encoding.Default.GetBytes(mes); SocketAsyncEventArgs senderSocketAsyncEventArgs = null; lock (s_lst) { if (s_lst.Count > 0) { senderSocketAsyncEventArgs = s_lst[s_lst.Count - 1]; s_lst.RemoveAt(s_lst.Count - 1); } } if (senderSocketAsyncEventArgs == null) { senderSocketAsyncEventArgs = new SocketAsyncEventArgs(); senderSocketAsyncEventArgs.UserToken = this.clientSocket; senderSocketAsyncEventArgs.RemoteEndPoint = this.clientSocket.RemoteEndPoint; if (handler == null) { handler = delegate(object sender, SocketAsyncEventArgs _e) { lock (s_lst) { s_lst.Add(senderSocketAsyncEventArgs); } }; } senderSocketAsyncEventArgs.Completed += handler; } senderSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length); this.clientSocket.SendAsync(senderSocketAsyncEventArgs); } else { this.connected = false; } } /// /// 监听服务端 /// public void Listen() { if (this.connected && this.clientSocket != null) { try { (lisnterSocketAsyncEventArgs.UserToken as Socket).ReceiveAsync(lisnterSocketAsyncEventArgs); } catch (Exception) { } } } /// /// 断开连接 /// /// private int Disconnect() { int res = 0; try { this.clientSocket.Shutdown(SocketShutdown.Both); } catch (Exception) { } try { this.clientSocket.Close(); } catch (Exception) { } this.connected = false; return res; } /// /// 数据接受 /// /// /// private void OnReceive(object sender, SocketAsyncEventArgs e) { if (e.BytesTransferred == 0) { try { this.clientSocket.Shutdown(SocketShutdown.Both); } catch (Exception) { } finally { if (this.clientSocket.Connected) { this.clientSocket.Close(); } } byte[] info = new Byte[] { 0 }; this.OnMsgReceived(info); } else { byte[] buffer = new byte[e.BytesTransferred]; for (int i = 0; i < e.BytesTransferred; i++) { buffer[i] = e.Buffer[i]; } this.OnMsgReceived(buffer); Listen(); } } /// /// 接受完成 /// /// private void OmrlonSocketClient_OnMsgReceived(byte[] info) { if (info[0] != 0) { if (this.SendOrRecv == 1) { this.SendDataPro = info; this.SendOrRecv = 0; } else if (this.SendOrRecv == 2) { this.SendData = info; this.SendOrRecv = 0; } else if (this.SendOrRecv == 3) { this.RecvDataPro = info; this.SendOrRecv = 0; } else if (this.SendOrRecv == 4) { this.RecvData = info; this.SendOrRecv = 0; } } else { if (this.SendOrRecv == 1) { this.SendDataPro = new Byte[] { 0 }; this.SendOrRecv = 0; } else if (this.SendOrRecv == 2) { this.SendData = new Byte[] { 0 }; this.SendOrRecv = 0; } else if (this.SendOrRecv == 3) { this.RecvDataPro = new Byte[] { 0 }; this.SendOrRecv = 0; } else if (this.SendOrRecv == 4) { this.RecvData = new Byte[] { 0 }; this.SendOrRecv = 0; } } } /// /// 建立连接的方法 /// /// public bool OpenLinkPLC() { bool flag = false; this.StartListen += new StartListeHandler(OmrlonSocketClient_StartListen); this.OnMsgReceived += new ReceiveMsgHandler(OmrlonSocketClient_OnMsgReceived); flag = this.Connect(); if (!flag) { return flag; } return true; } /// /// 关闭连接的方法 /// /// public int CloseLinkPLC() { return this.Disconnect(); } /// /// 监听的方法 /// private void OmrlonSocketClient_StartListen() { this.Listen(); } /// /// 校验 /// /// /// private string FCS(string Value) { int num2 = 0; for (int i = 0; i < Value.Length; i++) { byte[] bytes = Encoding.ASCII.GetBytes(Value.Substring(i, 1)); num2 ^= bytes[0]; } return num2.ToString("X"); } #region 写入PLC数据 /// /// 写一个DM数据 /// /// /// /// /// public int WritePlcDMValue(string stationNO, int address, string value) { int flag = -1; string str = ""; string str2 = ""; string str3 = value; str2 = address.ToString().PadLeft(4, '0'); stationNO = stationNO.PadLeft(2, '0'); str = "@" + stationNO + "WD" + str2 + str3; str = string.Concat(new object[] { str, this.FCS(str), "*", '\r' }); this.SendOrRecv = 1; int numPro = 0; this.Send(str); while (this.SendOrRecv != 0 && numPro < 500) { Thread.Sleep(1); numPro++; } if (numPro < 500) { string STR = Encoding.Default.GetString(SendDataPro, 0, SendDataPro.Length); if (STR.Length > 7) { if (STR.Substring(5, 2) == "00" &&STR.Substring(3, 2) == "WD"&& STR.Substring(0, 1) == "@" && STR.Substring(STR.Length - 1, 1) == "\r") { flag = 0; } //if (this.SendDataPro.Length > 7) //{ // if (this.SendDataPro[5] == 0x30 && this.SendDataPro[6] == 0x30) // { // flag = 0; // } // return flag; //} } } else { this.SendOrRecv = 0; } return flag; } #endregion #region 读DM值 /// /// 读DM值 /// /// /// /// /// /// public int ReadPlcDMValue(string PlcNo, int Addr, out int value) { int A = 0; if (Addr == 3000) A = 0; int flag = -1; value = -1; string str = ""; string str2 = ""; str2 = Addr.ToString().PadLeft(4, '0'); PlcNo = PlcNo.PadLeft(2, '0'); str = "@" + PlcNo + "RD" + str2 + "0001"; str = string.Concat(new object[] { str, this.FCS(str), "*", '\r' }); this.SendOrRecv = 3; int numPro = 0; this.Send(str); while (this.SendOrRecv != 0 && numPro < 500) { Thread.Sleep(1); numPro++; } if (numPro < 500) { string STR = Encoding.Default.GetString(RecvDataPro, 0, RecvDataPro.Length); if (STR.Length > 11) { if (STR.Substring(5, 2) == "00" && STR.Substring(3, 2) == "RD" && STR.Substring(0, 1) == "@" && STR.Substring(STR.Length - 1, 1) == "\r") { value = int.Parse(STR.Trim().Substring(7, 4), NumberStyles.HexNumber); flag = 0; } } //if (this.RecvDataPro.Length > 11) //{ // if (this.RecvDataPro[5] == 0x30 && this.RecvDataPro[6] == 0x30) // { // flag = 0; // value = RecvDataPro[10] + RecvDataPro[9] * 16 + RecvDataPro[8] * 256 + RecvDataPro[7] * 16 * 256; // } // return flag; //} } else { this.SendOrRecv = 0; } return flag; } #endregion #region 读HR值 /// /// 读HR值 /// /// /// /// /// /// public int ReadPlcHRValue(string PlcNo, int Addr, out int Value) { int flag = -1; Value = -1; string str = ""; string str2 = ""; str2 = Addr.ToString().PadLeft(4, '0'); PlcNo = PlcNo.PadLeft(2, '0'); str = "@" + PlcNo + "RH" + str2 + "0001"; str = string.Concat(new object[] { str, this.FCS(str), "*", '\r' }); this.SendOrRecv = 4; int num = 0; this.Send(str); while (this.SendOrRecv != 0 && num < 500) { Thread.Sleep(1); num++; } if (num < 500) { string STR = Encoding.Default.GetString(RecvData, 0, RecvData.Length); if (STR.Length > 11) { if (STR.Substring(5, 2) == "00" && STR.Substring(3, 2) == "RH" && STR.Substring(0, 1) == "@" && STR.Substring(STR.Length - 1, 1) == "\r") { Value = int.Parse(STR.Trim().Substring(7, 4), NumberStyles.HexNumber); flag = 0; } } //if (this.RecvData.Length > 11) //{ // if (this.RecvData[5] == 0x30 && this.RecvData[6] == 0x30) // { // flag = 0; // Value = RecvData[10] + RecvData[9] * 16 + RecvData[8] * 256 + RecvData[7] * 16*256; // } // return flag; //} } else { this.SendOrRecv = 0; } return flag; } #endregion #region IDispose member public void Dispose() { if (this.clientSocket.Connected) { this.clientSocket.Close(); } } #endregion } }