123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using UAS_PLCDataReader.DataOperate;
- namespace UAS_PLCDataReader.PublicMethod
- {
- class ModBusTCPClient
- {
- private Socket socket;
- private IPEndPoint serverFullAddr;//完整终端地址
- private bool isOpen = false;
- private bool receiveData;
- private DataOperate.DataHelper dh;
- private Dictionary<string, string> returnvalue = new Dictionary<string, string>();
- 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<string, string> Returnvalue
- {
- get
- {
- return returnvalue;
- }
- set
- {
- returnvalue = value;
- }
- }
- internal DataHelper Dh
- {
- get
- {
- return dh;
- }
- set
- {
- dh = value;
- }
- }
- private string iP;
- private string port;
- 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.Connect(serverFullAddr);
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- LogicHandler.UpdateDeviceStatus(Dh,decode, dename, "disconnect");
- }
- }
- public void Send(string Command)
- {
- try
- {
- if (!socket.Connected)
- {
- socket.Close();
- socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- socket.Connect(serverFullAddr);
- }
- 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 * 1024];
- LogicHandler.UpdateDeviceStatus(Dh,decode, dename, "noanswer");
- int length = socket.Receive(receive);
- LogicHandler.UpdateDeviceStatus(Dh,decode, dename, "running");
- if (!returnvalue.ContainsKey(socket.RemoteEndPoint.ToString()))
- {
- returnvalue.Add(socket.RemoteEndPoint.ToString(), BaseUtil.ByteToHexadecimalString(receive, length));
- }
- }
- catch (Exception)
- {
- LogicHandler.UpdateDeviceStatus(Dh,decode, dename, "disconnect");
- }
- }
- }
- }
|