recover connection after changing slave ID in easymodbus RTU c#

999 Views Asked by At

i am trying to change the slave Id of my energy meter by writing a new value to right register. once the value is changed the connection is obviously lost but i can't find a way to renew it. i cant close the port without closing my entire application, there is no respond to modbusClient.Disconnect(); how can i please recover the connection and continue from there?

 private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                ModbusClient modbusClient = new ModbusClient(ConnectionSetUp.SetValueForCom);
                modbusClient.UnitIdentifier = byte.Parse(ConnectionSetUp.SetValueForAdress);
                // Not necessary since default baudrate = 9600
                modbusClient.Baudrate = int.Parse(ConnectionSetUp.SetValueForBuad);
                modbusClient.Parity = System.IO.Ports.Parity.None;
                modbusClient.StopBits = System.IO.Ports.StopBits.One;
                modbusClient.ConnectionTimeout = int.Parse(ConnectionSetUp.SetValueDelayTime);
                modbusClient.Connect();

                int Mult = int.Parse(MeterMult.Text);
                int Adress = int.Parse(MeterAdress.Text);
                int Baud = int.Parse(MeterBaud.Text);

                //mult
                modbusClient.WriteMultipleRegisters(4001, new int[1] { Mult });

                //Adress
                modbusClient.WriteMultipleRegisters(4002, new int[1] { Adress });
                ConnectionSetUp.SetValueForAdress = string.Format("{0}", Adress);

                modbusClient.Disconnect();
                
                modbusClient.Disconnect();
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(this, ex.Message, "bad settings",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

1

There are 1 best solutions below

1
Mandivamba On

Without knowing what device it is, it's hard to answer this one, Possibly the device needs a restart/power cycle before it recognizes the slave ID change. You could also improve your application,it doesn't make sense for an application to shutdown because you closed a port. As to why the disconnect doesn't work well as you said you have changed the Slave ID so possibly can't disconnect if the connection settings (Slave Id) has changed from the original initial connection.