using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using UAS_PLCDataReader.DataOperate; using UAS_PLCDataReader.Entity; namespace UAS_PLCDataReader.PublicMethod { class ModBusTCPClient { private Socket socket; private IPEndPoint serverFullAddr;//完整终端地址 private bool isOpen = false; private bool receiveData; private DataHelper dh; private Dictionary returnvalue = new Dictionary(); public bool IsOpen { get { return isOpen; } set { isOpen = value; } } public string IP { get { return iP; } set { iP = value; } } public string Port { get { return port; } set { port = value; } } public bool ReceiveData { get { return receiveData; } set { receiveData = value; } } public Dictionary Returnvalue { get { return returnvalue; } set { returnvalue = value; } } internal DataHelper Dh { get { return dh; } set { dh = value; } } private string iP; private string port; private int ResetCount = 0; string decode = ""; string dename = ""; public ModBusTCPClient(string IP, string Port, string Decode, string Dename) { try { decode = Decode; dename = Dename; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverFullAddr = new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port));//设置IP,端口 socket.ReceiveTimeout = 2000; socket.Connect(serverFullAddr); } catch (Exception ex) { LogicHandler.UpdateDeviceStatus(decode, dename, ex.Message, DeviceStatus.Disconnect, -1); LogicHandler.DoDevicePollingLog(decode, false); LogManager.DoLog(ex.Message + ex.StackTrace); } } public void Send(string Command) { string str = ""; try { if (!socket.Connected || ResetCount == 20) { socket.Close(); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.ReceiveTimeout = 2000; socket.Connect(serverFullAddr); ResetCount = 0; } Command = Command.Replace(" ", ""); byte[] arr = new byte[Command.Length / 2]; for (int i = 0; i < Command.Length / 2; i++) { arr[i] = (byte)Convert.ToInt32(Command.Substring(i * 2, 2), 16); } socket.Send(arr); byte[] receive = new byte[1024 * 10]; LogicHandler.UpdateDeviceStatus(decode, dename, "设备运行准备获取数据", DeviceStatus.Noanswer, 0); LogicHandler.DoDevicePollingLog(decode, true); int length = socket.Receive(receive); LogicHandler.UpdateDeviceStatus(decode, dename, "设备运行获取到数据返回数据", DeviceStatus.Running, 0); str = BaseUtil.ByteToHexadecimalString(receive, length); LogicHandler.DoDevicePollingLog(decode, BaseUtil.ASCIIToString(str)); if (!returnvalue.ContainsKey(socket.RemoteEndPoint.ToString())) { returnvalue.Add(socket.RemoteEndPoint.ToString(), str); } ResetCount = ResetCount + 1; } catch (Exception ex) { LogicHandler.UpdateDeviceStatus(decode, dename, ex.Message, DeviceStatus.Disconnect, -1); LogicHandler.DoDevicePollingLog(decode, false); Console.WriteLine(ex.Message + ex.StackTrace + "\n" + decode + " " + str); } } } }