I am developing Modbus/TCP master application in Java using jamod library. During consecutive readings from my slave device, connection is being abruptly closed.
My code:
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.net.TCPMasterConnection;
public static void main(String[] args) throws Exception {
TCPMasterConnection connection = new TCPMasterConnection(InetAddress.getByName("192.168.0.111"));
connection.setPort(502);
connection.connect();
if (!connection.isConnected())
return;
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
}
private static synchronized int readIntFromIntAddr(TCPMasterConnection connection, int address) throws Exception {
ReadMultipleRegistersRequest Rreq = new ReadMultipleRegistersRequest(address, 1); // reading one register
Rreq.setUnitID(1); // slaveAddress
ModbusTCPTransaction trans = null;
trans = new ModbusTCPTransaction(connection);
trans.setRetries(3);
trans.setReconnecting(true);
trans.setRequest(Rreq);
trans.execute();
ReadMultipleRegistersResponse Rres = (ReadMultipleRegistersResponse) trans.getResponse();
return Rres.getRegisterValue(0);
}
The error, which is thrown during 6th reading
net.wimpi.modbus.ModbusIOException: Premature end of stream (Header truncated).
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:190)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:192)
at cz.jlochman.marklar.drivers.connection.modbustcp.ModBusTcpConnection.readIntFromIntAddr(ModBusTcpConnection.java:280)
at cz.jlochman.marklar.drivers.connection.modbustcp.ModBusTcpConnection.main(ModBusTcpConnection.java:267)
After this error, I am not able to restore connection. I have to terminate my application thread and start application again. I have found some workarounds: Adding Thread.sleep(500)
after 5th reading removes this exception. Thread.sleep(200)
after each reading works as well. Unfortunately, these workarounds are not enough to satisfy my demand of continous reading from slave device.
Does anyone have any idea, what could be going on?