use of com.ghgande.j2mod.modbus.ModbusSlaveException in project OpenMUC by isc-konstanz.
the class ModbusRTUTCPTransaction method execute.
// setRetries
@Override
public void execute() throws ModbusIOException, ModbusSlaveException, ModbusException {
if (m_Request == null || m_Connection == null) {
throw new ModbusException("Invalid request or connection");
}
/*
* Automatically re-connect if disconnected.
*/
if (!m_Connection.isConnected()) {
try {
m_Connection.connect();
} catch (Exception ex) {
throw new ModbusIOException("Connection failed.");
}
}
/*
* Try sending the message up to m_Retries time. Note that the message is read immediately after being written,
* with no flushing of buffers.
*/
int retryCounter = 0;
int retryLimit = (m_Retries > 0 ? m_Retries : 1);
while (retryCounter < retryLimit) {
try {
synchronized (m_IO) {
if (Modbus.debug) {
System.err.println("request transaction ID = " + m_Request.getTransactionID());
}
m_IO.writeMessage(m_Request);
m_Response = null;
do {
m_Response = m_IO.readResponse();
if (Modbus.debug) {
System.err.println("response transaction ID = " + m_Response.getTransactionID());
if (m_Response.getTransactionID() != m_Request.getTransactionID()) {
System.err.println("expected " + m_Request.getTransactionID() + ", got " + m_Response.getTransactionID());
}
}
} while (m_Response != null && (!isCheckingValidity() || (m_Request.getTransactionID() != 0 && m_Request.getTransactionID() != m_Response.getTransactionID())) && ++retryCounter < retryLimit);
if (retryCounter >= retryLimit) {
throw new ModbusIOException("Executing transaction failed (tried " + m_Retries + " times)");
}
/*
* Both methods were successful, so the transaction must have been executed.
*/
break;
}
} catch (ModbusIOException ex) {
if (!m_Connection.isConnected()) {
try {
m_Connection.connect();
} catch (Exception e) {
/*
* Nope, fail this transaction.
*/
throw new ModbusIOException("Connection lost.");
}
}
retryCounter++;
if (retryCounter >= retryLimit) {
throw new ModbusIOException("Executing transaction failed (tried " + m_Retries + " times)");
}
}
}
/*
* The slave may have returned an exception -- check for that.
*/
if (m_Response instanceof ExceptionResponse) {
throw new ModbusSlaveException(((ExceptionResponse) m_Response).getExceptionCode());
}
/*
* Close the connection if it isn't supposed to stick around.
*/
if (isReconnecting()) {
m_Connection.close();
}
/*
* See if packets require validity checking.
*/
if (isCheckingValidity() && m_Request != null && m_Response != null) {
checkValidity();
}
incrementTransactionID();
}
Aggregations