Search in sources :

Example 1 with ModbusException

use of net.wimpi.modbus.ModbusException in project openhab1-addons by openhab.

the class ModbusSlave method executeWriteRequest.

/**
     *
     * @param request
     * @throws ModbusConnectionException when connection cannot be established
     * @throws ModbusException ModbusIOException on IO errors, ModbusSlaveException with protocol level exceptions
     * @throws ModbusUnexpectedTransactionIdException when response transaction id does not match the request
     */
private void executeWriteRequest(ModbusRequest request) throws ModbusConnectionException, ModbusException, ModbusUnexpectedTransactionIdException {
    ModbusSlaveEndpoint endpoint = getEndpoint();
    ModbusSlaveConnection connection = null;
    try {
        connection = getConnection(endpoint);
        if (connection == null) {
            logger.warn("ModbusSlave ({}): not connected -- aborting request {}", name, request);
            throw new ModbusConnectionException(endpoint);
        }
        transaction.setRequest(request);
        try {
            transaction.execute();
        } catch (Exception e) {
            // Note, one could catch ModbusIOException and ModbusSlaveException if more detailed
            // exception handling is required. For now, all exceptions are handled the same way with writes.
            logger.error("ModbusSlave ({}): error when executing write request ({}): {}", name, request, e.getMessage());
            invalidate(endpoint, connection);
            // set connection to null such that it is not returned to pool
            connection = null;
            throw e;
        }
        ModbusResponse response = transaction.getResponse();
        if ((response.getTransactionID() != transaction.getTransactionID()) && !response.isHeadless()) {
            logger.warn("ModbusSlave ({}): Transaction id of the response does not match request {}.  Endpoint {}. Connection: {}. Ignoring response.", name, request, endpoint, connection);
            throw new ModbusUnexpectedTransactionIdException();
        }
    } finally {
        returnConnection(endpoint, connection);
    }
}
Also used : ModbusSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusSlaveEndpoint) ModbusResponse(net.wimpi.modbus.msg.ModbusResponse) ModbusSlaveConnection(net.wimpi.modbus.net.ModbusSlaveConnection) ModbusException(net.wimpi.modbus.ModbusException)

Example 2 with ModbusException

use of net.wimpi.modbus.ModbusException in project openhab1-addons by openhab.

the class ModbusSlave method update.

/**
     * Reads data from the connected device and updates items with the new data
     *
     * @param binding ModbusBindig that stores providers information
     */
public void update(ModbusBinding binding) {
    try {
        Object local = null;
        Exception localReadError = null;
        try {
            if (ModbusBindingProvider.TYPE_COIL.equals(getType())) {
                ModbusRequest request = new ReadCoilsRequest(getStart(), getLength());
                if (this instanceof ModbusSerialSlave) {
                    request.setHeadless();
                }
                ReadCoilsResponse response = (ReadCoilsResponse) getModbusData(request);
                local = response.getCoils();
            } else if (ModbusBindingProvider.TYPE_DISCRETE.equals(getType())) {
                ModbusRequest request = new ReadInputDiscretesRequest(getStart(), getLength());
                ReadInputDiscretesResponse response = (ReadInputDiscretesResponse) getModbusData(request);
                local = response.getDiscretes();
            } else if (ModbusBindingProvider.TYPE_HOLDING.equals(getType())) {
                ModbusRequest request = new ReadMultipleRegistersRequest(getStart(), getLength());
                ReadMultipleRegistersResponse response = (ReadMultipleRegistersResponse) getModbusData(request);
                local = response.getRegisters();
            } else if (ModbusBindingProvider.TYPE_INPUT.equals(getType())) {
                ModbusRequest request = new ReadInputRegistersRequest(getStart(), getLength());
                ReadInputRegistersResponse response = (ReadInputRegistersResponse) getModbusData(request);
                local = response.getRegisters();
            }
        } catch (ModbusException e) {
            // Logging already done in getModbusData
            localReadError = e;
        } catch (ModbusConnectionException e) {
            // Logging already done in getModbusData
            localReadError = e;
        } catch (ModbusUnexpectedTransactionIdException e) {
            // Logging already done in getModbusData
            localReadError = e;
        }
        if (storage == null) {
            storage = local;
            readError = localReadError;
        } else {
            synchronized (storage) {
                storage = local;
                readError = localReadError;
            }
        }
        Collection<String> items = binding.getItemNames();
        for (String item : items) {
            updateItem(binding, item);
        }
    } catch (Exception e) {
        logger.error("ModbusSlave ({}) error getting response from slave", name, e);
    }
}
Also used : ReadInputDiscretesResponse(net.wimpi.modbus.msg.ReadInputDiscretesResponse) ReadInputDiscretesRequest(net.wimpi.modbus.msg.ReadInputDiscretesRequest) ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) ReadCoilsResponse(net.wimpi.modbus.msg.ReadCoilsResponse) ModbusException(net.wimpi.modbus.ModbusException) ReadInputRegistersResponse(net.wimpi.modbus.msg.ReadInputRegistersResponse) ModbusException(net.wimpi.modbus.ModbusException) ReadMultipleRegistersRequest(net.wimpi.modbus.msg.ReadMultipleRegistersRequest) ReadCoilsRequest(net.wimpi.modbus.msg.ReadCoilsRequest) ReadInputRegistersRequest(net.wimpi.modbus.msg.ReadInputRegistersRequest) ReadMultipleRegistersResponse(net.wimpi.modbus.msg.ReadMultipleRegistersResponse)

