Socket is Connected or not in dealing with EASYMODBUS in C#

109 Views Asked by At

I am using "EasyModBus" to communicate with a BUS system. I need the user to be aware immediately if connection lost or is getting down. Another issue is that if i disconnect the network, the software will get hang due to a non-connected Socket on the below mentioned line:

ushort[] inputs = master1.ReadHoldingRegisters(startAddress, numInputs);

I tested several ways listed bellow:

  1. if(tcpClient.Connected)
  2. if(tcpClient.Available!=0) and also socket.Poll
  3. Pinging and check status

result: Pinging is ok but, i have to change my reading time interval from 1000ms to at least 2500ms. Then, if i disconnect the socket, i get the exception. But i need to read pules every 1000ms.

There is the same question here: EasyModbus: disconnecting from network doesn't change the connection state

As i mentioned, i tried tcpclient.Available but, it does not work.

My Codes:

private NetWork _NetWork = null;
        bool PingSlave(IPAddress slaveIPB)
        {
            PingReply reply = _NetWork.SendPing(slaveIPB,2500);
            if (reply.Status == IPStatus.Success)
                return true;
            else return false;
        }


 void Master1_Slave1_Read()
        {
            try
            {
                ipAddressTCP1 = tBxIPAdrs.Text.ToString();
                tcpClient1 = new TcpClient();
                tcpClient1.Connect(ipAddressTCP1, ipPortTCP1);
                master1 = ModbusIpMaster.CreateIp(tcpClient1);
                ushort startAddress = 0;
                ushort numInputs = 10;

                if (PingSlave(ipS) == true)
                {
                    ushort[] inputs = master1.ReadHoldingRegisters(startAddress, numInputs);
                    for (int i = 0; i < numInputs; i++)
                    {
                        if (inputs != null)
                            rTBx0_IOMF.AppendText(inputs[i].ToString() + "\t");
                    }

                    rTBx0_IOMF.AppendText("\n");
                }
                else
                    rTBx1_IOMF.AppendText("\n" + "Warning:\t\t Check Your Connection!" + "\t\t" + DateTime.Now.ToString("dd-mm-yyyy:HH:mm:ss") + "\n");
            }
            catch (EasyModbus.Exceptions.ConnectionException ex)
            {
                rTBx0_IOMF.AppendText(ex.Message.ToString() + "\n");
            }
            catch (SocketException ex)
            {
                rTBx0_IOMF.AppendText(ex.Message.ToString() + "\n");
            }

           }

private void t0_Tick(object sender, EventArgs e)
        {
                Master1_Slave1_Read();
        }

Any help is appreciated.

0

There are 0 best solutions below