I'm trying to communicate with a device using Modbus TCP/IP. I'm using C# 4.0 .NET Sockets and have run into trouble getting responses back from the device. It will have to be asynchronous communication due to the nature of the device/network.
Right now I can connect to the device. When the Connect
command executes, the device LED lights up that represents that there is an active connection. Then I execute the Send
command and the light turns off (meaning I've lost connection) and when I receive, I get nothing. I've tried a bunch of different data packets but haven't been successful in any instance. I am thinking, is it something with the SocketType
when I initialize the Socket? Could it be the port (currently using port 4) I'm trying to use?
Here is the Modbus TCP/IP document I've tried to use: Modbus Documentation
and here is my code:
sockPort = new Socket(IPAddress.Parse(_commInfo.IPAddress).AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint m_localhost = new IPEndPoint(IPAddress.Parse(addr.Address.ToString()), 4);
sockPort.Bind(m_localhost);
sockPort.Connect(new IPEndPoint(IPAddress.Parse(_commInfo.IPAddress), 502));
byte[] rx = new byte[260];
byte[] data = { 0x03, 0x00, 0x20, 0x00, 0x04, 0x45, 0xf0 };
sockPort.Send(data);
var asf = sockPort.Receive(rx);
The problem is most probably with your interpretation of the application (modbus) protocol - endianness, packet layout, etc. Use wireshark or tcpdump(1)
to figure out what is sent to and from the device. Some other points:
bind(2)
the local end of the socket, kernel will select an ephemeral local port for you.connect(2)
is complete.As for workings of the device itself it's probably best to look for manufacturer documentation and search for device-specific mailing lists, user groups, and forums.
Hope this helps.