Example 3 with ModbusException

use of net.wimpi.modbus.ModbusException in project openhab1-addons by openhab.

the class ModbusTCPTransaction method execute.

// setRetries
@Override
public void execute() throws ModbusIOException, ModbusSlaveException, ModbusException {
    // 1. check that the transaction can be executed
    assertExecutable();
    try {
        // 2. Lock transaction
        /**
             * Note: The way this explicit synchronization is implemented at the moment,
             * there is no ordering of pending threads. The Mutex will simply call notify()
             * and the JVM will handle the rest.
             */
        m_TransactionLock.acquire();
        // 3. open the connection if not connected
        if (!m_Connection.isConnected()) {
            try {
                m_Connection.connect();
                m_IO = m_Connection.getModbusTransport();
            } catch (Exception ex) {
                throw new ModbusIOException("Connecting failed.");
            }
        }
        // 4. Retry transaction m_Retries times, in case of
        // I/O Exception problems.
        int tries = 0;
        do {
            try {
                // toggle and set the id
                m_Request.setTransactionID(c_TransactionID.increment());
                // 3. write request, and read response
                m_IO.writeMessage(m_Request);
                // read response message
                m_Response = m_IO.readResponse();
                break;
            } catch (ModbusIOException ex) {
                tries++;
                logger.error("execute try {}/{} error: {}. Request: {} (unit id {} & transaction {}). Address: {}:{}", tries, m_Retries, ex.getMessage(), m_Request, m_Request.getUnitID(), m_Request.getTransactionID(), m_Connection.getAddress(), m_Connection.getPort());
                if (tries >= m_Retries) {
                    logger.error("execute reached max tries {}, throwing last error: {}. Request: {}. Address: {}:{}", m_Retries, ex.getMessage(), m_Request, m_Connection.getAddress(), m_Connection.getPort());
                    throw new ModbusIOException("Executing transaction failed (tried " + m_Retries + " times)");
                }
                Thread.sleep(m_RetryDelayMillis);
            }
        } while (true);
        if (tries > 0) {
            logger.info("execute eventually succeeded with {} re-tries. Request: {}. Address: {}:{}", tries, m_Request, m_Connection.getAddress(), m_Connection.getPort());
        }
        // 5. deal with "application level" exceptions
        if (m_Response instanceof ExceptionResponse) {
            throw new ModbusSlaveException(((ExceptionResponse) m_Response).getExceptionCode());
        }
        // 6. Check transaction validity
        if (isCheckingValidity()) {
            checkValidity();
        }
    } catch (InterruptedException ex) {
        throw new ModbusIOException("Thread acquiring lock was interrupted.");
    } finally {
        // Finally: close connection if reconnecting
        if (isReconnecting() && m_Connection != null) {
            m_Connection.close();
        }
        m_TransactionLock.release();
    }
}
Also used : ExceptionResponse(net.wimpi.modbus.msg.ExceptionResponse) ModbusSlaveException(net.wimpi.modbus.ModbusSlaveException) ModbusSlaveException(net.wimpi.modbus.ModbusSlaveException) ModbusException(net.wimpi.modbus.ModbusException) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 4 with ModbusException

use of net.wimpi.modbus.ModbusException in project openhab1-addons by openhab.

the class ModbusUDPTransaction method execute.

