C#

C# MODBUS TCP Server, Client (예제 포함)

sheepone 2022. 10. 19. 16:07
반응형

EasyModbus 사용

IP : "127.0.0.1" (클라이언트쪽에서 변경해서 사용)

PORT : 502

서버와 클라이언트 화면 (위쪽 서버, 아래쪽 클라이언트)

클라이언트는 READ 버튼을 눌러서 읽어오고 COILS는 값 더블클릭, HOLDING REGISTERS는 값에 입력후 엔터

위에 1은 시작 주소로 20개씩 읽어옴

 

1. SERVER

using EasyModbus;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp10
{
    public partial class Form1 : Form
    {
        ModbusServer mServer ;
        //ModbusClient mClient ;

        delegate void VoidDelegate();

        public Form1()
        {
            InitializeComponent();

            mServer = new EasyModbus.ModbusServer();
            mServer.Listen(); //음 맘에 안드는 구만...

            mServer.CoilsChanged += mServer_CoilsChanged;
            mServer.HoldingRegistersChanged += mServer_HoldingRegistersChanged;
            mServer_CoilsChanged(0,0);            //2
            mServer_HoldingRegistersChanged(0,0); //4
            mServer_DiscreteChanged();            //1
            mServer_InputRegistersChanged();      //3
            

            //mClient = new EasyModbus.ModbusClient("127.0.0.1", 502);
            //mClient.Connect();

        }

        //----------------------------------------------------------------------------
        //1. Discrete Inputs Start
        //----------------------------------------------------------------------------
        private void mServer_DiscreteChanged()
        {
            int startingAddressDiscreteInputs = (int)numericUpDown1.Value;

            dataGridView1.Rows.Clear();
            
            startingAddressDiscreteInputs = (int)numericUpDown1.Value;
            for (int i = startingAddressDiscreteInputs; i < 20 + startingAddressDiscreteInputs; i++)
            {
                dataGridView1.Rows.Add(i, mServer.discreteInputs[i]);
                
                if (mServer.discreteInputs[i])
                    dataGridView1[1, i - startingAddressDiscreteInputs].Style.BackColor = Color.Green;
                else
                    dataGridView1[1, i - startingAddressDiscreteInputs].Style.BackColor = Color.Red;
            }
        }


        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int startingAddressDiscreteInputs = (int)numericUpDown1.Value;

            int rowindex = dataGridView1.SelectedCells[0].RowIndex;
            if (mServer.discreteInputs[rowindex+startingAddressDiscreteInputs] == false)
                mServer.discreteInputs[rowindex+startingAddressDiscreteInputs] = true;
            else
                mServer.discreteInputs[rowindex + startingAddressDiscreteInputs] = false;

            mServer_DiscreteChanged();
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            mServer_DiscreteChanged();
        }

        //----------------------------------------------------------------------------
        //1. Discrete Inputs End
        //----------------------------------------------------------------------------

        //----------------------------------------------------------------------------
        //2. Coils Start
        //----------------------------------------------------------------------------
        private void mServer_CoilsChanged(int coil, int numberOfCoils)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new VoidDelegate(delegate() { 
                    int startingAddressCoils = (int)numericUpDown2.Value;

                    dataGridView2.Rows.Clear();
                    for (int i = startingAddressCoils; i < 20 + startingAddressCoils; i++)
                    {
                        dataGridView2.Rows.Add(i, mServer.coils[i]);
                        if (mServer.coils[i])
                            dataGridView2[1, i - startingAddressCoils].Style.BackColor = Color.Green;
                        else
                            dataGridView2[1, i - startingAddressCoils].Style.BackColor = Color.Red;
                    }
                }));
            }
            else
            {
                int startingAddressCoils = (int)numericUpDown2.Value;

                dataGridView2.Rows.Clear();
                for (int i = startingAddressCoils; i < 20 + startingAddressCoils; i++)
                {
                    dataGridView2.Rows.Add(i, mServer.coils[i]);
                    if (mServer.coils[i])
                        dataGridView2[1, i - startingAddressCoils].Style.BackColor = Color.Green;
                    else
                        dataGridView2[1, i - startingAddressCoils].Style.BackColor = Color.Red;
                }

            }
        }

        private void dataGridView2_DoubleClick(object sender, EventArgs e)
        {
            int startingAddressCoils = (int)numericUpDown2.Value;

            int rowindex = dataGridView2.SelectedCells[0].RowIndex;
            if (mServer.coils[rowindex + startingAddressCoils] == false)
                mServer.coils[rowindex + startingAddressCoils] = true;
            else
                mServer.coils[rowindex + startingAddressCoils] = false;
            mServer_CoilsChanged(0, 0);
        }

        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            mServer_CoilsChanged(0, 0);
        }

        //----------------------------------------------------------------------------
        //2. Coils End
        //----------------------------------------------------------------------------

        //----------------------------------------------------------------------------
        //3. InputRegister Start
        //----------------------------------------------------------------------------

        private void mServer_InputRegistersChanged()
        {
            int startingAddressInputRegisters = (int)numericUpDown3.Value;
            dataGridView3.Rows.Clear();
            for (int i = startingAddressInputRegisters; i < 20 + startingAddressInputRegisters; i++)
                dataGridView3.Rows.Add(i, mServer.inputRegisters[i]);
        }

        private void numericUpDown3_ValueChanged(object sender, EventArgs e)
        {
            mServer_InputRegistersChanged();
        }

        private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int startingAddressInputRegisters = (int)numericUpDown3.Value;

            if (dataGridView3.SelectedCells.Count > 0)
            {
                int rowindex = dataGridView3.SelectedCells[0].RowIndex;
                try
                {
                    mServer.inputRegisters[rowindex + startingAddressInputRegisters] = Int16.Parse(dataGridView3.SelectedCells[0].Value.ToString());
                }
                catch (Exception) { }
                mServer_InputRegistersChanged();
            }

        }
        //----------------------------------------------------------------------------
        //3. InputRegister End
        //----------------------------------------------------------------------------

        //----------------------------------------------------------------------------
        //4. HoldingRegister Start
        //----------------------------------------------------------------------------
        private void mServer_HoldingRegistersChanged(int register, int numberOfRegisters)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new VoidDelegate(delegate() { 
                    int startingAddressHoldingRegisters = (int)numericUpDown4.Value;
                    dataGridView4.Rows.Clear();
                    for (int i = startingAddressHoldingRegisters; i < 20 + startingAddressHoldingRegisters; i++)
                        dataGridView4.Rows.Add(i, mServer.holdingRegisters[i]);
                }));
            }
            else
            {
                int startingAddressHoldingRegisters = (int)numericUpDown4.Value;
                dataGridView4.Rows.Clear();
                for (int i = startingAddressHoldingRegisters; i < 20 + startingAddressHoldingRegisters; i++)
                    dataGridView4.Rows.Add(i, mServer.holdingRegisters[i]);
            }
        }

        private void numericUpDown4_ValueChanged(object sender, EventArgs e)
        {
            mServer_HoldingRegistersChanged(0,0);

        }

        private void dataGridView4_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int startingAddressHoldingRegisters = (int)numericUpDown4.Value;

            if (dataGridView4.SelectedCells.Count > 0)
            {
                int rowindex = dataGridView4.SelectedCells[0].RowIndex;
                try
                {
                    mServer.holdingRegisters[rowindex + startingAddressHoldingRegisters] = Int16.Parse(dataGridView4.SelectedCells[0].Value.ToString());
                }
                catch (Exception) { }
                mServer_HoldingRegistersChanged(0, 0);
            }
        }

        //----------------------------------------------------------------------------
        //4. HoldingRegister End
        //----------------------------------------------------------------------------

    }
}

 

