Search in sources :

Example 1 with ModbusRequest

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

the class WriteCoilsAndDiscreteTestCase method verifyRequests.

private void verifyRequests(boolean readRequestExpected) throws Exception {
    try {
        ArrayList<ModbusRequest> requests = modbustRequestCaptor.getAllReturnValues();
        int expectedDOIndex = nonZeroOffset ? (itemIndex + 1) : itemIndex;
        WriteCoilRequest writeRequest;
        boolean writeExpected = type == ModbusBindingProvider.TYPE_COIL;
        int expectedRequests = (writeExpected ? 1 : 0) + (readRequestExpected ? 1 : 0);
        // One connection per request
        int expectedConnections = serverType.equals(ServerType.UDP) ? 1 : expectedRequests;
        // Give the system 5 seconds to make the expected connections & requests
        waitForConnectionsReceived(expectedConnections);
        waitForRequests(expectedRequests);
        assertThat(requests.size(), is(equalTo(expectedRequests)));
        if (readRequestExpected) {
            if (type == ModbusBindingProvider.TYPE_DISCRETE) {
                assertThat(requests.get(0), is(instanceOf(ReadInputDiscretesRequest.class)));
            } else if (type == ModbusBindingProvider.TYPE_COIL) {
                assertThat(requests.get(0), is(instanceOf(ReadCoilsRequest.class)));
            } else {
                throw new RuntimeException();
            }
        }
        if (writeExpected) {
            assertThat(requests.get(expectedRequests - 1), is(instanceOf(WriteCoilRequest.class)));
            writeRequest = (WriteCoilRequest) requests.get(expectedRequests - 1);
            assertThat(writeRequest.getCoil(), is(equalTo(expectedValue)));
            assertThat(writeRequest.getReference(), is(equalTo(expectedDOIndex)));
        }
    } catch (AssertionError e) {
        System.err.println(String.format("Unexpected assertion error: discreteInitial=%s, coilInitial=%s, nonZeroOffset=%s, command=%s, itemIndex=%d, type=%s", discreteInitialValue, coilInitialValue, nonZeroOffset, command, itemIndex, type));
        throw new AssertionError("Got unexpected assertion error", e);
    }
    System.err.println(String.format("OK: discreteInitial=%s, coilInitial=%s, nonZeroOffset=%s, command=%s, itemIndex=%d, type=%s", discreteInitialValue, coilInitialValue, nonZeroOffset, command, itemIndex, type));
}
Also used : ReadCoilsRequest(net.wimpi.modbus.msg.ReadCoilsRequest) ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) WriteCoilRequest(net.wimpi.modbus.msg.WriteCoilRequest)

Example 2 with ModbusRequest

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

the class WriteRegistersTestCase method verifyRequests.

