Tcp/ip()485通讯

Modbus板卡通讯

客户端动态检测DO

 public class TcpClient
    {
        public Form1 Client_DO;
        public TcpClient(Form1 parent)
        {
            Client_DO = parent;
        }
        IPAddress ip1 = IPAddress.Parse("192.168.1.75");
        int connPort1 = 502;
        System.Timers.Timer Draw_Timer;
        public  Socket ClientServer;
        public  Thread Thread_DO;
        public IPAddress IP1
        {
            get { return ip1; }
            set { ip1 = value; }
        }

        public int ConnPort1
        {
            get { return connPort1; }
            set { connPort1 = value; }
        }
        public  void ClientServerinit()
    {
            Thread_DO = new Thread(Refresh_State_DO);
            Thread_DO.IsBackground = true;
            Thread_DO.Start();
            Draw_Timer = new System.Timers.Timer(900);
            Draw_Timer.Elapsed += new System.Timers.ElapsedEventHandler(clear);
            Draw_Timer.AutoReset = true;
            Draw_Timer.Enabled = true;
            Thread.Sleep(500);
            IPAddress ip1 = IPAddress.Parse("192.168.1.75");
            int connPort1 = 502;
            ClientServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ClientServer.Connect(new IPEndPoint(ip1, connPort1)); 
        Console.WriteLine("连接服务器成功");
    }
        public  string ToHexString(int length, byte[] bytes)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();
                for (int i = 0; i < length; i++)
                {
                    for (int j = 0; j < 1; j++)
                    {
                        strB.Append(bytes[i].ToString("X2") + " ");
                    }
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        private int[] DO_State_Box = new int[16];
        byte[] CheckData_DO = new byte[12] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x01, 0x00, 0x00, 0x00, 0x10 };

        public void clear(object source, System.Timers.ElapsedEventArgs e)
        {
            Client_DO.richTextBox1.Invoke(new Action(() => { Client_DO.richTextBox1.Clear(); }));
        }
        private void Refresh_State_DO()
        {
            while(true)
            {
                Thread.Sleep(30);
                SendData();
            }
        }
        public void SendData()
        {
            int TimeOut = 10;
            int CycleCount = 0;
            if (ClientServer == null)
            {
                Console.WriteLine("发送失败,未连接客户端");
            }
            try
            {
                ClientServer.Send(CheckData_DO);
                Client_DO.richTextBox1.Invoke(new Action(() => { Client_DO.richTextBox1.AppendText(ToHexString(CheckData_DO.Length, CheckData_DO) + "\n"); }));
                while (true)
                {
                    try
                    {
                        byte[] buffer = new byte[256];
                        var effective = ClientServer.Receive(buffer);
                        if (effective > 0)
                        {
                            if (effective == 11)
                            {
                                Console.WriteLine(ToHexString(effective, buffer));
                                Client_DO.richTextBox1.Invoke(new Action(() => { Client_DO.richTextBox1.AppendText(ToHexString(effective, buffer) + "\n"); }));
                                if (buffer[5] == 0x05 && buffer[6] == 0x01 && buffer[7] == 0x01 && buffer[8] == 0x02)
                                {
                                    DO_State_Box = twobyteTointarr(buffer[10], buffer[9]);
                                    break;
                                }
                            }
                            Console.WriteLine(ToHexString(effective, buffer));
                            CycleCount = 0;
                            break;
                        }
                        else
                        {
                            Thread.Sleep(5);
                            CycleCount++;
                            if (CycleCount >= TimeOut)
                            {
                                CycleCount = 0;
                                Console.WriteLine("响应超时");
                                MessageBox.Show("Connnect Server Timeout!");
                                break;
                            }
                        }
                    }
                    catch (Exception a)
                    {
                        Console.WriteLine("接收数据的时候解析错误" + a);
                        break;
                    }
                }
            }
            catch (Exception t)
            {
                Console.WriteLine("发送失败" + t.ToString());
            }
        }
        
        public int[] twobyteTointarr(byte high, byte low)
        {
            string resultstr = Convert.ToString(high, 2).PadLeft(8, '0') + Convert.ToString(low, 2).PadLeft(8, '0');
            int[] result = new int[16];
            for (int i = 0; i < 16; i++)
            {
                result[i] = int.Parse(resultstr[15 - i].ToString());
                for (int j = 0; j < 16; j++)
                {
                    if (result[j] == 1)
                    {
                      Form1.count[j] = 1;
                    }
                }
            }
            for (int i = 0; i < result.Length; i++)
            {
                if (result[i] == 1)
                    Client_DO.ButtonList_Out[i].Invoke(new Action(() => { Client_DO.ButtonList_Out[i].BackColor = System.Drawing.Color.Red; }));
                else
                    Client_DO.ButtonList_Out[i].Invoke(new Action(() => { Client_DO.ButtonList_Out[i].BackColor = System.Drawing.Color.Blue; }));
            }
            return result;
        }
    }
}

