Search in sources :

Example 11 with ModbusRequest

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

the class ModbusSerialListener method listen.

/**
     * Listen to incoming messages.
     */
private void listen() {
    try {
        m_Listening = true;
        m_SerialCon.open();
        logger.trace("Opened Serial connection.");
        ModbusTransport transport = m_SerialCon.getModbusTransport();
        do {
            if (m_Listening) {
                try {
                    // 1. read the request
                    ModbusRequest request = transport.readRequest();
                    ModbusResponse response = null;
                    // test if Process image exists
                    if (ModbusCoupler.getReference().getProcessImage() == null) {
                        response = request.createExceptionResponse(Modbus.ILLEGAL_FUNCTION_EXCEPTION);
                    } else {
                        response = request.createResponse();
                    }
                    logger.debug("Request:{}", request.getHexMessage());
                    logger.debug("Response:{}", response.getHexMessage());
                    transport.writeMessage(response);
                    count();
                } catch (ModbusIOException ex) {
                    ex.printStackTrace();
                    continue;
                }
            }
        // ensure nice multithreading behaviour on specific platforms
        } while (true);
    } catch (Exception e) {
        // FIXME: this is a major failure, how do we handle this
        e.printStackTrace();
    }
}
Also used : ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) ModbusResponse(net.wimpi.modbus.msg.ModbusResponse) ModbusTransport(net.wimpi.modbus.io.ModbusTransport) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 12 with ModbusRequest

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

the class TCPConnectionHandler method run.

// setConnection
@Override
public void run() {
    try {
        do {
            // 1. read the request
            ModbusRequest request = m_Transport.readRequest();
            logger.trace("Request:{}", request.getHexMessage());
            ModbusResponse response = null;
            // test if Process image exists
            if (ModbusCoupler.getReference().getProcessImage() == null) {
                response = request.createExceptionResponse(Modbus.ILLEGAL_FUNCTION_EXCEPTION);
            } else {
                response = request.createResponse();
            }
            logger.debug("Request:{}", request.getHexMessage());
            logger.debug("Response:{}", response.getHexMessage());
            m_Transport.writeMessage(response);
        } while (true);
    } catch (ModbusIOException ex) {
        if (!ex.isEOF()) {
            // other troubles, output for debug
            ex.printStackTrace();
        }
    } finally {
        try {
            m_Connection.close();
        } catch (Exception ex) {
        // ignore
        }
    }
}
Also used : ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) ModbusResponse(net.wimpi.modbus.msg.ModbusResponse) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 13 with ModbusRequest

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

the class ModbusASCIITransport 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) {
                    if (in == -1) {
                        throw new IOException("readRequest: I/O exception - Serial port timeout.");
                    }
                    m_ByteInOut.writeByte(in);
                }
                // check LRC
                if ((m_InBuffer[m_ByteInOut.size() - 1] & 0xff) != ModbusUtil.calculateLRC(m_InBuffer, 0, m_ByteInOut.size() - 1)) {
                    continue;
                }
                ;
                m_ByteIn.reset(m_InBuffer, m_ByteInOut.size());
                in = m_ByteIn.readUnsignedByte();
                // check message with this slave 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 = "I/O exception - failed to read";
        logger.debug("{}: {}", errMsg, ex.getMessage());
        throw new ModbusIOException("readRequest: " + errMsg);
    }
}
Also used : ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) IOException(java.io.IOException) ModbusIOException(net.wimpi.modbus.ModbusIOException) IOException(java.io.IOException) ModbusIOException(net.wimpi.modbus.ModbusIOException) ModbusIOException(net.wimpi.modbus.ModbusIOException)

Example 14 with ModbusRequest

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

the class SimultaneousReadWriteTestCase method testSimultaneousReadWrite.

/**
     * Testing how binding handles simultaneous read and writes coming in.
     *
     * Even though the server in this test is able to handle at most one client at a time the binding
     * queues requests.
     *
     * Note higher artificialServerWait in constructor
     *
     * @throws Exception
     */