private void verifyRequests(boolean readRequestExpected) throws Exception {
    try {
        ArrayList<ModbusRequest> requests = modbustRequestCaptor.getAllReturnValues();
        int expectedRegisterWriteStartIndex = nonZeroOffset ? (itemIndex + 1) : itemIndex;
        boolean writeExpected = type == ModbusBindingProvider.TYPE_HOLDING;
        int expectedRequests = (writeExpected ? 1 : 0) + (readRequestExpected ? 1 : 0);
        // One connection per request
        int expectedConnections = serverType.equals(ServerType.UDP) ? 1 : expectedRequests;
        // Give the system 5 seconds to make the expected connections & requests
        waitForConnectionsReceived(expectedConnections);
        waitForRequests(expectedRequests);
        assertThat(requests.size(), is(equalTo(expectedRequests)));
        if (readRequestExpected) {
            if (type == ModbusBindingProvider.TYPE_INPUT) {
                assertThat(requests.get(0), is(instanceOf(ReadInputRegistersRequest.class)));
            } else if (type == ModbusBindingProvider.TYPE_HOLDING) {
                assertThat(requests.get(0), is(instanceOf(ReadMultipleRegistersRequest.class)));
            } else {
                throw new RuntimeException();
            }
        }
        if (writeExpected) {
            Register[] registers;
            if (expectingWriteMultiple(valueType)) {
                assertThat(requests.get(expectedRequests - 1), is(instanceOf(WriteMultipleRegistersRequest.class)));
                WriteMultipleRegistersRequest writeRequest = (WriteMultipleRegistersRequest) requests.get(expectedRequests - 1);
                assertThat(writeRequest.getReference(), is(equalTo(expectedRegisterWriteStartIndex)));
                if (expectedValue == null && expectingAssertionError) {
                    String msg = "Did not receive any AssertionErrors even though expected!";
                    errPrint(msg);
                    throw new RuntimeException(msg);
                }
                registers = writeRequest.getRegisters();
            } else {
                assertThat(requests.get(expectedRequests - 1), is(instanceOf(WriteSingleRegisterRequest.class)));
                WriteSingleRegisterRequest writeRequest = (WriteSingleRegisterRequest) requests.get(expectedRequests - 1);
                assertThat(writeRequest.getReference(), is(equalTo(expectedRegisterWriteStartIndex)));
                if (expectedValue == null && expectingAssertionError) {
                    String msg = "Did not receive any AssertionErrors even though expected!";
                    errPrint(msg);
                    throw new RuntimeException(msg);
                }
                registers = new Register[] { writeRequest.getRegister() };
            }
            short[] registersAsShort = new short[registers.length];
            for (int i = 0; i < registers.length; i++) {
                registersAsShort[i] = registers[i].toShort();
            }
            assertThat(registersAsShort, is(equalTo(expectedValue)));
        }
    } catch (AssertionError e) {
        if (expectingAssertionError) {
            errPrint("Expected failure");
            e.printStackTrace(System.err);
            return;
        } else {
            errPrint("Unexpected assertion error " + e.getMessage());
            e.printStackTrace(System.err);
            throw e;
        }
    }
    if (expectingAssertionError) {
        errPrint("Did not get assertion error (as expected)");
        throw new AssertionError("Did not get assertion error (as expected)");
    } else {
        errPrint("OK");
    }
}
Also used : WriteSingleRegisterRequest(net.wimpi.modbus.msg.WriteSingleRegisterRequest) ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) SimpleRegister(net.wimpi.modbus.procimg.SimpleRegister) SimpleInputRegister(net.wimpi.modbus.procimg.SimpleInputRegister) Register(net.wimpi.modbus.procimg.Register) ReadMultipleRegistersRequest(net.wimpi.modbus.msg.ReadMultipleRegistersRequest) WriteMultipleRegistersRequest(net.wimpi.modbus.msg.WriteMultipleRegistersRequest)

Example 3 with ModbusRequest

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

the class AITest method main.