// setRetries
@Override
public void execute() throws ModbusIOException, ModbusSlaveException, ModbusException {
    // 1. assert executeability
    assertExecutable();
    try {
        // 2. Lock transaction
        /**
             * Note: The way this explicit synchronization is implemented at the moment,
             * there is no ordering of pending threads. The Mutex will simply call notify()
             * and the JVM will handle the rest.
             */
        m_TransactionLock.acquire();
        // 3. open the connection if not connected
        if (!m_Terminal.isActive()) {
            try {
                m_Terminal.activate();
                m_IO = m_Terminal.getModbusTransport();
            } catch (Exception ex) {
                throw new ModbusIOException("Activation failed.");
            }
        }
        // 3. Retry transaction m_Retries times, in case of
        // I/O Exception problems.
        m_RetryCounter = 0;
        while (m_RetryCounter <= m_Retries) {
            if (m_RetryCounter != 0) {
                Thread.sleep(m_RetryDelayMillis);
            }
            try {
                // toggle the id
                m_Request.setTransactionID(c_TransactionID.increment());
                // while holding the lock on the IO object
                synchronized (m_IO) {
                    // write request message
                    m_IO.writeMessage(m_Request);
                    // read response message
                    m_Response = m_IO.readResponse();
                    break;
                }
            } catch (ModbusIOException ex) {
                m_RetryCounter++;
                continue;
            }
        }
        // 4. deal with "application level" exceptions
        if (m_Response instanceof ExceptionResponse) {
            throw new ModbusSlaveException(((ExceptionResponse) m_Response).getExceptionCode());
        }
        if (isCheckingValidity()) {
            checkValidity();
        }
    } catch (InterruptedException ex) {
        throw new ModbusIOException("Thread acquiring lock was interrupted.");
    } finally {
        m_TransactionLock.release();
    }
}
Also used : ExceptionResponse(net.wimpi.modbus.msg.ExceptionResponse) ModbusSlaveException(net.wimpi.modbus.ModbusSlaveException) ModbusSlaveException(net.wimpi.modbus.ModbusSlaveException) ModbusException(net.wimpi.modbus.ModbusException) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 5 with ModbusException

use of net.wimpi.modbus.ModbusException in project openhab1-addons by openhab.

the class SerialFacadeTest method main.

