Modbus Protocol - MJK Device - Get Device ID ( Slave ID )

851 views Asked by At

I need to read register values of difference device via TCP Listeners.

To get the values of register we need to request to device with device ID, in below code 0xF7 is hard coded passed.

Now we have more than 500 devices which will connect to our port, so Is there any way to get device ID ( slaveID ) when they connect to our TCP Port?

   Int32 port = int.Parse(TCPPort);
                IPAddress localAddr = IPAddress.Parse(TCPHost);
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
                TcpListener server = new TcpListener(localAddr, port);
                server.Start();
                while (true)
                {
                Console.WriteLine("Waiting for a connection...");
                Console.WriteLine();

                TcpClient client = new TcpClient();

                client = server.AcceptTcpClient();
                NetworkStream stream = client.GetStream();
                string loggerTime = RequestTime(client, stream);
                } ...

         


static string RequestTime(TcpClient client, NetworkStream stream)
        {
            // 0xF7 is hard coded here, this needs to find
            byte[] sendData = { 0xF7, 0x03, 0x00, 0x1F, 0x00, 0x02, 0xE1, 0x5B }; 

            stream = client.GetStream();
            stream.Write(sendData, 0, sendData.Length);

            Byte[] data = new Byte[9];

            try
            {
                Int32 bytes = stream.Read(data, 0, data.Length);
                if (ValidateCRC(data, data.Length) && bytes != 0)
                {
                    byte[] buf = new byte[] { data[3], data[4], data[5], data[6] };
                    buf.SwapBytes(0, 1);
                    buf.SwapBytes(2, 3);
                    Array.Reverse(buf, 0, buf.Length);
                    string hexValue = ConvertBytesToHexa(buf);

                    int secondsAfterEpoch = Int32.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
                    DateTime epoch = new DateTime(1970, 1, 1);
                    DateTime loggerTime = epoch.AddSeconds(secondsAfterEpoch);
                    Console.WriteLine("Logger UTC Time: {0}", loggerTime.ToUniversalTime());
                    Console.WriteLine();

                    return loggerTime.ToUniversalTime().ToString();
                }
                else
                {
                    Console.WriteLine("Response CRC is not matched for UTC Time");
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
               
            }
        }
0

There are 0 answers