public static void main(String[] args) {
    InetAddress addr = null;
    TCPMasterConnection con = null;
    ModbusRequest req = null;
    ModbusTransaction trans = null;
    int ref = 0;
    int count = 0;
    int repeat = 1;
    int port = Modbus.DEFAULT_PORT;
    try {
        // 1. Setup 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 = Integer.parseInt(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 ReadInputRegistersRequest(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();
            ReadInputRegistersResponse res = (ReadInputRegistersResponse) trans.getResponse();
            if (Modbus.debug) {
                System.out.println("Response: " + res.getHexMessage());
            }
            for (int n = 0; n < res.getWordCount(); n++) {
                System.out.println("Word " + n + "=" + res.getRegisterValue(n));
            }
            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) ReadInputRegistersRequest(net.wimpi.modbus.msg.ReadInputRegistersRequest) InetAddress(java.net.InetAddress) ModbusTransaction(net.wimpi.modbus.io.ModbusTransaction) ReadInputRegistersResponse(net.wimpi.modbus.msg.ReadInputRegistersResponse)

Example 4 with ModbusRequest

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

the class ModbusSlave method setRegister.

/**
     * Performs physical write to device when slave type is "holding" using Modbus FC06 function
     *
     * @param command command received from OpenHAB
     * @param config
     * @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
     */
protected void setRegister(Command command, ModbusBindingConfig config) throws ModbusConnectionException, ModbusException, ModbusUnexpectedTransactionIdException {
    int readIndex = config.readIndex;
    int writeRegister = getStart() + config.writeIndex;
    Register newValue;
    if (command instanceof IncreaseDecreaseType) {
        newValue = readCachedRegisterValue(readIndex);
        if (newValue == null) {
            logger.warn("Not polled value for item {}. Cannot process command {}", config.getItemName(), command);
            return;
        }
        if (command.equals(IncreaseDecreaseType.INCREASE)) {
            newValue.setValue(newValue.getValue() + 1);
        } else if (command.equals(IncreaseDecreaseType.DECREASE)) {
            newValue.setValue(newValue.getValue() - 1);
        }
    } else if (command instanceof UpDownType) {
        newValue = readCachedRegisterValue(readIndex);
        if (newValue == null) {
            logger.warn("Not polled value for item {}. Cannot process command {}", config.getItemName(), command);
            return;
        }
        if (command.equals(UpDownType.UP)) {
            newValue.setValue(newValue.getValue() + 1);
        } else if (command.equals(UpDownType.DOWN)) {
            newValue.setValue(newValue.getValue() - 1);
        }
    } else if (command instanceof DecimalType) {
        newValue = new SimpleRegister();
        newValue.setValue(((DecimalType) command).intValue());
    } else if (command instanceof OnOffType) {
        newValue = new SimpleRegister();
        if (command.equals(OnOffType.ON)) {
            newValue.setValue(1);
        } else if (command.equals(OnOffType.OFF)) {
            newValue.setValue(0);
        }
    } else if (command instanceof OpenClosedType) {
        newValue = new SimpleRegister();
        if (command.equals(OpenClosedType.OPEN)) {
            newValue.setValue(1);
        } else if (command.equals(OpenClosedType.CLOSED)) {
            newValue.setValue(0);
        }
    } else {
        logger.warn("Item {} received unsupported command: {}. Not setting register.", config.getItemName(), command);
        return;
    }
    ModbusRequest request = null;
    if (writeMultipleRegisters) {
        Register[] regs = new Register[1];
        regs[0] = newValue;
        request = new WriteMultipleRegistersRequest(writeRegister, regs);
    } else {
        request = new WriteSingleRegisterRequest(writeRegister, newValue);
    }
    request.setUnitID(getId());
    logger.debug("ModbusSlave ({}): FC{} ref={} value={}", name, request.getFunctionCode(), writeRegister, newValue.getValue());
    executeWriteRequest(request);
}
Also used : WriteSingleRegisterRequest(net.wimpi.modbus.msg.WriteSingleRegisterRequest) Register(net.wimpi.modbus.procimg.Register) InputRegister(net.wimpi.modbus.procimg.InputRegister) SimpleRegister(net.wimpi.modbus.procimg.SimpleRegister) OnOffType(org.openhab.core.library.types.OnOffType) OpenClosedType(org.openhab.core.library.types.OpenClosedType) DecimalType(org.openhab.core.library.types.DecimalType) ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) IncreaseDecreaseType(org.openhab.core.library.types.IncreaseDecreaseType) UpDownType(org.openhab.core.library.types.UpDownType) SimpleRegister(net.wimpi.modbus.procimg.SimpleRegister) ModbusSlaveEndpoint(org.openhab.binding.modbus.internal.pooling.ModbusSlaveEndpoint) WriteMultipleRegistersRequest(net.wimpi.modbus.msg.WriteMultipleRegistersRequest)

Example 5 with ModbusRequest

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

the class ModbusSlave method doSetCoil.

/**
     * Sends boolean (bit) data to the device using Modbus FC05 function
     *
     * @param writeRegister
     * @param b
     * @throws ModbusUnexpectedTransactionIdException
     * @throws ModbusException
     * @throws ModbusConnectionException
     */
public void doSetCoil(int writeRegister, boolean b) throws ModbusConnectionException, ModbusException, ModbusUnexpectedTransactionIdException {
    ModbusRequest request = new WriteCoilRequest(writeRegister, b);
    request.setUnitID(getId());
    logger.debug("ModbusSlave ({}): FC05 ref={} value={}", name, writeRegister, b);
    executeWriteRequest(request);
}
Also used : ModbusRequest(net.wimpi.modbus.msg.ModbusRequest) WriteCoilRequest(net.wimpi.modbus.msg.WriteCoilRequest)

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