public static void main(String[] args) {
    int inChar = -1;
    int result = 0;
    boolean finished = false;
    int slaveId = 88;
    String portname = null;
    ModbusSerialMaster msm = null;
    try {
        // 1. Setup the parameters
        if (args.length < 2) {
            printUsage();
            System.exit(1);
        } else {
            try {
                portname = args[0];
                slaveId = Integer.parseInt(args[1]);
            } catch (Exception ex) {
                ex.printStackTrace();
                printUsage();
                System.exit(1);
            }
        }
        System.out.println(" sending test messages to slave: " + slaveId);
        System.out.println("net.wimpi.modbus.debug set to: " + System.getProperty("net.wimpi.modbus.debug"));
        System.out.println("Hit enter to start and <s enter> to terminate the test.");
        inChar = System.in.read();
        if ((inChar == 's') || (inChar == 'S')) {
            System.out.println("Exiting");
            System.exit(0);
        }
        // 2. Setup serial parameters
        SerialParameters params = new SerialParameters();
        params.setPortName(portname);
        params.setBaudRate(38400);
        params.setDatabits(8);
        params.setParity("None");
        params.setStopbits(1);
        params.setEncoding("rtu");
        params.setEcho(true);
        if (Modbus.debug) {
            System.out.println("Encoding [" + params.getEncoding() + "]");
        }
        // 3. Create the master facade
        msm = new ModbusSerialMaster(params);
        msm.connect();
        do {
            if (msm.writeCoil(slaveId, 4, true) == true) {
                System.out.println("Set output 5 to true");
            } else {
                System.err.println("Error setting slave " + slaveId + " output 5");
            }
            BitVector coils = msm.readCoils(slaveId, 0, 8);
            if (coils != null) {
                System.out.print("Coils:");
                for (int i = 0; i < coils.size(); i++) {
                    System.out.print(" " + i + ": " + coils.getBit(i));
                }
                System.out.println();
                try {
                    msm.writeMultipleCoils(slaveId, 0, coils);
                } catch (ModbusException ex) {
                    System.out.println("Error writing coils: " + result);
                }
            } else {
                System.out.println("Outputs: null");
                msm.disconnect();
                System.exit(-1);
            }
            BitVector digInp = msm.readInputDiscretes(slaveId, 0, 8);
            if (digInp != null) {
                System.out.print("Digital Inputs:");
                for (int i = 0; i < digInp.size(); i++) {
                    System.out.print(" " + i + ": " + digInp.getBit(i));
                }
                System.out.println();
                System.out.println("Inputs: " + ModbusUtil.toHex(digInp.getBytes()));
            } else {
                System.out.println("Inputs: null");
                msm.disconnect();
                System.exit(-1);
            }
            InputRegister[] ai = null;
            for (int i = 1000; i < 1010; i++) {
                ai = msm.readInputRegisters(slaveId, i, 1);
                if (ai != null) {
                    System.out.print("Tag " + i + ": ");
                    for (int n = 0; n < ai.length; n++) {
                        System.out.print(" " + ai[n].getValue());
                    }
                    System.out.println();
                } else {
                    System.out.println("Tag: " + i + " null");
                    msm.disconnect();
                    System.exit(-1);
                }
            }
            Register[] regs = null;
            for (int i = 1000; i < 1005; i++) {
                regs = msm.readMultipleRegisters(slaveId, i, 1);
                if (regs != null) {
                    System.out.print("RWRegisters " + i + " length: " + regs.length);
                    for (int n = 0; n < regs.length; n++) {
                        System.out.print(" " + regs[n].getValue());
                    }
                    System.out.println();
                } else {
                    System.out.println("RWRegisters " + i + ": null");
                    msm.disconnect();
                    System.exit(-1);
                }
            }
            regs = msm.readMultipleRegisters(slaveId, 0, 10);
            System.out.println("Registers: ");
            if (regs != null) {
                System.out.print("regs :");
                for (int n = 0; n < regs.length; n++) {
                    System.out.print("  " + n + "= " + regs[n]);
                }
                System.out.println();
            } else {
                System.out.println("Registers: null");
                msm.disconnect();
                System.exit(-1);
            }
            while (System.in.available() > 0) {
                inChar = System.in.read();
                if ((inChar == 's') || (inChar == 'S')) {
                    finished = true;
                }
            }
        } while (!finished);
    } catch (Exception e) {
        System.err.println("SerialFacadeTest driver: " + e);
        e.printStackTrace();
    }
    msm.disconnect();
}
Also used : BitVector(net.wimpi.modbus.util.BitVector) InputRegister(net.wimpi.modbus.procimg.InputRegister) InputRegister(net.wimpi.modbus.procimg.InputRegister) Register(net.wimpi.modbus.procimg.Register) ModbusSerialMaster(net.wimpi.modbus.facade.ModbusSerialMaster) ModbusException(net.wimpi.modbus.ModbusException) SerialParameters(net.wimpi.modbus.util.SerialParameters) ModbusException(net.wimpi.modbus.ModbusException)

Aggregations

ModbusException (net.wimpi.modbus.ModbusException)6 ModbusIOException (net.wimpi.modbus.ModbusIOException)2 ModbusSlaveException (net.wimpi.modbus.ModbusSlaveException)2 ExceptionResponse (net.wimpi.modbus.msg.ExceptionResponse)2 ModbusResponse (net.wimpi.modbus.msg.ModbusResponse)2 ModbusSlaveConnection (net.wimpi.modbus.net.ModbusSlaveConnection)2 ModbusSlaveEndpoint (org.openhab.binding.modbus.internal.pooling.ModbusSlaveEndpoint)2 ModbusSerialMaster (net.wimpi.modbus.facade.ModbusSerialMaster)1 ModbusRequest (net.wimpi.modbus.msg.ModbusRequest)1 ReadCoilsRequest (net.wimpi.modbus.msg.ReadCoilsRequest)1 ReadCoilsResponse (net.wimpi.modbus.msg.ReadCoilsResponse)1 ReadInputDiscretesRequest (net.wimpi.modbus.msg.ReadInputDiscretesRequest)1 ReadInputDiscretesResponse (net.wimpi.modbus.msg.ReadInputDiscretesResponse)1 ReadInputRegistersRequest (net.wimpi.modbus.msg.ReadInputRegistersRequest)1 ReadInputRegistersResponse (net.wimpi.modbus.msg.ReadInputRegistersResponse)1 ReadMultipleRegistersRequest (net.wimpi.modbus.msg.ReadMultipleRegistersRequest)1 ReadMultipleRegistersResponse (net.wimpi.modbus.msg.ReadMultipleRegistersResponse)1 InputRegister (net.wimpi.modbus.procimg.InputRegister)1 Register (net.wimpi.modbus.procimg.Register)1 BitVector (net.wimpi.modbus.util.BitVector)1