2. CLIENT

using EasyModbus;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp10
{
    public partial class Form1 : Form
    {
        ModbusClient mClient ;

        delegate void VoidDelegate();

        public Form1()
        {
            InitializeComponent();

            mClient = new EasyModbus.ModbusClient();
            mClient.IPAddress = "127.0.0.1";
            mClient.Port      =  502       ;

            mClient.Connect();

            if(!mClient.Connected) return ;

            timer1.Enabled = true;
            //mServer_CoilsChanged(0,0);            //2
            //mServer_HoldingRegistersChanged(0,0); //4
            //mServer_DiscreteChanged();            //1
            //mServer_InputRegistersChanged();      //3
            

            //mClient = new EasyModbus.ModbusClient("127.0.0.1", 502);
            //mClient.Connect();

        }

        //----------------------------------------------------------------------------
        //1. Discrete Inputs Start
        //----------------------------------------------------------------------------
        private void mServer_DiscreteChanged()
        {
            int startingAddressDiscreteInputs = (int)numericUpDown1.Value ;

            dataGridView1.Rows.Clear();
            
            startingAddressDiscreteInputs = (int)numericUpDown1.Value;
            bool[] serverResponse = mClient.ReadDiscreteInputs(startingAddressDiscreteInputs-1, 20);
            for (int i = startingAddressDiscreteInputs; i < 20 + startingAddressDiscreteInputs; i++)
            {
                dataGridView1.Rows.Add(i, serverResponse[i-startingAddressDiscreteInputs]);
                
                if (serverResponse[i-startingAddressDiscreteInputs])
                    dataGridView1[1, i - startingAddressDiscreteInputs].Style.BackColor = Color.Green;
                else
                    dataGridView1[1, i - startingAddressDiscreteInputs].Style.BackColor = Color.Red;
            }
        }


        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            mServer_DiscreteChanged();
        }

        //----------------------------------------------------------------------------
        //1. Discrete Inputs End
        //----------------------------------------------------------------------------

        //----------------------------------------------------------------------------
        //2. Coils Start
        //----------------------------------------------------------------------------
        private void mServer_CoilsChanged(int coil, int numberOfCoils)
        {

            int startingAddressCoils = (int)numericUpDown2.Value;

            bool[] serverResponse = mClient.ReadCoils(startingAddressCoils-1, 20);

            dataGridView2.Rows.Clear();
            for (int i = startingAddressCoils; i < 20 + startingAddressCoils; i++)
            {
                dataGridView2.Rows.Add(i, serverResponse[i-startingAddressCoils]);
                if (serverResponse[i-startingAddressCoils])
                    dataGridView2[1, i - startingAddressCoils].Style.BackColor = Color.Green;
                else
                    dataGridView2[1, i - startingAddressCoils].Style.BackColor = Color.Red;
            }

        }

        private void dataGridView2_DoubleClick(object sender, EventArgs e)
        {
            int startingAddressCoils = (int)numericUpDown2.Value;

            int rowindex = dataGridView2.SelectedCells[0].RowIndex;

            if(dataGridView2[1, rowindex].Value.ToString() == "False")
            {
                mClient.WriteSingleCoil(rowindex + startingAddressCoils - 1,true );
            }
            else
            {
                mClient.WriteSingleCoil(rowindex + startingAddressCoils - 1,false);
            }
            mServer_CoilsChanged(0, 0);
        }

        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            mServer_CoilsChanged(0, 0);
        }

        //----------------------------------------------------------------------------
        //2. Coils End
        //----------------------------------------------------------------------------

        //----------------------------------------------------------------------------
        //3. InputRegister Start
        //----------------------------------------------------------------------------

        private void mServer_InputRegistersChanged()
        {
            int startingAddressInputRegisters = (int)numericUpDown3.Value;

            int[] serverResponse = mClient.ReadInputRegisters(startingAddressInputRegisters-1, 20);

            dataGridView3.Rows.Clear();
            for (int i = startingAddressInputRegisters; i < 20 + startingAddressInputRegisters; i++)
                dataGridView3.Rows.Add(i, serverResponse[i-startingAddressInputRegisters]);
        }

        private void numericUpDown3_ValueChanged(object sender, EventArgs e)
        {
            mServer_InputRegistersChanged();
        }

        private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

        }
        //----------------------------------------------------------------------------
        //3. InputRegister End
        //----------------------------------------------------------------------------

        //----------------------------------------------------------------------------
        //4. HoldingRegister Start
        //----------------------------------------------------------------------------
        private void mServer_HoldingRegistersChanged(int register, int numberOfRegisters)
        {

            int startingAddressHoldingRegisters = (int)numericUpDown4.Value;

            int[] serverResponse = mClient.ReadHoldingRegisters(startingAddressHoldingRegisters-1, 20);
            dataGridView4.Rows.Clear();
            for (int i = startingAddressHoldingRegisters; i < 20 + startingAddressHoldingRegisters; i++)
                dataGridView4.Rows.Add(i, serverResponse[i-startingAddressHoldingRegisters]);
        }

        private void numericUpDown4_ValueChanged(object sender, EventArgs e)
        {
            mServer_HoldingRegistersChanged(0,0);

        }

        private void dataGridView4_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int startingAddressHoldingRegisters = (int)numericUpDown4.Value;

            if (dataGridView4.SelectedCells.Count > 0)
            {
                int rowindex = dataGridView4.SelectedCells[0].RowIndex;
                try
                {
                    mClient.WriteSingleRegister(rowindex + startingAddressHoldingRegisters - 1, Int16.Parse(dataGridView4.SelectedCells[0].Value.ToString()));
                }
                catch (Exception) { }
                mServer_HoldingRegistersChanged(0, 0);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (mClient.Connected)
            {
                this.Text = "Modbus Client is Connected" ;
                //mServer_CoilsChanged(0,0);            //2
                //mServer_HoldingRegistersChanged(0,0); //4
                //mServer_DiscreteChanged();            //1
                //mServer_InputRegistersChanged();      //3
            }
            else
            {
                this.Text = "Modbus Client is Disconnected" ;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            mServer_CoilsChanged(0,0);            //2
            mServer_HoldingRegistersChanged(0,0); //4
            mServer_DiscreteChanged();            //1
            mServer_InputRegistersChanged();      //3
        }

        //----------------------------------------------------------------------------
        //4. HoldingRegister End
        //----------------------------------------------------------------------------

    }
}

 

3. 예제파일

WindowsFormsAppClient.zip
0.17MB
WindowsFormsAppServer.zip
0.17MB

반응형