Search in sources :

Example 1 with ModbusIOException

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

the class ModbusASCIITransport method writeMessage.

// close
@Override
public void writeMessage(ModbusMessage msg) throws ModbusIOException {
    try {
        synchronized (m_ByteOut) {
            // write message to byte out
            msg.setHeadless();
            msg.writeTo(m_ByteOut);
            byte[] buf = m_ByteOut.getBuffer();
            int len = m_ByteOut.size();
            // write message
            // FRAMESTART
            m_OutputStream.write(FRAME_START);
            // PDU
            m_OutputStream.write(buf, 0, len);
            logger.debug("Writing: {}", ModbusUtil.toHex(buf, 0, len));
            // LRC
            m_OutputStream.write(ModbusUtil.calculateLRC(buf, 0, len));
            // FRAMEEND
            m_OutputStream.write(FRAME_END);
            m_OutputStream.flush();
            m_ByteOut.reset();
            // for RS485
            if (m_Echo) {
                // read back the echoed message
                readEcho(len + 3);
            }
        }
    } catch (Exception ex) {
        throw new ModbusIOException("I/O failed to write" + ex);
    }
}
Also used : IOException(java.io.IOException) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 2 with ModbusIOException

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

the class ModbusBINTransport method readRequest.

// writeMessage
@Override
public ModbusRequest readRequest() throws ModbusIOException {
    boolean done = false;
    ModbusRequest request = null;
    int in = -1;
    try {
        do {
            // 1. Skip to FRAME_START
            while ((in = m_InputStream.read()) != FRAME_START) {
                ;
            }
            // 2. Read to FRAME_END
            synchronized (m_InBuffer) {
                m_ByteInOut.reset();
                while ((in = m_InputStream.read()) != FRAME_END) {
                    m_ByteInOut.writeByte(in);
                }
                // check CRC
                int[] crc = ModbusUtil.calculateCRC(m_InBuffer, 0, m_ByteInOut.size() - 2);
                if (!(// low byte first
                m_InBuffer[m_ByteInOut.size() - 2] == crc[0] && // hibyte
                m_InBuffer[m_ByteInOut.size() - 1] == crc[1])) {
                    continue;
                }
                m_ByteIn.reset(m_InBuffer, m_ByteInOut.size());
                in = m_ByteIn.readUnsignedByte();
                // check unit identifier
                if (in != ModbusCoupler.getReference().getUnitID()) {
                    continue;
                }
                in = m_ByteIn.readUnsignedByte();
                // create request
                request = ModbusRequest.createModbusRequest(in);
                request.setHeadless();
                // read message
                m_ByteIn.reset(m_InBuffer, m_ByteInOut.size());
                request.readFrom(m_ByteIn);
            }
            done = true;
        } while (!done);
        return request;
    } catch (Exception ex) {
        final String errMsg = "failed to read";
        logger.debug("{}: {}", errMsg, ex.getMessage());
        throw new ModbusIOException("I/O exception - " + errMsg);
    }
}
Also used : ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) IOException(java.io.IOException) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 3 with ModbusIOException

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

the class ModbusBINTransport method writeMessage.

// close
@Override
public void writeMessage(ModbusMessage msg) throws ModbusIOException {
    try {
        int len;
        synchronized (m_ByteOut) {
            // write message to byte out
            msg.setHeadless();
            msg.writeTo(m_ByteOut);
            byte[] buf = m_ByteOut.getBuffer();
            len = m_ByteOut.size();
            // write message
            // FRAMESTART
            m_OutputStream.write(FRAME_START);
            // PDU
            m_OutputStream.write(buf, 0, len);
            // CRC
            int[] crc = ModbusUtil.calculateCRC(buf, 0, len);
            m_OutputStream.write(crc[0]);
            m_OutputStream.write(crc[1]);
            // FRAMEEND
            m_OutputStream.write(FRAME_END);
            m_OutputStream.flush();
            m_ByteOut.reset();
        }
        // for RS485
        if (m_Echo) {
            // read back the echoed message
            readEcho(len + 4);
        }
    } catch (Exception ex) {
        throw new ModbusIOException("I/O failed to write");
    }
}
Also used : IOException(java.io.IOException) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 4 with ModbusIOException

use of net.wimpi.modbus.ModbusIOException 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 5 with ModbusIOException

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

the class ModbusTCPTransport method readResponse.

// readRequest
@Override
public ModbusResponse readResponse() throws ModbusIOException {
    try {
        ModbusResponse res = null;
        synchronized (m_ByteIn) {
            // use same buffer
            byte[] buffer = m_ByteIn.getBuffer();
            // read to byte length of message
            if (m_Input.read(buffer, 0, 6) == -1) {
                throw new ModbusIOException("Premature end of stream (Header truncated).");
            }
            // extract length of bytes following in message
            int bf = ModbusUtil.registerToShort(buffer, 4);
            // read rest
            if (m_Input.read(buffer, 6, bf) == -1) {
                throw new ModbusIOException("Premature end of stream (Message truncated).");
            }
            m_ByteIn.reset(buffer, (6 + bf));
            m_ByteIn.skip(7);
            int functionCode = m_ByteIn.readUnsignedByte();
            m_ByteIn.reset();
            res = ModbusResponse.createModbusResponse(functionCode);
            res.readFrom(m_ByteIn);
        }
        return res;
    /*
             * try {
             * int transactionID = m_Input.readUnsignedShort();
             * //System.out.println("Read tid="+transactionID);
             * int protocolID = m_Input.readUnsignedShort();
             * //System.out.println("Read pid="+protocolID);
             * int dataLength = m_Input.readUnsignedShort();
             * //System.out.println("Read length="+dataLength);
             * int unitID = m_Input.readUnsignedByte();
             * //System.out.println("Read uid="+unitID);
             * int functionCode = m_Input.readUnsignedByte();
             * //System.out.println("Read fc="+functionCode);
             * ModbusResponse response =
             * ModbusResponse.createModbusResponse(functionCode, m_Input, false);
             * if (response instanceof ExceptionResponse) {
             * //skip rest of bytes
             * for (int i = 0; i < dataLength - 2; i++) {
             * m_Input.readByte();
             * }
             * }
             * //set read parameters
             * response.setTransactionID(transactionID);
             * response.setProtocolID(protocolID);
             * response.setUnitID(unitID);
             * return response;
             */
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new ModbusIOException("I/O exception - failed to read.");
    }
}
Also used : ModbusResponse(net.wimpi.modbus.msg.ModbusResponse) ModbusIOException(net.wimpi.modbus.ModbusIOException) IOException(java.io.IOException) EOFException(java.io.EOFException) SocketException(java.net.SocketException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Aggregations

ModbusIOException (net.wimpi.modbus.ModbusIOException)19 IOException (java.io.IOException)14 ModbusResponse (net.wimpi.modbus.msg.ModbusResponse)7 ModbusRequest (net.wimpi.modbus.msg.ModbusRequest)6 EOFException (java.io.EOFException)3 InterruptedIOException (java.io.InterruptedIOException)3 SocketException (java.net.SocketException)3 ModbusSlaveException (net.wimpi.modbus.ModbusSlaveException)3 ExceptionResponse (net.wimpi.modbus.msg.ExceptionResponse)3 ModbusException (net.wimpi.modbus.ModbusException)2 ModbusTransport (net.wimpi.modbus.io.ModbusTransport)1