@Test
public void testSimultaneousReadWrite() throws Exception {
    binding = new ModbusBinding();
    binding.updated(addSlave(addSlave(newLongPollBindingConfig(), SLAVE_NAME, type, null, 0, READ_COUNT), SLAVE2_NAME, type, null, 0, READ_COUNT));
    configureItems(SLAVE_NAME);
    configureItems(SLAVE2_NAME);
    /*
         * - both slaves read twice -> 4 read requests
         * - followed by write (slave1) -> 1 write request
         * - both slaves read once -> 2 read requests.
         * - Finally three writes (slave2) -> 3 write requets
         */
    int expectedRequests = 10;
    ExecutorService pool = Executors.newFixedThreadPool(expectedRequests);
    binding.execute();
    pool.execute(new UpdateThread(binding));
    pool.execute(new WriteCommandThread(binding, SLAVE_NAME, command));
    pool.execute(new UpdateThread(binding));
    pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));
    pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));
    pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));
    pool.shutdown();
    pool.awaitTermination(artificialServerWait * 7 + 5000, TimeUnit.MILLISECONDS);
    waitForRequests(expectedRequests);
    ArrayList<ModbusRequest> values = modbustRequestCaptor.getAllReturnValues();
    System.err.println(values);
    int readCount = 0;
    int writeCount = 0;
    for (ModbusRequest request : values) {
        if (request instanceof ReadMultipleRegistersRequest) {
            readCount++;
        } else if (request instanceof WriteSingleRegisterRequest) {
            writeCount++;
        }
    }
    Assert.assertEquals(6, readCount);
    Assert.assertEquals(4, writeCount);
}
Also used : WriteSingleRegisterRequest(net.wimpi.modbus.msg.WriteSingleRegisterRequest) ReadMultipleRegistersRequest(net.wimpi.modbus.msg.ReadMultipleRegistersRequest) ExecutorService(java.util.concurrent.ExecutorService) ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) ModbusSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusSlaveEndpoint) ModbusTCPSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusTCPSlaveEndpoint) Test(org.junit.Test)

Example 15 with ModbusRequest

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

the class AIAOTest method main.

public static void main(String[] args) {
    InetAddress addr = null;
    TCPMasterConnection con = null;
    ModbusRequest ai_req = null;
    WriteSingleRegisterRequest ao_req = null;
    ModbusTransaction ai_trans = null;
    ModbusTransaction ao_trans = null;
    int ai_ref = 0;
    int ao_ref = 0;
    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);
                ai_ref = Integer.parseInt(args[1]);
                ao_ref = Integer.parseInt(args[2]);
            } 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 requests
        ai_req = new ReadInputRegistersRequest(ai_ref, 1);
        ao_req = new WriteSingleRegisterRequest();
        ao_req.setReference(ao_ref);
        ai_req.setUnitID(0);
        ao_req.setUnitID(0);
        // 4. Prepare the transactions
        ai_trans = new ModbusTCPTransaction(con);
        ai_trans.setRequest(ai_req);
        ao_trans = new ModbusTCPTransaction(con);
        ao_trans.setRequest(ao_req);
        // 5. Prepare holders to update only on change
        SimpleRegister new_out = new SimpleRegister(0);
        ao_req.setRegister(new_out);
        int last_out = Integer.MIN_VALUE;
        // 5. Execute the transaction repeatedly
        do {
            ai_trans.execute();
            int new_in = ((ReadInputRegistersResponse) ai_trans.getResponse()).getRegister(0).getValue();
            // write only if differ
            if (new_in != last_out) {
                // update register
                new_out.setValue(new_in);
                ao_trans.execute();
                last_out = new_in;
                if (Modbus.debug) {
                    System.out.println("Updated Register with value from Input Register.");
                }
            }
        } while (true);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        // 6. Close the connection
        con.close();
    }
}
Also used : ModbusTCPTransaction(net.wimpi.modbus.io.ModbusTCPTransaction) TCPMasterConnection(net.wimpi.modbus.net.TCPMasterConnection) WriteSingleRegisterRequest(net.wimpi.modbus.msg.WriteSingleRegisterRequest) ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) ReadInputRegistersRequest(net.wimpi.modbus.msg.ReadInputRegistersRequest) SimpleRegister(net.wimpi.modbus.procimg.SimpleRegister) InetAddress(java.net.InetAddress) ModbusTransaction(net.wimpi.modbus.io.ModbusTransaction)

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