Search in sources :

Example 6 with ModbusRequest

use of net.wimpi.modbus.msg.ModbusRequest 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 7 with ModbusRequest

use of net.wimpi.modbus.msg.ModbusRequest 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 8 with ModbusRequest

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

the class DOTest method main.

public static void main(String[] args) {
    InetAddress addr = null;
    TCPMasterConnection con = null;
    ModbusRequest req = null;
    ModbusTransaction trans = null;
    int ref = 0;
    boolean count = false;
    int repeat = 1;
    int port = Modbus.DEFAULT_PORT;
    try {
        // 1. Setup the parameters
        if (args.length < 3) {
            printUsage();
            System.exit(1);
        } else {
            try {
                String astr = args[0];
                int idx = astr.indexOf(':');
                if (idx > 0) {
                    port = Integer.parseInt(astr.substring(idx + 1));
                    astr = astr.substring(0, idx);
                }
                addr = InetAddress.getByName(astr);
                ref = Integer.parseInt(args[1]);
                count = "true".equals(args[2]);
                if (args.length == 4) {
                    repeat = Integer.parseInt(args[3]);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                printUsage();
                System.exit(1);
            }
        }
        // 2. Open the connection
        con = new TCPMasterConnection(addr);
        con.setPort(port);
        con.connect();
        if (Modbus.debug) {
            System.out.println("Connected to " + addr.toString() + ":" + con.getPort());
        }
        // 3. Prepare the request
        req = new WriteCoilRequest(ref, count);
        req.setUnitID(0);
        if (Modbus.debug) {
            System.out.println("Request: " + req.getHexMessage());
        }
        // 4. Prepare the transaction
        trans = new ModbusTCPTransaction(con);
        trans.setRequest(req);
        // 5. Execute the transaction repeat times
        int k = 0;
        do {
            trans.execute();
            if (Modbus.debug) {
                System.out.println("Response: " + trans.getResponse().getHexMessage());
            }
            k++;
        } while (k < repeat);
        // 6. Close the connection
        con.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Also used : ModbusTCPTransaction(net.wimpi.modbus.io.ModbusTCPTransaction) TCPMasterConnection(net.wimpi.modbus.net.TCPMasterConnection) ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) InetAddress(java.net.InetAddress) ModbusTransaction(net.wimpi.modbus.io.ModbusTransaction) WriteCoilRequest(net.wimpi.modbus.msg.WriteCoilRequest)

Example 9 with ModbusRequest

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

the class ModbusTCPTransport method readRequest.

// write
@Override
public ModbusRequest readRequest() throws ModbusIOException {
    // System.out.println("readRequest()");
    try {
        ModbusRequest req = 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 EOFException("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();
            req = ModbusRequest.createModbusRequest(functionCode);
            req.readFrom(m_ByteIn);
        }
        return req;
    /*
             * int transactionID = m_Input.readUnsignedShort();
             * int protocolID = m_Input.readUnsignedShort();
             * int dataLength = m_Input.readUnsignedShort();
             * if (protocolID != Modbus.DEFAULT_PROTOCOL_ID || dataLength > 256) {
             * throw new ModbusIOException();
             * }
             * int unitID = m_Input.readUnsignedByte();
             * int functionCode = m_Input.readUnsignedByte();
             * ModbusRequest request =
             * ModbusRequest.createModbusRequest(functionCode, m_Input, false);
             * if (request instanceof IllegalFunctionRequest) {
             * //skip rest of bytes
             * for (int i = 0; i < dataLength - 2; i++) {
             * m_Input.readByte();
             * }
             * }
             * //set read parameters
             * request.setTransactionID(transactionID);
             * request.setProtocolID(protocolID);
             * request.setUnitID(unitID);
             * return request;
             *
             */
    } catch (EOFException eoex) {
        throw new ModbusIOException(true);
    } catch (SocketException sockex) {
        // connection reset by peer, also EOF
        throw new ModbusIOException(true);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new ModbusIOException("I/O exception - failed to read.");
    }
}
Also used : SocketException(java.net.SocketException) EOFException(java.io.EOFException) ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) ModbusIOException(net.wimpi.modbus.ModbusIOException) IOException(java.io.IOException) EOFException(java.io.EOFException) SocketException(java.net.SocketException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 10 with ModbusRequest

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

the class ModbusUDPTransport method readRequest.

// write
@Override
public ModbusRequest readRequest() throws ModbusIOException {
    try {
        ModbusRequest req = null;
        synchronized (m_ByteIn) {
            m_ByteIn.reset(m_Terminal.receiveMessage());
            m_ByteIn.skip(7);
            int functionCode = m_ByteIn.readUnsignedByte();
            m_ByteIn.reset();
            req = ModbusRequest.createModbusRequest(functionCode);
            req.readFrom(m_ByteIn);
        }
        return req;
    } catch (Exception ex) {
        throw new ModbusIOException("I/O exception - failed to read.");
    }
}
Also used : ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Aggregations

ModbusRequest (net.wimpi.modbus.msg.ModbusRequest)17 ModbusIOException (net.wimpi.modbus.ModbusIOException)6 InetAddress (java.net.InetAddress)5 ModbusTCPTransaction (net.wimpi.modbus.io.ModbusTCPTransaction)5 WriteSingleRegisterRequest (net.wimpi.modbus.msg.WriteSingleRegisterRequest)5 TCPMasterConnection (net.wimpi.modbus.net.TCPMasterConnection)5 IOException (java.io.IOException)4 ModbusTransaction (net.wimpi.modbus.io.ModbusTransaction)4 WriteCoilRequest (net.wimpi.modbus.msg.WriteCoilRequest)4 SimpleRegister (net.wimpi.modbus.procimg.SimpleRegister)4 ReadInputRegistersRequest (net.wimpi.modbus.msg.ReadInputRegistersRequest)3 ReadMultipleRegistersRequest (net.wimpi.modbus.msg.ReadMultipleRegistersRequest)3 ModbusResponse (net.wimpi.modbus.msg.ModbusResponse)2 ReadCoilsRequest (net.wimpi.modbus.msg.ReadCoilsRequest)2 ReadInputDiscretesRequest (net.wimpi.modbus.msg.ReadInputDiscretesRequest)2 ReadInputRegistersResponse (net.wimpi.modbus.msg.ReadInputRegistersResponse)2 WriteMultipleRegistersRequest (net.wimpi.modbus.msg.WriteMultipleRegistersRequest)2 Register (net.wimpi.modbus.procimg.Register)2 ModbusSlaveEndpoint (org.openhab.binding.modbus.internal.pooling.ModbusSlaveEndpoint)2 EOFException (java.io.EOFException)1