modbus tcp test

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Modbus.Device;
using Modbus.Data;
using System.Threading;

namespace modbusTCP
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        //创建对象
        //public ModbusTcpSlave slave;//需要引用modbus.device
        //public TcpListener tcpListener;//需要引用system.net.sockets
        //public DataStore data;//需要引用modbus.data
        //public string ip;
        //public  int port;
        //ModbusDataCollection<ushort> result03;

        private ModbusIpMaster ipMaster;  //需要引用modbus.device
        private TcpClient tcpClient;  //需要引用system.net.sockets //TcpClient tcpClient = new TcpClient()
        byte slaveAddress;
        ushort startAddress;
        ushort num;

        System.Timers.Timer timer2 = new System.Timers.Timer();


        private void Form1_Load(object sender, EventArgs e)
        {
            btn_read.Enabled = false;

        }

        private void btn_con_Click(object sender, EventArgs e)
        {
            try
            {
                //tcpListener = new TcpListener(IPAddress.Parse(txb_ip.Text), Convert.ToInt32(txb_port.Text));//需要引用system.net
                //tcpListener.Start();
                //slave = ModbusTcpSlave.CreateTcp(1, tcpListener);
                //data = DataStoreFactory.CreateDefaultDataStore();
                //data.DataStoreWrittenTo += Data_DataStoreWrittenTo;
                //data.DataStoreReadFrom += Data_DataStoreReadFrom;
                //aaa = ModbusSerialMaster.CreateRtu(new System.IO.Ports.SerialPort());

                //slave.ModbusSlaveRequestReceived += Slave_ModbusSlaveRequestReceived;
                //slave.Listen();


                IPAddress ip = IPAddress.Parse(txb_ip.Text);  //需要引用system.net
                int port = int.Parse(txb_port.Text);

                //创建连接
                tcpClient = new TcpClient();
                tcpClient.Connect(ip, port);
                ipMaster = ModbusIpMaster.CreateIp(tcpClient);
                btn_con.BackColor = Color.LightGreen;
                btn_read.Enabled = true;


            }
            catch (Exception ex)
            {
                btn_con.BackColor = Control.DefaultBackColor;
                MessageBox.Show(ex.Message);
            }

        }
        /*
        private void Data_DataStoreReadFrom(object sender, DataStoreEventArgs e)
        {
            //throw new NotImplementedException();
            //switch (e.ModbusDataType)
            //{
            //    case ModbusDataType.Coil:
            //        ModbusDataCollection<bool> coil = slave.DataStore.CoilDiscretes;
            //        if (ckb0.InvokeRequired)
            //        {
            //            this.BeginInvoke(new Action(delegate
            //            {
            //                ckb0.Checked = coil[0];
            //            }));
            //        }
            //        break;
            //    case ModbusDataType.HoldingRegister:
            //        result03 = slave.DataStore.HoldingRegisters;
            //        break;
            //}

        }

        private void Data_DataStoreWrittenTo(object sender, DataStoreEventArgs e)
        {
            //throw new NotImplementedException();
            //switch (e.ModbusDataType)
            //{
            //    case ModbusDataType.Coil:
            //        ModbusDataCollection<bool> coil = slave.DataStore.CoilDiscretes;
            //        if (ckb0.InvokeRequired)
            //        {
            //            this.BeginInvoke(new Action(delegate
            //            {
            //                ckb0.Checked = coil[0];
            //            }));
            //        }
            //        break;
            //    case ModbusDataType.HoldingRegister:
            //        result03 = slave.DataStore.HoldingRegisters;
            //        break;
            //}

        }

        private void Slave_ModbusSlaveRequestReceived(object sender, ModbusSlaveRequestEventArgs e)
        {
            BeginInvoke(new MethodInvoker(() =>
            {
                txb_rec.Text = e.Message.ToString();
                
            }));
        }
        */

        private void txb_ip_TextChanged(object sender, EventArgs e)
        {
            //ip = txb_ip.Text;
        }

        private void txb_port_TextChanged(object sender, EventArgs e)
        {
            //port = Convert.ToInt32(txb_port.Text);
        }

        private void btn_read_Click(object sender, EventArgs e)
        {
            //txb_r0.Text= result03[0].ToString();
            //txb_r0.Text = data.HoldingRegisters[1].ToString();

            slaveAddress = byte.Parse(this.txb_slave_add.Text);
            startAddress = ushort.Parse(this.txb_startadd.Text);
            num = ushort.Parse(txb_numofpoints.Text);

            //读取保持寄存器,功能码03
            //ushort[]result= ipMaster.ReadHoldingRegisters(slaveAddress,startAddress, num);
            //将读到的数组赋值给文本框
            //for (int i=0;i<result.Length;i++)
            {
                //((TextBox)this.Controls[string.Format("txb_r{0}", i)]).Text = result[i].ToString();
            }

            timer1.Interval = 50;
            //timer1.Enabled = true;
            timer2.Interval = 50;
            timer2.AutoReset = true;
            timer2.Elapsed += new System.Timers.ElapsedEventHandler(Timer2_Elapsed);
            timer2.Start();
            


        }

        private void Timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string threadid = "线程ID:" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";
            bool[] coil = ipMaster.ReadCoils(slaveAddress, startAddress, num);
            //ushort[] result = ipMaster.ReadHoldingRegisters(slaveAddress, startAddress, num);


            this.BeginInvoke(new Action(() =>
            {
                txb_rec.Clear();
                txb_rec2.Clear();
                textBox1.Text = threadid;
                for (int i = 0; i < num; i++)
                {

                    //txb_rec.Text += "add" + i + ":" + result[i] + "\r\n";
                    //txb_rec.AppendText("add" + i + ":" + result[i] + "\r\n");
                    txb_rec2.Text += "add" + i + ":" + coil[i] + "\r\n";
                    //txb_rec2.AppendText("add" + i + ":" + coil[i] + "\r\n");
                }
            }));

        }

        private void btn_discon_Click(object sender, EventArgs e)
        {
            btn_stop_Click(sender, e);
            timer2.Close();
            ipMaster.Dispose();
            
            btn_con.BackColor = Control.DefaultBackColor;
            btn_read.Enabled = false;

        }

        private void btn_write_Click(object sender, EventArgs e)
        {
            ushort value = ushort.Parse(txb_w0.Text);
            ipMaster.WriteSingleRegister(1, 8, value);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            txb_rec.Clear();
            txb_rec2.Clear();
            textBox1.Text = "线程ID:" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";
            bool[] coil = ipMaster.ReadCoils(slaveAddress, startAddress, num);
            ushort[] result = ipMaster.ReadHoldingRegisters(slaveAddress, startAddress, num);
            for (int i = 0; i < num; i++)
            {

                //((TextBox)this.Controls[string.Format("txb_r{0}", i)]).Text = result[i].ToString();
                txb_rec.Text += "add" + i + ":" + result[i] + "\r\n";
                //txb_rec.AppendText( "add" + i + ":" + result[i] + "\r\n");
                txb_rec2.Text += "add" + i + ":" + coil[i] + "\r\n";
                //txb_rec2.AppendText("add" + i + ":" + coil[i] + "\r\n");
            }
        }


        private void btn_stop_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            timer2.Stop();
        }

        private void ckb0_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            ipMaster.WriteSingleCoil(1,9, checkBox1.Checked);
        }
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值