客户端动态检测DI

 class TcpInput
    {
        public Form1 Client_DI;
        public TcpInput(Form1 parent)
        {
            Client_DI = parent;
        }
        IPAddress ip1 = IPAddress.Parse("192.168.1.75");
        int connPort1 = 502;
        public Socket InputClient;
        public Thread Thread_DI;
        public IPAddress IP1
        {
            get { return ip1; }
            set { ip1 = value; }
        }
        public int ConnPort1
        {
            get { return connPort1; }
            set { connPort1 = value; }
        }
        public void TcpInputinit()
        {
            Thread_DI = new Thread(Refresh_State_DI);
            Thread_DI.IsBackground = true;
            Thread_DI.Start();
            IPAddress ip1 = IPAddress.Parse("192.168.1.75");
            int connPort1 = 502;
            InputClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            InputClient.Connect(new IPEndPoint(ip1, connPort1));
            Console.WriteLine("连接服务器成功");
        }
        public void Refresh_State_DI()
        {
            while (true)
            {
                Thread.Sleep(30);
                InputData();
            }
        }
        public void InputData()
        {
            int timeout = 10;
            int cyclecount = 0;
            if (InputClient == null)
            {
                Console.WriteLine("发送失败,未连接客户端");
            }
            try
            {
                //读16路输入状态
                //主机发送:00 00 00 00 00 06 01 02 00 00 00 10
                byte[] data = new byte[12] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x02, 0x00, 0x00, 0x00, 0x10 };
                InputClient.Send(data);
                while (true)
                {
                    try
                    {
                        byte[] buffer = new byte[256];
                        var effective = InputClient.Receive(buffer);
                        if (effective > 0)
                        {
                            if (effective == 11)
                            {
                                //从机应答:00 00 00 00 00 05 01 02 02 03 FF
                                Console.WriteLine(ToHexString(effective, buffer));
                                if (buffer[5] == 0x05 && buffer[6] == 0x01 && buffer[7] == 0x02 && buffer[8] == 0x02)
                                {
                                    DI_State_Box = TwobyteTointarr(buffer[10], buffer[9]);
                                    break;
                                }
                            }
                            Console.WriteLine(ToHexString(effective, buffer));
                            cyclecount = 0;
                            break;
                        }
                        else
                        {
                            Thread.Sleep(5);
                            cyclecount++;
                            if (cyclecount >= timeout)
                            {
                                cyclecount = 0;
                                Console.WriteLine("响应超时");
                                MessageBox.Show("Connnect Server Timeout!");
                                break;
                            }
                        }
                    }
                    catch (Exception a)
                    {
                        Console.WriteLine("接收数据的时候解析错误" + a);
                        break;
                    }
                }
            }
            catch (Exception t)
            {
                Console.WriteLine("发送失败" + t.ToString());
            }
        }
    private int[] DI_State_Box = new int[16];
    public int[] TwobyteTointarr(byte high, byte low)
    {
        string resultstr = Convert.ToString(high, 2).PadLeft(8, '0') + Convert.ToString(low, 2).PadLeft(8, '0');
        int[] result = new int[16];
        for (int i = 0; i < 16; i++)
        {
            result[i] = int.Parse(resultstr[15 - i].ToString());
            for (int j = 0; j < 16; j++)
            {
                if (result[j] == 1)
                {
                    Form1.count[j] = 1;
                }
            }
        }
            for (int i = 0; i < result.Length; i++)
            {
                if (result[i] == 1)
                    Client_DI.ButtonList_In[i].Invoke(new Action(() => { Client_DI.ButtonList_In[i].BackColor = System.Drawing.Color.Red; }));
            else
                    Client_DI.ButtonList_In[i].Invoke(new Action(() => { Client_DI.ButtonList_In[i].BackColor = System.Drawing.Color.Blue; }));
            }
            return result;
    }
    public string ToHexString(int length, byte[] bytes)
    {
        string hexString = string.Empty;
        if (bytes != null)
        {
            StringBuilder strB = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < 1; j++)
                {
                    strB.Append(bytes[i].ToString("X2") + " ");
                }
            }
            hexString = strB.ToString();
        }
        return hexString;
    }

}
}


版权声明:本文为weixin_43610684原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。